@adhdev/daemon-standalone 1.0.58-rc.2 → 1.0.58-rc.4

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.
@@ -48,7 +48,7 @@ ${JSON.stringify(t,null,2)}
48
48
  `):"");try{await navigator.clipboard.writeText(ee.join(`
49
49
  `)),k("Copied!"),setTimeout(()=>k("Snapshot"),1500)}catch(re){console.error("[SpecDebugPanel] clipboard write failed",re)}},X=V=>{f(q=>{const ee=new Set(q);return ee.has(V)?ee.delete(V):ee.add(V),ee})};return s.jsx(Vt,{children:s.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Spec debug",className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center bg-black/60 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] px-0 sm:items-center sm:p-4",onClick:t,style:{pointerEvents:"auto"},children:s.jsxs("div",{className:"bg-bg-secondary text-text-primary border border-border-default rounded-t-xl sm:rounded-lg shadow-2xl max-w-2xl w-full max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[88vh] flex flex-col",onClick:V=>V.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-border-default px-4 py-2.5 shrink-0 gap-2 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 overflow-hidden",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary shrink-0",children:"Spec Debug"}),O&&s.jsx("span",{className:"text-[11px] text-text-secondary font-mono bg-surface-secondary px-1.5 py-0.5 rounded truncate",children:O.spec_id})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(O==null?void 0:O.specPath)&&s.jsx("button",{type:"button",className:`text-[11px] transition-colors px-2 py-1 rounded border ${h?"text-accent-primary bg-accent-primary/20 border-accent":"text-text-secondary hover:text-text-primary hover:bg-bg-glass-hover border-transparent hover:border-border-default"}`,onClick:()=>{h?b(!1):z()},disabled:a,children:h?"Close Editor":"Edit Spec"}),s.jsx("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors px-2 py-1 rounded hover:bg-bg-glass-hover border border-transparent hover:border-border-default",onClick:()=>{Y()},disabled:a,children:g}),s.jsx("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors px-2 py-1 rounded hover:bg-bg-glass-hover border border-transparent hover:border-border-default",onClick:()=>{$()},disabled:a,children:a?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"text-text-secondary hover:text-text-primary transition-colors text-xl leading-none w-7 h-7 flex items-center justify-center rounded hover:bg-bg-glass-hover",onClick:t,"aria-label":"Close",children:"×"})]})]}),h&&s.jsxs("div",{className:"flex-1 flex flex-col min-h-0 px-4 py-3 gap-2",children:[s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsxs("div",{className:"inline-flex rounded border border-border-default overflow-hidden text-[10px]",children:[s.jsx("button",{type:"button",className:`px-2 py-0.5 ${y?"text-text-secondary hover:bg-bg-glass-hover":"bg-accent-primary/20 text-accent-primary"}`,onClick:()=>{if(y)try{const V=JSON.parse(v);x(V),K(V)}catch{return}C(!1)},disabled:!S&&y,children:"Form"}),s.jsx("button",{type:"button",className:`px-2 py-0.5 ${y?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>{S&&w(JSON.stringify(S,null,2)),C(!0)},children:"JSON"})]}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate flex-1",title:O==null?void 0:O.specPath,children:((O==null?void 0:O.specPath)??"").split("/").slice(-3).join("/")}),j&&s.jsx("span",{className:"text-status-warning text-[10px]",children:"unsaved"}),!y&&M.length>0&&s.jsxs("span",{className:"text-status-error text-[10px]",children:[M.length," error",M.length>1?"s":""]}),s.jsx("button",{type:"button",className:`text-[11px] px-2.5 py-1 rounded border transition-colors ${A==="saving"||!y&&M.length>0?"text-text-muted border-border-default cursor-not-allowed":"text-status-online bg-status-online/20 border-status-online/40 hover:bg-status-online/20"}`,onClick:()=>{me()},disabled:A==="saving"||!y&&M.length>0,children:A==="saving"?"Saving…":A==="saved"?"Saved ✓ (reloading)":"Save & Apply"})]}),I&&s.jsx("pre",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-2 text-[10px] whitespace-pre-wrap shrink-0 max-h-28 overflow-y-auto",children:I}),!y&&M.length>0&&s.jsx("div",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-1.5 text-[10px] shrink-0 max-h-24 overflow-y-auto space-y-0.5",children:M.map((V,q)=>s.jsx("div",{className:"font-mono",children:V},q))}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:y||!S?s.jsx("textarea",{value:v,onChange:V=>{w(V.target.value),N(!0),T("idle")},spellCheck:!1,className:"w-full h-full min-h-[300px] font-mono text-[11px] leading-relaxed bg-bg-secondary text-text-primary border border-border-default rounded p-3 resize-none outline-none focus:border-accent"}):s.jsx(aj,{model:S,onChange:ne,onPreview:ie,preview:D,onTestSections:Ce,sectionPreview:R})}),s.jsx("div",{className:"text-[10px] text-text-muted shrink-0",children:y?"Raw JSON — validated on save.":'Build the FSM; from/to are constrained to existing states. "test" evaluates a condition against the live screen. Save hot-reloads the session.'})]}),!h&&s.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))] space-y-3 text-[12px]",children:[c&&s.jsx("div",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-2",children:c}),a&&!o&&s.jsx("div",{className:"text-text-muted text-center py-6",children:"Loading…"}),o&&!o.isSpecProvider&&s.jsxs("div",{className:"text-text-muted text-center py-6",children:["Not a spec-driven provider (",o.providerType||"unknown",")."]}),O&&s.jsxs(s.Fragment,{children:[O.nativeSource&&s.jsxs("div",{className:"text-[11px] text-text-secondary bg-surface-secondary border border-border-default rounded-md px-3 py-2",children:[s.jsx("span",{className:"text-accent-primary font-semibold",children:"Native-source provider"}),s.jsx("span",{className:"text-text-muted",children:" — no state-machine spec."}),s.jsx("span",{className:"text-text-muted",children:" State History, FSM transitions, and Sections are "}),s.jsx("span",{className:"text-text-secondary font-mono",children:"N/A"}),s.jsx("span",{className:"text-text-muted",children:". Status, screen, modal, and transcript below are live."}),O.transcriptAuthority&&s.jsxs("span",{className:"text-text-muted font-mono",children:[" (transcriptAuthority: ",O.transcriptAuthority,")"]})]}),s.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-[11px] bg-surface-secondary rounded-md px-3 py-2 border border-border-default",children:[O.name&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Provider"}),s.jsxs("span",{className:"font-mono text-text-primary",children:[O.name," ",s.jsxs("span",{className:"text-text-muted",children:["(",O.cliType,")"]})]})]}),O.workingDir&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Dir"}),s.jsx("span",{className:"font-mono text-text-secondary truncate min-w-0",title:O.workingDir,children:O.workingDir})]}),O.spawnedAtMs?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Spawned"}),s.jsx("span",{className:"text-text-secondary",children:$n(O.spawnedAtMs)})]}):null,O.providerSessionId&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Session"}),s.jsx("span",{className:"font-mono text-text-muted text-[10px] truncate min-w-0",title:O.providerSessionId,children:O.providerSessionId})]})]}),s.jsxs("div",{className:"flex items-center gap-2 flex-wrap bg-surface-secondary rounded-md px-3 py-2 border border-border-default",children:[s.jsx("span",{className:`font-semibold font-mono text-[12px] px-2 py-0.5 rounded ${O.current_state?ir(O.current_state.id):"text-text-muted"}`,children:O.current_state?O.current_state.id:"none"}),((he=O.current_state)==null?void 0:he.label)&&O.current_state.label!==O.current_state.id&&s.jsx("span",{className:"text-text-secondary text-[11px]",children:O.current_state.label}),O.status&&O.status!==((Z=O.current_state)==null?void 0:Z.id)&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["engine: ",s.jsx("span",{className:`font-mono ${ir(O.status)} px-1 py-0.5 rounded text-[10px]`,children:O.status})]}),O.idleHoldPending&&s.jsx("span",{className:"text-yellow-200 text-[10px] bg-yellow-600/25 border border-yellow-500/35 px-1.5 py-0.5 rounded font-mono",children:"idle hold pending"}),O.exited&&s.jsx("span",{className:"text-status-error text-[10px] bg-status-error/20 border border-status-error/40 px-1.5 py-0.5 rounded font-mono",children:"exited"}),O.cursorPosition!=null&&s.jsxs("span",{className:"text-text-muted text-[11px] font-mono",children:["cursor: ",s.jsxs("span",{className:"text-text-secondary",children:[O.cursorPosition.row,",",O.cursorPosition.col]})]}),O.lastBusyAt>0&&s.jsxs("span",{className:"text-text-muted text-[11px] ml-auto",children:["last busy: ",s.jsx("span",{className:"text-text-secondary",children:$n(O.lastBusyAt)})]})]}),((fe=O.completionIdleDebounce)==null?void 0:fe.active)&&s.jsxs("div",{className:"flex items-center gap-2 text-[11px] bg-accent-primary/20 border border-accent rounded-md px-3 py-1.5 font-mono",children:[s.jsx("span",{className:"text-accent-primary",children:"completion_idle_after"}),s.jsxs("span",{className:"text-text-secondary",children:["age: ",s.jsxs("span",{className:"text-accent-primary",children:[O.completionIdleDebounce.ageMs,"ms"]})]}),s.jsx("span",{className:"text-text-muted",children:"/"}),s.jsxs("span",{className:"text-text-secondary",children:["hold: ",s.jsxs("span",{className:"text-text-secondary",children:[O.completionIdleDebounce.holdMs,"ms"]})]}),s.jsxs("span",{className:"text-text-secondary",children:["force: ",s.jsxs("span",{className:"text-text-secondary",children:[O.completionIdleDebounce.forceAfterMs,"ms"]})]}),s.jsx("span",{className:"text-text-muted ml-auto",children:O.completionIdleDebounce.ageMs<O.completionIdleDebounce.holdMs?s.jsxs("span",{className:"text-status-warning",children:["hold remaining: ",O.completionIdleDebounce.holdMs-O.completionIdleDebounce.ageMs,"ms"]}):O.completionIdleDebounce.ageMs<O.completionIdleDebounce.forceAfterMs?s.jsxs("span",{className:"text-orange-300",children:["force in: ",O.completionIdleDebounce.forceAfterMs-O.completionIdleDebounce.ageMs,"ms"]}):s.jsx("span",{className:"text-status-error",children:"overdue"})})]}),O.current_modal&&s.jsxs("div",{className:"bg-orange-900/30 border border-orange-600/40 rounded-md p-2.5",children:[s.jsx("span",{className:"text-orange-200 font-semibold",children:"Modal: "}),s.jsx("span",{className:"text-text-secondary",children:O.current_modal.title||""}),O.current_modal.buttons.length>0&&s.jsxs("span",{className:"text-text-secondary ml-2",children:["[",O.current_modal.buttons.map(V=>V.label).join(" / "),"]"]})]}),O.fsm&&s.jsxs(s.Fragment,{children:[s.jsx(lr,{}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsxs(Fn,{children:["FSM — outgoing from ",s.jsx("span",{className:"text-accent-primary font-mono normal-case",children:O.fsm.currentState})," (held ",$d(O.fsm.stateAgeMs),")"]}),s.jsxs("label",{className:"ml-auto flex items-center gap-1 text-[10px] text-text-muted cursor-pointer select-none mb-1.5",children:[s.jsx("input",{type:"checkbox",checked:_,onChange:V=>H(V.target.checked),className:"accent-[var(--accent-primary)]"}),"live"]})]}),s.jsxs("div",{className:"space-y-1",children:[O.fsm.transitions.length===0&&s.jsx("div",{className:"text-text-muted text-[11px] italic px-1",children:"no outgoing transitions (terminal state)"}),O.fsm.transitions.map((V,q)=>s.jsx(uj,{t:V},q))]})]})]}),s.jsx(lr,{}),O.nativeSource&&s.jsxs("div",{children:[s.jsx(Fn,{children:"Sections"}),s.jsx("div",{className:"text-text-muted text-[11px] italic px-1",children:"N/A (native-source provider)"})]}),!O.nativeSource&&O.sections&&Object.keys(O.sections).length>0&&s.jsxs("div",{children:[s.jsx(Fn,{children:"Sections"}),s.jsx("div",{className:"space-y-1",children:Object.entries(O.sections).map(([V,q])=>{var se;const ee=m.has(V),pe=q.split(`
50
50
  `),le=((se=pe[0])==null?void 0:se.slice(0,80))||"(empty)";return s.jsxs("div",{className:"border border-border-default rounded overflow-hidden bg-surface-secondary",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2.5 py-1.5 hover:bg-bg-glass-hover transition-colors text-left",onClick:()=>X(V),children:[s.jsx("span",{className:"text-[10px] text-text-muted w-3",children:ee?"▾":"▸"}),s.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-[11px]",children:V}),!ee&&s.jsx("span",{className:"text-text-secondary truncate font-mono text-[11px]",children:le}),s.jsxs("span",{className:"ml-auto text-text-muted text-[10px] shrink-0",children:[pe.length,"L"]})]}),ee&&s.jsx("pre",{className:"px-3 pb-2.5 pt-1 font-mono text-[11px] text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary max-h-40 overflow-y-auto border-t border-border-default",children:q||"(empty)"})]},V)})})]}),s.jsx(lr,{}),O.nativeSource&&s.jsxs("div",{children:[s.jsxs(Fn,{children:["Status History",O.statusHistory&&O.statusHistory.length>0?` (${O.statusHistory.length})`:""]}),O.statusHistory&&O.statusHistory.length>0?s.jsx("div",{className:"space-y-px",children:[...O.statusHistory].reverse().slice(0,20).map((V,q)=>s.jsx("div",{className:"rounded px-2 py-1 hover:bg-bg-glass-hover transition-colors",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:`font-mono text-[11px] font-semibold px-1.5 py-0.5 rounded shrink-0 ${ir(V.status)}`,children:V.status}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:$n(V.at)}),V.trigger&&s.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 text-text-secondary bg-bg-glass border border-border-default",children:V.trigger})]})},q))}):s.jsx("div",{className:"text-text-muted text-[11px] italic px-1",children:"N/A (native-source provider — no state-machine rules)"})]}),!O.nativeSource&&O.stateHistory&&O.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs(Fn,{children:["State History (",O.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...O.stateHistory].reverse().slice(0,20).map((V,q)=>s.jsxs("div",{className:"rounded px-2 py-1 hover:bg-bg-glass-hover transition-colors",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:`font-mono text-[11px] font-semibold px-1.5 py-0.5 rounded shrink-0 ${ir(V.stateId)}`,children:V.stateId}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:$n(V.at)}),V.durationMs>0&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["held ",s.jsx("span",{className:"text-text-secondary",children:$d(V.durationMs)})]}),V.reason&&s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${cj[String(V.reason)]??"text-text-secondary bg-bg-glass border border-border-default"}`,children:String(V.reason)}),V.debounceKind&&String(V.debounceKind)!=="none"&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["debounce:",String(V.debounceKind)]}),V.matchedStateId&&String(V.matchedStateId)!==V.stateId&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["eval→",s.jsx("span",{className:"text-text-secondary",children:String(V.matchedStateId)})]})]}),V.matchedRules&&V.matchedRules.length>0&&s.jsxs("div",{className:"flex items-start gap-1 flex-wrap mt-0.5 ml-1 pl-1 border-l border-border-default",children:[V.matchedRules.slice(0,3).map((ee,pe)=>s.jsx("span",{className:"font-mono text-[10px] text-accent-primary bg-accent-primary/20 border border-accent px-1.5 py-0.5 rounded break-all",children:typeof ee=="string"?ee:JSON.stringify(ee)},pe)),V.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",V.matchedRules.length-3," more"]})]})]},q))})]}),s.jsx(lr,{}),(()=>{const V=O.messages??O.committedMessages??[];if(V.length===0)return null;const q=V.filter(le=>le.role==="user").length,ee=V.filter(le=>le.role==="assistant").length,pe=[...V].reverse().find(le=>le.role==="assistant");return s.jsxs("div",{children:[s.jsxs(Fn,{children:["Transcript (",V.length," — ",q,"u / ",ee,"a)"]}),pe&&s.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-md p-2.5 text-[11px]",children:[s.jsxs("div",{className:"text-text-muted mb-1 text-[10px]",children:["Last assistant ",pe.receivedAt?$n(pe.receivedAt):""]}),s.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[pe.content.slice(0,400),pe.content.length>400?"…":""]})]})]})})(),O.specPath&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:O.specPath,children:O.specPath}),s.jsxs("div",{children:[s.jsxs("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors flex items-center gap-1.5",onClick:()=>u(V=>!V),children:[s.jsx("span",{className:"text-text-muted",children:p?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",O.screen?O.screen.split(`
51
- `).length:0," lines)"]})]}),p&&s.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-[11px] text-text-secondary whitespace-pre bg-bg-secondary rounded-md border border-border-default max-h-64 overflow-auto",children:O.screen||"(empty)"})]})]})]})]})})})}function mj({activeConv:e,clearToken:t=0,terminalRef:n,handleSendChat:a,isSendingChat:r=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var Be;const{t:d}=ke("common");Ss();const{sendPtyInput:p}=St(),[u,m]=l.useState(!1),f=l.useRef(!1);f.current=u;const[g,k]=l.useState("Runtime terminal unavailable"),[h,b]=l.useState(!1),[S,x]=l.useState(null),[y,C]=l.useState(!1),[v,w]=l.useState(!1),[j,N]=l.useState(1),[A,T]=l.useState(!1),[I,P]=l.useState(!1),[M,E]=l.useState(!1),[D,W]=l.useState(!1),[R,B]=l.useState(!1),[_,H]=l.useState({width:0,height:0}),[L,F]=l.useState({width:0,height:0}),[$,K]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[z,ne]=l.useState(null),ie=l.useRef(null),Ce=l.useRef(null),me=l.useRef(!1),O=l.useRef(!1),Y=l.useRef(i),X=l.useRef(0),Q=l.useRef(!1),ve=l.useRef(""),he=l.useRef(null),Z=l.useRef(!1),fe=l.useRef(!1),V=l.useRef(null),q=l.useRef(null),ee=l.useRef(null),pe=32*1024,le=()=>{var ge,je,Te,Fe;return((je=(ge=ie.current)==null?void 0:ge.ownerDocument)==null?void 0:je.defaultView)||((Fe=(Te=Ce.current)==null?void 0:Te.ownerDocument)==null?void 0:Fe.defaultView)||window},se=ge=>{const je=le();return{ownerWindow:je,frameId:je.requestAnimationFrame(ge)}},te=()=>{const ge=V.current;if(ge){try{ge.ownerWindow.cancelAnimationFrame(ge.frameId)}catch{}V.current=null}},ue=()=>{const ge=q.current;if(ge){try{ge.ownerWindow.clearTimeout(ge.timeoutId)}catch{}q.current=null}},ye=()=>{const ge=ee.current;if(ge){try{ge.ownerWindow.clearTimeout(ge.timeoutId)}catch{}ee.current=null}},Me=()=>{i&&V.current===null&&(V.current=se(()=>{oe()}))},re=e.tabKey,ce=e.sessionId||"",Ae=e.daemonId||((Be=e.routeId)==null?void 0:Be.split(":")[0])||e.routeId||"",be=sc(e),we=u?be?Rm:o:g,_e=u&&o||null,U=GC,Ne=qC,Ie=.05,We=()=>{const ge=L.width,je=L.height;if(!Number.isFinite(_.width)||_.width<=0||!Number.isFinite(_.height)||_.height<=0||!Number.isFinite(ge)||ge<=0||!Number.isFinite(je)||je<=0)return 1;const Te=_.width/ge,Fe=_.height/je;return Number(Math.min(Ne,Math.max(U,Math.min(Te,Fe))).toFixed(2))},Xe=We(),et=me.current&&j>Xe,J=Number.isFinite(L.width)&&L.width>0?Math.max(_.width,Math.round(L.width*j)):_.width,Le=Number.isFinite(L.height)&&L.height>0?Math.max(_.height,Math.round(L.height*j)):_.height,$e=()=>{se(()=>{const ge=Ce.current;ge&&(ge.scrollLeft=0,ge.scrollTop=ge.scrollHeight-ge.clientHeight)})},at=()=>{var ge,je;X.current=0,Q.current=!1,ve.current="",he.current=null,Z.current=!1,fe.current=!1,me.current||(O.current=!1,N(1)),V.current!==null&&te(),m(!1),k("Runtime terminal unavailable"),ye(),ue(),x(null),ne(null),T(!1),b(!1),C(!1),w(!1),(je=(ge=n.current)==null?void 0:ge.reset)==null||je.call(ge)},rt=()=>{var ge,je;X.current=0,Q.current=!1,ve.current="",he.current=null,Z.current=!1,fe.current=!1,V.current!==null&&te(),m(!0),k(""),ye(),ue(),x(null),ne(null),T(!1),b(!1),C(!1),w(!1),(je=(ge=n.current)==null?void 0:ge.reset)==null||je.call(ge)},G=()=>{fe.current&&(fe.current=!1,se(()=>{var ge,je;(je=(ge=n.current)==null?void 0:ge.scrollToTop)==null||je.call(ge)}))},oe=()=>{if(V.current=null,!i)return;const ge=ve.current;if(!ge)return;const je=ge.slice(0,pe);ve.current=ge.slice(je.length);const Te=n.current;if(!Te){ve.current=je+ve.current,Me();return}Te.write(je,()=>{if(ve.current.length>0){Me();return}G()})},de=ge=>{ge&&(ve.current+=ge,Me())},xe=(ge,je=0,Te,Fe,Ge={})=>{var Ve,ut,Kt,Et;const dt=!!Ge.force;!dt&&je>0&&X.current>=je||!dt&&je===0&&Q.current||(X.current=je,je>0&&C(!0),m(!0),k(""),typeof Te=="number"&&typeof Fe=="number"&&Te>0&&Fe>0&&((ut=(Ve=n.current)==null?void 0:Ve.resize)==null||ut.call(Ve,Te,Fe)),ve.current="",(Et=(Kt=n.current)==null?void 0:Kt.reset)==null||Et.call(Kt),ge?de(ge):G())};l.useEffect(()=>{at()},[ce]),l.useEffect(()=>{var je;if(!ce)return;const ge=((je=Ct.onRuntimeEvent)==null?void 0:je.call(Ct,ce,Te=>{if(!(!Te||Te.sessionId!==ce)){if(Te.type==="runtime_snapshot"){if(!i){he.current={text:Te.text||"",seq:Te.seq||0,cols:Te.cols,rows:Te.rows,force:!!Te.force};return}xe(Te.text||"",Te.seq||0,Te.cols,Te.rows,{force:!!Te.force});return}if(Te.type==="session_output"){Q.current=!0,typeof Te.seq=="number"&&(X.current=Math.max(X.current,Te.seq),Te.seq>0&&C(!0)),f.current||m(!0),f.current||k(""),typeof Te.data=="string"&&de(Te.data);return}if(Te.type==="session_cleared"){if(!i){Z.current=!0,ve.current="",he.current=null;return}rt();return}if(Te.type==="session_io_error"){const Fe=typeof Te.error=="string"&&Te.error?Te.error:typeof Te.reason=="string"&&Te.reason?Te.reason:"unknown error";m(!1),k(`Runtime input failed: ${Fe}`);return}}},Ae))||(()=>{});return()=>{ge()}},[Ae,ce,n,i]);const Se=async(ge={})=>{var je;if(!Ae||!ce)return{success:!1,error:"daemonId and sessionId are required"};ge.preserveStatus||k(ge.loadingMessage||"Loading runtime terminal...");try{const Te=await((je=Ct.requestRuntimeSnapshot)==null?void 0:je.call(Ct,Ae,ce,{sinceSeq:ge.sinceSeq,force:ge.force}));return Te&&Te.success===!1?(ge.preserveStatus||(m(!1),k(`Runtime terminal unavailable: ${Te.error}`)),Te):Te||{success:!0}}catch(Te){const Fe=(Te==null?void 0:Te.message)||String(Te);return ge.preserveStatus||(m(!1),k(`Runtime terminal unavailable: ${Fe}`)),{success:!1,error:Fe}}},Pe=async ge=>{var dt,Ve;const je=((dt=ie.current)==null?void 0:dt.ownerDocument)||document,Te=je.defaultView||window,Fe=(Ve=Te.navigator)==null?void 0:Ve.clipboard;if(Fe!=null&&Fe.writeText&&Te.isSecureContext)try{return await Fe.writeText(ge),!0}catch{}let Ge=null;try{return Ge=je.createElement("textarea"),Ge.value=ge,Ge.setAttribute("readonly","true"),Ge.style.position="fixed",Ge.style.left="-9999px",Ge.style.top="0",je.body.appendChild(Ge),Ge.focus(),Ge.select(),je.execCommand("copy")}catch{return!1}finally{Ge==null||Ge.remove()}},He=ge=>{ue(),ne(ge);const je=le();q.current={ownerWindow:je,timeoutId:je.setTimeout(()=>{q.current=null,ne(Te=>Te===ge?null:Te)},2200)}},Ee=ge=>{ye(),x(ge);const je=le();ee.current={ownerWindow:je,timeoutId:je.setTimeout(()=>{ee.current=null,x(Te=>Te===ge?null:Te)},2200)}},Je=async()=>{var Ge,dt,Ve,ut;const ge=((dt=(Ge=n.current)==null?void 0:Ge.getSelection)==null?void 0:dt.call(Ge))||"",je=((ut=(Ve=n.current)==null?void 0:Ve.getVisibleText)==null?void 0:ut.call(Ve))||"",Te=ge.trimEnd()||je.trimEnd();if(!Te){He("Nothing to copy");return}if(!await Pe(Te)){He("Copy failed");return}He(ge.trimEnd()?"Copied selection":"Copied visible terminal")},st=ge=>{if(!u||!i)return;((p==null?void 0:p(Ae,ce,ge))??!1)||He("Terminal input failed")},Ze=ge=>{st(KC({ctrl:I,alt:M,shift:D},ge)),P(!1),E(!1),W(!1)},Ue=async()=>{if(h)return;b(!0),x("Loading older terminal output..."),fe.current=!0;const ge=await Se({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:u});if(b(!1),(ge==null?void 0:ge.success)===!1){fe.current=!1,x(`Older terminal output unavailable: ${ge.error}`);return}w(!0),Ee("Older terminal output loaded"),se(()=>{var je;(je=n.current)==null||je.bumpResize()})};l.useEffect(()=>{var je,Te;if(!ce)return;Ae&&((je=Ct.getState)==null?void 0:je.call(Ct,Ae))==="connected"&&Se();const ge=(Te=Ct.onStateChange)==null?void 0:Te.call(Ct,(Fe,Ge)=>{Fe!==Ae||Ge!=="connected"||Se()});return()=>{ge==null||ge()}},[Ae,ce,n]),l.useEffect(()=>{t&&at()},[t,re,n]),l.useEffect(()=>{var Fe,Ge;const ge=ie.current,je=(Ge=(Fe=ge==null?void 0:ge.ownerDocument)==null?void 0:Fe.defaultView)==null?void 0:Ge.ResizeObserver;if(!ge||!je)return;const Te=new je(dt=>{const Ve=dt[0];if(!Ve)return;const{width:ut,height:Kt}=Ve.contentRect;H(Et=>{const ps=Math.round(ut),Zt=Math.round(Kt);return Et.width===ps&&Et.height===Zt?Et:{width:ps,height:Zt}})});return Te.observe(ge),()=>Te.disconnect()},[]),l.useEffect(()=>{if(me.current)return;const ge=We();!Number.isFinite(ge)||ge<=0||N(je=>O.current?ge<je-Ie?ge:je:(O.current=!0,ge))},[L.height,L.width,_.height,_.width]),l.useEffect(()=>{et&&$e()},[et,Le,J]),l.useEffect(()=>{var Te;const ge=Y.current;if(Y.current=i,!i)return;ge||w(!1),Z.current&&(Z.current=!1,rt());const je=he.current;je&&(he.current=null,xe(je.text,je.seq,je.cols,je.rows,{force:!!je.force})),Ae&&ce&&((Te=Ct.getState)==null?void 0:Te.call(Ct,Ae))==="connected"&&Se(),ve.current&&V.current===null&&Me(),se(()=>{var Fe;(Fe=n.current)==null||Fe.bumpResize()})},[Ae,i,ce]),l.useEffect(()=>()=>{V.current!==null&&te(),ue(),ye()},[]),l.useEffect(()=>{const ge=Fe=>{var dt;const Ge=Fe.detail;Ge!=null&&Ge.sessionId&&Ge.sessionId!==ce||u&&((dt=n.current)==null||dt.bumpResize())},je=le(),Te=je===window?[window]:[window,je];for(const Fe of Te)Fe.addEventListener("adhdev:fit-cli-terminal",ge);return()=>{for(const Fe of Te)Fe.removeEventListener("adhdev:fit-cli-terminal",ge)}},[u,ce,n]);const nt=u&&y&&!v&&($.atTop||!$.canScroll)||h||!!S;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:ie,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[nt&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Ue()},disabled:!ce||h,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:d(h?"terminal.loadingOlder":"terminal.loadOlderOutput")}),S&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:S})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[z&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:z}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>B(ge=>!ge),title:"Spec debug — inspect current state, sections, and transition history",children:d("terminal.debug")}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Je()},disabled:!u,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:d("terminal.copy")}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>T(ge=>!ge),disabled:!u,"aria-label":d(A?"terminal.closeControlKeys":"terminal.openControlKeys"),"aria-expanded":A,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),A&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":d("terminal.openControlKeys"),className:"absolute right-0 top-10 w-72 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>T(!1),"aria-label":d("terminal.closeControlKeys"),children:"×"})]}),s.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",I,P],["Alt",M,E],["Shift",D,W]].map(([ge,je,Te])=>s.jsx("button",{type:"button","aria-pressed":je,className:`h-9 rounded-lg border text-[12px] font-semibold transition-colors ${je?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>Te(Fe=>!Fe),children:ge},ge))}),s.jsx("div",{className:"my-2 h-px bg-white/10"}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("Escape"),children:"Esc"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("Tab"),children:"Tab"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("Enter"),children:"Enter"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("ArrowUp"),"aria-label":"Arrow up",children:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("ArrowLeft"),"aria-label":"Arrow left",children:"←"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("ArrowDown"),"aria-label":"Arrow down",children:"↓"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("ArrowRight"),"aria-label":"Arrow right",children:"→"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>st(""),title:"Send SIGINT (Ctrl-C)",children:"Ctrl-C"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("Space"),children:"Space"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("Backspace"),children:"Bksp"})]})]})]}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{me.current=!0,N(ge=>{const je=Math.max(Xe,Number((ge-.1).toFixed(2)));return je>Xe&&$e(),je})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{me.current=!0,N(ge=>{const je=Math.min(Ne,Number((ge+.1).toFixed(2)));return je>Xe&&$e(),je})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:Ce,className:et?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:J>0?`${J}px`:"100%",height:Le>0?`${Le}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:L.width>0?`${L.width}px`:"100%",height:L.height>0?`${L.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:j},children:s.jsx(Yp,{ref:n,readOnly:!u||!i,sizingMode:"measured",onViewportMetrics:F,onScrollMetrics:K,onInput:ge=>{!u||(p==null||p(Ae,ce,ge))}})})})}),!u&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:g})]}),s.jsx(vm,{contextKey:e.tabKey,panelLabel:kt(e),isSending:r,isBusy:!!be,statusMessage:we,inlineStatusMessage:_e,onSend:async ge=>be?!1:a(ge),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),R&&s.jsx(pj,{activeConv:e,onClose:()=>B(!1)})]})}const hj={accent:{track:"--accent-primary",head:"--accent-primary-light"},success:{track:"--status-online",head:"--status-online"},muted:{track:"--text-muted",head:"--text-muted"}};function ls({size:e=28,thickness:t=2.5,color:n="accent",className:a,label:r}){const o=hj[n],i={width:e,height:e,border:`${t}px solid color-mix(in srgb, var(${o.track}) 20%, transparent)`,borderTopColor:`var(${o.head})`};return s.jsx("span",{className:Pt("block shrink-0 rounded-full animate-spin",a),style:i,role:r?"status":void 0,"aria-label":r,"aria-hidden":r?void 0:!0})}const fj=5e3,gj=12e3,bj=15e3;function xj(e){return e==="disconnected"||e==="reconnecting"}function vj({wsStatus:e,showReconnected:t,loginUrl:n,onReconnect:a,reconnectDelayMs:r=fj,reconnectActionDelayMs:o=gj}){const{t:i}=ke(),c=xj(e),[d,p]=l.useState(()=>!c||r<=0),[u,m]=l.useState(()=>!c||o<=0),f=l.useRef(!1),[g,k]=l.useState(!1);l.useEffect(()=>{if(!c){p(!1);return}if(f.current=!1,r<=0){f.current=!0,p(!0);return}p(!1);const A=setTimeout(()=>{f.current=!0,p(!0)},r);return()=>clearTimeout(A)},[r,c]),l.useEffect(()=>{if(!c){m(!1);return}if(o<=0){m(!0);return}m(!1);const A=setTimeout(()=>{m(!0)},o);return()=>clearTimeout(A)},[o,c]),l.useEffect(()=>{e!=="reconnecting"&&k(!1)},[e]),l.useEffect(()=>{if(!g)return;const A=setTimeout(()=>k(!1),bj);return()=>clearTimeout(A)},[g]);const h=()=>{k(!0),a==null||a()},b=c?d:e==="offline"||e==="auth_failed",S=!!(a&&e!=="auth_failed"&&(!c||u)),x=l.useMemo(()=>!t||e!=="connected"?!1:r<=0||f.current,[r,t,e]),y=e==="auth_failed"?"red":e==="offline"?"orange":"accent",C={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},v={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},w={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},j="fixed left-1/2 top-[calc(env(safe-area-inset-top,0px)+64px)] sm:top-[calc(env(safe-area-inset-top,0px)+16px)] z-[var(--z-toast)] flex items-center justify-center pointer-events-none",N={transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[b&&s.jsx("div",{className:j,style:N,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:C[y],border:v[y],color:w[y]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&i("connection.networkOffline"),e==="disconnected"&&i("connection.reconnecting"),e==="reconnecting"&&i("connection.reconnecting"),e==="auth_failed"&&(n?s.jsxs(s.Fragment,{children:[i("connection.sessionExpired")," ",s.jsx("a",{href:n,className:"text-inherit underline",children:i("connection.logInAgain")})]}):i("connection.connectionFailed"))]}),S&&s.jsxs("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed inline-flex items-center gap-1.5",onClick:h,disabled:e==="offline"||g,children:[g&&s.jsx(ls,{size:11,thickness:2,color:"muted"}),i(g?"connection.reconnecting":"connection.reconnectNow")]})]})}),x&&s.jsx("div",{className:j,style:N,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),i("connection.connected")]})})]})}function oh({mode:e,onChange:t,compact:n=!1}){const{t:a}=ke("common"),r=n?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:a(e==="chat"?"cliView.switchToTerminal":"cliView.switchToChat"),children:e==="chat"?s.jsx(Bl,{size:r}):s.jsx(Is,{size:r})})}function yj(e){if(!e||e.isGitRepo===!1||e.reason==="not_git_repo")return null;if(e.hasConflicts)return`${e.branch||"Git"} · conflicts${e.changedFiles>0?` ${e.changedFiles}`:""}`;const t=[e.branch||"Git"];return e.changedFiles>0&&t.push(`±${e.changedFiles}`),e.ahead>0&&t.push(`↑${e.ahead}`),e.behind>0&&t.push(`↓${e.behind}`),t.length===1&&e.dirty&&t.push("dirty"),t.join(" ")}function wj(e){return!e||e.isGitRepo===!1||e.reason==="not_git_repo"?null:e.hasConflicts?"conflict":e.error?"error":e.dirty||e.changedFiles>0||e.ahead>0||e.behind>0?"dirty":"quiet"}function kj(e){switch(e){case"conflict":return"border-status-error/40 bg-status-error/10 text-status-error";case"error":return"border-yellow-500/25 bg-yellow-500/[0.08] text-yellow-500";case"dirty":return"border-orange-500/25 bg-orange-500/[0.08] text-orange-400";case"quiet":default:return"border-status-online/40 bg-status-online/10 text-status-online"}}function qr({git:e,className:t="",compact:n=!1}){const a=yj(e),r=wj(e);if(!a||!r)return null;const o=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return s.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${kj(r)} ${t}`.trim(),title:o.join(" · ")||a,"data-git-tone":r,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:a})]})}function Sj({wsStatus:e,isConnected:t,daemonCount:n,p2pStates:a={},usesP2P:r=!0}){if(e!=="connected")return{tone:"disconnected",titleKey:"connection.disconnected",subtitleKey:null};if(n>0&&!r)return t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null};const i=Object.values(a).filter(c=>c==="connected").length;return n>0?i>=n?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:"connection.machinesConnectedCount",subtitleParams:{connected:i,total:n}}:t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null}}function Fd({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Bd({notification:e,shortcutIndex:t,onOpen:n,onMarkRead:a,onMarkUnread:r,onDelete:o}){const{t:i}=ke(),c=za(e.updatedAt),d=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${d?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:n,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?i("notification.actionNeeded"):i("notification.taskComplete"),c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[d?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),a()},children:i("notification.markRead")}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),r()},children:i("notification.markUnread")}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),o()},children:i("notification.delete")})]})]})}function Cj({activeConv:e,wsStatus:t,isConnected:n,conversations:a,onOpenHistory:r,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:p,hiddenConversations:u=[],onShowConversation:m,onShowAllHidden:f,onResetPanelsToMain:g,inboxOpen:k,onInboxOpenChange:h,hiddenOpen:b,onHiddenOpenChange:S,onOpenNewSession:x,onOpenDashboardGuide:y,guideNudgeVisible:C=!1,actionShortcuts:v,notifications:w,notificationUnreadCount:j,onOpenNotification:N,onMarkNotificationRead:A,onMarkNotificationUnread:T,onDeleteNotification:I,onOpenGitDialog:P,onOpenMeshGraph:M}){var pe;const{t:E}=ke(),{ides:D,p2pStates:W={},usesP2P:R=!0}=Ss(),B=!!e&&bt(e)&&!ht(e),_=!!e&&ht(e),H=!!(e!=null&&e.daemonId)&&!!((pe=e==null?void 0:e.coordinator)!=null&&pe.meshId),L=c||(e?Tm(e)?"terminal":"chat":null),[F,$]=l.useState(!1),[K,z]=l.useState(!1),ne=l.useRef(null),ie=l.useRef(null),Ce=l.useRef(null),me=D.filter(le=>le.type==="adhdev-daemon"),O=Sj({wsStatus:t,isConnected:n,daemonCount:me.length,p2pStates:W,usesP2P:R}),Y=E(O.titleKey),X=O.subtitleKey?E(O.subtitleKey,O.subtitleParams):null,Q=O.tone==="connected"?"#22c55e":O.tone==="limited"?"#eab308":"#ef4444",ve=O.tone==="connected"?"0 0 4px #22c55e80":O.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",he=l.useMemo(()=>w.filter(le=>!le.readAt),[w]),Z=l.useMemo(()=>w.filter(le=>!!le.readAt),[w]),fe=l.useMemo(()=>he.slice(0,9),[he]),V=j;l.useEffect(()=>{if(!k)return;const le=se=>{var te;(te=ie.current)!=null&&te.contains(se.target)||h(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[k,h]),l.useEffect(()=>{if(!b)return;const le=se=>{var te;(te=Ce.current)!=null&&te.contains(se.target)||S(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[b,S]),l.useEffect(()=>{if(!b&&!k)return;const le=se=>{if(!se.altKey)return;const te=se.code.match(/^Digit([1-9])$/);if(!te)return;const ue=Number(te[1])-1,ye=b?u[ue]:void 0,Me=k?fe[ue]:void 0;if(!(!ye&&!Me)){if(se.preventDefault(),se.stopPropagation(),ye){m==null||m(ye),S(!1);return}Me&&(N(Me),h(!1))}};return window.addEventListener("keydown",le,!0),()=>window.removeEventListener("keydown",le,!0)},[u,b,k,fe,S,h,N,m]),l.useEffect(()=>{const le=u.length;if(ne.current===null){ne.current=le;return}le>ne.current&&z(!0),ne.current=le},[u.length]);const q=()=>z(!1),ee=le=>{if(!le)return;const se=a.find(te=>te.tabKey===le);se&&(p==null||p(se))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(Is,{size:18}),s.jsx("span",{className:"header-title-desktop",children:E("dashboard.header.title")}),s.jsx("span",{className:"header-title-mobile",children:e?kt(e):E("dashboard.header.title")}),s.jsx("span",{title:Y,"aria-label":Y,className:"header-title-status-dot",style:{background:Q,boxShadow:ve}}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:Q,boxShadow:ve}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[X&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",X]}),x&&s.jsx("button",{type:"button",onClick:x,className:"btn btn-secondary btn-sm ml-2",title:`${E("paneGroup.newSession")}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":E("paneGroup.newSession"),children:s.jsx(Wl,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[y&&s.jsxs("button",{type:"button",onClick:y,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:E("dashboard.header.guide"),"aria-label":E("dashboard.header.guideOpen"),children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),C&&s.jsx("span",{children:E("dashboard.header.guideShort")})]}),e&&(B||_||!ht(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:na(e)||kt(e),children:kt(e)}),P&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:E("dashboard.header.openGitStatus"),onClick:()=>P(e.daemonId,e.workspacePath),children:s.jsx(qr,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(qr,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),H&&M&&s.jsxs("button",{type:"button",onClick:()=>M(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:E("dashboard.header.openMeshGraph"),children:[s.jsx(cs,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:E("dashboard.header.meshGraph")})]}),(B||_)&&i&&s.jsxs(s.Fragment,{children:[B&&d&&L&&s.jsx(oh,{mode:L,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:E(_?"dashboard.header.stopAcpSession":"dashboard.header.stopCliProcess"),style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Dt,{size:14})})]}),!ht(e)&&s.jsx("button",{onClick:()=>r(e),className:"btn btn-secondary btn-sm",title:E("dashboard.header.chatHistory"),children:s.jsx($l,{size:14})}),!B&&!ht(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:E("dashboard.header.remoteControl"),children:s.jsx(us,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:ie,children:[s.jsxs("div",{className:`dashboard-header-hidden${F?" is-drop-target":""}${K?" hidden-spawn-flash":""}${(u??[]).some(Ha)?" hidden-generating-spin":""}`,onAnimationEnd:q,ref:Ce,onDragEnter:le=>{le.dataTransfer.types.includes("text/tab-key")&&(le.preventDefault(),$(!0))},onDragOver:le=>{le.dataTransfer.types.includes("text/tab-key")&&(le.preventDefault(),le.dataTransfer.dropEffect="move",$(!0))},onDragLeave:le=>{le.currentTarget.contains(le.relatedTarget)||$(!1)},onDrop:le=>{const se=le.dataTransfer.getData("text/tab-key");le.preventDefault(),$(!1),ee(se)},children:[s.jsxs("button",{type:"button",onClick:()=>S(!b),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${E("dashboard.hidden.title")}${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. ${E("dashboard.hidden.dragHint")}`,children:[s.jsx(mo,{size:16}),u.length>0&&s.jsx("span",{className:`dashboard-header-hidden-badge${K?" hidden-badge-pop":""}`,children:u.length})]}),b&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:E("dashboard.hidden.title")}),s.jsx(Fd,{value:v==null?void 0:v.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[g&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:g,children:E("dashboard.hidden.resetPanels")}),u.length>0&&f&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),S(!1)},children:E("dashboard.hidden.restoreAll")})]})]}),e&&p&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>p(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:E("dashboard.hidden.hideCurrentTab")}),s.jsx(Fd,{value:v==null?void 0:v.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:kt(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(le=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(le),S(!1)},children:[s.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[Ha(le)&&s.jsx(ls,{size:12,thickness:2,color:"success",label:E("dashboard.header.generating")}),kt(le)]}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(le)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(le)+1]}):null,na(le)]})]},le.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:E("dashboard.hidden.empty")})]})]}),s.jsxs("button",{type:"button",onClick:()=>h(!k),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:E("dashboard.header.activityInbox"),children:[s.jsx(la,{size:16}),V>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:V})]}),k&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[he.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:E("dashboard.inbox.unread")}),he.map(le=>s.jsx(Bd,{notification:le,shortcutIndex:fe.indexOf(le)>=0?fe.indexOf(le)+1:void 0,onOpen:()=>N(le),onMarkRead:()=>A(le.id),onMarkUnread:()=>T(le.id),onDelete:()=>I(le.id)},le.id))]}),Z.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:E("dashboard.inbox.read")}),Z.map(le=>s.jsx(Bd,{notification:le,onOpen:()=>N(le),onMarkRead:()=>A(le.id),onMarkUnread:()=>T(le.id),onDelete:()=>I(le.id)},le.id))]}),w.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:E("dashboard.inbox.empty")})]})]})]})]})}function qt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function jj(e,t){return String(e||"")!==String(t||"")}function Nj(e,t={}){const n=String(t.textQuery||"").trim().toLowerCase(),a=String(t.workspaceQuery||"").trim().toLowerCase(),r=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.resumableOnly;return!n&&!a&&!r&&!o?e:e.filter(i=>!(o&&!i.canResume||n&&![i.title,i.preview].map(d=>String(d||"").toLowerCase()).join(`
51
+ `).length:0," lines)"]})]}),p&&s.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-[11px] text-text-secondary whitespace-pre bg-bg-secondary rounded-md border border-border-default max-h-64 overflow-auto",children:O.screen||"(empty)"})]})]})]})]})})})}function mj({activeConv:e,clearToken:t=0,terminalRef:n,handleSendChat:a,isSendingChat:r=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var Be;const{t:d}=ke("common");Ss();const{sendPtyInput:p}=St(),[u,m]=l.useState(!1),f=l.useRef(!1);f.current=u;const[g,k]=l.useState("Runtime terminal unavailable"),[h,b]=l.useState(!1),[S,x]=l.useState(null),[y,C]=l.useState(!1),[v,w]=l.useState(!1),[j,N]=l.useState(1),[A,T]=l.useState(!1),[I,P]=l.useState(!1),[M,E]=l.useState(!1),[D,W]=l.useState(!1),[R,B]=l.useState(!1),[_,H]=l.useState({width:0,height:0}),[L,F]=l.useState({width:0,height:0}),[$,K]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[z,ne]=l.useState(null),ie=l.useRef(null),Ce=l.useRef(null),me=l.useRef(!1),O=l.useRef(!1),Y=l.useRef(i),X=l.useRef(0),Q=l.useRef(!1),ve=l.useRef(""),he=l.useRef(null),Z=l.useRef(!1),fe=l.useRef(!1),V=l.useRef(null),q=l.useRef(null),ee=l.useRef(null),pe=32*1024,le=()=>{var ge,je,Te,Fe;return((je=(ge=ie.current)==null?void 0:ge.ownerDocument)==null?void 0:je.defaultView)||((Fe=(Te=Ce.current)==null?void 0:Te.ownerDocument)==null?void 0:Fe.defaultView)||window},se=ge=>{const je=le();return{ownerWindow:je,frameId:je.requestAnimationFrame(ge)}},te=()=>{const ge=V.current;if(ge){try{ge.ownerWindow.cancelAnimationFrame(ge.frameId)}catch{}V.current=null}},ue=()=>{const ge=q.current;if(ge){try{ge.ownerWindow.clearTimeout(ge.timeoutId)}catch{}q.current=null}},ye=()=>{const ge=ee.current;if(ge){try{ge.ownerWindow.clearTimeout(ge.timeoutId)}catch{}ee.current=null}},Me=()=>{i&&V.current===null&&(V.current=se(()=>{oe()}))},re=e.tabKey,ce=e.sessionId||"",Ae=e.daemonId||((Be=e.routeId)==null?void 0:Be.split(":")[0])||e.routeId||"",be=sc(e),we=u?be?Rm:o:g,_e=u&&o||null,U=GC,Ne=qC,Ie=.05,We=()=>{const ge=L.width,je=L.height;if(!Number.isFinite(_.width)||_.width<=0||!Number.isFinite(_.height)||_.height<=0||!Number.isFinite(ge)||ge<=0||!Number.isFinite(je)||je<=0)return 1;const Te=_.width/ge,Fe=_.height/je;return Number(Math.min(Ne,Math.max(U,Math.min(Te,Fe))).toFixed(2))},Xe=We(),et=me.current&&j>Xe,J=Number.isFinite(L.width)&&L.width>0?Math.max(_.width,Math.round(L.width*j)):_.width,Le=Number.isFinite(L.height)&&L.height>0?Math.max(_.height,Math.round(L.height*j)):_.height,$e=()=>{se(()=>{const ge=Ce.current;ge&&(ge.scrollLeft=0,ge.scrollTop=ge.scrollHeight-ge.clientHeight)})},at=()=>{var ge,je;X.current=0,Q.current=!1,ve.current="",he.current=null,Z.current=!1,fe.current=!1,me.current||(O.current=!1,N(1)),V.current!==null&&te(),m(!1),k("Runtime terminal unavailable"),ye(),ue(),x(null),ne(null),T(!1),b(!1),C(!1),w(!1),(je=(ge=n.current)==null?void 0:ge.reset)==null||je.call(ge)},rt=()=>{var ge,je;X.current=0,Q.current=!1,ve.current="",he.current=null,Z.current=!1,fe.current=!1,V.current!==null&&te(),m(!0),k(""),ye(),ue(),x(null),ne(null),T(!1),b(!1),C(!1),w(!1),(je=(ge=n.current)==null?void 0:ge.reset)==null||je.call(ge)},G=()=>{fe.current&&(fe.current=!1,se(()=>{var ge,je;(je=(ge=n.current)==null?void 0:ge.scrollToTop)==null||je.call(ge)}))},oe=()=>{if(V.current=null,!i)return;const ge=ve.current;if(!ge)return;const je=ge.slice(0,pe);ve.current=ge.slice(je.length);const Te=n.current;if(!Te){ve.current=je+ve.current,Me();return}Te.write(je,()=>{if(ve.current.length>0){Me();return}G()})},de=ge=>{ge&&(ve.current+=ge,Me())},xe=(ge,je=0,Te,Fe,Ge={})=>{var Ve,ut,Kt,Et;const dt=!!Ge.force;!dt&&je>0&&X.current>=je||!dt&&je===0&&Q.current||(X.current=je,je>0&&C(!0),m(!0),k(""),typeof Te=="number"&&typeof Fe=="number"&&Te>0&&Fe>0&&((ut=(Ve=n.current)==null?void 0:Ve.resize)==null||ut.call(Ve,Te,Fe)),ve.current="",(Et=(Kt=n.current)==null?void 0:Kt.reset)==null||Et.call(Kt),ge?de(ge):G())};l.useEffect(()=>{at()},[ce]),l.useEffect(()=>{var je;if(!ce)return;const ge=((je=Ct.onRuntimeEvent)==null?void 0:je.call(Ct,ce,Te=>{if(!(!Te||Te.sessionId!==ce)){if(Te.type==="runtime_snapshot"){if(!i){he.current={text:Te.text||"",seq:Te.seq||0,cols:Te.cols,rows:Te.rows,force:!!Te.force};return}xe(Te.text||"",Te.seq||0,Te.cols,Te.rows,{force:!!Te.force});return}if(Te.type==="session_output"){Q.current=!0,typeof Te.seq=="number"&&(X.current=Math.max(X.current,Te.seq),Te.seq>0&&C(!0)),f.current||m(!0),f.current||k(""),typeof Te.data=="string"&&de(Te.data);return}if(Te.type==="session_cleared"){if(!i){Z.current=!0,ve.current="",he.current=null;return}rt();return}if(Te.type==="session_io_error"){const Fe=typeof Te.error=="string"&&Te.error?Te.error:typeof Te.reason=="string"&&Te.reason?Te.reason:"unknown error";m(!1),k(`Runtime input failed: ${Fe}`);return}}},Ae))||(()=>{});return()=>{ge()}},[Ae,ce,n,i]);const Se=async(ge={})=>{var je;if(!Ae||!ce)return{success:!1,error:"daemonId and sessionId are required"};ge.preserveStatus||k(ge.loadingMessage||"Loading runtime terminal...");try{const Te=await((je=Ct.requestRuntimeSnapshot)==null?void 0:je.call(Ct,Ae,ce,{sinceSeq:ge.sinceSeq,force:ge.force}));return Te&&Te.success===!1?(ge.preserveStatus||(m(!1),k(`Runtime terminal unavailable: ${Te.error}`)),Te):Te||{success:!0}}catch(Te){const Fe=(Te==null?void 0:Te.message)||String(Te);return ge.preserveStatus||(m(!1),k(`Runtime terminal unavailable: ${Fe}`)),{success:!1,error:Fe}}},Pe=async ge=>{var dt,Ve;const je=((dt=ie.current)==null?void 0:dt.ownerDocument)||document,Te=je.defaultView||window,Fe=(Ve=Te.navigator)==null?void 0:Ve.clipboard;if(Fe!=null&&Fe.writeText&&Te.isSecureContext)try{return await Fe.writeText(ge),!0}catch{}let Ge=null;try{return Ge=je.createElement("textarea"),Ge.value=ge,Ge.setAttribute("readonly","true"),Ge.style.position="fixed",Ge.style.left="-9999px",Ge.style.top="0",je.body.appendChild(Ge),Ge.focus(),Ge.select(),je.execCommand("copy")}catch{return!1}finally{Ge==null||Ge.remove()}},He=ge=>{ue(),ne(ge);const je=le();q.current={ownerWindow:je,timeoutId:je.setTimeout(()=>{q.current=null,ne(Te=>Te===ge?null:Te)},2200)}},Ee=ge=>{ye(),x(ge);const je=le();ee.current={ownerWindow:je,timeoutId:je.setTimeout(()=>{ee.current=null,x(Te=>Te===ge?null:Te)},2200)}},Je=async()=>{var Ge,dt,Ve,ut;const ge=((dt=(Ge=n.current)==null?void 0:Ge.getSelection)==null?void 0:dt.call(Ge))||"",je=((ut=(Ve=n.current)==null?void 0:Ve.getVisibleText)==null?void 0:ut.call(Ve))||"",Te=ge.trimEnd()||je.trimEnd();if(!Te){He("Nothing to copy");return}if(!await Pe(Te)){He("Copy failed");return}He(ge.trimEnd()?"Copied selection":"Copied visible terminal")},st=ge=>{if(!u||!i)return;((p==null?void 0:p(Ae,ce,ge))??!1)||He("Terminal input failed")},Ze=ge=>{st(KC({ctrl:I,alt:M,shift:D},ge)),P(!1),E(!1),W(!1)},Ue=async()=>{if(h)return;b(!0),x("Loading older terminal output..."),fe.current=!0;const ge=await Se({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:u});if(b(!1),(ge==null?void 0:ge.success)===!1){fe.current=!1,x(`Older terminal output unavailable: ${ge.error}`);return}w(!0),Ee("Older terminal output loaded"),se(()=>{var je;(je=n.current)==null||je.bumpResize()})};l.useEffect(()=>{var je,Te;if(!ce)return;Ae&&((je=Ct.getState)==null?void 0:je.call(Ct,Ae))==="connected"&&Se();const ge=(Te=Ct.onStateChange)==null?void 0:Te.call(Ct,(Fe,Ge)=>{Fe!==Ae||Ge!=="connected"||Se()});return()=>{ge==null||ge()}},[Ae,ce,n]),l.useEffect(()=>{t&&at()},[t,re,n]),l.useEffect(()=>{var Fe,Ge;const ge=ie.current,je=(Ge=(Fe=ge==null?void 0:ge.ownerDocument)==null?void 0:Fe.defaultView)==null?void 0:Ge.ResizeObserver;if(!ge||!je)return;const Te=new je(dt=>{const Ve=dt[0];if(!Ve)return;const{width:ut,height:Kt}=Ve.contentRect;H(Et=>{const ps=Math.round(ut),Zt=Math.round(Kt);return Et.width===ps&&Et.height===Zt?Et:{width:ps,height:Zt}})});return Te.observe(ge),()=>Te.disconnect()},[]),l.useEffect(()=>{if(me.current)return;const ge=We();!Number.isFinite(ge)||ge<=0||N(je=>O.current?ge<je-Ie?ge:je:(O.current=!0,ge))},[L.height,L.width,_.height,_.width]),l.useEffect(()=>{et&&$e()},[et,Le,J]),l.useEffect(()=>{var Te;const ge=Y.current;if(Y.current=i,!i)return;ge||w(!1),Z.current&&(Z.current=!1,rt());const je=he.current;je&&(he.current=null,xe(je.text,je.seq,je.cols,je.rows,{force:!!je.force})),Ae&&ce&&((Te=Ct.getState)==null?void 0:Te.call(Ct,Ae))==="connected"&&Se(),ve.current&&V.current===null&&Me(),se(()=>{var Fe;(Fe=n.current)==null||Fe.bumpResize()})},[Ae,i,ce]),l.useEffect(()=>()=>{V.current!==null&&te(),ue(),ye()},[]),l.useEffect(()=>{const ge=Fe=>{var dt;const Ge=Fe.detail;Ge!=null&&Ge.sessionId&&Ge.sessionId!==ce||u&&((dt=n.current)==null||dt.bumpResize())},je=le(),Te=je===window?[window]:[window,je];for(const Fe of Te)Fe.addEventListener("adhdev:fit-cli-terminal",ge);return()=>{for(const Fe of Te)Fe.removeEventListener("adhdev:fit-cli-terminal",ge)}},[u,ce,n]);const nt=u&&y&&!v&&($.atTop||!$.canScroll)||h||!!S;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:ie,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[nt&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Ue()},disabled:!ce||h,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:d(h?"terminal.loadingOlder":"terminal.loadOlderOutput")}),S&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:S})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[z&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:z}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>B(ge=>!ge),title:"Spec debug — inspect current state, sections, and transition history",children:d("terminal.debug")}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Je()},disabled:!u,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:d("terminal.copy")}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>T(ge=>!ge),disabled:!u,"aria-label":d(A?"terminal.closeControlKeys":"terminal.openControlKeys"),"aria-expanded":A,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),A&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":d("terminal.openControlKeys"),className:"absolute right-0 top-10 w-72 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>T(!1),"aria-label":d("terminal.closeControlKeys"),children:"×"})]}),s.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",I,P],["Alt",M,E],["Shift",D,W]].map(([ge,je,Te])=>s.jsx("button",{type:"button","aria-pressed":je,className:`h-9 rounded-lg border text-xs font-semibold transition-colors ${je?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>Te(Fe=>!Fe),children:ge},ge))}),s.jsx("div",{className:"my-2 h-px bg-white/10"}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-xs font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("Escape"),children:"Esc"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-xs font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("Tab"),children:"Tab"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-xs font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("Enter"),children:"Enter"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("ArrowUp"),"aria-label":"Arrow up",children:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("ArrowLeft"),"aria-label":"Arrow left",children:"←"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("ArrowDown"),"aria-label":"Arrow down",children:"↓"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("ArrowRight"),"aria-label":"Arrow right",children:"→"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-xs font-semibold hover:bg-white/[0.12]",onClick:()=>st(""),title:"Send SIGINT (Ctrl-C)",children:"Ctrl-C"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-xs font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("Space"),children:"Space"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-xs font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("Backspace"),children:"Bksp"})]})]})]}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{me.current=!0,N(ge=>{const je=Math.max(Xe,Number((ge-.1).toFixed(2)));return je>Xe&&$e(),je})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{me.current=!0,N(ge=>{const je=Math.min(Ne,Number((ge+.1).toFixed(2)));return je>Xe&&$e(),je})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:Ce,className:et?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:J>0?`${J}px`:"100%",height:Le>0?`${Le}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:L.width>0?`${L.width}px`:"100%",height:L.height>0?`${L.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:j},children:s.jsx(Yp,{ref:n,readOnly:!u||!i,sizingMode:"measured",onViewportMetrics:F,onScrollMetrics:K,onInput:ge=>{!u||(p==null||p(Ae,ce,ge))}})})})}),!u&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:g})]}),s.jsx(vm,{contextKey:e.tabKey,panelLabel:kt(e),isSending:r,isBusy:!!be,statusMessage:we,inlineStatusMessage:_e,onSend:async ge=>be?!1:a(ge),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),R&&s.jsx(pj,{activeConv:e,onClose:()=>B(!1)})]})}const hj={accent:{track:"--accent-primary",head:"--accent-primary-light"},success:{track:"--status-online",head:"--status-online"},muted:{track:"--text-muted",head:"--text-muted"}};function ls({size:e=28,thickness:t=2.5,color:n="accent",className:a,label:r}){const o=hj[n],i={width:e,height:e,border:`${t}px solid color-mix(in srgb, var(${o.track}) 20%, transparent)`,borderTopColor:`var(${o.head})`};return s.jsx("span",{className:Pt("block shrink-0 rounded-full animate-spin",a),style:i,role:r?"status":void 0,"aria-label":r,"aria-hidden":r?void 0:!0})}const fj=5e3,gj=12e3,bj=15e3;function xj(e){return e==="disconnected"||e==="reconnecting"}function vj({wsStatus:e,showReconnected:t,loginUrl:n,onReconnect:a,reconnectDelayMs:r=fj,reconnectActionDelayMs:o=gj}){const{t:i}=ke(),c=xj(e),[d,p]=l.useState(()=>!c||r<=0),[u,m]=l.useState(()=>!c||o<=0),f=l.useRef(!1),[g,k]=l.useState(!1);l.useEffect(()=>{if(!c){p(!1);return}if(f.current=!1,r<=0){f.current=!0,p(!0);return}p(!1);const A=setTimeout(()=>{f.current=!0,p(!0)},r);return()=>clearTimeout(A)},[r,c]),l.useEffect(()=>{if(!c){m(!1);return}if(o<=0){m(!0);return}m(!1);const A=setTimeout(()=>{m(!0)},o);return()=>clearTimeout(A)},[o,c]),l.useEffect(()=>{e!=="reconnecting"&&k(!1)},[e]),l.useEffect(()=>{if(!g)return;const A=setTimeout(()=>k(!1),bj);return()=>clearTimeout(A)},[g]);const h=()=>{k(!0),a==null||a()},b=c?d:e==="offline"||e==="auth_failed",S=!!(a&&e!=="auth_failed"&&(!c||u)),x=l.useMemo(()=>!t||e!=="connected"?!1:r<=0||f.current,[r,t,e]),y=e==="auth_failed"?"red":e==="offline"?"orange":"accent",C={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},v={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},w={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},j="fixed left-1/2 top-[calc(env(safe-area-inset-top,0px)+64px)] sm:top-[calc(env(safe-area-inset-top,0px)+16px)] z-[var(--z-toast)] flex items-center justify-center pointer-events-none",N={transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[b&&s.jsx("div",{className:j,style:N,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:C[y],border:v[y],color:w[y]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&i("connection.networkOffline"),e==="disconnected"&&i("connection.reconnecting"),e==="reconnecting"&&i("connection.reconnecting"),e==="auth_failed"&&(n?s.jsxs(s.Fragment,{children:[i("connection.sessionExpired")," ",s.jsx("a",{href:n,className:"text-inherit underline",children:i("connection.logInAgain")})]}):i("connection.connectionFailed"))]}),S&&s.jsxs("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed inline-flex items-center gap-1.5",onClick:h,disabled:e==="offline"||g,children:[g&&s.jsx(ls,{size:11,thickness:2,color:"muted"}),i(g?"connection.reconnecting":"connection.reconnectNow")]})]})}),x&&s.jsx("div",{className:j,style:N,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),i("connection.connected")]})})]})}function oh({mode:e,onChange:t,compact:n=!1}){const{t:a}=ke("common"),r=n?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:a(e==="chat"?"cliView.switchToTerminal":"cliView.switchToChat"),children:e==="chat"?s.jsx(Bl,{size:r}):s.jsx(Is,{size:r})})}function yj(e){if(!e||e.isGitRepo===!1||e.reason==="not_git_repo")return null;if(e.hasConflicts)return`${e.branch||"Git"} · conflicts${e.changedFiles>0?` ${e.changedFiles}`:""}`;const t=[e.branch||"Git"];return e.changedFiles>0&&t.push(`±${e.changedFiles}`),e.ahead>0&&t.push(`↑${e.ahead}`),e.behind>0&&t.push(`↓${e.behind}`),t.length===1&&e.dirty&&t.push("dirty"),t.join(" ")}function wj(e){return!e||e.isGitRepo===!1||e.reason==="not_git_repo"?null:e.hasConflicts?"conflict":e.error?"error":e.dirty||e.changedFiles>0||e.ahead>0||e.behind>0?"dirty":"quiet"}function kj(e){switch(e){case"conflict":return"border-status-error/40 bg-status-error/10 text-status-error";case"error":return"border-yellow-500/25 bg-yellow-500/[0.08] text-yellow-500";case"dirty":return"border-orange-500/25 bg-orange-500/[0.08] text-orange-400";case"quiet":default:return"border-status-online/40 bg-status-online/10 text-status-online"}}function qr({git:e,className:t="",compact:n=!1}){const a=yj(e),r=wj(e);if(!a||!r)return null;const o=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return s.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${kj(r)} ${t}`.trim(),title:o.join(" · ")||a,"data-git-tone":r,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:a})]})}function Sj({wsStatus:e,isConnected:t,daemonCount:n,p2pStates:a={},usesP2P:r=!0}){if(e!=="connected")return{tone:"disconnected",titleKey:"connection.disconnected",subtitleKey:null};if(n>0&&!r)return t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null};const i=Object.values(a).filter(c=>c==="connected").length;return n>0?i>=n?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:"connection.machinesConnectedCount",subtitleParams:{connected:i,total:n}}:t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null}}function Fd({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Bd({notification:e,shortcutIndex:t,onOpen:n,onMarkRead:a,onMarkUnread:r,onDelete:o}){const{t:i}=ke(),c=za(e.updatedAt),d=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${d?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:n,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?i("notification.actionNeeded"):i("notification.taskComplete"),c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[d?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),a()},children:i("notification.markRead")}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),r()},children:i("notification.markUnread")}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),o()},children:i("notification.delete")})]})]})}function Cj({activeConv:e,wsStatus:t,isConnected:n,conversations:a,onOpenHistory:r,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:p,hiddenConversations:u=[],onShowConversation:m,onShowAllHidden:f,onResetPanelsToMain:g,inboxOpen:k,onInboxOpenChange:h,hiddenOpen:b,onHiddenOpenChange:S,onOpenNewSession:x,onOpenDashboardGuide:y,guideNudgeVisible:C=!1,actionShortcuts:v,notifications:w,notificationUnreadCount:j,onOpenNotification:N,onMarkNotificationRead:A,onMarkNotificationUnread:T,onDeleteNotification:I,onOpenGitDialog:P,onOpenMeshGraph:M}){var pe;const{t:E}=ke(),{ides:D,p2pStates:W={},usesP2P:R=!0}=Ss(),B=!!e&&bt(e)&&!ht(e),_=!!e&&ht(e),H=!!(e!=null&&e.daemonId)&&!!((pe=e==null?void 0:e.coordinator)!=null&&pe.meshId),L=c||(e?Tm(e)?"terminal":"chat":null),[F,$]=l.useState(!1),[K,z]=l.useState(!1),ne=l.useRef(null),ie=l.useRef(null),Ce=l.useRef(null),me=D.filter(le=>le.type==="adhdev-daemon"),O=Sj({wsStatus:t,isConnected:n,daemonCount:me.length,p2pStates:W,usesP2P:R}),Y=E(O.titleKey),X=O.subtitleKey?E(O.subtitleKey,O.subtitleParams):null,Q=O.tone==="connected"?"#22c55e":O.tone==="limited"?"#eab308":"#ef4444",ve=O.tone==="connected"?"0 0 4px #22c55e80":O.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",he=l.useMemo(()=>w.filter(le=>!le.readAt),[w]),Z=l.useMemo(()=>w.filter(le=>!!le.readAt),[w]),fe=l.useMemo(()=>he.slice(0,9),[he]),V=j;l.useEffect(()=>{if(!k)return;const le=se=>{var te;(te=ie.current)!=null&&te.contains(se.target)||h(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[k,h]),l.useEffect(()=>{if(!b)return;const le=se=>{var te;(te=Ce.current)!=null&&te.contains(se.target)||S(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[b,S]),l.useEffect(()=>{if(!b&&!k)return;const le=se=>{if(!se.altKey)return;const te=se.code.match(/^Digit([1-9])$/);if(!te)return;const ue=Number(te[1])-1,ye=b?u[ue]:void 0,Me=k?fe[ue]:void 0;if(!(!ye&&!Me)){if(se.preventDefault(),se.stopPropagation(),ye){m==null||m(ye),S(!1);return}Me&&(N(Me),h(!1))}};return window.addEventListener("keydown",le,!0),()=>window.removeEventListener("keydown",le,!0)},[u,b,k,fe,S,h,N,m]),l.useEffect(()=>{const le=u.length;if(ne.current===null){ne.current=le;return}le>ne.current&&z(!0),ne.current=le},[u.length]);const q=()=>z(!1),ee=le=>{if(!le)return;const se=a.find(te=>te.tabKey===le);se&&(p==null||p(se))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(Is,{size:18}),s.jsx("span",{className:"header-title-desktop",children:E("dashboard.header.title")}),s.jsx("span",{className:"header-title-mobile",children:e?kt(e):E("dashboard.header.title")}),s.jsx("span",{title:Y,"aria-label":Y,className:"header-title-status-dot",style:{background:Q,boxShadow:ve}}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:Q,boxShadow:ve}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[X&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",X]}),x&&s.jsx("button",{type:"button",onClick:x,className:"btn btn-secondary btn-sm ml-2",title:`${E("paneGroup.newSession")}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":E("paneGroup.newSession"),children:s.jsx(Wl,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[y&&s.jsxs("button",{type:"button",onClick:y,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:E("dashboard.header.guide"),"aria-label":E("dashboard.header.guideOpen"),children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),C&&s.jsx("span",{children:E("dashboard.header.guideShort")})]}),e&&(B||_||!ht(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:na(e)||kt(e),children:kt(e)}),P&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:E("dashboard.header.openGitStatus"),onClick:()=>P(e.daemonId,e.workspacePath),children:s.jsx(qr,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(qr,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),H&&M&&s.jsxs("button",{type:"button",onClick:()=>M(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:E("dashboard.header.openMeshGraph"),children:[s.jsx(cs,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:E("dashboard.header.meshGraph")})]}),(B||_)&&i&&s.jsxs(s.Fragment,{children:[B&&d&&L&&s.jsx(oh,{mode:L,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:E(_?"dashboard.header.stopAcpSession":"dashboard.header.stopCliProcess"),style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Dt,{size:14})})]}),!ht(e)&&s.jsx("button",{onClick:()=>r(e),className:"btn btn-secondary btn-sm",title:E("dashboard.header.chatHistory"),children:s.jsx($l,{size:14})}),!B&&!ht(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:E("dashboard.header.remoteControl"),children:s.jsx(us,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:ie,children:[s.jsxs("div",{className:`dashboard-header-hidden${F?" is-drop-target":""}${K?" hidden-spawn-flash":""}${(u??[]).some(Ha)?" hidden-generating-spin":""}`,onAnimationEnd:q,ref:Ce,onDragEnter:le=>{le.dataTransfer.types.includes("text/tab-key")&&(le.preventDefault(),$(!0))},onDragOver:le=>{le.dataTransfer.types.includes("text/tab-key")&&(le.preventDefault(),le.dataTransfer.dropEffect="move",$(!0))},onDragLeave:le=>{le.currentTarget.contains(le.relatedTarget)||$(!1)},onDrop:le=>{const se=le.dataTransfer.getData("text/tab-key");le.preventDefault(),$(!1),ee(se)},children:[s.jsxs("button",{type:"button",onClick:()=>S(!b),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${E("dashboard.hidden.title")}${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. ${E("dashboard.hidden.dragHint")}`,children:[s.jsx(mo,{size:16}),u.length>0&&s.jsx("span",{className:`dashboard-header-hidden-badge${K?" hidden-badge-pop":""}`,children:u.length})]}),b&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:E("dashboard.hidden.title")}),s.jsx(Fd,{value:v==null?void 0:v.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[g&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:g,children:E("dashboard.hidden.resetPanels")}),u.length>0&&f&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),S(!1)},children:E("dashboard.hidden.restoreAll")})]})]}),e&&p&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>p(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:E("dashboard.hidden.hideCurrentTab")}),s.jsx(Fd,{value:v==null?void 0:v.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:kt(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(le=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(le),S(!1)},children:[s.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[Ha(le)&&s.jsx(ls,{size:12,thickness:2,color:"success",label:E("dashboard.header.generating")}),kt(le)]}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(le)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(le)+1]}):null,na(le)]})]},le.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:E("dashboard.hidden.empty")})]})]}),s.jsxs("button",{type:"button",onClick:()=>h(!k),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:E("dashboard.header.activityInbox"),children:[s.jsx(la,{size:16}),V>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:V})]}),k&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[he.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:E("dashboard.inbox.unread")}),he.map(le=>s.jsx(Bd,{notification:le,shortcutIndex:fe.indexOf(le)>=0?fe.indexOf(le)+1:void 0,onOpen:()=>N(le),onMarkRead:()=>A(le.id),onMarkUnread:()=>T(le.id),onDelete:()=>I(le.id)},le.id))]}),Z.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:E("dashboard.inbox.read")}),Z.map(le=>s.jsx(Bd,{notification:le,onOpen:()=>N(le),onMarkRead:()=>A(le.id),onMarkUnread:()=>T(le.id),onDelete:()=>I(le.id)},le.id))]}),w.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:E("dashboard.inbox.empty")})]})]})]})]})}function qt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function jj(e,t){return String(e||"")!==String(t||"")}function Nj(e,t={}){const n=String(t.textQuery||"").trim().toLowerCase(),a=String(t.workspaceQuery||"").trim().toLowerCase(),r=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.resumableOnly;return!n&&!a&&!r&&!o?e:e.filter(i=>!(o&&!i.canResume||n&&![i.title,i.preview].map(d=>String(d||"").toLowerCase()).join(`
52
52
  `).includes(n)||a&&!String(i.workspace||"").toLowerCase().includes(a)||r&&!mm(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
53
53
  `).includes(r)))}function Aj(e,t="recent"){const n=e.slice();return n.sort((a,r)=>{if(t==="oldest")return(Number(a.lastMessageAt)||0)-(Number(r.lastMessageAt)||0);if(t==="messages"){const o=(Number(r.messageCount)||0)-(Number(a.messageCount)||0);if(o!==0)return o}return(Number(r.lastMessageAt)||0)-(Number(a.lastMessageAt)||0)}),n}function ih(e,t={}){return Aj(Nj(e,t),t.sortMode||"recent")}function cl(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function lh(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function Tj(e){return e?e("launch.startFresh"):"Start fresh"}function Mj(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Pj(e){return e?e("launch.openSavedHistory"):"Open saved history"}function Dj(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function oc(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function Ij(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function Lj(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function Rj(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function zr(e,t,n){if(typeof e=="function"){const o=t,i=n;return o==="start-fresh"?e("launch.startFreshWith",{label:i}):e("launch.restart",{label:i})}const a=e,r=t;return a==="start-fresh"?`Start fresh with ${r}?`:`Restart ${r}?`}function Kr(e,t){if(typeof e=="function"){const a=t;return e(a==="start-fresh"?"launch.startFreshReview":a==="restart-ide"?"launch.restartIdeReview":"launch.restartStoppedReview")}const n=e;return n==="start-fresh"?"Review the provider and target folder before starting fresh.":n==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Vr(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function Yr(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function ch(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function dh(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function Wd(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function uh({activeConv:e,ides:t,isCreatingChat:n,isRefreshingHistory:a,savedSessions:r=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:p,onClose:u,onNewChat:m,onSwitchSession:f,onRefreshHistory:g,onResumeSavedSession:k}){var E;const{t:h}=ke("common"),b=t.find(D=>D.id===e.routeId),S=(b==null?void 0:b.chats)||[],x=(E=b==null?void 0:b.activeChat)==null?void 0:E.id,y=bt(e)&&!ht(e),[C,v]=l.useState(()=>qt()),[w,j]=l.useState(null),N=c||C,A=String(d||"").trim(),T=D=>{if(p){p(D);return}v(D)},I=l.useMemo(()=>r.map(D=>{const W=String(D.workspace||"").trim();return D.canResume||W||!A?D:{...D,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,r]),P=l.useMemo(()=>ih(I,{textQuery:N.textQuery,workspaceQuery:N.workspaceQuery,modelQuery:N.modelQuery,resumableOnly:N.resumableOnly,sortMode:N.sortMode}),[I,N.modelQuery,N.resumableOnly,N.sortMode,N.textQuery,N.workspaceQuery]),M=s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:y?Dj(h):h("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:XC(e)}),y&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:oc(h)})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(Dt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!y&&s.jsx("button",{onClick:m,disabled:n,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:h(n?"historyModal.creating":"historyModal.startNewChat")}),y?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:N.textQuery,onChange:D=>T({...N,textQuery:D.target.value}),placeholder:h("historyModal.searchPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:N.workspaceQuery,onChange:D=>T({...N,workspaceQuery:D.target.value}),placeholder:h("historyModal.filterWorkspace"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:N.modelQuery,onChange:D=>T({...N,modelQuery:D.target.value}),placeholder:h("historyModal.filterModel"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:N.sortMode,onChange:D=>T({...N,sortMode:D.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:h("historyModal.sortRecent")}),s.jsx("option",{value:"oldest",children:h("historyModal.sortOldest")}),s.jsx("option",{value:"messages",children:h("historyModal.sortMessages")})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:N.resumableOnly,onChange:D=>T({...N,resumableOnly:D.target.checked})}),h("historyModal.resumeReadyOnly")]})]}),P.map(D=>{const W=e.providerSessionId===D.providerSessionId,R=W||!D.canResume||!!i,B=D.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{R||!k||j({kind:"saved",session:D})},disabled:R,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${W?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${R?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${W?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:D.title||h("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:D.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Wd(D.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:D.preview||h("historyModal.noSavedPreview")}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[D.workspace||h("historyModal.workspaceUnknown"),B?h("historyModal.selectedWorkspaceSuffix"):"",Mn(D.summaryMetadata)?` · ${Mn(D.summaryMetadata)}`:"",D.messageCount>0?` · ${h("historyModal.msgCount",{count:D.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:W?h("historyModal.statusActive"):D.canResume?B?h("historyModal.statusResumeSelectedWorkspace"):i===D.providerSessionId?h("historyModal.statusResuming"):h("historyModal.statusResume"):h("historyModal.statusMissingWorkspace")})]})]},D.id)})]}):S.map(D=>s.jsxs("div",{onClick:()=>{D.id!==x&&j({kind:"chat",id:D.id,title:D.title||h("historyModal.untitledSession")})},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${x===D.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${x===D.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:D.title||h("historyModal.untitledSession")}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[D.id.substring(0,12),"..."]}),x===D.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:h("historyModal.statusActive")})]})]},D.id)),(y&&!o&&P.length===0||!y&&S.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Sb,{size:32})}),s.jsx("div",{className:"text-[13px]",children:y?r.length>0?h("historyModal.noMatchingHistory"):Ij(h):h("historyModal.noRecentChats")})]}),y&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Rj(h)})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:g,disabled:a||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:a||o?h("historyModal.refreshing"):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(po,{size:13})," ",y?Lj(h):h("historyModal.refreshHistory")]})})})]}),w&&s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center p-4",children:[s.jsx("div",{onClick:()=>j(null),className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-full sm:w-[min(92vw,420px)] max-w-[420px] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[s.jsx("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:h("historyModal.confirmSwitchTitle")}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:h("historyModal.confirmSwitchDescription",{target:w.kind==="chat"?w.title:w.session.title||h("historyModal.untitledSession")})}),w.kind==="saved"&&s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted font-mono truncate",children:[w.session.workspace||h("historyModal.workspaceUnknown"),w.session.lastMessageAt?` · ${Wd(w.session.lastMessageAt)}`:""]})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:()=>{const D=w;j(null),D.kind==="chat"?(f(e.routeId,D.id),u()):k&&k(D.session)},className:"btn btn-primary w-full justify-center min-h-[42px]",children:h("historyModal.confirmSwitchAction")}),s.jsx("button",{onClick:()=>j(null),className:"btn btn-secondary w-full justify-center min-h-[42px]",children:h("common.cancel")})]})]})]})]});return typeof document>"u"?M:zs.createPortal(M,document.body)}const Od={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.success"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.warning"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.info"}};function ph({toasts:e,onDismiss:t,onClickToast:n}){const{t:a}=ke();return s.jsx("div",{className:"fixed right-4 top-[calc(env(safe-area-inset-top,0px)+64px)] z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none sm:top-[calc(env(safe-area-inset-top,0px)+16px)]",children:e.map(r=>{const o=Od[r.type]||Od.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=r.actions)!=null&&i.length||n&&n(r)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${o.accent}, color-mix(in srgb, ${o.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(r.id)},"aria-label":a("toast.dismiss"),children:s.jsx(Dt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:o.chipBg,color:o.chipText,border:`1px solid color-mix(in srgb, ${o.accent} 22%, transparent)`},children:a(o.labelKey)})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:r.message}),r.actions&&r.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:r.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:d=>{d.stopPropagation(),i.onClick(),t(r.id)},children:i.label},c))})]})]},r.id)})})}const Ej=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function _j(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function Hj(e,t){return mh(e)||t}function mh(e){var r,o,i;const t=(o=(r=e.summaryMetadata)==null?void 0:r.items)==null?void 0:o.find(c=>(c==null?void 0:c.id)==="model"),n=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(n)return n;const a=(i=e.controlValues)==null?void 0:i.model;return typeof a=="string"&&a.trim()?a.trim():""}function $j(e){return mh(e)||void 0}function Fj(e){return e.sessionId||e.instanceId||e.agentType}function hh(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=ds(n,{fallbackId:n.id}));return t}function fh(e,t={}){var a;const n=e.daemonId||((a=e.id)==null?void 0:a.split(":")[0])||e.id;return{machineName:V0(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function ic(e,t={}){return Bj(e,fh(e,t))}function Bj(e,t={}){var f,g,k,h,b,S,x,y,C;const n=[],a=t.machineName,r=t.connectionState,o=_j(e),i=e.workspace||"",c=ek(e.type,{agentName:e.cliName}),d=bt(e)||ht(e)?c:Ot(e.type),p=Hj(e,d),u=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var w,j,N;return{sessionId:v.id,instanceId:v.id,providerSessionId:v.providerSessionId,activeChatId:(w=v.activeChat)==null?void 0:w.id,transport:v.transport,sessionCapabilities:v.capabilities,agentType:v.providerType,agentName:v.providerName||Ot(v.providerType),model:$j(v),status:v.status,title:v.title,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,messages:((j=v.activeChat)==null?void 0:j.messages)||[],activeModal:((N=v.activeChat)==null?void 0:N.activeModal)||void 0,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,surfaceHidden:v.surfaceHidden,muted:v.muted,git:v.git,settings:v.settings,coordinator:v.coordinator,messageInput:v.messageInput}}):[],m=Ej(e);if(m){const v=e.sessionId||e.instanceId,w=(f=e.settings)==null?void 0:f.meshCoordinatorFor,j=((g=e.settings)==null?void 0:g.meshNodeFor)||!((k=e.settings)!=null&&k.meshCoordinatorFor)&&((h=e.settings)==null?void 0:h.launchedByCoordinator),N=w?" (Coordinator)":j?" (Mesh Node)":"",A=c+N,T=(b=e.activeChat)==null?void 0:b.activeModal,I=T&&Array.isArray(T.buttons)&&T.buttons.length>0,P=tk(e.activeChat,[{status:e.status,activeModal:(S=e.activeChat)==null?void 0:S.activeModal}],e.agents||[]),M=e.activeChat||{title:"",messages:[]};let E=M.title&&String(M.title).trim()?String(M.title).trim():"";const D=(x=e.activeChat)==null?void 0:x.id,W=e.chats;if(D&&Array.isArray(W)&&W.length>0){const K=W.find(z=>z.id===D||z.id&&String(z.id)===String(D));K!=null&&K.title&&String(K.title).trim()&&(E=String(K.title).trim())}const R=(bt(e)||ht(e),e.type),B=(bt(e)||ht(e))&&cd(E,A,R)?"":E,_=M.messages||[],H=typeof D=="string"?D.trim():"",L=(bt(e)||ht(e))&&H===String(e.type||"").trim(),F=H&&!L?H:e.providerSessionId,$=e.coordinator||(typeof((y=e.settings)==null?void 0:y.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,historySessionId:F,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:bt(e)&&e.mode||"chat",agentName:A,agentType:R,status:P,title:B,messages:_,resume:e.resume,hostIdeType:!bt(e)&&!ht(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||B||(bt(e)?e.mode==="chat"?A:`Terminal${N}`:A),displaySecondary:p,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:I?T.buttons:void 0,modalMessage:I?T.message:void 0,streamSource:"native",tabKey:Uo(v,e.id),machineName:a,connectionState:r,settings:e.settings,coordinator:$,messageInput:e.messageInput})}if(m&&(bt(e)||ht(e)))return n;for(const v of u){const w=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,j=sk(v),N=Fj(v),A=`${e.id}:${N}`,T=v.title&&String(v.title).trim()||"",I=cd(T,v.agentName,v.agentType)?"":T,P=v.messages||[];if(!(v.transport==="cdp-webview"||!!v.sessionId||!!v.providerSessionId||P.length>0||w||!!I||!["idle","panel_hidden","disconnected","not_monitored"].includes(j)))continue;const E=v.coordinator||(typeof((C=v.settings)==null?void 0:C.meshCoordinatorFor)=="string"&&v.settings.meshCoordinatorFor?{meshId:v.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:v.sessionId||v.instanceId,providerSessionId:v.providerSessionId,historySessionId:v.activeChatId||v.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:v.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:v.sessionCapabilities,mode:"chat",agentName:v.agentName,agentType:v.agentType,status:j,title:I,messages:P,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:v.git||e.git,displayPrimary:o||I||v.agentName||d,displaySecondary:v.model&&v.model.trim()?v.model.trim():`${d} · ${v.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,lastUpdated:v.lastUpdated||e.lastUpdated,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,modalButtons:w?v.activeModal.buttons:void 0,modalMessage:w?v.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Uo(v.sessionId||v.instanceId,A),machineName:a,connectionState:r,settings:v.settings,coordinator:E,messageInput:v.messageInput})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||d,displaySecondary:p,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Uo(e.sessionId||e.instanceId,e.id),connectionState:r,settings:e.settings,messageInput:e.messageInput}),n}function gh(e){return String(e.type||e.id||"").trim()}function Qr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function Wj(e,t){const n=(t||"").trim();if(!n)return[];const a=(e||[]).find(r=>r.type===n);return Qr(a==null?void 0:a.modelOptions)}function Oj(e,t){const n=(t||"").trim();if(!n)return[];const a=(e||[]).find(r=>r.type===n);return Qr(a==null?void 0:a.thinkingLevelOptions)}function bh(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:Qr(n.modelOptions),thinking:Qr(n.thinkingLevelOptions)});return t}function Uj(e){var t;return e.category!=="cli"||!gh(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function cn(e){var a;const t=new Set,n=[];for(const r of e||[]){if(!Uj(r))continue;const o=gh(r);if(!o||t.has(o))continue;t.add(o);const i=String(r.displayName||r.name||o),c=r.detectedPath||((a=r.lastDetection)==null?void 0:a.path)||null;n.push({type:o,label:i,icon:r.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c,...Array.isArray(r.modelOptions)&&r.modelOptions.length?{modelOptions:r.modelOptions}:{},...Array.isArray(r.thinkingLevelOptions)&&r.thinkingLevelOptions.length?{thinkingLevelOptions:r.thinkingLevelOptions}:{}})}return n}function Ya(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],n=new Set,a=[];for(const r of t){const o=typeof r=="string"?r.trim():"";!o||n.has(o)||(n.add(o),a.push(o))}return a}function Dn(e){return e.map(t=>t.type)}function Gj(e,t){const n=Ya(e),a=t.trim();return!a||n.includes(a)?n:[...n,a]}function qj(e,t){return Ya(e).filter(n=>n!==t)}function Ud(e,t,n){const a=Ya(e),r=a.indexOf(t);if(r<0)return a;const o=a.filter(c=>c!==t);if(n==="top")return[t,...o];if(n==="bottom")return[...o,t];const i=n==="up"?Math.max(0,r-1):Math.min(o.length,r+1);return o.splice(i,0,t),o}const zj={"claude-cli":{monogram:"CL",hue:"#D97757"},"codex-cli":{monogram:"CX",hue:"#10A37F"},"gemini-cli":{monogram:"GM",hue:"#4285F4"},"kimi-cli":{monogram:"KM",hue:"#6366F1"},"antigravity-cli":{monogram:"AG",hue:"#8B5CF6"},"cursor-cli":{monogram:"CU",hue:"#64748B"},"opencode-cli":{monogram:"OC",hue:"#CA8A04"},"hermes-cli":{monogram:"HM",hue:"#14B8A6"},"grok-cli":{monogram:"GK",hue:"#475569"},antigravity:{monogram:"AG",hue:"#8B5CF6"},cursor:{monogram:"CU",hue:"#64748B"},kiro:{monogram:"KI",hue:"#F59E0B"},pearai:{monogram:"PA",hue:"#22C55E"},trae:{monogram:"TR",hue:"#EF4444"},vscode:{monogram:"VS",hue:"#3B82F6"},vscodium:{monogram:"VC",hue:"#2DD4BF"},windsurf:{monogram:"WS",hue:"#0EA5E9"},cline:{monogram:"CN",hue:"#0284C7"},"roo-code":{monogram:"RC",hue:"#F97316"}},Gd=["#0EA5E9","#8B5CF6","#10B981","#F59E0B","#EF4444","#14B8A6","#6366F1","#EC4899","#84CC16","#F97316","#06B6D4","#A855F7"];function Kj(e){let t=0;for(let n=0;n<e.length;n+=1)t=(t<<5)-t+e.charCodeAt(n)|0;return Math.abs(t)}function Vj(e){const t=e.replace(/[-_./]+/g," ").split(/\s+/).map(n=>n.trim()).filter(Boolean);return t.length===0?"?":t.length===1?t[0].slice(0,2).toUpperCase():(t[0][0]+t[1][0]).toUpperCase()}function Qa({type:e,label:t,size:n=16,className:a}){const r=(e||"").trim().toLowerCase(),o=(t==null?void 0:t.trim())||r;if(!o)return s.jsx(Rb,{size:n,className:a});const i=zj[r],c=(i==null?void 0:i.monogram)??Vj((t==null?void 0:t.trim())||r.replace(/-cli$/,"")),d=(i==null?void 0:i.hue)??Gd[Kj(r||o)%Gd.length];return s.jsx("span",{"aria-hidden":!0,className:`inline-flex shrink-0 select-none items-center justify-center font-semibold ${a??""}`,style:{width:n,height:n,borderRadius:Math.max(4,Math.round(n*.3)),backgroundColor:`${d}21`,border:`1px solid ${d}4D`,color:d,fontSize:Math.max(7,Math.round(n*.42)),letterSpacing:"0.02em",lineHeight:1},children:c})}function qd({direction:e}){return s.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="up"?s.jsx("polyline",{points:"18 15 12 9 6 15"}):s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function Yj({value:e,availableProviders:t,onChange:n,disabled:a=!1,saveButton:r}){const{t:o}=ke("common"),[i,c]=l.useState(""),d=l.useMemo(()=>new Map(t.map(g=>[g.type,g])),[t]),p=l.useMemo(()=>Ya(e),[e]),u=p.filter(g=>!d.has(g)).length,m=t.filter(g=>!p.includes(g.type)),f=()=>{i&&(n(Gj(p,i)),c(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:p.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):p.map((g,k)=>{const h=d.get(g),b=!!h;return s.jsxs("div",{className:`flex flex-col gap-2 rounded-md border border-border-subtle px-3 py-2 sm:flex-row sm:items-center sm:justify-between ${b?"bg-bg-primary":"bg-bg-primary/40"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",k+1]}),s.jsx(Qa,{type:g,label:h==null?void 0:h.label,size:14}),s.jsx("span",{className:`font-mono text-[12px] ${b?"text-text-primary":"text-text-muted"}`,children:g}),b?s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:o("settings.providerPriority.available")}):s.jsx("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-[9px] font-semibold text-amber-400",children:o("settings.providerPriority.notOnMachine")})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:h?`${h.label} · ${h.statusLabel}`:"Kept in order; skipped at launch until detected here."})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:a||k===0,title:"Move up",onClick:()=>n(Ud(p,g,"up")),children:s.jsx(qd,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:a||k===p.length-1,title:"Move down",onClick:()=>n(Ud(p,g,"down")),children:s.jsx(qd,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:a,onClick:()=>n(qj(p,g)),children:o("settings.providerPriority.remove")})]})]},g)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:o("settings.providerPriority.addCliLabel")}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:i,onChange:g=>c(g.target.value),disabled:a||m.length===0,children:[s.jsx("option",{value:"",children:m.length?"Select provider…":"No additional detected CLI providers"}),m.map(g=>s.jsxs("option",{value:g.type,children:[g.label," (",g.type,")"]},g.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:a||!i,onClick:f,children:o("settings.providerPriority.addProvider")}),r]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Launches use this order, top to bottom.",u>0?` ${u} provider${u===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function Qj(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function xh(e,t){const n=Qj(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const vh=[{id:"antigravity",name:"Antigravity",icon:"🌀"},{id:"cursor",name:"Cursor",icon:"⚡"},{id:"kiro",name:"Kiro",icon:"🎯"},{id:"pearai",name:"PearAI",icon:"🍐"},{id:"trae",name:"Trae",icon:"🔮"},{id:"vscode",name:"VS Code",icon:"💙"},{id:"vscodium",name:"VSCodium",icon:"💚"},{id:"windsurf",name:"Windsurf",icon:"🏄"}],yh=[{id:"antigravity-cli",name:"Antigravity CLI",icon:"🪐"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"grok-cli",name:"Grok",icon:"🛰️"},{id:"hermes-cli",name:"Hermes",icon:"⚕️"},{id:"kimi",name:"Kimi",icon:"🌙"},{id:"opencode",name:"OpenCode CLI",icon:"◆"}],wh=[{id:"cline",name:"Cline",icon:"🧠"},{id:"codex",name:"Codex",icon:"📦"},{id:"roo-code",name:"Roo Code",icon:"🦘"},{id:"claude-code-vscode",name:"Claude Code (VS Code)",icon:"🟠"}],Jj=vh,Xj=yh,Zj=wh;function e1({icon:e,title:t,subtitle:n,badge:a,actions:r,className:o}){return s.jsxs("div",{className:Pt("dashboard-header",o),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,a&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[a.count!==void 0?a.count:""," ",a.text]})]}),n&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:n})]}),r&&s.jsx("div",{className:"flex gap-2",children:r})]})}function Ja({icon:e,title:t,subtitle:n,badge:a,actions:r,widthClassName:o="max-w-6xl",contentClassName:i,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(e1,{icon:e,title:t,subtitle:n,badge:a,actions:r}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Pt("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const dl="adhdev:themechange";function t1(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function zn(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Kn(e){return e==="system"?t1():e}function kh(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Mr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(dl,{detail:{preference:e,theme:t}}))}function s1(){const e=zn(),t=Kn(e);kh(t),Mr(e,t)}function Rs(){const[e,t]=l.useState(zn),[n,a]=l.useState(()=>Kn(zn()));l.useEffect(()=>{kh(n)},[n]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const p=d.matches?"light":"dark";a(p),Mr("system",p)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=d=>{const p=d.detail||{},u=p.preference,m=p.theme;t(u==="dark"||u==="light"||u==="system"?u:zn()),a(m==="dark"||m==="light"?m:Kn(zn()))},c=d=>{if(d.key!=="theme")return;const p=zn(),u=Kn(p);t(p),a(u)};return window.addEventListener(dl,i),window.addEventListener("storage",c),()=>{window.removeEventListener(dl,i),window.removeEventListener("storage",c)}},[]);const r=l.useCallback(i=>{const c=Kn(i);t(i),a(c);try{localStorage.setItem("theme",i)}catch{}Mr(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=Kn(c);a(d);try{localStorage.setItem("theme",c)}catch{}return Mr(c,d),c})},[]);return{theme:n,preference:e,setPreference:r,cycleTheme:o,isDark:n==="dark"}}const zd={dark:"Dark",light:"Light",system:"System"};function n1({collapsed:e}){const{preference:t,cycleTheme:n}=Rs(),a=t==="dark"?s.jsx(Rp,{size:16}):t==="light"?s.jsx(Lp,{size:16}):s.jsx(Ep,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${zd[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:a}),!e&&s.jsx("span",{className:"text-xs",children:zd[t]})]})}const ul="adhdev:langchange";function a1(){const e=wt.language;return Yn(e)?e:nm()}function r1(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ul,{detail:{language:e}}))}function o1(){const[e,t]=l.useState(a1);l.useEffect(()=>{const a=i=>{Yn(i)&&t(i)},r=i=>{const c=i.detail||{};Yn(c.language)&&t(c.language)},o=i=>{if(i.key!==Yi)return;const c=i.newValue;Yn(c)&&c!==wt.language&&(wt.changeLanguage(c),Qi(c))};return wt.on("languageChanged",a),window.addEventListener(ul,r),window.addEventListener("storage",o),()=>{wt.off("languageChanged",a),window.removeEventListener(ul,r),window.removeEventListener("storage",o)}},[]);const n=l.useCallback(a=>{if(Yn(a)){t(a);try{localStorage.setItem(Yi,a)}catch{}wt.changeLanguage(a),Qi(a),r1(a)}},[]);return{language:e,setLanguage:n}}function i1({trigger:e,viewport:t,menu:n,variant:a,gap:r=6,margin:o=8}){const i=e.top-o,c=t.height-e.bottom-o,d=a==="sidebar";let p=d;d&&i<n.height&&c>i&&(p=!1),!d&&c<n.height&&i>c&&(p=!0);const u=p?i:c,m=Math.max(80,Math.min(n.height,u));let f;p?f=e.top-r-m:f=e.bottom+r,f=Kd(f,o,Math.max(o,t.height-m-o));const g=Kd(e.left,o,Math.max(o,t.width-n.width-o));return{top:f,left:g,maxHeight:m}}function Kd(e,t,n){return Math.min(Math.max(e,t),n)}function l1({open:e}){return s.jsx("svg",{width:12,height:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:`lang-switch-caret${e?" open":""}`,children:s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function c1({collapsed:e,variant:t="sidebar"}){const{language:n,setLanguage:a}=o1(),{t:r}=ke("common"),[o,i]=l.useState(!1),[c,d]=l.useState(0),p=l.useRef(null),u=l.useRef(null),m=l.useRef(null),f=l.useId(),[g,k]=l.useState(null),h=l.useCallback(()=>{const P=u.current;if(!P)return;const M=P.getBoundingClientRect(),E=m.current,D=Math.max((E==null?void 0:E.offsetWidth)??0,168),W=(E==null?void 0:E.scrollHeight)??pn.length*36+12;k(i1({trigger:{top:M.top,left:M.left,right:M.right,bottom:M.bottom,width:M.width,height:M.height},viewport:{width:window.innerWidth,height:window.innerHeight},menu:{width:D,height:W},variant:t}))},[t]),b=Math.max(0,pn.findIndex(P=>P.code===n)),S=pn[b]??pn[0],x=r("language.label",{defaultValue:"Language"}),y=r("language.select",{defaultValue:"Select language"}),C=P=>`${f}-opt-${P}`,v=l.useCallback(()=>{d(b),i(!0)},[b]),w=l.useCallback((P=!0)=>{var M;i(!1),P&&((M=u.current)==null||M.focus())},[]),j=l.useCallback(P=>{const M=pn[P];M&&a(M.code),w()},[a,w]);l.useEffect(()=>{if(!o)return;const P=D=>{var W,R;return!!((W=p.current)!=null&&W.contains(D)||(R=m.current)!=null&&R.contains(D))},M=D=>{P(D.target)||i(!1)},E=D=>{P(D.target)||i(!1)};return document.addEventListener("pointerdown",M,!0),document.addEventListener("focusin",E,!0),()=>{document.removeEventListener("pointerdown",M,!0),document.removeEventListener("focusin",E,!0)}},[o]),l.useLayoutEffect(()=>{if(!o){k(null);return}h();const P=()=>h();return window.addEventListener("resize",P),window.addEventListener("scroll",P,!0),()=>{window.removeEventListener("resize",P),window.removeEventListener("scroll",P,!0)}},[o,h]),l.useEffect(()=>{var P;o&&g&&((P=m.current)==null||P.focus())},[o,g]);const N=P=>{const M=pn.length-1;switch(P.key){case"ArrowDown":P.preventDefault(),d(E=>E>=M?0:E+1);break;case"ArrowUp":P.preventDefault(),d(E=>E<=0?M:E-1);break;case"Home":P.preventDefault(),d(0);break;case"End":P.preventDefault(),d(M);break;case"Enter":case" ":P.preventDefault(),j(c);break;case"Escape":P.preventDefault(),w();break;case"Tab":i(!1);break}},A=P=>{o||(P.key==="ArrowDown"||P.key==="ArrowUp"||P.key==="Enter"||P.key===" ")&&(P.preventDefault(),v())},T=t==="landing"?"lang-switch-trigger lang-switch-trigger--landing":`lang-switch-trigger lang-switch-trigger--sidebar nav-item cursor-pointer${e?" justify-center py-2.5 px-0":""}`,I=t==="landing"||!e;return s.jsxs("div",{ref:p,className:"lang-switch",children:[s.jsxs("button",{ref:u,type:"button",className:T,"aria-haspopup":"listbox","aria-expanded":o,"aria-label":`${x}: ${S.label}`,title:`${x}: ${S.label}`,onClick:()=>o?w(!1):v(),onKeyDown:A,children:[s.jsx("span",{className:"nav-icon lang-switch-icon",children:s.jsx(_p,{size:16})}),I&&s.jsx("span",{className:"lang-switch-label text-xs",children:S.label}),I&&s.jsx(l1,{open:o})]}),o&&typeof document<"u"&&zs.createPortal(s.jsx("ul",{ref:m,role:"listbox",tabIndex:-1,"aria-label":y,"aria-activedescendant":C(c),className:`lang-switch-menu lang-switch-menu--${t}`,style:{position:"fixed",top:(g==null?void 0:g.top)??0,left:(g==null?void 0:g.left)??0,maxHeight:g==null?void 0:g.maxHeight,overflowY:"auto",visibility:g?"visible":"hidden"},onKeyDown:N,children:pn.map((P,M)=>{const E=P.code===S.code,D=M===c;return s.jsxs("li",{id:C(M),role:"option","aria-selected":E,className:`lang-switch-option${D?" is-active":""}${E?" is-selected":""}`,onMouseEnter:()=>d(M),onClick:()=>j(M),children:[s.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:E?s.jsx(co,{size:14}):null}),s.jsx("span",{className:"lang-switch-option-label",children:P.label})]},P.code)})}),document.body)]})}const d1=[],u1=[];function Xo(e,t){return e?typeof e=="function"?e(t):e:null}const p1=l.memo(function({renderState:t,brand:n,navItems:a,sidebarSections:r,footerItems:o,footerInfo:i,footerActions:c,closeMobileMenu:d}){const{t:p}=ke("common"),{collapsed:u,mobileMenuOpen:m}=t,f=k=>`nav-item${k.active?" active":""} cursor-pointer ${u?"justify-center py-2.5 px-0":""}${k.className?` ${k.className}`:""}`,g=k=>s.jsxs("div",{className:f(k),id:`nav-${k.id}`,onClick:()=>{k.onSelect(),d()},title:u?k.title??(typeof k.label=="string"?k.label:void 0):k.title,children:[s.jsx("span",{className:"nav-icon",children:k.icon}),!u&&k.label]},k.id);return s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${u?"justify-center gap-0":""}`,children:Xo(n,t)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":p("app.closeMenu"),onClick:d,children:s.jsx(Dt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:a.map(g)}),r.map(k=>s.jsxs("div",{className:k.className??"border-t border-border-subtle pt-2 mt-2",children:[!u&&k.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:k.title}):null,k.items.map(g)]},k.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[o.map(g),Xo(i,t),s.jsx(n1,{collapsed:u}),s.jsx(c1,{collapsed:u}),Xo(c,t)]})]})});function m1({children:e,brand:t,navItems:n,sidebarSections:a=d1,footerItems:r=u1,footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const{t:p}=ke("common"),[u,m]=l.useState(!1),[f,g]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),k=l.useCallback(()=>m(!0),[]),h=l.useCallback(()=>m(!1),[]),b=l.useCallback(()=>{g(x=>{const y=!x;try{localStorage.setItem(d,y?"1":"0")}catch{}return y})},[d]),S=l.useMemo(()=>({collapsed:f,mobileMenuOpen:u,openMobileMenu:k,closeMobileMenu:h,toggleCollapsed:b}),[f,u,k,h,b]);return s.jsxs("div",{className:`app-layout${u?" mobile-menu-open":""}${f?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":p("app.openMenu"),onClick:k,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),u&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":p("app.closeMenu"),onClick:h,onKeyDown:x=>x.key==="Escape"&&h()}),s.jsx(p1,{renderState:S,brand:t,navItems:n,sidebarSections:a,footerItems:r,footerInfo:o,footerActions:i,closeMobileMenu:h}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function xt({title:e,icon:t,description:n,accentColor:a,className:r,collapsible:o,defaultOpen:i=!0,badge:c,children:d}){const[p,u]=l.useState(i),m=o?p:!0,f=(e||n)&&s.jsxs("div",{className:Pt("flex items-start justify-between gap-3",m&&"mb-4"),children:[s.jsxs("div",{className:"min-w-0",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary flex items-center gap-1.5",children:[t&&s.jsx("span",{children:t}),s.jsx("span",{children:e}),c]}),n&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:n})]}),o&&s.jsx("span",{className:Pt("mt-0.5 shrink-0 text-text-muted transition-transform select-none",m?"rotate-90":"rotate-0"),"aria-hidden":!0,children:"▸"})]});return s.jsxs("div",{className:Pt("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",a&&"border-l-[3px]",r),style:a?{borderLeftColor:a}:void 0,children:[o&&f?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>u(g=>!g),"aria-expanded":m,children:f}):f,m&&d]})}function Xa({icon:e,title:t,description:n,action:a,className:r}){return s.jsxs("div",{className:Pt("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",r),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:n}),a]})}const h1={error:"bg-red-500/10 border-red-500/30 text-red-400",warning:"bg-yellow-500/10 border-yellow-500/30 text-yellow-400",success:"bg-green-500/10 border-green-500/30 text-green-400",info:"bg-indigo-500/10 border-indigo-500/30 text-indigo-400"},f1={error:Ls,warning:Ls,success:Ga,info:uo};function Mt({variant:e,children:t,onDismiss:n,className:a}){return s.jsxs("div",{className:Pt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",h1[e],a),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const r=f1[e];return s.jsx(r,{size:14})})(),s.jsx("span",{children:t})]}),n&&s.jsx("button",{onClick:n,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function Tt({label:e,hint:t,children:n,className:a}){return s.jsxs("div",{className:Pt("mb-5",a),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),n,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function xs(e){const{className:t,...n}=e;return s.jsx("input",{...n,className:Pt("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const g1={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},Gs=l.forwardRef(function({variant:t="secondary",size:n="md",type:a,className:r,...o},i){return s.jsx("button",{ref:i,type:a??"button",className:Pt("btn",g1[t],n==="sm"&&"btn-sm",r),...o})}),b1=l.forwardRef(function({options:t,children:n,className:a,...r},o){return s.jsx("select",{ref:o,className:Pt("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none cursor-pointer","focus:border-accent transition-colors",a),...r,children:n??(t==null?void 0:t.map(i=>s.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})}),x1={online:"bg-green-500/10 text-green-400 border-green-500/30",idle:"bg-yellow-500/10 text-yellow-400 border-yellow-500/30",busy:"bg-orange-500/10 text-orange-400 border-orange-500/30",error:"bg-red-500/10 text-red-400 border-red-500/30",offline:"bg-gray-500/10 text-text-secondary border-gray-500/30"},v1={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function y1({status:e,label:t,className:n}){const a=t||e;return s.jsxs("span",{className:Pt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",x1[e],n),children:[s.jsx("span",{className:Pt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",v1[e])}),a]})}function w1({tabs:e,defaultTabKey:t,activeKey:n,onTabChange:a,variant:r="pill",ariaLabel:o,className:i,tabListClassName:c,panelClassName:d,tabIdPrefix:p,unmountInactivePanels:u=!1}){var S;const[m,f]=l.useState(t??((S=e[0])==null?void 0:S.key)),g=n!==void 0,k=g?n:m,h=x=>{g||f(x),a==null||a(x)},b=r==="underline";return s.jsxs("div",{className:i,children:[s.jsx("div",{className:Pt(b?"flex shrink-0 items-center gap-1 border-b border-border-subtle px-4 md:px-6":"mb-5 inline-flex w-full flex-wrap items-center gap-1 rounded-xl border border-border-subtle bg-bg-secondary/60 p-1 sm:w-fit",c),role:"tablist","aria-label":o,children:e.map(x=>{const y=x.key===k;return s.jsxs("button",{id:p?`${p}-${x.key}`:void 0,type:"button",role:"tab","aria-selected":y,className:Pt(b?["-mb-px flex cursor-pointer items-center gap-1.5 border-b-2 px-3 py-2.5 text-[13px] font-medium transition-colors",y?"border-accent text-accent":"border-transparent text-text-muted hover:text-text-secondary"]:["flex flex-1 items-center justify-center gap-1.5 rounded-lg px-3.5 py-1.5 text-[13px] font-medium transition-colors sm:flex-none",y?"bg-bg-card text-text-primary shadow-sm border border-border-default":"text-text-muted border border-transparent hover:text-text-secondary hover:bg-white/[0.03]"]),onClick:()=>h(x.key),children:[x.icon,x.label]},x.key)})}),e.map(x=>{const y=x.key===k;return u&&!y?null:s.jsx("div",{className:y?Pt("flex flex-col gap-4",d):"hidden",children:x.content},x.key)})]})}function xn({label:e,description:t,checked:n,disabled:a,onChange:r,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${a?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o,s.jsxs("button",{type:"button",role:"switch","aria-checked":n,"aria-disabled":a,disabled:a,onClick:()=>r(!n),className:`relative inline-flex items-center ${a?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:n?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${n?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function k1({onPrefChange:e}){const{t}=ke("common"),[n,a]=pk(),[r,o]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){o("unsupported");return}o(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,d)=>{a({[c]:d}),e==null||e(c,d)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(la,{size:15})," ",t("notifications.masterToggleLabel")]}),description:t("notifications.masterToggleDesc"),checked:n.globalEnabled,onChange:c=>i("globalEnabled",c)}),n.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),n.globalEnabled&&s.jsx(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:15})," ",t("notifications.browserNotificationsLabel")]}),description:t("notifications.browserNotificationsDesc"),checked:n.browserNotifications,onChange:c=>i("browserNotifications",c)}),n.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t("notifications.standaloneBackgroundInfo")}),r==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-status-warning",children:[s.jsx("span",{children:t("notifications.standalonePermissionDefault")}),s.jsx("button",{onClick:()=>{gm().then(o)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:t("notifications.allowNotifications")})]}),r==="denied"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.permissionDenied")}),r==="unsupported"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.standalonePermissionUnsupported")})]}),n.globalEnabled&&n.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ga,{size:15})," ",t("notifications.completionAlertsLabel")]}),description:t("notifications.completionAlertsDesc"),checked:n.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Cb,{size:15})," ",t("notifications.approvalAlertsLabel")]}),description:t("notifications.approvalAlertsDesc"),checked:n.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_a,{size:15})," ",t("notifications.connectionAlertsLabel")]}),description:t("notifications.connectionAlertsDesc"),checked:n.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!n.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:t("notifications.allDisabled")})]})}function Jr(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const n=t[4]??null;let a=null;if(n){const r=n.match(/(?:^|\.)(\d+)$/);a=r?Number(r[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:a,isPrerelease:n!==null}}function Vd(e){var t;return((t=Jr(e))==null?void 0:t.base)??null}function Sh(e,t){const n=Jr(e),a=Jr(t);if(!n||!a)return e!==t;for(let r=0;r<3;r+=1){if(n.base[r]<a.base[r])return!0;if(n.base[r]>a.base[r])return!1}return n.isPrerelease&&a.isPrerelease?n.prereleaseNumber===null||a.prereleaseNumber===null?!1:n.prereleaseNumber<a.prereleaseNumber:!1}function jo(e,t){const n=e.version||null;return!n||!t||e.versionMismatch===!0&&!Jr(t)?!1:Sh(n,t)}function Da(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||!Sh(n,t))return!1;const a=Vd(n),r=Vd(t);return!a||!r?!1:a[0]!==r[0]||a[1]!==r[1]}function Zo(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="stable"||t==="latest"?"stable":t==="preview"||t==="next"?"preview":null}function S1(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="latest"||t==="stable"?"latest":t==="next"||t==="preview"?"next":null}function ja(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function lc(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=Zo(t.channel)||Zo(e.updateChannel)||Zo(e.releaseChannel)||void 0,a=S1(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),r=ja(t.targetVersion)||ja(e.serverVersion)||void 0,o=ja(t.minVersion)||void 0,i=ja(t.updateCommand)||(n?"adhdev update":void 0);return{...n?{channel:n}:{},...a?{npmTag:a}:{},...r?{targetVersion:r}:{},...o?{minVersion:o}:{},...i?{updateCommand:i}:{}}}function Js(e,t=null){return lc(e).targetVersion||t}function C1(e){return lc(e).channel||null}function No(e){return!e||!lc(e).channel?null:{}}function Ch(e,t={}){const n=ja(t.targetVersion);return n?`Update to v${n}`:t.fallback||(t.required?"Update now":"Upgrade")}const jh="Cannot update: node update policy unavailable; refresh and try again";async function j1(e,t,n){var r,o,i,c,d,p;const a=No(n);if(!a)return{state:"error",message:jh};try{const u=await e(t,"daemon_upgrade",a);return(r=u==null?void 0:u.result)!=null&&r.alreadyLatest?{state:"done",message:`Already on v${((o=u==null?void 0:u.result)==null?void 0:o.version)||"latest"}.`}:(i=u==null?void 0:u.result)!=null&&i.upgraded||(c=u==null?void 0:u.result)!=null&&c.success?{state:"done",message:`Upgrade to v${((d=u==null?void 0:u.result)==null?void 0:d.version)||"latest"} started. Daemon is restarting…`}:{state:"error",message:((p=u==null?void 0:u.result)==null?void 0:p.error)||"Upgrade failed"}}catch(u){return{state:"error",message:u instanceof Error?u.message:"Upgrade failed"}}}function N1(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function ei(e,t){return e instanceof Error?e.message:t}function A1({ides:e,emptyMessage:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){const{t:o}=ke("common"),i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(Xa,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:o("machine.connectedMachines.noMachines"),description:t||o("machine.connectedMachines.defaultDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>s.jsx(M1,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r},c.id))})}function Yd({title:e,message:t,confirmLabel:n,confirmColor:a,onConfirm:r,onCancel:o}){const{t:i}=ke("common"),c=a==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return zs.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:"var(--z-modal)"},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:d=>d.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:i("common.cancel")}),s.jsx("button",{onClick:r,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:a==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:n})]})]})}),document.body)}function T1(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),a=[...Jj,...Xj,...Zj].find(r=>r.id===t||t.includes(r.id)||r.id.includes(t));return a?{icon:a.icon,name:a.name}:{icon:"",name:e}}function M1({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){var D,W;const{t:o}=ke("common"),[i,c]=l.useState("idle"),[d,p]=l.useState(""),[u,m]=l.useState(null),[f,g]=l.useState("idle"),[k,h]=l.useState(""),b=e.version||null,S=((D=e.machine)==null?void 0:D.platform)||((W=e.system)==null?void 0:W.platform)||"",x=ds(e,{fallbackId:e.id}),y=t.filter(R=>R.daemonId===e.id&&R.transport==="cdp-page"),C=t.filter(R=>R.daemonId===e.id&&R.transport==="pty"),v=t.filter(R=>R.daemonId===e.id&&R.transport==="acp"),w=e.p2p,j=async()=>{if(!n)return;const R=No(e);if(!R){c("error"),p(jh);return}c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const B=N1(await n(e.id,"daemon_upgrade",R));B.alreadyLatest?(c("done"),p(`Already on v${B.version||"latest"}.`)):B.upgraded||B.success?(c("done"),p(`Upgrade to v${B.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(B.error||"Upgrade failed"))}catch(B){c("error"),p(ei(B,"Connection lost during upgrade"))}},N=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),h(o("machine.connectedMachines.machineDisconnected"))}catch(R){g("error"),h(ei(R,o("machine.connectedMachines.failedToDisconnect")))}}},A=async()=>{if(m(null),!!r){g("loading");try{await r(e.id),g("done"),h(o("machine.connectedMachines.tokenRevoked"))}catch(R){g("error"),h(ei(R,o("machine.connectedMachines.failedToRevokeToken")))}}},T="1.0.57",I=Js(e,T),P=jo(e,I),M=Da(e,I),E=y.length+C.length+v.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-text-muted",title:S,children:s.jsx(us,{size:18})}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:x}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),b&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${P?"":"bg-bg-secondary"}`,style:P?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",b,!P&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&P&&s.jsx("button",{onClick:j,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${T}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(ls,{size:12,thickness:2})," ",o("machine.connectedMachines.upgrading")]}):i==="done"?o("machine.connectedMachines.updated"):M?o("machine.connectedMachines.updateNow"):o("machine.connectedMachines.updateTo",{version:T})}),a&&s.jsx("button",{onClick:()=>m("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:o("machine.connectedMachines.disconnect")}),r&&s.jsx("button",{onClick:()=>m("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:o("machine.connectedMachines.remove")}),s.jsx(y1,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[w&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${w.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${w.state==="connecting"||w.state==="new"?"animate-pulse":""}`,style:w.state==="connecting"||w.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",w.state==="connected"?"connected":w.state==="connecting"||w.state==="new"?o("machine.connectedMachines.connecting"):w.state||"off"]}),w.peers!==void 0&&w.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",w.peers," peer",w.peers!==1?"s":"",")"]})]}),w&&E>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),E>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[y.map(R=>{const B=T1(R.type),_=R.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx(Qa,{type:R.type,label:B.name,size:13}),s.jsx("span",{children:B.name}),_!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${_?"bg-status-online":"animate-pulse"}`,style:_?void 0:{background:"var(--status-warning)"},title:o(_?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},R.id)}),C.map(R=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:R.cliName||"CLI"})]},R.id)),v.map(R=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{className:"inline-flex",children:s.jsx(Ib,{size:12})}),s.jsx("span",{children:R.cliName||"ACP"})]},R.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:o("machine.connectedMachines.noIdesConnected")})]}),(d||k)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-status-error":i==="done"||f==="done"?"text-status-online":"text-text-muted"}`,children:k||d})]}),u==="disconnect"&&s.jsx(Yd,{title:o("machine.connectedMachines.disconnectTitle"),message:`Disconnect "${x}" from ADHDev?
54
54
 
@@ -62,7 +62,7 @@ This will:
62
62
  • Require running \`adhdev setup\` again on that machine
63
63
 
64
64
  The machine's IDE, workspace and provider settings are kept.`,confirmLabel:o("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:A,onCancel:()=>m(null)})]})}const P1=[{id:"dark",label:"Dark",icon:Rp},{id:"light",label:"Light",icon:Lp},{id:"system",label:"System",icon:Ep}];function D1(){const{preference:e,setPreference:t}=Rs();return s.jsx("div",{className:"flex gap-2",children:P1.map(n=>s.jsxs("button",{onClick:()=>t(n.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===n.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===n.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx(n.icon,{size:14}),n.label]},n.id))})}function I1(e){const t=e.trim();return/^#[0-9a-fA-F]{6}$/.test(t)?t:/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:null}function L1(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function ti(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Qd(e){const{r:t,g:n,b:a}=L1(e);return .2126*ti(t)+.7152*ti(n)+.0722*ti(a)}function Jd(e,t){const n=Qd(e),a=Qd(t),r=Math.max(n,a),o=Math.min(n,a);return(r+.05)/(o+.05)}function Nh(e){const t=I1(e);if(!t)return"#111827";const n="#111827",a="#ffffff";return Jd(t,n)>=Jd(t,a)?n:a}const pl={bgPrimary:"#0a0e1a",bgSecondary:"#0f1320",surfacePrimary:"#111726",textPrimary:"#f0f0f5",textSecondary:"#9ca3af",textMuted:"#6b7280",borderSubtle:"#1d2536",borderDefault:"#313c52",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#111726",assistantText:"#f0f0f5",containerBg:"#0f1320",sendButton:"#d97706",inputBorder:"#313c52",bubbleRadius:16},ml={bgPrimary:"#fff8ee",bgSecondary:"#fff1de",surfacePrimary:"#ffffff",textPrimary:"#24160f",textSecondary:"#6f6255",textMuted:"#938374",borderSubtle:"#e7d3ba",borderDefault:"#d7b892",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#fffaf4",assistantText:"#24160f",containerBg:"#fff8ee",sendButton:"#d97706",inputBorder:"#d7b892",bubbleRadius:16},R1=[{id:"midnight",name:"Midnight",description:"Classic violet theme",preview:{dark:{userBubble:"#8b5cf6",assistantBubble:"#18181d",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0f0f13",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#7c3aed",assistantBubble:"#ffffff",assistantBorder:"1px solid rgba(0,0,0,0.08)",containerBg:"#f0f1f5",textColor:"#52525b"}}},{id:"ember",name:"Ember",description:"Default landing-inspired amber theme",preview:{dark:{userBubble:"#f59e0b",assistantBubble:"#111726",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0a0e1a",textColor:"#9ca3af"},light:{userBubble:"#f59e0b",assistantBubble:"#fffaf4",assistantBorder:"1px solid rgba(146,64,14,0.10)",containerBg:"#fff8ee",textColor:"#6f6255"}}},{id:"aurora",name:"Aurora",description:"Pink accent theme",preview:{dark:{userBubble:"#ec4899",assistantBubble:"#1e1b2e",assistantBorder:"1px solid rgba(236,72,153,0.12)",containerBg:"#0f0d17",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#ec4899",assistantBubble:"#fef2f8",assistantBorder:"1px solid rgba(236,72,153,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}},{id:"honey",name:"Honey",description:"Warm yellow accents",preview:{dark:{userBubble:"#fbbf24",assistantBubble:"#1c1c1e",assistantBorder:"1px solid rgba(255,255,255,0.06)",containerBg:"#111113",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#fbbf24",assistantBubble:"#fffbeb",assistantBorder:"1px solid rgba(251,191,36,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}}],Ah="adhdev-chat-theme",Th="adhdev-chat-theme-custom";function Pr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Ah)||"ember"}catch{return"ember"}}function bs(e){try{const t=localStorage.getItem(Th);if(t){const n=JSON.parse(t);return{...e==="dark"?pl:ml,...n[e]}}}catch{}return e==="dark"?pl:ml}function cr(e,t){try{localStorage.setItem(Th,JSON.stringify({dark:e,light:t}))}catch{}}function as(e,t){const n=parseInt(e.slice(1,3),16),a=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16);return`rgba(${n}, ${a}, ${r}, ${t})`}function Xr(e,t){const n=Math.min(255,parseInt(e.slice(1,3),16)+t),a=Math.min(255,parseInt(e.slice(3,5),16)+t),r=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}`}const E1={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Ia(e,t){var r;const n=(r=E1[e])==null?void 0:r[t];if(!n)return;const a=document.documentElement;a.style.setProperty("--accent-primary",n),a.style.setProperty("--accent-primary-light",Xr(n,24)),a.style.setProperty("--accent-on-primary",Nh(n)),a.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${Xr(n,18)})`),a.style.setProperty("--border-accent",as(n,.35)),a.style.setProperty("--nav-active-bg",as(n,.1)),a.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${as(n,.06)}`)}function Cn(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",as(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",as(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",as(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",as(e.borderSubtle,.5)),t.style.setProperty("--border-default",as(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Xr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Nh(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Xr(e.accentColor,40)})`),t.style.setProperty("--border-accent",as(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",as(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${as(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${as(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function cc(){const e=document.documentElement;["--bg-primary","--bg-secondary","--bg-card","--surface-primary","--surface-secondary","--bg-glass","--bg-glass-hover","--text-primary","--text-secondary","--text-muted","--border-subtle","--border-default","--accent-primary","--accent-primary-light","--accent-on-primary","--accent-gradient","--border-accent","--nav-active-bg","--nav-active-shadow","--chat-user-bg","--chat-user-color","--chat-user-radius","--chat-assistant-bg","--chat-assistant-color","--chat-assistant-radius","--chat-assistant-border","--chat-container-bg","--dashboard-pane-bg","--chat-thought-accent","--chat-tool-accent","--chat-action-color","--chat-send-bg","--chat-input-border"].forEach(n=>e.style.removeProperty(n))}function _1(e){try{localStorage.setItem(Ah,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=jn()?"dark":"light";Cn(bs(t))}else cc(),Ia(e,jn()?"dark":"light")}function H1(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Pr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=jn()?"dark":"light";Cn(bs(t))}else cc(),Ia(e,jn()?"dark":"light")}function jn(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Gt({label:e,value:t,onChange:n}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:a=>n(a.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:a=>{/^#[0-9a-fA-F]{0,6}$/.test(a.target.value)&&n(a.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function xa({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function $1({dark:e,onColorsChange:t}){const{t:n}=ke("common"),a=e?"dark":"light",[r,o]=l.useState(()=>bs(a));l.useEffect(()=>{o(bs(a))},[a]);const i=l.useCallback((c,d)=>{o(p=>{const u={...p,[c]:d},f=bs(a==="dark"?"light":"dark");return a==="dark"?cr(u,f):cr(f,u),Cn(u),t(u),u})},[a,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[n("settings.theme.customEditorTitle"),s.jsx("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:n(e?"settings.theme.darkMode":"settings.theme.lightMode")})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(xa,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(Gt,{label:n("settings.theme.colorBackground"),value:r.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Gt,{label:n("settings.theme.colorSurface"),value:r.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Gt,{label:n("settings.theme.colorCard"),value:r.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(xa,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Gt,{label:n("settings.theme.colorPrimary"),value:r.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Gt,{label:n("settings.theme.colorSecondary"),value:r.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Gt,{label:n("settings.theme.colorMuted"),value:r.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(xa,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Gt,{label:n("settings.theme.colorBorderSubtle"),value:r.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Gt,{label:n("settings.theme.colorBorderDefault"),value:r.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Gt,{label:n("settings.theme.colorAccent"),value:r.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(xa,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Gt,{label:n("settings.theme.colorUserBubble"),value:r.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Gt,{label:n("settings.theme.colorUserText"),value:r.userText,onChange:c=>i("userText",c)}),s.jsx(Gt,{label:n("settings.theme.colorAgentBubble"),value:r.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Gt,{label:n("settings.theme.colorAgentText"),value:r.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(xa,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Gt,{label:n("settings.theme.colorChatBg"),value:r.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Gt,{label:n("settings.theme.colorSendButton"),value:r.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Gt,{label:n("settings.theme.colorInputBorder"),value:r.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:n("settings.theme.labelBubbleRadius")}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:r.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[r.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?pl:ml,p=bs(e?"light":"dark");e?cr(c,p):cr(p,c),o(c),Cn(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:n("settings.theme.resetToDefaults")})]})}function F1(){const{t:e}=ke("common"),[t,n]=l.useState(Pr),[a,r]=l.useState(!0),[o,i]=l.useState(()=>bs("dark"));l.useEffect(()=>{r(jn());const p=new MutationObserver(()=>{const f=jn();r(f);const g=Pr();g==="custom"?Cn(bs(f?"dark":"light")):Ia(g,f?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const u=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=jn();r(f);const g=Pr();g==="custom"?Cn(bs(f?"dark":"light")):Ia(g,f?"dark":"light")};return u.addEventListener("change",m),()=>{p.disconnect(),u.removeEventListener("change",m)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?Cn(bs(a?"dark":"light")):(cc(),Ia(t,a?"dark":"light"))},[t,a]),l.useEffect(()=>{i(bs(a?"dark":"light"))},[a]);const c=p=>{n(p),_1(p)},d=[...R1,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText},light:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(p=>{const u=t===p.id,m=a?p.preview.dark:p.preview.light,f=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return s.jsxs("button",{onClick:()=>c(p.id),className:"text-left rounded-xl p-3 transition-all",style:{background:u?"var(--bg-glass-hover)":"var(--bg-glass)",border:u?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:u?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.helloHelp")}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:f},children:e("settings.theme.fixBug")}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.onIt")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[u&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?e("settings.theme.customLabel"):p.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&s.jsx($1,{dark:a,onColorsChange:p=>i(p)})]})}const dc="adhdev_mobileDashboardMode_v1",hl="adhdev:mobile-dashboard-mode-change";function uc(){try{return localStorage.getItem(dc)==="workspace"?"workspace":"chat"}catch{return"chat"}}function B1(e){if(typeof window>"u")return()=>{};const t=r=>{e(r??uc())},n=r=>{const o=r.detail;t(o)},a=r=>{r.key&&r.key!==dc||t()};return window.addEventListener(hl,n),window.addEventListener("storage",a),()=>{window.removeEventListener(hl,n),window.removeEventListener("storage",a)}}function W1(e){try{localStorage.setItem(dc,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(hl,{detail:e}))}function O1(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(uc()==="chat")},[]),s.jsx(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Is,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:n=>{t(n),W1(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const U1="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",G1="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function q1({themeDescription:e=U1,mobileDescription:t=G1,fontsSlot:n}){const{t:a}=ke("common");return s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:a("settings.appearance.modeLabel")}),s.jsx(D1,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:a("settings.appearance.themeLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e}),s.jsx(F1,{})]}),n,s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:a("settings.appearance.mobileLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:t}),s.jsx(O1,{})]})]})}const si=new Map,Xd=new Map;function z1(e){if(!e||typeof e!="object")return null;const t=e,n=t.result&&typeof t.result=="object"?t.result:t,a=n.machine;return!a||typeof a!="object"?null:{machine:a,timestamp:typeof n.timestamp=="number"?n.timestamp:void 0}}function K1(e,t,n,a){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:a,platform:n.platform,machine:n}}function Mh(){const{sendCommand:e}=St(),{injectEntries:t,getIdes:n}=Ea();return l.useCallback(async(a,r)=>{if(!a)return;const o=(r==null?void 0:r.minFreshMs)??QS,i=Xd.get(a)||0;if(!(r!=null&&r.force)&&i>0&&Date.now()-i<o)return;const c=si.get(a);if(c)return c;const d=(async()=>{const p=await e(a,"get_machine_runtime_stats"),u=z1(p);if(!u)return;const m=n().find(g=>g.id===a),f=K1(m,a,u.machine,u.timestamp||Date.now());t([f]),Xd.set(a,Date.now())})().finally(()=>{si.delete(a)});return si.set(a,d),d},[n,t,e])}function V1(e,t,n){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n.timestamp,platform:n.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...n.machine}}}function Y1(e,t){const{sendData:n}=St(),{injectEntries:a,getIdes:r}=Ea(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!n)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(d=>ys.subscribe({sendData:n},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const m=r().find(g=>g.id===d),f=V1(m,d,u);a([f])}));return()=>{c.forEach(d=>d())}},[o,r,a,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function Q1(e,t){const{sendData:n}=St(),[a,r]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){r(null),i(!1);return}if(!(t!=null&&t.enabled)||!n){i(!1);return}r(null),i(!0);let c=null;const d=ys.subscribe({sendData:n},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},p=>{c&&(clearTimeout(c),c=null),r(p.diagnostics),i(!1)});return d.initialSendAccepted?c=setTimeout(()=>{i(!1)},ZS):i(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,n]),{diagnostics:a,loading:o,applyDiagnostics:r}}function J1(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Ph(e){const{sendData:t}=St(),[n,a]=l.useState({});return l.useEffect(()=>{const r=J1(e);if(!r||!e.sessionId||!t){a({});return}const o=ys.subscribe({sendData:t},r,{type:"subscribe",topic:"session.modal",key:`daemon:${r}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{a({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),ea.record({interactionId:i.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:i.status,modalButtonCount:Array.isArray(i.modalButtons)?i.modalButtons.length:0}})});return o.initialSendAccepted||a({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),n}function X1(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function Z1(e){const t=(e==null?void 0:e.result)??e;return typeof(t==null?void 0:t.error)=="string"?t.error:"Interactive prompt response failed"}async function eN(e,t,n){const a=await n(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let r=`HTTP ${a.status}`;try{const o=await a.json();typeof(o==null?void 0:o.error)=="string"&&(r=o.error)}catch{}throw new Error(r)}}async function tN({promptSession:e,response:t,useP2PCommand:n,sendCommand:a,fetchImpl:r=fetch}){if(n){const o=await a(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!X1(o))throw new Error(Z1(o));return}await eN(e.sessionId,t,r)}function Dh(e){const{ides:t,isP2PActive:n,p2pStates:a}=Ss(),{sendCommand:r}=St(),[o,i]=l.useState(null),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useRef(!1),f=l.useMemo(()=>Nx(t,e),[t,e]),g=!!f,k=l.useMemo(()=>f?f.prompt.promptId===o?null:f:null,[o,f]),h=l.useCallback(async x=>{if(!k||m.current)return;m.current=!0;const y=Jp(k.prompt,x);d(!0),u(null);try{const C=(a==null?void 0:a[k.daemonId])==="connected"||n===!0;await tN({promptSession:k,response:y,useP2PCommand:C,sendCommand:r}),i(k.prompt.promptId)}catch(C){throw u(C instanceof Error?C.message:String(C)),C}finally{d(!1),m.current=!1}},[n,a,k,r]),b=l.useCallback(()=>{k&&i(k.prompt.promptId)},[k]),S=l.useCallback(()=>{i(null),u(null)},[]);return{promptSession:k,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:h,cancel:b,reopen:S}}function Ih(e){return e instanceof Error?e.message:String(e||"")}function sN(e){const t=Ih(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function nN(e){const t=Ih(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Lh({conversation:e,mode:t,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:r}){if(!e||!bt(e)||ht(e))return;const o=ca(e);if(o===t)return;const i=e.sessionId;i&&r(c=>({...c,[i]:t}));try{await a(Vs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Ds(e),mode:t})}catch(c){const d=nN(c);i&&!d&&r(p=>{const u={...p};return o===rN(n,i)?delete u[i]:u[i]=o,u}),sN(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function Zd(e,t){const n=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!n||e.transport!=="pty")return e;const a=t[n];return!a||e.mode===a?e:{...e,mode:a}}function aN(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let n=!1;const a=e.map(r=>{const o=Zd(r,t),i=Array.isArray(r.childSessions)?r.childSessions.map(d=>Zd(d,t)):r.childSessions,c=i!==r.childSessions;return o!==r||c?(n=!0,{...o,...c?{childSessions:i}:{}}):r});return n?a:e}function rN(e,t){if(!t)return null;for(const n of e){if(n.sessionId===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal";for(const a of n.childSessions||[])if(a.id===t&&a.transport==="pty")return a.mode==="chat"?"chat":"terminal"}return null}function oN({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:a,isConversationMuted:r}){l.useEffect(()=>{gm()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:nh(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null,target:{providerSessionId:i.providerSessionId,sessionId:i.sessionId,tabKey:i.tabKey,routeId:i.routeId},muted:r?r(i):!1})),[e,r]);return bk(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(d=>{const p=Date.now(),u={};for(const[m,f]of Object.entries(d))p-f<5e3&&(u[m]=f);return Object.keys(u).length===Object.keys(d).length?d:u})},5500);return()=>clearTimeout(c)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;a(d=>{const p=d.filter(u=>u.timestamp>c).slice(-100);return p.length===d.length?d:p})},6e4);return()=>clearInterval(i)},[a]),null}function eu(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function Nn(e){const t=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1],n=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,a=eu(t==null?void 0:t.receivedAt)||eu(t==null?void 0:t.timestamp)||0;return Math.max(n,a)}function fl(e,t=0){return Nn(e)||e.lastUpdated||t||0}function Rh(e){return Nn(e)||e.lastUpdated||0}function Eh(e,t,n=Rh){const a=n(t)-n(e);if(a!==0)return a;const r=(e.machineName||"").localeCompare(t.machineName||"");if(r!==0)return r;const o=e.displayPrimary.localeCompare(t.displayPrimary);if(o!==0)return o;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function gl(e){var n;const t=os(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function iN(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!gl(e)&&!e.title.trim()}function lN(e){return e.length===0?null:[...e].sort((t,n)=>{const a=Number(gl(n))-Number(gl(t));if(a!==0)return a;const r=n.messages.length-t.messages.length;return r!==0?r:Eh(t,n)})[0]||null}function ws(e,t){const n=e.filter(i=>i.routeId===t);if(n.length===0)return null;const a=n.find(i=>i.streamSource==="native")||null,r=n.filter(i=>i.streamSource==="agent-stream"),o=lN(r);return a?o&&iN(a)?o:a:o||n[0]||null}function cN(e){const t=e.filter(r=>r.type!=="adhdev-daemon"),n=new Set;for(const r of t){if(!tl(r))continue;const o=dm(r);o&&n.add(o)}const a=new Map;for(const r of t){const o=K0(r,n),i=a.get(o);if(!i){a.set(o,r);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),d=c(i),p=c(r),u=p>d||p===d&&(r.timestamp||0)>(i.timestamp||0)?r:i;a.set(o,dN(u,u===r?i:r))}return Array.from(a.values())}function dN(e,t){const n=tl(t),a=tl(e);if(!n&&!a)return e;const r=a?n?void 0:t:e,o=a?e:n?t:void 0,i=r&&String(r.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,d=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...d&&!a&&{settings:{...d,...e.settings??{}}}}}function ni(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function uN(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function tu(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],a=n?uN(ta(n.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((n==null?void 0:n.id)||""),String((n==null?void 0:n.index)??""),String((n==null?void 0:n.receivedAt)??(n==null?void 0:n.timestamp)??""),a].join(":")}function pN(e){const t=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),tu(e.activeChat),...t.map(n=>[n.id||"",n.providerSessionId||"",n.transport||"",n.mode||"",n.status||"",n.title||"",n.lastMessageHash||"",String(n.lastMessageAt||""),n.lastMessagePreview||"",n.lastMessageRole||"",String(n.lastUpdated||""),tu(n.activeChat)].join(":"))].join("|")}function mN(e,t){const n=Date.now();return e.map(a=>{const r=t[a.tabKey];return r&&n-r<5e3?{...a,messages:[],title:""}:a})}function hN(e,t){const n=new Map;for(const a of e){const r=t.get(a.routeId)||a;for(const o of Ma({routeId:a.routeId}))n.set(o,r);for(const o of Ma({providerSessionId:a.providerSessionId,sessionId:a.sessionId}))n.set(o,a.streamSource==="native"?r:a);for(const o of Ma({tabKey:a.tabKey}))n.set(o,a)}return n}function fN(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function gN(e){const t=fN(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const n=String(t.role||""),a=ta(t.content).slice(0,240);return`${e.messages.length}:${n}:${a}`}function bN({ides:e,connectionStates:t,clearedTabs:n}){const a=l.useMemo(()=>cN(e),[e]),r=l.useMemo(()=>em(e),[e]),o=l.useMemo(()=>hh(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),p=l.useRef(new Map),u=l.useRef(new Map),m=l.useMemo(()=>{const C=new Map,v=[];for(const A of a){const{connectionState:T="new",machineName:I}=fh(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),P=pN(A),M=p.current.get(A.id);if(M&&M.ide===A&&M.sourceSignature===P&&M.connectionState===T&&M.machineName===I){C.set(A.id,M),v.push(...M.conversations);continue}const E=ic(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),D={ide:A,sourceSignature:P,connectionState:T,machineName:I,conversations:E};C.set(A.id,D),v.push(...E)}p.current=C;const w=new Map,j=A=>{const T=gN(A),I=u.current.get(A.tabKey);if(I&&I.signature===T)return w.set(A.tabKey,I),I.timestamp;const P={signature:T,timestamp:Rh(A)||(I==null?void 0:I.timestamp)||0};return w.set(A.tabKey,P),P.timestamp},N=[...v].sort((A,T)=>Eh(A,T,j));return u.current=w,N},[a,t,o]),f=l.useMemo(()=>{const C=mN(m,n);return ni(i.current,C)?i.current:(i.current=C,C)},[m,n]),g=l.useMemo(()=>{const C=new Map,v=Array.from(new Set(f.map(w=>w.routeId)));for(const w of v){const j=ws(f,w);j&&C.set(w,j)}return C},[f]),k=l.useMemo(()=>{const C=new Map;for(const v of f){const w=g.get(v.routeId),j=v.streamSource==="native"&&w?w:v;for(const N of Ma({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))C.set(N,j)}return C},[f,g]),h=l.useMemo(()=>hN(f,g),[f,g]),b=l.useCallback(C=>{if(C)return k.get(C)},[k]),S=l.useCallback(C=>{if(C)return h.get(C)},[h]),x=l.useMemo(()=>{const C=f.filter(v=>!rn(v,r).surfaceHidden);return ni(c.current,C)?c.current:(c.current=C,C)},[f,r]),y=l.useMemo(()=>{const C=x.map(v=>v.tabKey);return ni(d.current,C)?d.current:(d.current=C,C)},[x]);return{chatIdes:a,conversations:f,visibleConversations:x,visibleTabKeys:y,resolveConversationBySessionId:b,resolveConversationByTarget:S}}function xN({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:n,setSearchParams:a}){const r=l.useMemo(()=>{var c;return e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),o=l.useMemo(()=>{var c;return!e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),i=l.useCallback(()=>{t&&a(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[a,t]);return{requestedDesktopTabKey:r,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function vN({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:a}){l.useEffect(()=>{ft.setIdes(e)},[e]),l.useEffect(()=>{ft.setResolveAction((r,o,i)=>{t(r,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const r=ft.onToast(o=>{n(c=>c.some(p=>p.message===o.message&&o.timestamp-p.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>n(c=>c.filter(d=>d.id!==o.id)),i)});return()=>{r()}},[n]),l.useEffect(()=>{const r=Zm.on("status_event",o=>{ft.handleRawEvent(o,"ws")});return()=>{r()}},[]),l.useEffect(()=>{var o;const r=i=>{var h;const c=i.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,p=a(d),u=(p==null?void 0:p.routeId)||c.daemonId;if(!u)return;const m=Number(c.buttonIndex),f=c.button||((h=p==null?void 0:p.modalButtons)==null?void 0:h[m])||"Approve",g=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(u,"resolve_action",{action:k?"approve":"reject",button:f,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(b=>console.error("[SW Action] approval failed:",b))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",r),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",r)}},[a,t])}const yN="adhdev_dashboardLayout_v1",wN="adhdev_dashboardDockview_v1",kN="adhdev_dashboardDockviewHiddenRestore_v1",va={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function pc(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function SN(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function _h(e){return`${yN}:${e}`}function CN(e){const t=_h(e);return pc(t,null)}function jN(e,t){try{const n=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,a=_h(e);if(n){localStorage.removeItem(a);return}localStorage.setItem(a,JSON.stringify(t))}catch{}}function Hh(e){return`${wN}:${e}`}function NN(e){const t=Hh(e);return pc(t,null)}function AN(e,t){try{const n=Hh(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function $h(e){return`${kN}:${e}`}function TN(e){const t=$h(e);return pc(t,{})}function MN(e,t){try{const n=$h(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function PN(){return{groupAssignments:[...va.groupAssignments],focusedGroup:va.focusedGroup,groupActiveTabIds:{...va.groupActiveTabIds},groupTabOrders:{...va.groupTabOrders},groupSizes:[...va.groupSizes]}}function DN(e,t){return e?e.length===t.length&&e.every((n,a)=>n===t[a]):t.length===0}function IN(){const[e]=l.useState(()=>SN(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[a,r]=l.useState(0),[o,i]=l.useState({}),[c,d]=l.useState({}),[p,u]=l.useState([]),[m,f]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,k]=l.useState(!1),h=l.useCallback(()=>{if(g)return;const A=CN(e)??PN();n(new Map(A.groupAssignments)),r(A.focusedGroup),i(A.groupActiveTabIds),d(A.groupTabOrders),u(A.groupSizes),k(!0)},[g,e]);l.useEffect(()=>{g&&jN(e,{groupAssignments:[...t.entries()],focusedGroup:a,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[g,e,t,a,o,c,p]),l.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),T=I=>f(I.matches);return A.addEventListener("change",T),()=>A.removeEventListener("change",T)},[]);const b=l.useCallback(A=>{n(A)},[]),S=l.useCallback(A=>{r(A)},[]),x=l.useCallback(A=>{i(A)},[]),y=l.useCallback(A=>{d(A)},[]),C=l.useCallback(A=>{u(A)},[]),v=l.useCallback(A=>{S(A)},[S]),w=l.useCallback((A,T)=>{i(I=>(I[A]??null)===(T??null)?I:{...I,[A]:T})},[]),j=l.useCallback((A,T)=>{d(I=>{const P=I[A];return DN(P,T)?I:{...I,[A]:T}})},[]),N=l.useCallback((A,T)=>{const I=T.get(A)??0;return w(I,A),v(I),I},[v,w]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:b,focusedGroup:a,updateFocusedGroup:S,focusGroup:v,groupActiveTabIds:o,updateGroupActiveTabIds:x,setGroupActiveTab:w,groupTabOrders:c,updateGroupTabOrders:y,setGroupTabOrder:j,groupSizes:p,updateGroupSizes:C,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:h,focusConversationTab:N}}function LN(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],a=bo(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function RN({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:a,hasHydratedStoredLayout:r,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:p,isRefreshingHistory:u,ides:m,handleRefreshHistory:f}){const g=l.useRef(!1),k=l.useRef(!1),h=l.useRef(null),b=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!r){o();return}const S=n(e);S&&(i(S.tabKey,a),g.current=!0,k.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),c(x=>{const y=new URLSearchParams(x);return y.delete("activeTab"),y},{replace:!0}))},[e,t,n,a,r,o,i,c]),l.useEffect(()=>{if(!(k.current||r)&&t.length!==0){if(!e){o(),k.current=!0;return}if(g.current){k.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(k.current||r)&&(o(),k.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,t.length,r,o]),l.useEffect(()=>{if(!d){b.current=!1;return}if(!p||b.current||u)return;const S=m.find(x=>x.id===p.routeId);S&&(!S.chats||S.chats.length===0||LN(S.chats,p))&&(b.current=!0,f())},[d,p,u,m,f])}function ai(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0];if((n==null?void 0:n.active)===!0)return!0;const a=bo(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function Fh({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:a,setToasts:r,setClearedTabs:o}){const[i,c]=l.useState(!1),[d,p]=l.useState(!1),u=l.useCallback(async k=>{try{await e("standalone","launch_ide",{ideType:k,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),m=l.useCallback(async(k,h)=>{try{const b=k||(t==null?void 0:t.daemonId)||"",S=await e(b,"switch_chat",{id:h,sessionId:h,...wn(t)}),x=S==null?void 0:S.result;if((S==null?void 0:S.success)===!0||x==="switched"||x==="switched-by-title")return;x===!1||x==="not_found"?qn(r,"⚠️ Session tab not found — try refreshing history"):typeof x=="string"&&x.startsWith("error:")?qn(r,`⚠️ Switch error: ${x}`):qn(r,"⚠️ Session switch failed")}catch(b){console.error("Switch failed",b),qn(r,`❌ Switch failed: ${b.message||"connection error"}`)}},[t,e,r]),f=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const k=kn(t);await e(k,"new_chat",{...wn(t)}),xC(k,t.sessionId,bo(t)[0]),o(h=>({...h,[t.tabKey]:Date.now()}))}catch(k){console.error("New chat failed",k)}finally{c(!1)}}},[t,i,e,o]),g=l.useCallback(async()=>{var k,h;if(!(!t||d)){p(!0);try{const b=kn(t),S=async()=>e(b,"list_chats",{forceExpand:!0,...wn(t)});let x=await S(),y=(x==null?void 0:x.chats)||((k=x==null?void 0:x.result)==null?void 0:k.chats);ai(y,t)&&(await new Promise(C=>setTimeout(C,450)),x=await S(),y=(x==null?void 0:x.chats)||((h=x==null?void 0:x.result)==null?void 0:h.chats)),x!=null&&x.success&&Array.isArray(y)&&(a(t.routeId,y),ai(y,t)&&!ai(n,t)&&qn(r,"⚠️ History dialog did not fully open — try once more"))}catch(b){console.error("Refresh history failed",b)}finally{p(!1)}}},[t,n,d,e,a,r]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:m,handleNewChat:f,handleRefreshHistory:g}}function EN(e,t){if(e.size!==t.size)return!1;for(const[n,a]of e)if(t.get(n)!==a)return!1;return!0}function _N(e,t){return e.length!==t.length?!1:e.every((n,a)=>n===t[a])}function su(e,t){const n=Object.keys(e),a=Object.keys(t);return n.length!==a.length?!1:n.every(r=>t[Number(r)]===e[Number(r)])}function dr(e,t){const n=new Set(t),a=t.length>0?[0]:[];for(const[i,c]of e)!n.has(i)||c<=0||a.includes(c)||a.push(c);a.sort((i,c)=>i-c);const r={};a.forEach((i,c)=>{r[i]=c}),a.length===0&&(r[0]=0);const o=new Map;for(const[i,c]of e){if(!n.has(i)||c<=0)continue;const d=r[c];typeof d=="number"&&d>0&&o.set(i,d)}return{assignments:o,groupCount:Math.max(1,a.length),mapping:r,usedGroups:a}}function nu(e,t){const n={};for(const[a,r]of Object.entries(e)){const o=t[Number(a)];typeof o=="number"&&(n[o]=r)}return n}function HN(e,t,n){if(t.length===0)return 0;if(typeof n[e]=="number")return n[e];const a=[...t].reverse().find(r=>r<e)??t[0];return n[a]??0}function $N(e,t,n){if(t.length<=1)return[];const a=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),r=a.length===t.length?a:Array(n).fill(100/n),o=r.reduce((i,c)=>i+c,0);return o>0?r.map(i=>i/o*100):Array(n).fill(100/n)}function au(e,t){const n={};for(const[a,r]of Object.entries(e)){const o=Number(a);n[o>=t?o+1:o]=r}return n}function ru(e){return Array(e).fill(100/e)}function FN({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:a,updateGroupTabOrders:r,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:p}){const u=l.useRef(null),m=l.useMemo(()=>dr(e,p),[e,p]),f=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),k=g>1,h=l.useCallback((v,w)=>{t(j=>{const N=new Map(dr(j,p).assignments);return w===0?N.delete(v):N.set(v,w),N}),a(j=>({...j,[w]:v})),n(w)},[t,p,a,n]),b=l.useCallback(v=>{t(w=>{const j=dr(w,p).assignments,N=new Map;for(const[A,T]of j)T!==v&&(T>v?N.set(A,T-1):N.set(A,T));return N}),i(w=>{if(w.length<=1)return[];const j=[...w];j.splice(v,1);const N=j.reduce((A,T)=>A+T,0);return N>0?j.map(A=>A/N*100):[]}),n(0)},[t,p,i,n]),S=l.useCallback((v,w)=>{w.preventDefault();const j=u.current;if(!j)return;const N=w.clientX,A=j.offsetWidth,T=o.length===g?[...o]:ru(g),I=M=>{const D=(M.clientX-N)/A*100,W=[...T];W[v]=Math.max(15,T[v]+D),W[v+1]=Math.max(15,T[v+1]-D),i(W)},P=()=>{document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",P),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",I),document.addEventListener("mouseup",P)},[o,g,i]),x=l.useCallback((v,w,j)=>{if(g>=4)return;const N=j==="left"?w:w+1;t(A=>{const T=dr(A,p).assignments,I=new Map;for(const P of d){const M=T.get(P.tabKey)??0,E=M>=N?M+1:M;E>0&&I.set(P.tabKey,E)}return N>0&&I.set(v,N),I}),i(A=>{const T=A.length===g?[...A]:ru(g),I=T[w]??100/g,P=Math.max(15,I/2),M=Math.max(15,I/2),E=[...T];E[w]=P,E.splice(N,0,M);const D=E.reduce((W,R)=>W+R,0);return E.map(W=>W/D*100)}),a(A=>{const T=au(A,N);return T[N]=v,T}),r(A=>{const T=au(A,N);return T[N]=[v],T}),n(N)},[g,t,p,d,i,a,r,n]);l.useEffect(()=>{EN(e,f)||t(f)},[e,f,t]),l.useEffect(()=>{const{mapping:v,usedGroups:w}=m;a(j=>{const N=nu(j,v);return su(j,N)?j:N}),r(j=>{const N=nu(j,v);return su(j,N)?j:N}),n(j=>{const N=c?0:HN(j,w,v);return j===N?j:N}),i(j=>{const N=c?[]:$N(j,w,m.groupCount);return _N(j,N)?j:N})},[m,c,a,r,n,i]);const y=l.useMemo(()=>{const v=Array.from({length:g},()=>[]);for(const w of d){const j=f.get(w.tabKey)??0,N=Math.min(j,g-1);v[N].push(w)}return v},[d,f,g]),C=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:u,normalizedGroupAssignments:f,numGroups:g,isSplitMode:k,groupedConvs:y,moveTabToGroup:h,closeGroup:b,handleResizeStart:S,splitTabRelative:x,clearAllSplits:C}}function BN({ides:e,sendDaemonCommand:t}){const n="1.0.57",a=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:jo(m,Js(m,n))).sort((m,f)=>Number(Da(f,Js(f,n)))-Number(Da(m,Js(m,n)))),[n,e]),r=l.useMemo(()=>a.some(m=>Da(m,Js(m,n))),[n,a]),o=l.useMemo(()=>a.map(m=>Js(m,n)).find(m=>typeof m=="string"&&m.trim().length>0)||n,[n,a]),[i,c]=l.useState(!1),[d,p]=l.useState({}),u=l.useCallback(async m=>{var k,h;const f=e.find(b=>b.id===m);if(!f)return;p(b=>({...b,[m]:"upgrading"}));const g=No(f);if(!g){p(b=>({...b,[m]:"error"}));return}try{const b=await t(m,"daemon_upgrade",g);(k=b==null?void 0:b.result)!=null&&k.upgraded||(h=b==null?void 0:b.result)!=null&&h.success?p(S=>({...S,[m]:"done"})):p(S=>({...S,[m]:"error"}))}catch{p(b=>({...b,[m]:"error"}))}},[e,t]);return{versionMismatchDaemons:a,hasRequiredVersionDaemons:r,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const Bh=80;function Dr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function WN(e){return{...e,createdAt:Dr(e.createdAt),updatedAt:Dr(e.updatedAt,e.createdAt),lastEventAt:Dr(e.lastEventAt,e.updatedAt||e.createdAt)}}function ON(e){const t=cm(e);return t==="unknown:"?e.id:t}function UN(e){return[e.type,lm(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function GN(e,t=Bh){const n=new Map;for(const a of e){if(a.deletedAt)continue;const r=ON(a),o=n.get(r);if(!o){n.set(r,a);continue}(a.updatedAt>o.updatedAt||a.updatedAt===o.updatedAt&&a.createdAt>o.createdAt)&&n.set(r,a)}return Array.from(n.values()).sort((a,r)=>{const o=r.updatedAt-a.updatedAt;return o!==0?o:r.createdAt-a.createdAt}).slice(0,Math.max(0,t))}function qN(e,t){const n=Date.now(),a=[];for(const r of e){const o=r.sessionId?t.get(r.sessionId):void 0;if(o!=null&&o.surfaceHidden||o!=null&&o.muted)continue;const i=go(r,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=Dr(r.lastMessageAt||(o==null?void 0:o.lastUpdated)||r.lastUpdated,n),p=UN({type:c,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,lastMessageHash:r.lastMessageHash,lastMessageAt:r.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||r.lastUpdated});a.push(WN({id:p,dedupKey:p,type:c,routeId:r.routeId,machineId:r.daemonId||r.routeId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,title:Pm(r),preview:PS(r),createdAt:d,updatedAt:d,lastEventAt:d}))}return GN(a)}function zN(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function KN(e){const{conversations:t,liveSessionInboxState:n,maxItems:a=Bh}=e,r=l.useMemo(()=>qN(t,n).slice(0,Math.max(0,a)),[t,n,a]),o=l.useMemo(()=>zN(r),[r]);return{notifications:r,unreadCount:o}}function VN({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(o=>{const i=e.find(d=>d.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),r=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:n,handleMarkDashboardNotificationUnread:a,handleDeleteDashboardNotification:r}}function mc(...e){const t=new Set,n=[],a=r=>{const o=typeof r=="string"?r.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),n.push(o))};for(const r of e){if(Array.isArray(r)){for(const o of r)a(o);continue}a(r)}return n}function YN(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const n=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(n){const a=n[1].toUpperCase(),r=(n[2]||"").replace(/[\\/]+/g,"\\");return r?`${a}:\\${r}`:`${a}:\\`}return null}function hc(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const a=YN(n);if(a)return a}return"C:\\"}for(const n of t){const a=typeof n=="string"?n.trim():"";if(a)return a}return"~"}function QN(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const n=t.includes("\\")?"\\":"/",a=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(a[0]||"")?a.length<=2?`${a[0]}\\`:a.slice(0,-1).join("\\"):a.length<=2?n:a.slice(0,-1).join(n)||n}function JN(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function fc(e,t,n){const a=await e(t,"file_list_browse",{path:n}),r=JN(a);if(!(r!=null&&r.success))throw new Error((r==null?void 0:r.error)||(a==null?void 0:a.error)||"Could not browse folder");const o=typeof(r==null?void 0:r.path)=="string"?r.path:n,i=o.includes("\\")?"\\":"/",c=(p,u)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${u}`:p==="/"||p==="\\"?`${i}${u}`:`${p.replace(/[\\/]+$/,"")}${i}${u}`,d=Array.isArray(r==null?void 0:r.files)?r.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:c(o,p.name)})).sort((p,u)=>p.name.localeCompare(u.name)):[];return{path:o,directories:d}}function ou(e,t){const n=t.meshId||"",a={meshId:n,workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp",adhdevMcpArgs:t.adhdevMcpArgs||`mcp --mode ipc --repo-mesh ${n}`};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(r,o)=>a[o]||"")}function Wh(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const r=ou(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"}).trim();return!r.includes(`
65
- `)&&!r.startsWith("{")?null:{serverName:n.serverName||"adhdev-mesh",configFormat:n.format,configPathCommand:n.configPathCommand,requiresRestart:n.requiresRestart===!0,instructions:n.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:ou(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function XN(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.instructions=="string"?t.instructions:"",a=typeof t.template=="string"?t.template:"";return!n&&!a?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:n||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:a}}function Wa(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Oh(e){return xo(e)||e.tabKey||e.routeId||null}function Uh(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",n=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",a=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",r=e.conversations.find(o=>{if(a&&o.routeId!==a)return!1;const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||n&&i.includes(n)||a&&o.routeId===a)});if(r!=null&&r.tabKey)return r.tabKey;if(a){const o=ws(e.conversations,a)||e.conversations.find(i=>i.routeId===a);if(o!=null&&o.tabKey)return o.tabKey}return t||n||a||null}function Xs(e){return String(e||"").trim()}function Gh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Zr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ZN(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function eA(e,t){const n=Xs(e.providerSessionId),a=Xs(e.targetSessionId),r=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Xs).filter(Boolean);return!!(n&&i.includes(n)||a&&i.includes(a))});return r?r.tabKey:a||n||null}function tA(e,t,n){if(t.event!=="agent:generating_completed")return null;const a=Gh(t.daemonId);if(a&&a!==e.machineId)return null;const r=Xs(t.providerType);if(e.providerType&&r!==e.providerType)return null;const o=Xs(e.resumeSessionId),i=Xs(e.launchedSessionId),c=Xs(t.providerSessionId),d=Xs(t.targetSessionId);if(o&&o!==c&&o!==d||i&&i!==c&&i!==d)return null;const p=Zr(e.workspacePath);if(p){const u=Zr(t.workspaceName);if(u&&!ZN(u,p))return null}return eA(t,n)}function iu(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function sA({ides:e,conversations:t,onOpenSession:n}){const[a,r]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,r(null)},[]),c=l.useCallback(d=>{o.current=d,r(d)},[]);return l.useEffect(()=>{if(!a)return;const d=Zr(a.workspacePath),p=e.find(m=>{var b,S,x,y;if(!m||m.type==="adhdev-daemon"||Gh(m.daemonId||m.id)!==a.machineId||(Fa(m)?"cli":Xn(m)?"acp":"ide")!==a.kind)return!1;const k=String(m.agentType||m.type||"");if(a.providerType&&k!==a.providerType)return!1;if(a.resumeSessionId)return String(m.providerSessionId||"")===a.resumeSessionId;if(a.launchedSessionId){const C=String(a.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(w=>String(w||"")).filter(Boolean).includes(C)}if(d){const C=Zr(m.workspace||m.runtimeWorkspaceLabel);return C?C===d:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((y=(x=(S=(b=m.activeChat)==null?void 0:b.messages)==null?void 0:S.at)==null?void 0:x.call(S,-1))==null?void 0:y.timestamp)||0)>=a.startedAt-5e3});if(!p)return;const u=Uh({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});u&&(i(),n(u))},[i,t,e,n,a]),l.useEffect(()=>ft.onStatusEvent(d=>{const p=o.current;if(!p)return;const u=tA(p,d,t);u&&(i(),n(u))}),[i,t,n]),l.useEffect(()=>{if(!a)return;const d=window.setTimeout(()=>{r(p=>!p||p.startedAt!==a.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[a]),{trackPendingLaunch:c}}function nA(e,t){var a,r,o,i;const n={cliType:e};return(a=t==null?void 0:t.workspacePath)!=null&&a.trim()?n.dir=t.workspacePath.trim():t!=null&&t.workspaceId?n.workspaceId=t.workspaceId:t!=null&&t.useHome&&(n.useHome=!0),(r=t==null?void 0:t.resumeSessionId)!=null&&r.trim()&&(n.resumeSessionId=t.resumeSessionId.trim()),Array.isArray(t==null?void 0:t.cliArgs)&&t.cliArgs.length>0&&(n.cliArgs=t.cliArgs),(o=t==null?void 0:t.initialModel)!=null&&o.trim()&&(n.initialModel=t.initialModel.trim()),(i=t==null?void 0:t.initialThinkingLevel)!=null&&i.trim()&&(n.initialThinkingLevel=t.initialThinkingLevel.trim()),t!=null&&t.settings&&(n.settings=t.settings),n}function aA(e,t,n){var i,c,d,p;const a={meshId:e.trim()};t.trim()&&(a.cliType=t.trim());const r=(i=n==null?void 0:n.initialModel)==null?void 0:i.trim(),o=(c=n==null?void 0:n.initialThinkingLevel)==null?void 0:c.trim();return r&&(a.initialModel=r),o&&(a.initialThinkingLevel=o),(d=n==null?void 0:n.settings)!=null&&d.autoApproveMode?a.autoApproveMode=n.settings.autoApproveMode:typeof((p=n==null?void 0:n.settings)==null?void 0:p.autoApprove)=="boolean"&&(a.autoApprove=n.settings.autoApprove),a}function rA({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:a,ides:r,setCliViewModeOverrides:o}){const i=Ql(),{launchCli:c}=fo(),d=l.useCallback(async(b,S)=>fc(e,b,S),[e]),p=l.useCallback(async(b,S)=>{if(!S.trim())return{ok:!1,error:"Choose a workspace path first."};try{const x=await e(b,"workspace_add",{path:S.trim()});return x!=null&&x.success?{ok:!0}:{ok:!1,error:(x==null?void 0:x.error)||"Could not save workspace"}}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Could not save workspace"}}},[e]),u=l.useCallback(async(b,S,x)=>{var y;try{const C={ideType:S,enableCdp:!0};(y=x==null?void 0:x.workspacePath)!=null&&y.trim()&&(C.workspace=x.workspacePath.trim());const v=await e(b,"launch_ide",C);return!(v!=null&&v.success)&&(v==null?void 0:v.success)!==void 0?{ok:!1,error:(v==null?void 0:v.error)||"Could not launch IDE"}:(t({machineId:b,kind:"ide",providerType:S,workspacePath:(x==null?void 0:x.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(C){return{ok:!1,error:C instanceof Error?C.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(b,S,x,y)=>{const C=Date.now();try{const v=nA(x,y),w=await c(b,v),j=(w==null?void 0:w.result)||w,N=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return w!=null&&w.success&&N?(t({machineId:b,kind:S,providerType:x,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,launchedSessionId:N,startedAt:C}),{ok:!0}):w!=null&&w.success?(t({machineId:b,kind:S,providerType:x,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:(w==null?void 0:w.error)||(j==null?void 0:j.error)||`Could not launch ${S.toUpperCase()} session`,code:(w==null?void 0:w.code)||(j==null?void 0:j.code)||void 0}}catch(v){return iu(v)?(t({machineId:b,kind:S,providerType:x,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:`Could not launch ${S.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async b=>{var S;if(i!=null&&i.listMeshes)return i.listMeshes(b);if(!b)return[];try{const x=await e(b,"list_meshes",{}),y=(x==null?void 0:x.result)??x;if((y==null?void 0:y.success)===!1)throw new Error((y==null?void 0:y.error)||"Could not load meshes");return(Array.isArray(y==null?void 0:y.meshes)?y.meshes:Array.isArray((S=y==null?void 0:y.result)==null?void 0:S.meshes)?y.result.meshes:[]).map(v=>{var w;return{id:String((v==null?void 0:v.id)||""),name:String((v==null?void 0:v.name)||(v==null?void 0:v.id)||"Untitled mesh"),repoIdentity:(v==null?void 0:v.repoIdentity)||(v==null?void 0:v.repo_identity)||null,workspace:Array.isArray(v==null?void 0:v.nodes)&&v.nodes.length>0?String(((w=v.nodes[0])==null?void 0:w.workspace)||""):null,nodesCount:Array.isArray(v==null?void 0:v.nodes)?v.nodes.length:void 0,status:(v==null?void 0:v.status)||null}}).filter(v=>v.id)}catch(x){throw console.error("List meshes failed",x),x}},[i,e]),g=l.useCallback(async(b,S,x,y)=>{if(!S.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(b,S,x,y);const C=Date.now();try{const v=aA(S,x,y),w=await e(b,"launch_mesh_coordinator",v),j=(w==null?void 0:w.result)??w;if((j==null?void 0:j.success)===!1||(w==null?void 0:w.success)===!1){const A=String((j==null?void 0:j.code)||(w==null?void 0:w.code)||""),T=XN((j==null?void 0:j.meshCoordinatorSetup)||(j==null?void 0:j.manualSetup)||(w==null?void 0:w.meshCoordinatorSetup)||(w==null?void 0:w.manualSetup));return{ok:!1,error:(j==null?void 0:j.error)||(w==null?void 0:w.error)||"Could not launch mesh coordinator",code:A||void 0,manualSetup:T}}const N=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return N?n(N):t({machineId:b,kind:"cli",providerType:(j==null?void 0:j.cliType)||x.trim()||void 0,workspacePath:(j==null?void 0:j.workspace)||null,startedAt:C}),{ok:!0}}catch(v){return iu(v)?(t({machineId:b,kind:"cli",providerType:x.trim()||void 0,startedAt:C}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),k=l.useCallback(async(b,S)=>{if(!b||!S)return[];try{const x=await e(b,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),y=(x==null?void 0:x.result)??x;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(x){return console.error("List saved sessions failed",x),[]}},[e]),h=l.useCallback(async b=>{await Lh({conversation:a,mode:b,ides:r,sendDaemonCommand:e,setCliViewModeOverrides:o})},[a,r,e,o]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:p,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineMeshes:f,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:k,setActiveCliViewMode:h}}function oA(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":return!0;case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function iA(e,t,n=Date.now()){return!e||!oA(t)?null:{tabKey:e,nonce:n}}function lA({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:a,focusedGroup:r,groupedConvs:o,setSearchParams:i}){const[c,d]=l.useState(null),[p,u]=l.useState(null),m=l.useMemo(()=>{var b,S;if(!e){if(c){const x=t.find(y=>y.tabKey===c);if(x)return x}return n[0]}const h=a[r];if(h){const x=t.find(y=>y.tabKey===h);if(x)return x}return((b=o[r])==null?void 0:b[0])||((S=o[0])==null?void 0:S[0])},[t,c,r,a,o,e,n]),f=l.useCallback(h=>{d(h)},[]),g=l.useCallback(h=>{d(h.tabKey),i(b=>{const S=new URLSearchParams(b),x=IS(h);return x?S.set("activeTab",x):S.delete("activeTab"),S},{replace:!0})},[i]),k=l.useCallback((h,b)=>{const S=iA(h,b);S&&u(S)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:k,scrollToBottomRequest:p,setDesktopActiveTab:f}}function cA(e){const t=e.completedKey||null,n=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:n!==null&&n!==e.autoReadKey,nextPendingKey:n===e.autoReadKey?n:null}:n===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:n}:{shouldSchedule:!0,shouldCancelPending:n!==null&&n!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!n,nextPendingKey:null}}function dA(e){const t=String(e.liveState.completionMarker||""),n=String(e.liveState.seenCompletionMarker||""),a=String(e.liveState.inboxBucket||"idle"),r=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,n,a,r?"1":"0"].join(":");return{shouldMarkSeen:!!(a==="task_complete"&&r&&(!t||t!==n)),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function uA({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:a}){const r=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),d=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){p(),r.current=null;return}if(!(e!=null&&e.sessionId)){p(),r.current=null;return}const u=rn(e,n),m=dA({tabKey:e.tabKey,historySessionId:xo(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Nn(e),liveState:u}),f=m.autoReadKey,g=cA({autoReadKey:f,shouldMarkSeen:m.shouldMarkSeen,completedKey:r.current,pendingKey:o.current});if(!m.shouldMarkSeen){g.shouldCancelPending&&p(),r.current=f;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&p();const k=()=>{if(document.visibilityState!=="visible"||r.current===f)return;r.current=f,o.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const b=m.readAt;a(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:b,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(k,1500);const b=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=b,document.addEventListener("visibilitychange",b);return}const h=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(k,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=h,document.addEventListener("visibilitychange",h)},[e,t,n,a]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function ri(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const n=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(n)?n:""}function pA({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:a,sendDaemonCommand:r,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var B;const{launchCli:p}=fo(),[u,m]=l.useState(!1),[f,g]=l.useState([]),[k,h]=l.useState(()=>qt()),[b,S]=l.useState(!1),[x,y]=l.useState(null),C=l.useRef(null),v=l.useMemo(()=>n||t||e,[e,n,t]),w=!!v&&bt(v)&&!ht(v),j=l.useMemo(()=>{if(!v||!w)return null;const _=v.daemonId||v.routeId||"",H=Ds(v),L=ri(v);return`${_}:${H}:${v.providerSessionId||""}:${L}`},[v,w]),N=l.useMemo(()=>!v||!w?"":ri(v),[v,w]),{isCreatingChat:A,isRefreshingHistory:T,handleSwitchSession:I,handleNewChat:P,handleRefreshHistory:M}=Fh({sendDaemonCommand:r,activeConv:v,chats:(B=a.find(_=>_.id===(v==null?void 0:v.routeId)))==null?void 0:B.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),E=l.useCallback(()=>{m(!0)},[]),D=l.useCallback(()=>{m(!1)},[]),W=l.useCallback(async()=>{if(!(!v||!w||b)){S(!0);try{const _=v.daemonId||v.routeId,H=Ds(v),L=ri(v),F=await r(_,"list_saved_sessions",{agentType:H,providerType:H,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},...L?{workspace:L}:{}}),$=(F==null?void 0:F.result)??F;g(Array.isArray($==null?void 0:$.sessions)?$.sessions:[])}catch(_){console.error("Refresh saved sessions failed",_),g([])}finally{S(!1)}}},[v,b,w,r]);l.useEffect(()=>{if(!u){C.current=null;return}if(!w){C.current=null,g([]),S(!1);return}!j||b||C.current!==j&&(C.current=j,W())},[W,u,b,w,j]);const R=l.useCallback(async _=>{if(!v||!w||!_.providerSessionId||!_.workspace)return;const H=v.daemonId||v.routeId,L=Ds(v);try{y(_.providerSessionId);const F=await p(H,{cliType:L,dir:_.workspace,resumeSessionId:_.providerSessionId,initialModel:hm(_.summaryMetadata,"model",{preferShortValue:!0})||void 0}),$=(F==null?void 0:F.result)??F,K=typeof($==null?void 0:$.sessionId)=="string"?$.sessionId:typeof($==null?void 0:$.id)=="string"?$.id:"";K&&d(z=>{const ne=new URLSearchParams(z);return ne.set("activeTab",K),ne},{replace:!0}),D()}catch(F){console.error("Resume saved session failed",F)}finally{y(null)}},[D,v,w,r,d]);return{historyModalOpen:u,openHistoryModal:E,closeHistoryModal:D,historyTargetConv:v,isSavedSessionHistoryTarget:w,isHistoryCreatingChat:A,isHistoryRefreshingHistory:T,handleHistorySwitchSession:I,handleHistoryNewChat:P,handleHistoryRefresh:M,savedHistorySessions:f,savedHistoryFilters:k,setSavedHistoryFilters:h,missingWorkspaceResumePath:N,isSavedHistoryLoading:b,resumingSavedHistorySessionId:x,handleRefreshSavedHistory:W,handleResumeSavedHistorySession:R}}function mA({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}){const[d,p]=l.useState(null),[u,m]=l.useState(null),f=l.useMemo(()=>{if(e||!a)return null;const S=c(a);return S&&!bt(S)&&!ht(S)?S:null},[e,a,c]),g=l.useMemo(()=>{const S=d==null?void 0:d.routeId;if(!S)return null;const x=d!=null&&d.tabKey?o.find(y=>y.tabKey===d.tabKey):r?o.find(y=>y.tabKey===r):null;return(x==null?void 0:x.routeId)===S?x:ws(o,S)},[o,d,r]),k=l.useMemo(()=>{if(g)return i.find(S=>S.id===g.routeId)},[i,g]);l.useEffect(()=>{f&&(p({routeId:f.routeId,tabKey:xd(f)}),m(f),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,f]);const h=l.useCallback(S=>{S&&(p({routeId:S.routeId,tabKey:xd(S)}),m(S))},[]),b=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:k,remoteDialogActiveConv:u,setRemoteDialogActiveConv:m,openRemoteDialog:h,closeRemoteDialog:b}}function hA({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:p}){const{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h}=mA({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}),[b,S]=l.useState(!1),[x,y]=l.useState(null),C=l.useCallback(async j=>{const N=j||d;!N||!bt(N)&&!ht(N)||(y(N),S(!0))},[d]),v=l.useCallback(()=>{S(!1),y(null)},[]),w=l.useCallback(async j=>{const N=x||d;if(!N||!bt(N)&&!ht(N)){v();return}S(!1);try{const A=Ds(N),T=N.routeId||N.daemonId||"";await p(T,"stop_cli",{cliType:A,targetSessionId:N.sessionId,mode:j,...ko(N)})}catch(A){console.error("Stop CLI failed:",A)}finally{y(null)}},[d,v,x,p]);return{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h,cliStopDialogOpen:b,cliStopTargetConv:x,requestCliStop:C,cancelCliStop:v,confirmCliStop:w}}function oi(e,t=!0){return(e??!0)&&t}const gc=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:a,ideEntry:r,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:b,isInputActive:S=!0,isVisible:x=!0}){const y=a,C=!a,v=oi(x,y),w=oi(x,C),j=oi(x),N=Ph(t),A=N.status||N.modalMessage||N.modalButtons?{...t,...N.status?{status:N.status}:{},...N.modalMessage!==void 0?{modalMessage:N.modalMessage}:{},...N.modalButtons!==void 0?{modalButtons:N.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(tm,{activeConv:A,onModalButton:i}),A.transport!=="pty"&&A.transport!=="acp"&&A.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(Ls,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:c,children:"Relaunch with CDP"})]})}):null,A.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!a,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:y?"visible":"hidden",pointerEvents:y?"auto":"none"},children:s.jsx(mj,{activeConv:A,clearToken:n,terminalRef:o,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,isVisible:v,isInputActive:S&&v})}),s.jsx("div",{"aria-hidden":a,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(ll,{activeConv:A,ideEntry:r,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:b,isInputActive:S&&w,isVisible:w})})]}):s.jsx(ll,{activeConv:A,ideEntry:r,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:b,isInputActive:S&&j,isVisible:j})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.handleForceSendChat===t.handleForceSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function fA({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:a,interactive:r=!0,meshOnly:o=!1}){var C,v,w;const{t:i}=ke("common"),c=ia(),d=Vs(e),p=o?null:Mm(e),u=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),m=!o&&e.streamSource==="agent-stream"&&!!e.agentName,f=!o&&!m&&(e.transport==="pty"||e.transport==="acp"),g=sa(e),k=DS(e),h=(C=e.settings)==null?void 0:C.meshNodeFor,b=e.meshQueueStats,S=((v=e.coordinator)==null?void 0:v.meshId)||((w=e.settings)==null?void 0:w.meshCoordinatorFor),x=l.useCallback(()=>{if(a){a();return}d&&c("/dashboard",{state:{openMachineId:d}})},[d,c,a]),y=l.useCallback(()=>{if(n){n();return}const j=Oh(e);j&&c(Wa(j))},[e,c,n]);return!u&&!m&&!f&&!p&&!h&&!b?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:y,title:k,children:[s.jsx(us,{size:12}),s.jsx("span",{children:k})]}):s.jsxs("span",{className:"conversation-meta-chip",title:k,children:[s.jsx(us,{size:12}),s.jsx("span",{children:k})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(_a,{size:12}),s.jsx("span",{children:g})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(_a,{size:12}),s.jsx("span",{children:g})]}),p&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:x,title:p,children:[s.jsx(nn,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(nn,{size:12}),s.jsx("span",{children:p})]})),h&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(nn,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),S&&b&&s.jsxs("span",{className:`conversation-meta-chip ${b.pending>0?"is-active":""}`,style:b.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${b.pending} pending, ${b.assigned} assigned, ${b.completed} completed, ${b.failed} failed`,children:[s.jsx(xb,{size:12}),s.jsxs("span",{children:[b.pending," Pending"]})]})]})}function gA({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:a,actionLogs:r,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:p,onOpenNativeConversation:u,onOpenMachine:m,onOpenHistory:f,onOpenRemote:g,onOpenMeshGraph:k,onStopCli:h,cliViewMode:b,onSetCliViewMode:S,handleSendChat:x,handleForceSendChat:y,handleFocusAgent:C,handleModalButton:v,handleRelaunch:w}){var P,M;const j=l.useRef(null),N=bt(e)&&!t,A=N&&b==="terminal",T=!!e.daemonId&&!!((P=e.coordinator)!=null&&P.meshId||(M=e.settings)!=null&&M.meshCoordinatorFor),I=n?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${I} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(_l,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:kt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(fA,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[N&&b&&s.jsx(oh,{mode:b,onChange:S,compact:!0}),N&&h&&s.jsx("button",{onClick:()=>{h(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Dt,{size:14})}),T&&k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(cs,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx($l,{size:14})}),!t&&!N&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(us,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(gc,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:a,terminalRef:j,handleModalButton:v,handleRelaunch:w,handleSendChat:x,handleForceSendChat:y,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:C,isFocusingAgent:d,actionLogs:r,userName:o})})]})}const ii={unix:{cmd:"curl -fsSL https://adhf.dev/install | sh",shell:"Terminal",prompt:"$ "},powershell:{cmd:"irm https://adhf.dev/install.ps1 | iex",shell:"PowerShell",prompt:"PS> "},cmd:{cmd:"curl -fsSL https://adhf.dev/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd",shell:"CMD",prompt:"> "}};function bA(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function qh(){const[e,t]=l.useState("unix"),[n,a]=l.useState("powershell"),[r,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(bA())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(ii[i].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[i]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("powershell"),children:"PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:c,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:ii[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:ii[i].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:r?s.jsx(co,{size:12}):s.jsx(Hl,{size:12})})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function zh({section:e,onSectionChange:t}){const{t:n}=ke("common"),a=[{key:"machines",label:n("nav.machines"),icon:us},{key:"chats",label:n("nav.chats"),icon:Is}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:a.map(({key:r,label:o,icon:i})=>{const c=e===r;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(r),type:"button","aria-pressed":c,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(i,{size:15})}),s.jsx("span",{children:o})]},r)})})})}function ur({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function Bn({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function hn({icon:e,title:t,subtitle:n,children:a}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:n}),a]})}function xA({conversation:e,onCancel:t,onConfirm:n}){const{t:a}=ke(),r=kt(e);return s.jsx(Vt,{children:s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:t,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"card fade-in mobile-compact-dialog relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base md:text-lg font-extrabold",children:a("mobileInbox.hideTitle",{title:r})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:a("mobileInbox.hideDescription")})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:n,className:"btn btn-primary w-full justify-center min-h-[42px]",children:a("mobileInbox.hide")}),s.jsx("button",{onClick:t,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:a("common.cancel")})]})]})]})})}function pr({item:e,type:t,getAvatarText:n,onOpenConversation:a,onRequestHideConversation:r,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:d,onToggleMute:p}){const{t:u}=ke(),m=t==="needs_attention"||t==="task_complete",f=t==="working",g=t==="earlier",k=t==="task_complete",{isReconnecting:h,isConnecting:b}=En(e.conversation),S=kt(e.conversation),x=na(e.conversation),y=sh(e.conversation,{requiresAction:t==="needs_attention"}),C=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":f?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":g?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",v=m?"bg-accent-primary shadow-glow":f?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":g?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",w=g?"text-text-secondary":"text-text-primary",j=g?"text-text-muted":"text-text-secondary",N=g?"text-text-secondary opacity-80":"text-text-muted",A=g?"text-text-muted opacity-80":"text-text-muted",T=!f&&!k,I=eh(e.conversation),P="text-[color:var(--status-warning)]",M=E=>{if(!c)return;E.preventDefault(),E.stopPropagation();const D=c==null?void 0:c(e.conversation);Promise.resolve(D).catch(W=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",W)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${C}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||f?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${v}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(S)}),I&&i&&s.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:E=>{E.preventDefault(),E.stopPropagation(),i(e.conversation)},"aria-label":u("mobileInbox.openMeshGraphFor",{title:S}),title:u("mobileInbox.openLiveMeshGraph"),children:s.jsx(cs,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>a(e.conversation),onContextMenu:M,type:"button",children:[s.jsx("div",{className:"flex items-center gap-2 pr-[124px]",children:s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${w}`,children:S})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${j}`,children:[s.jsx("span",{className:"truncate",children:x}),s.jsx(qr,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),h?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${P} animate-pulse`,children:u("mobileInbox.reconnectingItem")})]}):b?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:u("mobileInbox.connectingItem")})]}):y==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:P,children:u("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${N}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[T&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${A}`,children:Zp(e.timestamp)}),k&&s.jsx("span",{className:"rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:u("mobileInbox.done")}),p&&s.jsx("button",{type:"button",className:`mobile-inbox-mute-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${d?"border-amber-500/60 bg-amber-500 text-white hover:bg-amber-600":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:E=>{E.preventDefault(),E.stopPropagation(),p()},"aria-label":d?u("mobileInbox.unmute",{title:S}):u("mobileInbox.mute",{title:S}),title:u(d?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:d?s.jsx(Ip,{size:13}):s.jsx(la,{size:13})}),r&&s.jsx("button",{type:"button",className:"mobile-inbox-hide-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:E=>{E.preventDefault(),E.stopPropagation(),r()},"aria-label":u("mobileInbox.hideConversationAria",{title:S}),title:u("mobileInbox.hideConversationTitle"),children:s.jsx(mo,{size:13})}),o&&s.jsx("button",{type:"button",className:"mobile-inbox-stop-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-status-error/30 bg-bg-primary/70 text-status-error transition-colors hover:border-status-error/60 hover:bg-status-error/10",onClick:E=>{E.preventDefault(),E.stopPropagation(),o()},"aria-label":u("mobileInbox.stopSessionAria",{title:S}),title:u("mobileInbox.stopSessionTitle"),children:s.jsx(Dt,{size:13})})]})]})},e.conversation.tabKey)}function lu({count:e,label:t}){return e<=0?null:s.jsxs("span",{className:"inline-flex items-center gap-1.5 text-accent-primary","aria-live":"polite",children:[s.jsxs("span",{className:"relative flex h-2 w-2 shrink-0",children:[s.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-accent-primary/60"}),s.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-accent-primary"})]}),s.jsx("span",{className:"font-semibold",children:t})]})}function vA({section:e,attentionItems:t,unreadItems:n,workingItems:a,completedItems:r,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:p,onOpenConversation:u,onShowAllHidden:m,onHideConversation:f,onOpenMeshGraph:g,onStopCli:k,onOpenNewSession:h,onOpenMachine:b,onOpenSettings:S,onSectionChange:x,wsStatus:y="connected",initialDataLoaded:C=!0,conversationsLoaded:v,isStandalone:w=!1,onCollectChatDebugBundle:j,isConversationMuted:N,onToggleMuteConversation:A}){const{t:T}=ke(),[I,P]=l.useState(null),M=y==="disconnected"||y==="reconnecting"||y==="offline"||y==="auth_failed",E=!M&&!C,D=!M&&!(v??C),W=i.length>0,R=t.length>0||n.length>0||a.length>0||r.length>0,B=T(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),_=w?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",H=w?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",L=l.useCallback(async K=>{const z=kn(K);if(!z)return;const ne=Array.isArray(K.messages)?K.messages:[],ie=_m({activeConv:K,visibleMessages:ne,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:ne.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),Ce=await p(z,"get_chat_debug_bundle",{...wn(K),delivery:"daemon_file",frontendSnapshot:ie}),me=Pa(Ce),O=Fm(me),Y=await $m(O);Y==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ft.showToast(Hm(me,{locatorCopyStatus:Y}),Y==="failed"?"warning":"success")},[d,p]),F=j||L,$=l.useCallback(()=>{I&&(f==null||f(I),P(null))},[I,f]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${_}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:B}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||n.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(la,{size:13}),s.jsx("span",{children:t.length+n.length})]}),s.jsx("button",{onClick:S,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(Ua,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${H}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:M?s.jsx(hn,{icon:s.jsx(ls,{size:32}),title:T(y==="offline"?"mobileInbox.networkOffline":y==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:T(y==="offline"?"mobileInbox.waitingForNetwork":y==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):E?s.jsx(hn,{icon:s.jsx(ls,{size:32}),title:T("mobileInbox.loading"),subtitle:T("mobileInbox.loadingSubtitle")}):i.length===0?s.jsx(hn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:T(w?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:T(w?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!w&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(qh,{})})}):s.jsx(Bn,{children:i.map((K,z)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${z>0?"border-t border-border-subtle/70":""}`,onClick:()=>b(K.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:c(K.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:K.label}),s.jsxs("span",{className:"flex items-center gap-2 text-[11px] font-medium text-text-muted shrink-0",children:[s.jsx(lu,{count:K.generatingCount,label:T("mobileInbox.generatingCount",{count:K.generatingCount})}),K.unread>0?s.jsx("span",{className:"text-accent-primary",children:T("mobileInbox.newCount",{count:K.unread})}):K.total>0?T("mobileInbox.chatCount",{count:K.total}):T("mobileInbox.idle")]})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:K.subtitle}),K.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[T("mobileInbox.chatCount",{count:K.total}),K.unread>0?T("mobileInbox.unreadSuffix",{count:K.unread}):"",K.generatingCount>0?T("mobileInbox.collapsedGeneratingSuffix",{count:K.generatingCount}):""]}):K.generatingCount>0?s.jsx("div",{className:"text-[13px] text-accent-primary mt-0.5 font-medium",children:T("mobileInbox.generatingCount",{count:K.generatingCount})}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:T("mobileInbox.noActiveChats")})]})]},K.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(ur,{title:T("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(Bn,{children:t.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(pr,{item:K,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:A?()=>A(K.conversation):void 0})},K.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(ur,{title:T("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(Bn,{children:n.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(pr,{item:K,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:A?()=>A(K.conversation):void 0})},K.conversation.tabKey))})]}),e==="chats"&&a.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(ur,{title:T("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(Bn,{children:a.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(pr,{item:K,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:A?()=>A(K.conversation):void 0})},K.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[r.length>0&&s.jsx(ur,{title:T("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),r.length>0?s.jsx(Bn,{children:r.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(pr,{item:K,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:A?()=>A(K.conversation):void 0})},K.conversation.tabKey))}):R?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:T("mobileInbox.allCaughtUp")}):M?s.jsx(hn,{icon:s.jsx(ls,{size:28}),title:T("mobileInbox.connecting"),subtitle:T("mobileInbox.connectingSubtitle")}):D?s.jsx(hn,{icon:s.jsx(ls,{size:28}),title:T("mobileInbox.loading"),subtitle:T("mobileInbox.loadingSubtitle")}):W?s.jsx(hn,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(Is,{size:20})}),title:T("mobileInbox.noConversations"),subtitle:T("paneGroup.newSessionDescription"),children:h&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":T("paneGroup.newSession"),title:T("paneGroup.newSession"),children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:T("paneGroup.newSession")})]})}):s.jsx(hn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:T("mobileInbox.noMachinesConnected"),subtitle:T("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&(()=>{const K=Dx(o);return s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(Bn,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:T("mobileInbox.hiddenTabs")}),s.jsx(lu,{count:K,label:T("mobileInbox.generatingCount",{count:K})})]}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[T("mobileInbox.collapsedCount",{count:o.length}),K>0?T("mobileInbox.collapsedGeneratingSuffix",{count:K}):""]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:m,children:T("mobileInbox.restoreAll")})]})})})})()]}),e==="chats"&&h&&R&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:h,"aria-label":T("paneGroup.newSession"),title:T("paneGroup.newSession"),children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),I&&s.jsx(xA,{conversation:I,onCancel:()=>P(null),onConfirm:$}),s.jsx(zh,{section:e,onSectionChange:x})]})}function yA(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function Kh(e){const t=[e.workspace||"Workspace unknown"],n=Mn(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const a=yA(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:a?`Updated ${a}`:"",preview:(e.preview||"").trim()}}function bc({title:e,description:t,currentPath:n,directories:a,busy:r=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:d,onConfirm:p}){const[u,m]=l.useState(n),{t:f}=ke("common");l.useEffect(()=>{m(n)},[n]);const g=QN(n),k=u.trim();return s.jsx(Vt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:c,"aria-label":"Close folder browser",children:s.jsx(Dt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!g||r||d(g)},disabled:!g||r,children:[s.jsx(_l,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:f("machine.workspaceBrowse.currentFolder")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:h=>m(h.target.value),onKeyDown:h=>{h.key!=="Enter"||!k||r||(h.preventDefault(),d(k))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!k||r||d(k)},disabled:!k||r,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:r?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):a.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:a.map(h=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(h.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Tn,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:h.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:h.path})]})]},h.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(k||n),disabled:!k&&!n||r,children:i})]})]})})})}function Ao({title:e,description:t,details:n,workspaceOptions:a,selectedWorkspaceKey:r,onWorkspaceChange:o,confirmLabel:i,busyLabel:c,busy:d=!1,showArgsInput:p,argsValue:u,onArgsChange:m,showModelInput:f,modelValue:g,onModelChange:k,historyProviderNode:h,onConfirm:b,onCancel:S}){const{t:x}=ke("common"),y=i??x("machine.launchConfirm.launch"),C=c??x("machine.launchConfirm.launching"),v=a==null?void 0:a.find(j=>j.key===r),w=s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:S,"aria-label":x("machine.launchConfirm.closeAria"),children:s.jsx(Dt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[a&&a.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:x("machine.launchConfirm.workspace")}),s.jsx("select",{value:r||"",onChange:j=>o(j.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:a.map(j=>s.jsx("option",{value:j.key,children:j.label},j.key))}),(v==null?void 0:v.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v.description})]}),h,n.map(j=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:j.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:j.value})]},`${j.label}:${j.value}`)),f&&k&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:x("machine.launchConfirm.languageModel")}),s.jsx("input",{type:"text",value:g||"",onChange:j=>k(j.target.value),placeholder:x("machine.launchConfirm.autoDetect"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),p&&m&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:x("machine.launchConfirm.cliArgs")}),s.jsx("input",{type:"text",value:u||"",onChange:j=>m(j.target.value),placeholder:x("machine.launchConfirm.cliArgsPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:S,disabled:d,children:x("machine.launchConfirm.cancel")}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:b,disabled:d,children:[s.jsx(Dp,{size:14}),d?C:y]})]})]})});return typeof document>"u"?w:zs.createPortal(w,document.body)}function cu(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Vh(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:a,includeHome:r=!0,homeLabel:o="Home directory",homeDescription:i="Launch without a workspace"}=e,c=[];r&&c.push({key:"__home__",label:o,description:i,workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])c.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${cu(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const d=(n==null?void 0:n.trim())||"",p=d?(t.workspaces||[]).find(u=>u.path===d):null;if(d&&!p&&c.push({key:`custom:${d}`,label:cu(d),description:d,workspaceId:null,workspacePath:d}),a){const u=`saved:${a}`;if(c.some(m=>m.key===u))return{options:c,selectedKey:u}}return p?{options:c,selectedKey:`saved:${p.id}`}:d?{options:c,selectedKey:`custom:${d}`}:{options:c,selectedKey:"__home__"}}function wA(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function kA(e){return[wA(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function SA(e){return e.lastLaunchedAt?za(e.lastLaunchedAt):""}function Yh(e){return{metaText:kA(e),updatedLabel:SA(e)}}function li(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function CA({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:a,onBrowseDirectory:r,onListSavedSessions:o}){var Ie,We,Xe,et;const i=da(),[c,d]=l.useState(!1),p=(((Ie=e.detectedIdes)==null?void 0:Ie.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(J=>({id:J.id,path:J.path,label:J.label})),[e]),m=e.defaultWorkspaceId||null,[f,g]=l.useState(m||((We=u[0])==null?void 0:We.id)||""),[k,h]=l.useState(""),[b,S]=l.useState(""),[x,y]=l.useState([]),[C,v]=l.useState(!1),[w,j]=l.useState(""),[N,A]=l.useState(!1),[T,I]=l.useState(li(p,t.length,n.length)),P=l.useRef(null),[M,E]=l.useState(null),D=l.useRef("__home__"),[W,R]=l.useState("__home__"),[B,_]=l.useState(""),[H,L]=l.useState(""),[F,$]=l.useState(""),[K,z]=l.useState([]),[ne,ie]=l.useState(()=>qt().textQuery),[Ce,me]=l.useState(()=>qt().workspaceQuery),[O,Y]=l.useState(()=>qt().modelQuery),[X,Q]=l.useState(()=>qt().resumableOnly),[ve,he]=l.useState(()=>qt().sortMode),[Z,fe]=l.useState(!1),[V,q]=l.useState(!1),ee=l.useRef(null),pe=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const le=f==="__custom__"?k.trim():((Xe=u.find(J=>J.id===f))==null?void 0:Xe.path)||"",se=f==="__custom__"&&!!le&&a.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(a.message),te=f!=="__custom__"&&((et=u.find(J=>J.id===f))==null?void 0:et.path)||"",ue=l.useMemo(()=>(e.recentLaunches||[]).map(J=>J.workspace),[e]),ye=l.useCallback(async J=>{v(!0),j("");try{const Le=await r(J);S(Le.path),h(Le.path),y(Le.directories)}catch(Le){j(Le instanceof Error?Le.message:"Could not load folder")}finally{v(!1)}},[r]),Me=l.useCallback(()=>{var Le;g("__custom__"),A(!0);const J=hc(e.platform,mc(k.trim(),te,ue,e.defaultWorkspacePath,(Le=u.find($e=>$e.id===m))==null?void 0:Le.path,u.map($e=>$e.path)));ye(J)},[k,m,ye,ue,te,e.platform,u]),re=l.useCallback(J=>{if(J!=null&&J.workspaceId){g(J.workspaceId),h("");return}if(J!=null&&J.workspacePath){g("__custom__"),h(J.workspacePath);return}g(""),h("")},[]),ce=l.useCallback(J=>{if(g(J),J==="__custom__"){Me();return}h("")},[Me]),Ae=l.useCallback(J=>{g("__custom__"),h(J)},[]),be=l.useCallback((J,Le)=>{P.current=Le,D.current=J.selectedWorkspaceKey||"__home__",R(J.selectedWorkspaceKey||"__home__"),_(J.initialArgs||""),L(J.initialModel||""),$(""),z([]);const $e=J.providerType?`${e.id}:${J.providerType}`:null;if(jj(pe.current,$e)){const at=qt();ie(at.textQuery),me(at.workspaceQuery),Y(at.modelQuery),Q(at.resumableOnly),he(at.sortMode)}pe.current=$e,E(J),J.providerType&&o&&(fe(!0),o(J.providerType).then(at=>z(at||[])).catch(at=>console.warn("Failed to load saved sessions",at)).finally(()=>fe(!1)))},[o,e.id]),we=l.useMemo(()=>ih(K,{textQuery:ne,workspaceQuery:Ce,modelQuery:O,resumableOnly:X,sortMode:ve}),[O,X,K,ve,ne,Ce]);l.useEffect(()=>{F&&(we.some(J=>J.providerSessionId===F)||$(""))},[we,F]);const _e=l.useCallback(()=>{P.current&&(q(!0),P.current().finally(()=>{P.current=null,q(!1),E(null)}))},[]),U=l.useCallback(()=>{P.current=null,E(null)},[]),Ne=l.useCallback(J=>{D.current=J,R(J)},[]);return l.useEffect(()=>{var J;ee.current!==e.id&&(ee.current=e.id,g(m||((J=u[0])==null?void 0:J.id)||"__custom__"),h(""),S(""),y([]),j(""),A(!1),ie(qt().textQuery),me(qt().workspaceQuery),Y(qt().modelQuery),Q(qt().resumableOnly),he(qt().sortMode),pe.current=null,I(li(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,u]),l.useEffect(()=>{var J;f!=="__custom__"&&(f&&u.some(Le=>Le.id===f)||g(m||((J=u[0])==null?void 0:J.id)||"__custom__"))},[m,f,u]),l.useEffect(()=>{T==="ide"&&p||T==="cli"&&t.length>0||T==="acp"&&n.length>0||I(li(p,t.length,n.length))},[T,n.length,t.length,p]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:p,workspaceRows:u,defaultWorkspaceId:m,workspaceChoice:f,customWorkspacePath:k,browseCurrentPath:b,browseDirectories:x,browseBusy:C,browseError:w,browseDialogOpen:N,activeLauncherKind:T,launchConfirm:M,launchConfirmWorkspaceKeyRef:D,launchConfirmWorkspaceKey:W,launchConfirmArgs:B,launchConfirmModel:H,launchConfirmResumeId:F,launchConfirmSavedSessions:K,launchConfirmTextFilter:ne,launchConfirmWorkspaceFilter:Ce,launchConfirmModelFilter:O,launchConfirmResumableOnly:X,launchConfirmSortMode:ve,filteredLaunchConfirmSavedSessions:we,launchConfirmSessionsLoading:Z,launchConfirmBusy:V,resolvedWorkspacePath:le,canCreateMissingWorkspace:se,openBrowseDialog:Me,loadBrowsePath:ye,handleWorkspaceChoiceChange:ce,chooseCustomWorkspacePath:Ae,setCustomWorkspacePath:h,setBrowseDialogOpen:A,setActiveLauncherKind:I,openLaunchConfirm:be,handleConfirmLaunch:_e,closeLaunchConfirm:U,setWorkspaceSelectionFromOption:re,setLaunchConfirmWorkspaceKeyAndSync:Ne,setLaunchConfirmArgs:_,setLaunchConfirmModel:L,setLaunchConfirmResumeId:$,setLaunchConfirmTextFilter:ie,setLaunchConfirmWorkspaceFilter:me,setLaunchConfirmModelFilter:Y,setLaunchConfirmResumableOnly:Q,setLaunchConfirmSortMode:he}}function jA({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:a,acpProviders:r,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:d,section:p,showBottomNav:u,onBack:m,onSectionChange:f,onOpenConversation:g,onOpenRecent:k,onOpenMachineDetails:h,onMachineUpgrade:b,onLaunchDetectedIde:S,onAddWorkspace:x,onBrowseDirectory:y,onLaunchWorkspaceProvider:C,onListSavedSessions:v}){const{t:w}=ke("common"),j=R=>R==="ide"?"IDE":R==="cli"?"CLI":"ACP",N=n.slice(0,4),A=t.slice(0,3),T=CA({selectedMachineEntry:e,cliProviders:a,acpProviders:r,machineAction:c,onBrowseDirectory:y,onListSavedSessions:v}),I=l.useMemo(()=>N.map(R=>{const{metaText:B,updatedLabel:_}=Yh(R);return{key:`recent-launch:${R.id}`,primary:R.label,secondary:B,updatedLabel:_,onClick:()=>{const{options:H,selectedKey:L}=Vh({machine:{workspaces:T.workspaceRows,defaultWorkspaceId:T.defaultWorkspaceId},currentWorkspacePath:R.workspace,homeLabel:w("newSession.homeDirectory"),homeDescription:w("newSession.launchWithoutWorkspace")});T.openLaunchConfirm({title:R.kind==="ide"?zr(w,"restart-ide",R.label):R.providerSessionId?ch(w,R.label):zr(w,"start-fresh",R.label),description:R.kind==="ide"?Kr(w,"restart-ide"):R.providerSessionId?dh(w):Kr(w,"start-fresh"),confirmLabel:R.kind==="ide"?Vr(w,"restart-ide"):R.providerSessionId?cl(w,!0):Vr(w,"start-fresh"),busyLabel:R.kind==="ide"?Yr(w,"restart-ide"):R.providerSessionId?lh(w,!0):Yr(w,"start-fresh"),workspaceOptions:H,selectedWorkspaceKey:L,details:[{label:"Mode",value:j(R.kind)},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]},async()=>{const F=H.find($=>$.key===T.launchConfirmWorkspaceKeyRef.current);T.setWorkspaceSelectionFromOption(F),await k({...R,workspace:(F==null?void 0:F.workspacePath)??null})})}}}),[T,k,N,w]),P=l.useMemo(()=>A.map(R=>({key:`recent-chat:${R.conversation.tabKey}`,primary:kt(R.conversation),secondary:QC(R.conversation,{timestampLabel:R.timestamp?Zp(R.timestamp):null}),unread:R.unread,onClick:()=>g(R.conversation)})),[g,A]),M=T.showAllRecent?I:I.slice(0,4),E=I.length>0,D=P.length>0,W=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${W} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx(_l,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:ds(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[D&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:P.map(R=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${R.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:R.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:R.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))})]}),E&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:M.map(R=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:R.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:R.primary}),R.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:R.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))}),I.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>T.setShowAllRecent(R=>!R),children:T.showAllRecent?"Show fewer":`Show ${I.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:b,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:h,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),T.browseDialogOpen&&s.jsx(bc,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:T.browseCurrentPath,directories:T.browseDirectories,busy:T.browseBusy,error:T.browseError,confirmLabel:"Use this folder",onClose:()=>T.setBrowseDialogOpen(!1),onNavigate:R=>{T.loadBrowsePath(R)},onConfirm:R=>{T.chooseCustomWorkspacePath(R),T.setBrowseDialogOpen(!1)}}),T.launchConfirm&&s.jsx(Ao,{title:T.launchConfirm.title,description:T.launchConfirm.description,details:T.launchConfirm.details,workspaceOptions:T.launchConfirm.workspaceOptions,selectedWorkspaceKey:T.launchConfirmWorkspaceKey,onWorkspaceChange:T.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:T.launchConfirm.providerType?cl(w,!!T.launchConfirmResumeId):T.launchConfirm.confirmLabel,busyLabel:T.launchConfirm.providerType?void 0:T.launchConfirm.busyLabel,busy:T.launchConfirmBusy,showArgsInput:T.launchConfirm.showArgsInput,argsValue:T.launchConfirmArgs,onArgsChange:T.setLaunchConfirmArgs,showModelInput:T.launchConfirm.showModelInput,modelValue:T.launchConfirmModel,onModelChange:T.setLaunchConfirmModel,historyProviderNode:T.launchConfirm.providerType&&(T.launchConfirmSessionsLoading||T.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),T.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:oc(w)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:T.launchConfirmTextFilter,onChange:R=>T.setLaunchConfirmTextFilter(R.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmWorkspaceFilter,onChange:R=>T.setLaunchConfirmWorkspaceFilter(R.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmModelFilter,onChange:R=>T.setLaunchConfirmModelFilter(R.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsxs("select",{value:T.launchConfirmSortMode,onChange:R=>T.setLaunchConfirmSortMode(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:T.launchConfirmResumableOnly,onChange:R=>T.setLaunchConfirmResumableOnly(R.target.checked),disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:T.launchConfirmResumeId,onChange:R=>T.setLaunchConfirmResumeId(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Tj(w)}),T.filteredLaunchConfirmSavedSessions.map(R=>s.jsxs("option",{value:R.providerSessionId,disabled:!R.canResume,children:[R.title||R.providerSessionId," ",R.canResume?"":"(workspace missing)"]},R.providerSessionId))]}),!T.launchConfirmSessionsLoading&&T.launchConfirmSavedSessions.length>0&&T.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),T.launchConfirmResumeId&&(()=>{const R=T.filteredLaunchConfirmSavedSessions.find(_=>_.providerSessionId===T.launchConfirmResumeId);if(!R)return null;const B=Kh(R);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:B.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:B.providerSessionId}),s.jsx("div",{className:"mt-1",children:B.metaLine}),B.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:B.updatedLabel}),B.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:B.preview})]})})()]}),onConfirm:T.handleConfirmLaunch,onCancel:T.closeLaunchConfirm}),u&&s.jsx(zh,{section:p,onSectionChange:f})]})}const du=8e3;function NA(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,n=t&&typeof t=="object",a=n&&t.success===!1,r=n&&t.mirrorStale===!0;return!a&&!r?{confirmed:!0}:{confirmed:!1,reason:a&&typeof t.error=="string"?t.error:r?"the coordinator did not confirm the change":"command was rejected"}}function Qh(e,t,n){const a=l.useRef(new Map),[,r]=l.useState(0),o=l.useCallback(()=>r(g=>g+1),[]);l.useEffect(()=>{const g=a.current;if(g.size===0)return;const k=Date.now();let h=!1;for(const[b,S]of g){const x=e.get(b),y=S.muted===void 0||(x?x.muted===S.muted:!1),C=S.hidden===void 0||(x?x.surfaceHidden===S.hidden:!1),v=k-S.at>du;(y&&C||v)&&(g.delete(b),h=!0)}h&&o()},[e,o]),l.useEffect(()=>{if(a.current.size===0)return;const g=setInterval(()=>{const k=a.current,h=Date.now();let b=!1;for(const[S,x]of k)h-x.at>du&&(k.delete(S),b=!0);b&&o(),k.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,k)=>{const h=a.current.get(g);a.current.set(g,{...h,...k,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const k=g.sessionId,h=k?a.current.get(k):void 0;return(h==null?void 0:h.muted)!==void 0?h.muted:rn(g,e).muted??!1},[e]),d=l.useCallback(g=>{const k=g.sessionId,h=k?a.current.get(k):void 0;return(h==null?void 0:h.hidden)!==void 0?h.hidden:rn(g,e).surfaceHidden??!1},[e]),p=l.useCallback((g,k)=>{const h=Vs(g),b=g.sessionId;!h||!b||(i(b,k),t(h,"set_conversation_prefs",{sessionId:b,...k,...ko(g)}).then(S=>{const x=NA(S);x.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",x.reason),a.current.delete(b),o(),n==null||n(`Couldn't update conversation — ${x.reason}`))}).catch(S=>{console.warn("[conversation-prefs] set_conversation_prefs failed",S),a.current.delete(b),o();const x=S instanceof Error?S.message:String(S??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${x}`)}))},[t,i,o,n]),u=l.useCallback(g=>{p(g,{muted:!c(g)})},[p,c]),m=l.useCallback((g,k)=>{p(g,{hidden:k})},[p]),f=l.useCallback(g=>{p(g,{hidden:!d(g)})},[p,d]);return{isMuted:c,isHidden:d,toggleMute:u,setHidden:m,toggleHidden:f}}function Ir(e){return[...e].sort((t,n)=>{const a=n.timestamp-t.timestamp;return a!==0?a:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function AA(e,t=[]){const n=new Map(e.map(r=>[r.conversation.tabKey,r])),a=t.map(r=>n.get(r)).filter(r=>!!r);return a.length===e.length?a:Ir(e)}function TA(e,t=[]){const n=e.filter(i=>i.requiresAction),a=e.filter(i=>i.unread&&!i.requiresAction),r=e.filter(i=>!i.unread&&!i.requiresAction&&i.isWorking),o=e.filter(i=>!i.unread&&!i.requiresAction&&!i.isWorking);return{attentionItems:Ir(n),unreadItems:Ir(a),workingItems:AA(r,t),completedItems:Ir(o)}}function To(e,t){if(!t)return!1;const n=e.filter(a=>a.type==="adhdev-daemon"&&Jh(a)==="Connected");return n.length===0?!0:n.every(a=>a._sessionListAuthoritative===!0)}function Jh(e){var a,r,o;const t=((a=e.p2p)==null?void 0:a.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((r=e.p2p)!=null&&r.available)||!!((o=e.p2p)!=null&&o.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function MA(e,t){if(!e)return[];const n=e.recentLaunches||[];return n.length>0?n.map(a=>({id:a.id,label:a.title||a.providerName||a.providerType,kind:a.kind,providerType:a.providerType,providerSessionId:a.providerSessionId,subtitle:Mn(a.summaryMetadata)||a.workspace||void 0,workspace:a.workspace,summaryMetadata:a.summaryMetadata})):t.filter(a=>a.type!=="adhdev-daemon"&&a.daemonId===e.id).map(a=>{var i;const r=Fa(a)?"cli":Xn(a)?"acp":"ide",o=Mn(a.summaryMetadata);return{id:`${r}:${a.type}:${a.workspace||""}`,label:((i=a.activeChat)==null?void 0:i.title)||(Fa(a)?a.cliName||a.type:Xn(a)&&a.cliName||a.type),kind:r,providerType:a.type,providerSessionId:a.providerSessionId,subtitle:Xn(a)?o||a.workspace||void 0:a.workspace||void 0,workspace:a.workspace||void 0,timestamp:a.lastMessageAt||0}}).sort((a,r)=>r.timestamp-a.timestamp).map(({timestamp:a,...r})=>r)}function PA(e,t,n=[]){const a=new Map;for(const o of t){const i=Vs(o.conversation),c=a.get(i);c?c.push(o):a.set(i,[o])}const r=new Map;for(const o of n){const i=Vs(o),c=r.get(i);c?c.push(o):r.set(i,[o])}return e.map(o=>{const i=a.get(o.id)||[],c=r.get(o.id)||[],d=[...i].sort((h,b)=>b.timestamp-h.timestamp)[0]||null,p=(d==null?void 0:d.conversation)||null,u=sl(o),m=i.filter(h=>h.unread||h.requiresAction).length,f=i.filter(h=>Ha(h.conversation)).length+c.filter(Ha).length,g=Jh(o),k=[o.platform||"machine",g].filter(Boolean);return{id:o.id,label:ds(o,{fallbackId:o.id}),subtitle:k.join(" · "),unread:m,total:i.length,generatingCount:f,latestConversation:p,latestTimestamp:(d==null?void 0:d.timestamp)||0,fallbackActivityAt:u,preview:p?JC(p,Vm(p)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((o,i)=>{const c=o.latestTimestamp||o.fallbackActivityAt||0,d=i.latestTimestamp||i.fallbackActivityAt||0;return d!==c?d-c:o.label.localeCompare(i.label)})}function DA(e){return e==="chat"}function mr(e,t){var n;if(!(typeof window>"u"))try{if(!(!!((n=import.meta.env)!=null&&n.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function IA({conversations:e,machineEntries:t,items:n,selectedConversation:a,selectedTabKey:r,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:k,setScreen:h,setSelectedMachineId:b,setSection:S,setMachineBackTarget:x,resetMachineAction:y}){const C=l.useRef(null),v=l.useCallback(w=>{if(!(w!=null&&w.sessionId))return;const j=rn(w,i),N=Math.max(Date.now(),Nn(w),j.lastUpdated||0);mr("mark_read:start",{tabKey:w.tabKey,sessionId:w.sessionId,displayPrimary:kt(w),inboxBucket:j.inboxBucket,unread:j.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:Nn(w),readAt:N}),c(Vs(w)||w.routeId,"mark_session_seen",{sessionId:w.sessionId,providerSessionId:w.providerSessionId,seenAt:N,completionMarker:j.completionMarker}).then(A=>{mr("mark_read:result",{tabKey:w.tabKey,sessionId:w.sessionId,result:A})}).catch(A=>{mr("mark_read:error",{tabKey:w.tabKey,sessionId:w.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var j;if(!a){DA(o)&&h("inbox"),k(((j=e[0])==null?void 0:j.tabKey)||null),C.current=null;return}if(o!=="chat"){C.current=null;return}const w=`${a.tabKey}:${a.sessionId||""}`;C.current!==w&&(C.current=w,v(a))},[e,v,o,a,h,k]),l.useEffect(()=>{if(!d)return;const w=e.find(j=>j.tabKey===d);w&&(k(w.tabKey),h("chat"),p==null||p())},[e,p,d,h,k]),l.useEffect(()=>{if(!u)return;const w=t.find(j=>j.id===u);w&&(b(w.id),y(),S("machines"),x("inbox"),h("machine"),m==null||m())},[t,m,u,y,x,h,S,b]),l.useEffect(()=>{f&&(S(f),h("inbox"),g==null||g())},[g,f,h,S]),l.useEffect(()=>{const w=n.filter(j=>j.inboxBucket==="task_complete"||j.unread);w.length!==0&&mr("inbox_state",{screen:o,selectedTabKey:r,items:w.map(j=>{const N=rn(j.conversation,i);return{liveState:N,tabKey:j.conversation.tabKey,sessionId:j.conversation.sessionId,displayPrimary:kt(j.conversation),serverBucket:N.inboxBucket,computedBucket:j.inboxBucket,serverUnread:N.unread,computedUnread:j.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:Nn(j.conversation)}})})},[n,i,o,r]),{markConversationRead:v}}function LA(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function uu(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function RA(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function EA({sendDaemonCommand:e,navigate:t,ides:n,conversations:a}){const{launchCli:r}=fo(),[o,i]=l.useState("idle"),[c,d]=l.useState(""),[p,u]=l.useState(null),m=l.useCallback(()=>{i("idle"),d(""),u(null)},[]),f=l.useCallback(async(y,C,v)=>{var w;try{i("loading"),d(`Launching ${C}…`);const j={ideType:C,enableCdp:!0};(w=v==null?void 0:v.workspacePath)!=null&&w.trim()&&(j.workspace=v.workspacePath.trim()),await e(y,"launch_ide",j),i("done"),d(`${C} launch requested`)}catch(j){i("error"),d(j instanceof Error?j.message:"Launch IDE failed"),console.error("Launch IDE failed",j)}},[e]),g=l.useCallback(async(y,C,v)=>{if(C.trim())try{i("loading"),d(v!=null&&v.createIfMissing?"Creating folder…":"Saving workspace…");const w=await e(y,"workspace_add",{path:C.trim(),createIfMissing:(v==null?void 0:v.createIfMissing)===!0});if(w!=null&&w.success){i("done"),d(v!=null&&v.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((w==null?void 0:w.error)||"Could not save workspace")}catch(w){i("error"),d(w instanceof Error?w.message:"Could not save workspace")}},[e]),k=l.useCallback(async y=>{i("loading"),d("Starting daemon upgrade…");const C=n.find(w=>w.id===y||w.daemonId===y),v=await j1(e,y,C);i(v.state),d(v.message)},[n,e]),h=l.useCallback(async(y,C,v,w)=>{var A,T,I;const j=Date.now(),N={machineId:y,kind:C,providerType:v,workspaceId:(w==null?void 0:w.workspaceId)||null,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:j};try{i("loading"),d(`Launching ${v}…`),u(N);const P={cliType:v};(A=w==null?void 0:w.workspacePath)!=null&&A.trim()?P.dir=w.workspacePath.trim():w!=null&&w.workspaceId?P.workspaceId=w.workspaceId:w!=null&&w.useHome&&(P.useHome=!0),w!=null&&w.resumeSessionId&&(P.resumeSessionId=w.resumeSessionId),(T=w==null?void 0:w.args)!=null&&T.trim()&&(P.cliArgs=w.args.trim().split(/\s+/).filter(Boolean)),(I=w==null?void 0:w.model)!=null&&I.trim()&&(P.initialModel=w.model.trim());const M=await r(y,P),E=(M==null?void 0:M.result)||M,D=(E==null?void 0:E.sessionId)||(E==null?void 0:E.id);if(M!=null&&M.success&&D){u(null),i("done"),d(`${v} launched`),t(Wa(D));return}if(M!=null&&M.success){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d((M==null?void 0:M.error)||(E==null?void 0:E.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(P){if(RA(P)){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d(P instanceof Error?P.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),b=l.useCallback(async(y,C)=>{try{const v=await e(y,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),w=(v==null?void 0:v.result)??v;return Array.isArray(w==null?void 0:w.sessions)?w.sessions:[]}catch(v){return console.error("Failed to list saved sessions on mobile:",v),[]}},[e]),S=l.useCallback(async(y,C)=>fc(e,y,C),[e]);l.useEffect(()=>{if(!p)return;const y=uu(p.workspacePath),C=n.find(w=>{var P,M,E,D;if(!w||w.type==="adhdev-daemon"||LA(w.daemonId||w.id)!==p.machineId||(w.transport==="acp"?"acp":w.transport==="pty"?"cli":null)!==p.kind||String(w.agentType||w.type||"")!==p.providerType)return!1;const T=String(w.providerSessionId||"");if(p.resumeSessionId&&T)return T===p.resumeSessionId;if(y){const W=uu(w.workspace||w.runtimeWorkspaceLabel);return W?W===y:!1}return Number(w.lastUpdated||w._lastUpdate||w.timestamp||((D=(E=(M=(P=w.activeChat)==null?void 0:P.messages)==null?void 0:M.at)==null?void 0:E.call(M,-1))==null?void 0:D.timestamp)||0)>=p.startedAt-5e3});if(!C)return;const v=Uh({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:a});v&&(u(null),i("done"),d(`${p.providerType} launched`),t(Wa(v)))},[a,n,t,p]),l.useEffect(()=>{if(!p)return;const y=window.setTimeout(()=>{u(C=>!C||C.startedAt!==p.startedAt?C:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(y)},[p]);const x=l.useCallback(async(y,C)=>{var v;if(C.kind==="ide"&&C.providerType){await f(y,C.providerType,{workspacePath:C.workspace||null});return}if((C.kind==="cli"||C.kind==="acp")&&C.providerType){const w=((v=C.workspace)==null?void 0:v.trim())||"";await h(y,C.kind,C.providerType,{workspacePath:w||null,useHome:!w,resumeSessionId:C.providerSessionId||null})}},[f,h]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:g,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:h,handleListSavedSessions:b,handleBrowseDirectory:S,handleOpenRecent:x}}function _A({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:a,resetMachineAction:r,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:p}){const u=l.useCallback(S=>{o(S.tabKey),i("chat"),a(S)},[a,i,o]),m=l.useCallback(S=>{const x=e.find(y=>y.routeId===S.routeId&&y.streamSource==="native");x&&(o(x.tabKey),i("chat"),a(x))},[e,a,i,o]),f=l.useCallback(()=>{a(t),i("inbox")},[a,t,i]),g=l.useCallback((S,x="inbox")=>{c(S),r(),d("machines"),p(x),i("machine")},[r,p,i,d,c]),k=l.useCallback(S=>{const x=Vs(S);x&&g(x,"chat")},[g]),h=l.useCallback(()=>{r(),i(n)},[n,r,i]),b=l.useCallback(S=>{d(S),i("inbox")},[i,d]);return{openConversation:u,openNativeConversation:m,backFromConversation:f,openMachine:g,openConversationMachine:k,backFromMachine:h,changeMachineSection:b}}function aa(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function HA(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function $A({conversations:e,hiddenConversations:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,onOpenHistory:k,onOpenRemote:h,onStopCli:b,wsStatus:S,isConnected:x,initialDataLoaded:y=!0,onShowAllHiddenConversations:C,onHideConversation:v,onOpenMeshGraph:w,onOpenNewSession:j,liveSessionInboxState:N,setCliViewModeOverrides:A}){const[T,I]=l.useState(()=>{var ce;return((ce=e[0])==null?void 0:ce.tabKey)||null}),[P,M]=l.useState(()=>e[0]?"chat":"inbox"),[E,D]=l.useState("chats"),[W,R]=l.useState(null),[B,_]=l.useState("inbox"),H=l.useRef([]),L=ia(),F="1.0.57",$=l.useMemo(()=>e.find(ce=>ce.tabKey===T)||e[0]||null,[e,T]),K=l.useMemo(()=>$?n.find(ce=>ce.id===$.routeId):void 0,[n,$]),z=l.useMemo(()=>!$||ht($)||!bt($)?null:ca($),[$]),ne=l.useMemo(()=>n.filter(ce=>ce.type==="adhdev-daemon").sort(Kl),[n]),ie=l.useMemo(()=>ne.find(ce=>ce.id===W)||null,[ne,W]),Ce=So({sendDaemonCommand:r,activeConv:$||void 0,setActionLogs:o,isStandalone:i}),me=EA({sendDaemonCommand:r,navigate:L,ides:n,conversations:e}),O=NC(e),Y=l.useMemo(()=>e.map(ce=>{const Ae=P==="chat"&&($==null?void 0:$.tabKey)===ce.tabKey,be=go(ce,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ae}),we=Nn(ce),_e=Vm(ce),U=th(ce,_e);return{conversation:ce,timestamp:we,preview:U,unread:be.unread,requiresAction:be.requiresAction,isWorking:be.isWorking,inboxBucket:be.inboxBucket}}),[e,N,P,$,O]),{markConversationRead:X}=IA({conversations:e,machineEntries:ne,items:Y,selectedConversation:$,selectedTabKey:T,screen:P,liveSessionInboxState:N,sendDaemonCommand:r,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:I,setScreen:M,setSelectedMachineId:R,setSection:D,setMachineBackTarget:_,resetMachineAction:me.resetMachineAction}),Q=_A({conversations:e,selectedConversation:$,machineBackTarget:B,markConversationRead:X,resetMachineAction:me.resetMachineAction,setSelectedTabKey:I,setScreen:M,setSelectedMachineId:R,setSection:D,setMachineBackTarget:_}),{isMuted:ve,toggleMute:he}=Qh(N,r),{attentionItems:Z,unreadItems:fe,workingItems:V,completedItems:q}=l.useMemo(()=>TA(Y,H.current),[Y]);l.useEffect(()=>{H.current=V.map(ce=>ce.conversation.tabKey)},[V]);const ee=l.useMemo(()=>ie?Y.filter(ce=>Vs(ce.conversation)===ie.id):[],[Y,ie]),pe=l.useMemo(()=>MA(ie,n),[n,ie]),le=!!ie&&jo(ie,Js(ie,F)),se=l.useMemo(()=>(ie==null?void 0:ie.availableProviders)||[],[ie]),te=l.useMemo(()=>se.filter(ce=>aa(ce,"cli")).map(ce=>({type:ce.type,displayName:ce.displayName||ce.type,icon:ce.icon})),[se]),ue=l.useMemo(()=>se.filter(ce=>aa(ce,"acp")).map(ce=>({type:ce.type,displayName:ce.displayName||ce.type,icon:ce.icon})),[se]),ye=l.useMemo(()=>PA(ne,Y,t),[Y,ne,t]),Me=l.useMemo(()=>To(n,y),[n,y]),re=l.useCallback(async ce=>{ie&&await me.handleOpenRecent(ie.id,ce)},[me,ie]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:P==="chat"&&$?s.jsx(gA,{selectedConversation:$,isAcp:ht($),isStandalone:i,selectedIdeEntry:K,actionLogs:a,userName:c,isSendingChat:Ce.isSendingChat,sendFeedbackMessage:Ce.sendFeedbackMessage,isFocusingAgent:Ce.isFocusingAgent,handleModalButton:Ce.handleModalButton,handleRelaunch:Ce.handleRelaunch,onBack:Q.backFromConversation,onOpenNativeConversation:Q.openNativeConversation,onOpenMachine:Q.openConversationMachine,onOpenHistory:k,onOpenRemote:h,onOpenMeshGraph:w,onStopCli:b,cliViewMode:z,onSetCliViewMode:async ce=>{await Lh({conversation:$,mode:ce,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:A})},handleSendChat:Ce.handleSendChat,handleForceSendChat:Ce.handleForceSendChat,handleFocusAgent:Ce.handleFocusAgent}):P==="machine"&&ie?s.jsx(jA,{selectedMachineEntry:ie,selectedMachineConversations:ee,selectedMachineRecentLaunches:pe,cliProviders:te,acpProviders:ue,selectedMachineNeedsUpgrade:le,appVersion:F,machineAction:me.machineAction,isStandalone:i,section:E,showBottomNav:B==="inbox",onBack:Q.backFromMachine,onSectionChange:Q.changeMachineSection,onOpenConversation:Q.openConversation,onOpenRecent:re,onOpenMachineDetails:()=>L(`/machines/${ie.id}`),onMachineUpgrade:()=>me.handleMachineUpgrade(ie.id),onLaunchDetectedIde:(ce,Ae)=>me.handleLaunchDetectedIde(ie.id,ce,Ae),onAddWorkspace:(ce,Ae)=>me.handleAddWorkspace(ie.id,ce,Ae),onBrowseDirectory:ce=>me.handleBrowseDirectory(ie.id,ce),onLaunchWorkspaceProvider:(ce,Ae,be)=>me.handleLaunchWorkspaceProvider(ie.id,ce,Ae,be),onListSavedSessions:ce=>me.handleListSavedSessions(ie.id,ce)}):s.jsx(vA,{section:E,attentionItems:Z,unreadItems:fe,workingItems:V,completedItems:q,hiddenConversations:t,machineCards:ye,getAvatarText:HA,actionLogs:a,sendDaemonCommand:r,onOpenConversation:Q.openConversation,onShowAllHidden:C,onHideConversation:v,onOpenMeshGraph:w,onStopCli:b,onOpenNewSession:j,onOpenMachine:Q.openMachine,onOpenSettings:()=>L("/settings"),onSectionChange:D,wsStatus:S,isConnected:x,initialDataLoaded:y,conversationsLoaded:Me,isStandalone:i,isConversationMuted:ve,onToggleMuteConversation:he})})}function ci(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function FA({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:a,onOwnTabDrop:r,onClearPreviewOrder:o}){const i=l.useRef(0),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useCallback(()=>{i.current=0,d(!1),u(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const f=l.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),g=l.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!ci(t,n)){u("merge");return}const S=b.currentTarget.getBoundingClientRect(),x=b.clientX-S.left,y=S.width/3;x<y?u("split-left"):x>y*2?u("split-right"):u("merge")},[t,n]),k=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),u(null))},[]),h=l.useCallback(b=>{i.current=0,d(!1);const S=b.dataTransfer.getData("text/tab-key"),x=S?e.some(C=>C.tabKey===S):!1,y=p;if(u(null),o(),!!S){if(b.preventDefault(),y==="split-left"&&ci(t,n)){n==null||n(S,"split-left");return}if(y==="split-right"&&ci(t,n)){n==null||n(S,"split-right");return}if(x){r(S);return}a==null||a(S)}},[e,p,t,n,a,r,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:f,handleDragOver:g,handleDragLeave:k,handleDrop:h}}function BA(e,t){const n=new Set(t.map(o=>o.tabKey)),a=e.filter(o=>n.has(o)),r=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...a,...r]}function WA({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:a,onTabOrderChange:r}){const[o,i]=l.useState(t??null),[c,d]=l.useState(n??[]),[p,u]=l.useState(null),m=l.useRef(null),f=l.useRef(null),g=l.useRef(a),k=l.useRef(r);l.useEffect(()=>{g.current=a},[a]),l.useEffect(()=>{k.current=r},[r]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(j=>{const N=BA(j,e);return N.length===j.length&&N.every((A,T)=>A===j[T])?j:N})},[e]);const h=l.useMemo(()=>{const j=p??c;if(j.length===0)return e;const N=new Map(j.map((A,T)=>[A,T]));return[...e].sort((A,T)=>{const I=N.get(A.tabKey)??999,P=N.get(T.tabKey)??999;return I-P})},[e,p,c]);l.useEffect(()=>{var N,A;if(h.length===0){o!==null&&(i(null),(N=g.current)==null||N.call(g,null));return}if(o&&h.some(T=>T.tabKey===o))return;const j=h[0].tabKey;j!==o&&(i(j),(A=g.current)==null||A.call(g,j))},[h,o]);const b=l.useMemo(()=>h.find(j=>j.tabKey===o),[h,o]),S=l.useCallback(j=>{var N;i(j),(N=g.current)==null||N.call(g,j)},[]),x=l.useCallback((j,N,A)=>{d(T=>{var E;const I=T.filter(D=>D!==j),P=I.indexOf(N);if(P<0)return T;const M=A==="left"?P:P+1;return I.splice(M,0,j),(E=k.current)==null||E.call(k,I),I}),u(null)},[]),y=l.useCallback((j,N,A)=>{const I=(c.length>0?c:e.map(E=>E.tabKey)).filter(E=>E!==j),P=I.indexOf(N);if(P<0)return;const M=A==="left"?P:P+1;I.splice(M,0,j),m.current=I,u(I)},[c,e]),C=l.useCallback(()=>{var N;const j=m.current;j&&(d(j),(N=k.current)==null||N.call(k,j))},[]),v=l.useCallback(()=>{m.current=null,u(null)},[]),w=l.useCallback(j=>{d(N=>{var T;const A=N.filter(I=>I!==j);return A.push(j),(T=k.current)==null||T.call(k,A),A})},[]);return{activeTabId:o,activeConv:b,sortedConversations:h,previewOrderRef:m,draggingTabRef:f,selectTab:S,handleTabReorder:x,updatePreviewOrder:y,commitPreviewOrder:C,clearPreviewOrder:v,moveTabToEnd:w,setDraggingTabKey:j=>{f.current=j}}}function OA({dropAction:e,canSplit:t}){return s.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),s.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function xc({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:a=!1,suppressGuide:r=!1,onOpenNewSession:o,isLoading:i=!1}){const{t:c}=ke("common");if(r)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});if(i)return s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center gap-3 -mt-8 text-text-muted",children:[s.jsx(ls,{}),s.jsx("p",{className:"text-sm",children:c("paneGroup.loadingSessions")})]});const d=!n&&!a,p=a&&!!o,u=c(a?"paneGroup.noConversations":n?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),m=c(a?"paneGroup.newSessionDescription":n?"paneGroup.daemonDescription":"paneGroup.installDescription");return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:u}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),p&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:c("paneGroup.newSession"),"aria-label":c("paneGroup.newSession"),children:[s.jsx(Wl,{size:14}),s.jsx("span",{children:c("paneGroup.newSession")})]})}),d&&s.jsx(qh,{}),d&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const Xh="adhdev-tab-shortcuts";function Zh(){try{return JSON.parse(localStorage.getItem(Xh)||"{}")}catch{return{}}}function ef({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:a}){const r=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>Zh()),[c,d]=l.useState(null),p=l.useCallback(m=>{const f=[];return m.metaKey&&f.push(r?"⌘":"Meta"),m.ctrlKey&&f.push("Ctrl"),m.altKey&&f.push(r?"⌥":"Alt"),m.shiftKey&&f.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(f.push(m.key.length===1?m.key.toUpperCase():m.key),f.join("+"))},[r]),u=l.useCallback(m=>{i(m);try{localStorage.setItem(Xh,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){d(null);return}const g=p(f);if(!g)return;const k={...o};for(const[h,b]of Object.entries(k))b===g&&delete k[h];k[c]=g,u(k),d(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,u,p]),l.useEffect(()=>{if(!e)return;const m=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[g,k]of Object.entries(o))if(t.includes(g)&&p(f)===k){f.preventDefault(),n(),a(g);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,n,a,p]),{isMac:r,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const di=e=>{e.preventDefault()},UA=l.memo(function({conv:t,isActive:n,isDraggedTab:a,isTaskCompleteUnread:r,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:p,onConversationActivated:u,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:g,onClearPreviewOrder:k,onDragStateReset:h,onDragTabKeyChange:b,onReceiveTab:S,onOpenContextMenu:x,longPressTimer:y,isGroupActive:C}){const v=En(t),w=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",j=v.isReconnecting,N=VC(t),A=YC(t),T=eh(t),I=l.useCallback(H=>{c.current=t.tabKey,b(t.tabKey),H.dataTransfer.setData("text/tab-key",t.tabKey),H.dataTransfer.effectAllowed="move"},[t.tabKey,c,b]),P=l.useCallback(()=>{c.current=null,b(null),g(),k(),h()},[c,b,g,k,h]),M=l.useCallback(H=>{const L=c.current;if(!(!L||L===t.tabKey)&&H.dataTransfer.types.includes("text/tab-key")){H.preventDefault(),H.stopPropagation();const F=H.currentTarget.getBoundingClientRect(),$=H.clientX<F.left+F.width/2?"left":"right";m(L,t.tabKey,$)}},[t.tabKey,c,m]),E=l.useCallback(H=>{H.preventDefault(),H.stopPropagation();const L=H.dataTransfer.getData("text/tab-key");if(L&&L!==t.tabKey){const F=H.currentTarget.getBoundingClientRect(),$=H.clientX<F.left+F.width/2?"left":"right";i.includes(L)?f(L,t.tabKey,$):S&&S(L)}k()},[t.tabKey,i,f,S,k]),D=l.useCallback(H=>{H.stopPropagation(),d(),p(t.tabKey),u(t)},[t,u,d,p]),W=l.useCallback(H=>{H.preventDefault(),x(H.clientX,H.clientY,t.tabKey)},[t.tabKey,x]),R=l.useCallback(H=>{const L=H.touches[0];y.current=setTimeout(()=>{x(L.clientX,L.clientY,t.tabKey)},600)},[t.tabKey,y,x]),B=l.useCallback(()=>{y.current&&clearTimeout(y.current)},[y]),_=["adhdev-dockview-tab",w,n&&"is-active",C&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:_,draggable:!0,onDragStart:I,onDragEnd:P,onDragOver:M,onDrop:E,onClick:D,onContextMenu:W,onTouchStart:R,onTouchEnd:B,onTouchMove:B,style:{position:"relative",cursor:"pointer",opacity:a?.4:void 0},children:[T&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-badge pointer-events-none absolute top-0.5 right-0.5 text-text-muted",title:"Mesh chat","aria-label":"Mesh chat",children:s.jsx(cs,{size:11})}),r&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:v.isGenerating?s.jsx(ls,{size:12,thickness:2,color:"success"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?s.jsx(ls,{size:12,thickness:2}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),N.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:A,"aria-label":A||N.join(" · "),children:N.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:kt(t),children:kt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[j?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Sn(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Sn(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:Sn(t)}),s.jsx(qr,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),o&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${o}`,children:o})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function GA({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:a,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onHideTab:h,isGroupActive:b,allowTabShortcuts:S=!0}){const{t:x}=ke("common"),[y,C]=l.useState(null),v=l.useRef(null),w=l.useRef(null),j=l.useMemo(()=>e.map(E=>E.tabKey),[e]);qa("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(y==null?void 0:y.tabKey)||null});const{isMac:N,tabShortcuts:A,shortcutListening:T,setShortcutListening:I,saveShortcuts:P}=ef({enabled:S,sortedTabKeys:e.map(E=>E.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!y)return;const E=D=>{const W=document.querySelector("[data-pane-context-menu]");W&&W.contains(D.target)||C(null)};return window.addEventListener("mousedown",E,!0),()=>window.removeEventListener("mousedown",E,!0)},[y]),l.useEffect(()=>{const E=w.current;if(!E)return;const D=W=>{Math.abs(W.deltaY)<=Math.abs(W.deltaX)||(W.preventDefault(),E.scrollLeft+=W.deltaY)};return E.addEventListener("wheel",D,{passive:!1}),()=>E.removeEventListener("wheel",D)},[]);const M=l.useCallback((E,D,W)=>{C({x:E,y:D,tabKey:W})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:w,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(E=>s.jsx(UA,{conv:E,isActive:t===E.tabKey,isDraggedTab:r.current===E.tabKey,isTaskCompleteUnread:a.has(E.tabKey),shortcut:S?A[E.tabKey]:void 0,conversationKeys:j,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onOpenContextMenu:M,longPressTimer:v,isGroupActive:b},E.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:x("paneGroup.noTabsInGroup")})]})}),y&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:y.x,top:y.y},children:[S&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:di,onClick:E=>{E.stopPropagation(),I(y.tabKey),C(null)},children:["⌨ ",A[y.tabKey]?`Change shortcut (${A[y.tabKey]})`:"Set shortcut"]}),A[y.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:di,onClick:()=>{const E={...A};delete E[y.tabKey],P(E),C(null)},children:"✕ Remove shortcut"})]}),h&&s.jsxs(s.Fragment,{children:[S&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:di,onClick:()=>{h(y.tabKey),C(null)},children:s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(mo,{size:12}),"Hide from Dashboard"]})})]})]}),S&&T&&s.jsx(Vt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>I(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:E=>E.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",N?"⌘+1":"Ctrl+1",", ",N?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:x("paneGroup.pressEscToCancel")})]})})})]})}function qA({conversations:e,ides:t,clearedTabs:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d=!0,userName:p,groupIndex:u,onFocus:m,isSplitMode:f,numGroups:g,onMoveTab:k,onReceiveTab:h,style:b,onActiveTabChange:S,initialActiveTabId:x,initialTabOrder:y,onTabOrderChange:C,onHideTab:v,isFocused:w,allowTabShortcuts:j=!0,onOpenNewSession:N,liveSessionInboxState:A}){const{sendCommand:T}=St(),I=l.useRef(null),{activeTabId:P,activeConv:M,sortedConversations:E,draggingTabRef:D,selectTab:W,handleTabReorder:R,updatePreviewOrder:B,commitPreviewOrder:_,clearPreviewOrder:H,moveTabToEnd:L,setDraggingTabKey:F}=WA({conversations:e,initialActiveTabId:x,initialTabOrder:y,onActiveTabChange:S,onTabOrderChange:C}),$=So({sendDaemonCommand:r,activeConv:M,setActionLogs:o,isStandalone:i}),{dragOver:K,dropAction:z,resetDragState:ne,handleDragEnter:ie,handleDragOver:Ce,handleDragLeave:me,handleDrop:O}=FA({conversations:e,numGroups:g,onMoveTab:k,onReceiveTab:h,onOwnTabDrop:L,onClearPreviewOrder:H}),Y=M&&!ht(M)&&ca(M)==="terminal",X=l.useMemo(()=>M?t.find(Z=>Z.id===M.routeId):void 0,[t,M]),Q=l.useMemo(()=>M?a.filter(Z=>Z.routeId===M.tabKey):[],[a,M]),ve=l.useMemo(()=>new Set(E.filter(Z=>Lx(Z,A,{isOpenConversation:Z.tabKey===P})).map(Z=>Z.tabKey)),[P,A,E]);qa("PaneGroup",{groupIndex:u,conversationCount:e.length,activeTabId:P,dragOver:K});const he=l.useCallback(Z=>{Z.streamSource==="agent-stream"&&Z.agentType&&T(Z.routeId,Em(),{agentType:Z.agentType,...Z.sessionId&&{targetSessionId:Z.sessionId}}).catch(()=>{})},[T]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:m,style:{...b,outline:K?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(GA,{conversations:E,activeTabId:P,groupIndex:u,numGroups:g,unreadTabKeys:ve,draggingTabRef:D,onFocus:m,onSelectTab:W,onConversationActivated:he,onPreviewReorder:B,onReorderTab:R,onCommitPreviewOrder:_,onClearPreviewOrder:H,onDragStateReset:ne,onDragTabKeyChange:F,onMoveTab:k,onReceiveTab:h,onHideTab:v,isGroupActive:w??!1,allowTabShortcuts:j}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ie,onDragOver:Ce,onDragLeave:me,onDrop:O,children:[K&&s.jsx(OA,{dropAction:z,canSplit:!!(g<4&&k)}),M?s.jsx(gc,{activeConv:M,clearToken:n[M.tabKey]||0,isCliTerminal:!!Y,ideEntry:X,terminalRef:I,handleModalButton:$.handleModalButton,handleRelaunch:$.handleRelaunch,handleSendChat:$.handleSendChat,handleForceSendChat:$.handleForceSendChat,isSendingChat:$.isSendingChat,sendFeedbackMessage:$.sendFeedbackMessage,handleFocusAgent:$.handleFocusAgent,isFocusingAgent:$.isFocusingAgent,actionLogs:Q,userName:p,isInputActive:!f||!!w}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(xc,{conversationsCount:e.length,isSplitMode:f,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N,isLoading:!To(t,d)})})]})]})}function zA({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:a,groupedConvs:r,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,initialDataLoaded:f,userName:g,focusedGroup:k,focusGroup:h,moveTabToGroup:b,splitTabRelative:S,closeGroup:x,handleResizeStart:y,groupActiveTabIds:C,setGroupActiveTab:v,groupTabOrders:w,setGroupTabOrder:j,toggleHiddenTab:N,onOpenNewSession:A,allowTabShortcuts:T=!0,liveSessionInboxState:I}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:r.map((P,M)=>{const E=t&&a.length===n?`${a[M]}%`:void 0;return s.jsxs(Rt.Fragment,{children:[t&&M>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:D=>y(M-1,D),onDoubleClick:()=>x(M),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(qA,{style:t?{flexBasis:E??`${100/n}%`,flexGrow:E?0:1,flexShrink:E?0:1}:void 0,conversations:P,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,initialDataLoaded:f,userName:g,groupIndex:M,isFocused:t&&k===M,onFocus:()=>h(M),isSplitMode:t,numGroups:n,onMoveTab:(D,W)=>{W==="left"&&M>0?b(D,M-1):W==="right"&&M<n-1?b(D,M+1):W==="split-left"&&n<4?S(D,M,"left"):W==="split-right"&&n<4&&S(D,M,"right")},onReceiveTab:D=>b(D,M),onActiveTabChange:D=>v(M,D),initialActiveTabId:C[M],initialTabOrder:w[M],onTabOrderChange:D=>j(M,D),onHideTab:N,onOpenNewSession:A,allowTabShortcuts:T,liveSessionInboxState:I})]},M)})})}const tf="adhdev-dashboard-action-shortcuts",KA=1200,VA=[["toggleHiddenTabs","G H"],["openNewSession","N"],["setActiveTabShortcut","G S"],["selectPreviousGroupTab","G K"],["selectPreviousGroupTab","T ←"],["selectPreviousGroupTab","⌥+["],["selectPreviousGroupTab","Ctrl+Alt+["],["selectNextGroupTab","G J"],["selectNextGroupTab","T →"],["selectNextGroupTab","⌥+]"],["selectNextGroupTab","Ctrl+Alt+]"],["splitActiveTabDown","S ↓"],["splitActiveTabDown","⌘+⌥+-"],["splitActiveTabDown","Ctrl+Alt+-"],["splitActiveTabRight","S →"],["splitActiveTabRight","⌘+⌥+\\"],["splitActiveTabRight","⌘+⌥+="],["splitActiveTabRight","Ctrl+Alt+\\"],["focusLeftPane","F ←"],["focusLeftPane","⌘+⌥+←"],["focusLeftPane","⌘+⌥+["],["focusLeftPane","Ctrl+Alt+←"],["focusRightPane","F →"],["focusRightPane","⌘+⌥+→"],["focusRightPane","⌘+⌥+]"],["focusRightPane","Ctrl+Alt+→"],["focusUpPane","F ↑"],["focusUpPane","⌘+⌥+U"],["focusUpPane","Ctrl+Alt+↑"],["focusDownPane","F ↓"],["focusDownPane","⌘+⌥+J"],["focusDownPane","Ctrl+Alt+↓"],["moveActiveTabToLeftPane","M ←"],["moveActiveTabToLeftPane","⌘+⌥+⇧+←"],["moveActiveTabToLeftPane","⌘+⌥+,"],["moveActiveTabToLeftPane","Ctrl+Alt+Shift+←"],["moveActiveTabToRightPane","M →"],["moveActiveTabToRightPane","⌘+⌥+⇧+→"],["moveActiveTabToRightPane","⌘+⌥+."],["moveActiveTabToRightPane","Ctrl+Alt+Shift+→"],["moveActiveTabToUpPane","M ↑"],["moveActiveTabToUpPane","⌘+⌥+I"],["moveActiveTabToUpPane","Ctrl+Alt+Shift+↑"],["moveActiveTabToDownPane","M ↓"],["moveActiveTabToDownPane","⌘+⌥+K"],["moveActiveTabToDownPane","Ctrl+Alt+Shift+↓"],["triggerPrimaryApprovalAction","⌥+A"],["triggerSecondaryApprovalAction","⌥+D"],["toggleCliView","T"]];function YA(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function gt(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function sf(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:gt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:gt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:gt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:gt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:gt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:gt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:gt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:gt("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:gt("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:gt("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:gt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:gt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:gt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:gt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:gt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:gt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:gt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:gt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:gt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:gt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:gt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:gt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:gt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:gt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:gt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:gt("toggleCliView",e)}]}function bl(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function eo(e){const t=Object.fromEntries(sf(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(tf)||"{}"),a={...t,...n};for(const[r,o]of VA)a[r]===o&&(a[r]=t[r]);return a}catch{return t}}function nf(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function QA({enabled:e=!0,onTrigger:t}){const n=YA(),[a,r]=l.useState(()=>eo(n)),[o,i]=l.useState(null),[c,d]=l.useState([]),p=l.useRef({parts:[],timer:null}),u=l.useCallback(h=>{const b=[];return h.metaKey&&b.push(n?"⌘":"Meta"),h.ctrlKey&&b.push("Ctrl"),h.altKey&&b.push(n?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&b.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(b.push(nf(h.key)),b.join("+"))},[n]),m=l.useCallback(h=>{r(h);try{localStorage.setItem(tf,JSON.stringify(h))}catch{}},[]);l.useEffect(()=>{const h=eo(n),b=Object.entries(a),S=Object.entries(h);b.length===S.length&&b.every(([x,y])=>h[x]===y)||m(h)},[a,n,m]);const f=l.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),g=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},KA))},[]);l.useEffect(()=>{if(!o)return;const h=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){i(null),d([]);return}const S=u(b);if(!S)return;const y=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(S);if(c.length===0&&y){d([S]);return}const v=[...c,S].slice(0,2).join(" "),w={...a};for(const[j,N]of Object.entries(w))N===v&&delete w[j];w[o]=v,m(w),i(null),d([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[a,u,m,o,c]),l.useEffect(()=>{if(!e||o)return;const h=b=>{if(b.defaultPrevented)return;const S=u(b);if(!S)return;const x=b.metaKey||b.ctrlKey||b.altKey;if(bl(b.target))return;const y=p.current.parts,C=x?[S]:[...y.slice(-1),S].slice(-2),v=C.join(" "),w=C[C.length-1],j=Object.entries(a).filter(([,P])=>!!P),N=j.find(([,P])=>P===v);if(N){b.preventDefault(),f(),t(N[0]);return}if(j.some(([,P])=>P.startsWith(`${v} `))){b.preventDefault(),p.current.parts=C,g();return}const T=j.find(([,P])=>P===w);if(T){b.preventDefault(),f(),t(T[0]);return}if(j.some(([,P])=>P.startsWith(`${w} `))){b.preventDefault(),p.current.parts=[w],g();return}f()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[a,g,e,u,t,f,o]),l.useEffect(()=>()=>f(),[f]);const k=l.useMemo(()=>sf(n),[n]);return{isMac:n,actionDefinitions:k,actionShortcuts:a,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:m}}function JA({isTabInPopout:e,isTabFloating:t,tabShortcut:n,actionShortcuts:a}){const r=[];return e?(t&&r.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:a.dockActiveTab}),r.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:a.dockActiveTab})):t?r.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:a.dockActiveTab}):r.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:a.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:a.popoutActiveTab}),r.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:n?`Change shortcut (${n})`:"Set shortcut",shortcut:a.setActiveTabShortcut}),n&&r.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),r.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:a.hideCurrentTab,tone:"muted"}),r}function af(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function pu({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:a}){return!e||n>0?!1:t?!af(a):!0}function XA({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:af(n)}const rf=1e3,ZA=4;function mu(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function hu(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function eT({detachDelayMs:e=rf,stillnessThresholdPx:t=ZA,onDetach:n,setTimeoutFn:a=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:r=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,d=null,p=null,u=!1;const m=()=>{p!=null&&(r(p),p=null)},f=()=>{m(),c=null},g=()=>{m(),o=null,i=null,c=null,d=null,u=!1},k=()=>{!o||!c||!d||u||p!=null||(p=a(()=>{p=null,!(!o||!c||!d||u)&&mu(d,i)&&(hu(c,d,t)||(u=!0,n({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},h=S=>{if(!(!o||u)){if(!mu(S,i)){d={clientX:S.clientX,clientY:S.clientY},f();return}(!c||hu(c,S,t))&&(m(),c={clientX:S.clientX,clientY:S.clientY}),d={clientX:S.clientX,clientY:S.clientY},k()}},b=S=>{!o||u||(S&&(d={clientX:S.clientX,clientY:S.clientY}),f())};return{startDrag:S=>{m(),o=S.panelId,i=S.selfPanelBounds??null,c=null,d={clientX:S.clientX,clientY:S.clientY},u=!1},markSelfPanel:h,markNonSelfPanel:b,markNoDropTarget:b,markDockTarget:b,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>u,dispose:g}}function tT(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Lr(e){return kt(e)||e.tabKey}function sT(e){return`remote:${e}`}function fs(e){return e.startsWith("remote:")}function fu(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ui(e){var a;const t=e==null?void 0:e.defaultView;if(!t)return;const n=r=>{if(r)try{r.focus({preventScroll:!0})}catch{try{r.focus()}catch{}}};try{t.focus(),n(e==null?void 0:e.body),n(e==null?void 0:e.documentElement),(a=t.requestAnimationFrame)==null||a.call(t,()=>{try{t.focus(),n(e==null?void 0:e.body)}catch{}})}catch{}}function pi(e,t){e.classList.remove(Wi.className,Oi.className),e.classList.add(t==="light"?Wi.className:Oi.className)}function gu(e){return e?Array.from(new Set(e.groups.map(t=>{var n,a;return(a=(n=t.element)==null?void 0:n.ownerDocument)==null?void 0:a.defaultView}).filter(t=>!!t&&t!==window))):[]}function nT(e,t,n){var i;const a=[t];let r;for(const c of a){let d;for(const p of c){const u=e.addPanel({id:p.tabKey,component:"conversation",title:Lr(p),params:{kind:"conversation",tabKey:p.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:r?{position:{referencePanel:r,direction:"right"},inactive:!0}:{}});d||(d=u.id)}r=d??r}return n??((i=t[0])==null?void 0:i.tabKey)??null}function bu(e,t){const n=new Set(t.map(r=>r.tabKey)),a=new Map;for(const r of t)a.set(r.tabKey,(a.get(r.tabKey)||0)+1);for(const r of[...e.panels])fs(r.id)||n.has(r.id)||e.removePanel(r);for(const r of t){const o=e.getPanel(r.tabKey);if(o){(a.get(r.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:r.tabKey,daemonId:r.daemonId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,panelId:o.id}),o.update({params:{tabKey:r.tabKey}}),o.title!==Lr(r)&&o.api.setTitle(Lr(r));continue}e.addPanel({id:r.tabKey,component:"conversation",title:Lr(r),params:{kind:"conversation",tabKey:r.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function xu(e,t,n){var d,p;const a=n?sT(n):null;for(const u of[...e.panels])fs(u.id)&&(!a||u.id!==a)&&e.removePanel(u);if(!n||!a)return;const r=ws(t,n);if(!r&&e.totalPanels===0)return;const o=e.getPanel(a),i=ah(r);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(r==null?void 0:r.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((p=e.panels.find(u=>!fs(u.id)))==null?void 0:p.id);e.addPanel({id:a,component:"remote",title:i,params:{kind:"remote",routeId:n},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function of({doId:e,targetSessionId:t,connState:n,viewMode:a}){const[r,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?Ct.onScreenshot("ide-page",(u,m)=>{if(u!==e)return;const f=new FileReader;f.onload=()=>o(f.result),f.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&o(null)},[n]),l.useEffect(()=>{var u;return e?((u=Ct.onStatus)==null?void 0:u.call(Ct,(m,f)=>{m===e&&f!=null&&f.screenshotUsage&&c(f.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?Ct.get(e):null;if(!(!p||n!=="connected"))return a!=="chat"&&t?p.startScreenshots(t):p.stopScreenshots(t),()=>{p.stopScreenshots(t)}},[a,n,t,e]);const d=l.useCallback(async(p,u)=>{const m=e?Ct.get(e):null;return!m||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(p,u,t)},[e,n,t]);return{connScreenshot:r,screenshotUsage:i,handleRemoteAction:d}}const lf=l.createContext(null);function Mo(){const e=l.useContext(lf);if(!e)throw new Error("DashboardDockviewContext missing");return e}function aT(e){const[,t]=l.useState(0);l.useEffect(()=>{const n=()=>t(r=>r+1),a=[e.api.onDidActiveGroupChange(n),e.api.onDidTitleChange(n),e.api.onDidGroupChange(n),e.containerApi.onDidActivePanelChange(n)];return()=>{for(const r of a)r.dispose()}},[e.api,e.containerApi])}function rT({params:e}){var d;const t=Mo(),n=l.useMemo(()=>ws([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),a=l.useMemo(()=>t.ides.find(p=>p.id===e.routeId),[t.ides,e.routeId]),r=(n==null?void 0:n.daemonId)||((d=n==null?void 0:n.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=of({doId:r,targetSessionId:n?Lm(n):(a==null?void 0:a.sessionId)||(a==null?void 0:a.instanceId),connState:(n==null?void 0:n.connectionState)||"new",viewMode:"remote"});return n?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(Qp,{addLog:()=>{},connState:n.connectionState||"new",connScreenshot:o,screenshotUsage:i,transportType:n.transport,onAction:c})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function oT(){const e=Mo();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(xc,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels,isLoading:!To(e.ides,e.initialDataLoaded)})})}function iT(e){var x,y;aT(e);const t=Mo(),n=l.useCallback(C=>{"button"in C&&C.button!==0||e.api.setActive()},[e.api]),a=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),r=a==null?void 0:a.sessionId,o=l.useCallback(C=>PC(C),[]),i=l.useCallback(()=>MC(r),[r]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const C=ws([...t.conversationsByTabKey.values()],e.params.routeId),v=((x=e.api.group.activePanel)==null?void 0:x.id)===e.api.id,w=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${v?" is-active":""}${w?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(C==null?void 0:C.tabKey)||"",onMouseDown:n,onTouchStart:n,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:C!=null&&C.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:C.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const d=t.conversationsByTabKey.get(e.params.tabKey);if(!d)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const p=((y=e.api.group.activePanel)==null?void 0:y.id)===e.api.id,u=e.api.isGroupActive,m=go(d,t.liveSessionInboxState,{isOpenConversation:p}),f=m.isReconnecting,g=m.isConnecting,k=m.isGenerating||c,h=m.isWaiting,b=m.unread,S=t.tabShortcuts[d.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${u?" is-group-active":""}${f?" is-reconnecting":""}`,title:kt(d),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:C=>{var v;C.preventDefault(),n(C),t.openTabContextMenu({x:C.clientX,y:C.clientY,tabKey:d.tabKey,sourceDocument:((v=C.target)==null?void 0:v.ownerDocument)??document})},children:[b&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:k?s.jsx(ls,{size:12,thickness:2,color:"success"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):g?s.jsx(ls,{size:12,thickness:2}):d.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:kt(d)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Sn(d)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Sn(d)}):s.jsx("span",{children:Sn(d)})})]}),S&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:S,children:S})]})}function hr(e){return e.isActive}function vu(e){return e.isVisible}function lT(e){e.preventDefault()}function cT({params:e,api:t}){var g;const n=Mo(),a=l.useRef(null),[r,o]=l.useState(()=>hr(t)),[i,c]=l.useState(()=>vu(t)),d=n.conversationsByTabKey.get(e.tabKey),p=So({sendDaemonCommand:n.sendDaemonCommand,activeConv:d,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(hr(t)),c(vu(t));const k=[t.onDidActiveChange(h=>o(h.isActive)),t.onDidActiveGroupChange(h=>{if(!hr(t)&&!h.isActive){o(!1);return}o(hr(t))}),t.onDidVisibilityChange(h=>c(h.isVisible))];return()=>{for(const h of k)h.dispose()}},[t]);const u=l.useMemo(()=>d?n.ides.find(k=>k.id===d.routeId):void 0,[n.ides,d]),m=l.useMemo(()=>d?n.actionLogs.filter(k=>k.routeId===d.tabKey):[],[n.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(xc,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels,isLoading:!To(n.ides,n.initialDataLoaded)})});const f=!ht(d)&&ca(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(gc,{activeConv:d,clearToken:n.clearedTabs[d.tabKey]||0,isCliTerminal:f,ideEntry:u,terminalRef:a,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((g=n.scrollToBottomRequest)==null?void 0:g.tabKey)===d.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:r,isVisible:i})})}function dT({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:p,toggleHiddenTab:u,actionShortcuts:m,registerActionHandlers:f,onActiveTabChange:g,onOpenNewSession:k,onRequestScrollToBottom:h,requestedActiveTabKey:b,requestedRemoteIdeId:S,onRequestedActiveTabConsumed:x,scrollToBottomRequest:y,liveSessionInboxState:C,layoutProfile:v}){var $e,at,rt;const{theme:w}=Rs(),{sendCommand:j}=St(),N=l.useRef(null),A=l.useRef(null),T=l.useRef(null),I=l.useRef(!1),P=l.useRef(!1),M=l.useRef(!1),E=l.useRef(null),D=l.useRef([]),[W,R]=l.useState(null),[B,_]=l.useState(0),H=l.useRef(typeof window>"u"?{}:TN(v)),L=l.useMemo(()=>new Map(e.map(G=>[G.tabKey,G])),[e]),F=l.useMemo(()=>{const G=N.current;return G?G.groups.some(oe=>{try{const de=oe.model.location.type;return de!=="floating"&&de!=="popout"?!1:oe.panels.some(xe=>L.has(xe.id))}catch{return!1}}):!1},[L,B,e]),$=l.useCallback(()=>{var G;(G=N.current)==null||G.focus()},[]),K=l.useCallback((G,oe)=>{h==null||h(G,oe)},[h]),z=l.useCallback(G=>{const oe=document,de=G.document;for(const Ee of oe.querySelectorAll('link[rel="stylesheet"]')){const Je=de.createElement("link");Je.rel="stylesheet",Je.href=Ee.href,Ee.crossOrigin&&(Je.crossOrigin=Ee.crossOrigin),de.head.appendChild(Je)}for(const Ee of oe.querySelectorAll("style")){const Je=de.createElement("style");Je.textContent=Ee.textContent,de.head.appendChild(Je)}const xe=[];for(const Ee of oe.styleSheets)try{for(const Je of Ee.cssRules)Je instanceof CSSStyleRule&&(Je.selectorText===":root"||Je.selectorText==="html")&&xe.push(Je.cssText)}catch{}if(xe.length>0){const Ee=de.createElement("style");Ee.textContent=xe.join(`
65
+ `)&&!r.startsWith("{")?null:{serverName:n.serverName||"adhdev-mesh",configFormat:n.format,configPathCommand:n.configPathCommand,requiresRestart:n.requiresRestart===!0,instructions:n.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:ou(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function XN(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.instructions=="string"?t.instructions:"",a=typeof t.template=="string"?t.template:"";return!n&&!a?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:n||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:a}}function Wa(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Oh(e){return xo(e)||e.tabKey||e.routeId||null}function Uh(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",n=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",a=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",r=e.conversations.find(o=>{if(a&&o.routeId!==a)return!1;const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||n&&i.includes(n)||a&&o.routeId===a)});if(r!=null&&r.tabKey)return r.tabKey;if(a){const o=ws(e.conversations,a)||e.conversations.find(i=>i.routeId===a);if(o!=null&&o.tabKey)return o.tabKey}return t||n||a||null}function Xs(e){return String(e||"").trim()}function Gh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Zr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ZN(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function eA(e,t){const n=Xs(e.providerSessionId),a=Xs(e.targetSessionId),r=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Xs).filter(Boolean);return!!(n&&i.includes(n)||a&&i.includes(a))});return r?r.tabKey:a||n||null}function tA(e,t,n){if(t.event!=="agent:generating_completed")return null;const a=Gh(t.daemonId);if(a&&a!==e.machineId)return null;const r=Xs(t.providerType);if(e.providerType&&r!==e.providerType)return null;const o=Xs(e.resumeSessionId),i=Xs(e.launchedSessionId),c=Xs(t.providerSessionId),d=Xs(t.targetSessionId);if(o&&o!==c&&o!==d||i&&i!==c&&i!==d)return null;const p=Zr(e.workspacePath);if(p){const u=Zr(t.workspaceName);if(u&&!ZN(u,p))return null}return eA(t,n)}function iu(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function sA({ides:e,conversations:t,onOpenSession:n}){const[a,r]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,r(null)},[]),c=l.useCallback(d=>{o.current=d,r(d)},[]);return l.useEffect(()=>{if(!a)return;const d=Zr(a.workspacePath),p=e.find(m=>{var b,S,x,y;if(!m||m.type==="adhdev-daemon"||Gh(m.daemonId||m.id)!==a.machineId||(Fa(m)?"cli":Xn(m)?"acp":"ide")!==a.kind)return!1;const k=String(m.agentType||m.type||"");if(a.providerType&&k!==a.providerType)return!1;if(a.resumeSessionId)return String(m.providerSessionId||"")===a.resumeSessionId;if(a.launchedSessionId){const C=String(a.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(w=>String(w||"")).filter(Boolean).includes(C)}if(d){const C=Zr(m.workspace||m.runtimeWorkspaceLabel);return C?C===d:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((y=(x=(S=(b=m.activeChat)==null?void 0:b.messages)==null?void 0:S.at)==null?void 0:x.call(S,-1))==null?void 0:y.timestamp)||0)>=a.startedAt-5e3});if(!p)return;const u=Uh({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});u&&(i(),n(u))},[i,t,e,n,a]),l.useEffect(()=>ft.onStatusEvent(d=>{const p=o.current;if(!p)return;const u=tA(p,d,t);u&&(i(),n(u))}),[i,t,n]),l.useEffect(()=>{if(!a)return;const d=window.setTimeout(()=>{r(p=>!p||p.startedAt!==a.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[a]),{trackPendingLaunch:c}}function nA(e,t){var a,r,o,i;const n={cliType:e};return(a=t==null?void 0:t.workspacePath)!=null&&a.trim()?n.dir=t.workspacePath.trim():t!=null&&t.workspaceId?n.workspaceId=t.workspaceId:t!=null&&t.useHome&&(n.useHome=!0),(r=t==null?void 0:t.resumeSessionId)!=null&&r.trim()&&(n.resumeSessionId=t.resumeSessionId.trim()),Array.isArray(t==null?void 0:t.cliArgs)&&t.cliArgs.length>0&&(n.cliArgs=t.cliArgs),(o=t==null?void 0:t.initialModel)!=null&&o.trim()&&(n.initialModel=t.initialModel.trim()),(i=t==null?void 0:t.initialThinkingLevel)!=null&&i.trim()&&(n.initialThinkingLevel=t.initialThinkingLevel.trim()),t!=null&&t.settings&&(n.settings=t.settings),n}function aA(e,t,n){var i,c,d,p;const a={meshId:e.trim()};t.trim()&&(a.cliType=t.trim());const r=(i=n==null?void 0:n.initialModel)==null?void 0:i.trim(),o=(c=n==null?void 0:n.initialThinkingLevel)==null?void 0:c.trim();return r&&(a.initialModel=r),o&&(a.initialThinkingLevel=o),(d=n==null?void 0:n.settings)!=null&&d.autoApproveMode?a.autoApproveMode=n.settings.autoApproveMode:typeof((p=n==null?void 0:n.settings)==null?void 0:p.autoApprove)=="boolean"&&(a.autoApprove=n.settings.autoApprove),a}function rA({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:a,ides:r,setCliViewModeOverrides:o}){const i=Ql(),{launchCli:c}=fo(),d=l.useCallback(async(b,S)=>fc(e,b,S),[e]),p=l.useCallback(async(b,S)=>{if(!S.trim())return{ok:!1,error:"Choose a workspace path first."};try{const x=await e(b,"workspace_add",{path:S.trim()});return x!=null&&x.success?{ok:!0}:{ok:!1,error:(x==null?void 0:x.error)||"Could not save workspace"}}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Could not save workspace"}}},[e]),u=l.useCallback(async(b,S,x)=>{var y;try{const C={ideType:S,enableCdp:!0};(y=x==null?void 0:x.workspacePath)!=null&&y.trim()&&(C.workspace=x.workspacePath.trim());const v=await e(b,"launch_ide",C);return!(v!=null&&v.success)&&(v==null?void 0:v.success)!==void 0?{ok:!1,error:(v==null?void 0:v.error)||"Could not launch IDE"}:(t({machineId:b,kind:"ide",providerType:S,workspacePath:(x==null?void 0:x.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(C){return{ok:!1,error:C instanceof Error?C.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(b,S,x,y)=>{const C=Date.now();try{const v=nA(x,y),w=await c(b,v),j=(w==null?void 0:w.result)||w,N=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return w!=null&&w.success&&N?(t({machineId:b,kind:S,providerType:x,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,launchedSessionId:N,startedAt:C}),{ok:!0}):w!=null&&w.success?(t({machineId:b,kind:S,providerType:x,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:(w==null?void 0:w.error)||(j==null?void 0:j.error)||`Could not launch ${S.toUpperCase()} session`,code:(w==null?void 0:w.code)||(j==null?void 0:j.code)||void 0}}catch(v){return iu(v)?(t({machineId:b,kind:S,providerType:x,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:`Could not launch ${S.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async b=>{var S;if(i!=null&&i.listMeshes)return i.listMeshes(b);if(!b)return[];try{const x=await e(b,"list_meshes",{}),y=(x==null?void 0:x.result)??x;if((y==null?void 0:y.success)===!1)throw new Error((y==null?void 0:y.error)||"Could not load meshes");return(Array.isArray(y==null?void 0:y.meshes)?y.meshes:Array.isArray((S=y==null?void 0:y.result)==null?void 0:S.meshes)?y.result.meshes:[]).map(v=>{var w;return{id:String((v==null?void 0:v.id)||""),name:String((v==null?void 0:v.name)||(v==null?void 0:v.id)||"Untitled mesh"),repoIdentity:(v==null?void 0:v.repoIdentity)||(v==null?void 0:v.repo_identity)||null,workspace:Array.isArray(v==null?void 0:v.nodes)&&v.nodes.length>0?String(((w=v.nodes[0])==null?void 0:w.workspace)||""):null,nodesCount:Array.isArray(v==null?void 0:v.nodes)?v.nodes.length:void 0,status:(v==null?void 0:v.status)||null}}).filter(v=>v.id)}catch(x){throw console.error("List meshes failed",x),x}},[i,e]),g=l.useCallback(async(b,S,x,y)=>{if(!S.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(b,S,x,y);const C=Date.now();try{const v=aA(S,x,y),w=await e(b,"launch_mesh_coordinator",v),j=(w==null?void 0:w.result)??w;if((j==null?void 0:j.success)===!1||(w==null?void 0:w.success)===!1){const A=String((j==null?void 0:j.code)||(w==null?void 0:w.code)||""),T=XN((j==null?void 0:j.meshCoordinatorSetup)||(j==null?void 0:j.manualSetup)||(w==null?void 0:w.meshCoordinatorSetup)||(w==null?void 0:w.manualSetup));return{ok:!1,error:(j==null?void 0:j.error)||(w==null?void 0:w.error)||"Could not launch mesh coordinator",code:A||void 0,manualSetup:T}}const N=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return N?n(N):t({machineId:b,kind:"cli",providerType:(j==null?void 0:j.cliType)||x.trim()||void 0,workspacePath:(j==null?void 0:j.workspace)||null,startedAt:C}),{ok:!0}}catch(v){return iu(v)?(t({machineId:b,kind:"cli",providerType:x.trim()||void 0,startedAt:C}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),k=l.useCallback(async(b,S)=>{if(!b||!S)return[];try{const x=await e(b,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),y=(x==null?void 0:x.result)??x;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(x){return console.error("List saved sessions failed",x),[]}},[e]),h=l.useCallback(async b=>{await Lh({conversation:a,mode:b,ides:r,sendDaemonCommand:e,setCliViewModeOverrides:o})},[a,r,e,o]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:p,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineMeshes:f,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:k,setActiveCliViewMode:h}}function oA(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":return!0;case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function iA(e,t,n=Date.now()){return!e||!oA(t)?null:{tabKey:e,nonce:n}}function lA({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:a,focusedGroup:r,groupedConvs:o,setSearchParams:i}){const[c,d]=l.useState(null),[p,u]=l.useState(null),m=l.useMemo(()=>{var b,S;if(!e){if(c){const x=t.find(y=>y.tabKey===c);if(x)return x}return n[0]}const h=a[r];if(h){const x=t.find(y=>y.tabKey===h);if(x)return x}return((b=o[r])==null?void 0:b[0])||((S=o[0])==null?void 0:S[0])},[t,c,r,a,o,e,n]),f=l.useCallback(h=>{d(h)},[]),g=l.useCallback(h=>{d(h.tabKey),i(b=>{const S=new URLSearchParams(b),x=IS(h);return x?S.set("activeTab",x):S.delete("activeTab"),S},{replace:!0})},[i]),k=l.useCallback((h,b)=>{const S=iA(h,b);S&&u(S)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:k,scrollToBottomRequest:p,setDesktopActiveTab:f}}function cA(e){const t=e.completedKey||null,n=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:n!==null&&n!==e.autoReadKey,nextPendingKey:n===e.autoReadKey?n:null}:n===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:n}:{shouldSchedule:!0,shouldCancelPending:n!==null&&n!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!n,nextPendingKey:null}}function dA(e){const t=String(e.liveState.completionMarker||""),n=String(e.liveState.seenCompletionMarker||""),a=String(e.liveState.inboxBucket||"idle"),r=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,n,a,r?"1":"0"].join(":");return{shouldMarkSeen:!!(a==="task_complete"&&r&&(!t||t!==n)),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function uA({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:a}){const r=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),d=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){p(),r.current=null;return}if(!(e!=null&&e.sessionId)){p(),r.current=null;return}const u=rn(e,n),m=dA({tabKey:e.tabKey,historySessionId:xo(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Nn(e),liveState:u}),f=m.autoReadKey,g=cA({autoReadKey:f,shouldMarkSeen:m.shouldMarkSeen,completedKey:r.current,pendingKey:o.current});if(!m.shouldMarkSeen){g.shouldCancelPending&&p(),r.current=f;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&p();const k=()=>{if(document.visibilityState!=="visible"||r.current===f)return;r.current=f,o.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const b=m.readAt;a(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:b,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(k,1500);const b=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=b,document.addEventListener("visibilitychange",b);return}const h=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(k,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=h,document.addEventListener("visibilitychange",h)},[e,t,n,a]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function ri(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const n=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(n)?n:""}function pA({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:a,sendDaemonCommand:r,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var B;const{launchCli:p}=fo(),[u,m]=l.useState(!1),[f,g]=l.useState([]),[k,h]=l.useState(()=>qt()),[b,S]=l.useState(!1),[x,y]=l.useState(null),C=l.useRef(null),v=l.useMemo(()=>n||t||e,[e,n,t]),w=!!v&&bt(v)&&!ht(v),j=l.useMemo(()=>{if(!v||!w)return null;const _=v.daemonId||v.routeId||"",H=Ds(v),L=ri(v);return`${_}:${H}:${v.providerSessionId||""}:${L}`},[v,w]),N=l.useMemo(()=>!v||!w?"":ri(v),[v,w]),{isCreatingChat:A,isRefreshingHistory:T,handleSwitchSession:I,handleNewChat:P,handleRefreshHistory:M}=Fh({sendDaemonCommand:r,activeConv:v,chats:(B=a.find(_=>_.id===(v==null?void 0:v.routeId)))==null?void 0:B.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),E=l.useCallback(()=>{m(!0)},[]),D=l.useCallback(()=>{m(!1)},[]),W=l.useCallback(async()=>{if(!(!v||!w||b)){S(!0);try{const _=v.daemonId||v.routeId,H=Ds(v),L=ri(v),F=await r(_,"list_saved_sessions",{agentType:H,providerType:H,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},...L?{workspace:L}:{}}),$=(F==null?void 0:F.result)??F;g(Array.isArray($==null?void 0:$.sessions)?$.sessions:[])}catch(_){console.error("Refresh saved sessions failed",_),g([])}finally{S(!1)}}},[v,b,w,r]);l.useEffect(()=>{if(!u){C.current=null;return}if(!w){C.current=null,g([]),S(!1);return}!j||b||C.current!==j&&(C.current=j,W())},[W,u,b,w,j]);const R=l.useCallback(async _=>{if(!v||!w||!_.providerSessionId||!_.workspace)return;const H=v.daemonId||v.routeId,L=Ds(v);try{y(_.providerSessionId);const F=await p(H,{cliType:L,dir:_.workspace,resumeSessionId:_.providerSessionId,initialModel:hm(_.summaryMetadata,"model",{preferShortValue:!0})||void 0}),$=(F==null?void 0:F.result)??F,K=typeof($==null?void 0:$.sessionId)=="string"?$.sessionId:typeof($==null?void 0:$.id)=="string"?$.id:"";K&&d(z=>{const ne=new URLSearchParams(z);return ne.set("activeTab",K),ne},{replace:!0}),D()}catch(F){console.error("Resume saved session failed",F)}finally{y(null)}},[D,v,w,r,d]);return{historyModalOpen:u,openHistoryModal:E,closeHistoryModal:D,historyTargetConv:v,isSavedSessionHistoryTarget:w,isHistoryCreatingChat:A,isHistoryRefreshingHistory:T,handleHistorySwitchSession:I,handleHistoryNewChat:P,handleHistoryRefresh:M,savedHistorySessions:f,savedHistoryFilters:k,setSavedHistoryFilters:h,missingWorkspaceResumePath:N,isSavedHistoryLoading:b,resumingSavedHistorySessionId:x,handleRefreshSavedHistory:W,handleResumeSavedHistorySession:R}}function mA({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}){const[d,p]=l.useState(null),[u,m]=l.useState(null),f=l.useMemo(()=>{if(e||!a)return null;const S=c(a);return S&&!bt(S)&&!ht(S)?S:null},[e,a,c]),g=l.useMemo(()=>{const S=d==null?void 0:d.routeId;if(!S)return null;const x=d!=null&&d.tabKey?o.find(y=>y.tabKey===d.tabKey):r?o.find(y=>y.tabKey===r):null;return(x==null?void 0:x.routeId)===S?x:ws(o,S)},[o,d,r]),k=l.useMemo(()=>{if(g)return i.find(S=>S.id===g.routeId)},[i,g]);l.useEffect(()=>{f&&(p({routeId:f.routeId,tabKey:xd(f)}),m(f),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,f]);const h=l.useCallback(S=>{S&&(p({routeId:S.routeId,tabKey:xd(S)}),m(S))},[]),b=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:k,remoteDialogActiveConv:u,setRemoteDialogActiveConv:m,openRemoteDialog:h,closeRemoteDialog:b}}function hA({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:p}){const{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h}=mA({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}),[b,S]=l.useState(!1),[x,y]=l.useState(null),C=l.useCallback(async j=>{const N=j||d;!N||!bt(N)&&!ht(N)||(y(N),S(!0))},[d]),v=l.useCallback(()=>{S(!1),y(null)},[]),w=l.useCallback(async j=>{const N=x||d;if(!N||!bt(N)&&!ht(N)){v();return}S(!1);try{const A=Ds(N),T=N.routeId||N.daemonId||"";await p(T,"stop_cli",{cliType:A,targetSessionId:N.sessionId,mode:j,...ko(N)})}catch(A){console.error("Stop CLI failed:",A)}finally{y(null)}},[d,v,x,p]);return{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h,cliStopDialogOpen:b,cliStopTargetConv:x,requestCliStop:C,cancelCliStop:v,confirmCliStop:w}}function oi(e,t=!0){return(e??!0)&&t}const gc=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:a,ideEntry:r,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:b,isInputActive:S=!0,isVisible:x=!0}){const y=a,C=!a,v=oi(x,y),w=oi(x,C),j=oi(x),N=Ph(t),A=N.status||N.modalMessage||N.modalButtons?{...t,...N.status?{status:N.status}:{},...N.modalMessage!==void 0?{modalMessage:N.modalMessage}:{},...N.modalButtons!==void 0?{modalButtons:N.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(tm,{activeConv:A,onModalButton:i}),A.transport!=="pty"&&A.transport!=="acp"&&A.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(Ls,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:c,children:"Relaunch with CDP"})]})}):null,A.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!a,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:y?"visible":"hidden",pointerEvents:y?"auto":"none"},children:s.jsx(mj,{activeConv:A,clearToken:n,terminalRef:o,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,isVisible:v,isInputActive:S&&v})}),s.jsx("div",{"aria-hidden":a,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(ll,{activeConv:A,ideEntry:r,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:b,isInputActive:S&&w,isVisible:w})})]}):s.jsx(ll,{activeConv:A,ideEntry:r,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:b,isInputActive:S&&j,isVisible:j})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.handleForceSendChat===t.handleForceSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function fA({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:a,interactive:r=!0,meshOnly:o=!1}){var C,v,w;const{t:i}=ke("common"),c=ia(),d=Vs(e),p=o?null:Mm(e),u=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),m=!o&&e.streamSource==="agent-stream"&&!!e.agentName,f=!o&&!m&&(e.transport==="pty"||e.transport==="acp"),g=sa(e),k=DS(e),h=(C=e.settings)==null?void 0:C.meshNodeFor,b=e.meshQueueStats,S=((v=e.coordinator)==null?void 0:v.meshId)||((w=e.settings)==null?void 0:w.meshCoordinatorFor),x=l.useCallback(()=>{if(a){a();return}d&&c("/dashboard",{state:{openMachineId:d}})},[d,c,a]),y=l.useCallback(()=>{if(n){n();return}const j=Oh(e);j&&c(Wa(j))},[e,c,n]);return!u&&!m&&!f&&!p&&!h&&!b?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:y,title:k,children:[s.jsx(us,{size:12}),s.jsx("span",{children:k})]}):s.jsxs("span",{className:"conversation-meta-chip",title:k,children:[s.jsx(us,{size:12}),s.jsx("span",{children:k})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(_a,{size:12}),s.jsx("span",{children:g})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(_a,{size:12}),s.jsx("span",{children:g})]}),p&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:x,title:p,children:[s.jsx(nn,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(nn,{size:12}),s.jsx("span",{children:p})]})),h&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(nn,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),S&&b&&s.jsxs("span",{className:`conversation-meta-chip ${b.pending>0?"is-active":""}`,style:b.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${b.pending} pending, ${b.assigned} assigned, ${b.completed} completed, ${b.failed} failed`,children:[s.jsx(xb,{size:12}),s.jsxs("span",{children:[b.pending," Pending"]})]})]})}function gA({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:a,actionLogs:r,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:p,onOpenNativeConversation:u,onOpenMachine:m,onOpenHistory:f,onOpenRemote:g,onOpenMeshGraph:k,onStopCli:h,cliViewMode:b,onSetCliViewMode:S,handleSendChat:x,handleForceSendChat:y,handleFocusAgent:C,handleModalButton:v,handleRelaunch:w}){var P,M;const j=l.useRef(null),N=bt(e)&&!t,A=N&&b==="terminal",T=!!e.daemonId&&!!((P=e.coordinator)!=null&&P.meshId||(M=e.settings)!=null&&M.meshCoordinatorFor),I=n?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${I} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(_l,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:kt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(fA,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[N&&b&&s.jsx(oh,{mode:b,onChange:S,compact:!0}),N&&h&&s.jsx("button",{onClick:()=>{h(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Dt,{size:14})}),T&&k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(cs,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx($l,{size:14})}),!t&&!N&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(us,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(gc,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:a,terminalRef:j,handleModalButton:v,handleRelaunch:w,handleSendChat:x,handleForceSendChat:y,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:C,isFocusingAgent:d,actionLogs:r,userName:o})})]})}const ii={unix:{cmd:"curl -fsSL https://adhf.dev/install | sh",shell:"Terminal",prompt:"$ "},powershell:{cmd:"irm https://adhf.dev/install.ps1 | iex",shell:"PowerShell",prompt:"PS> "},cmd:{cmd:"curl -fsSL https://adhf.dev/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd",shell:"CMD",prompt:"> "}};function bA(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function qh(){const[e,t]=l.useState("unix"),[n,a]=l.useState("powershell"),[r,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(bA())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(ii[i].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[i]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("powershell"),children:"PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:c,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:ii[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:ii[i].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:r?s.jsx(co,{size:12}):s.jsx(Hl,{size:12})})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function zh({section:e,onSectionChange:t}){const{t:n}=ke("common"),a=[{key:"machines",label:n("nav.machines"),icon:us},{key:"chats",label:n("nav.chats"),icon:Is}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:a.map(({key:r,label:o,icon:i})=>{const c=e===r;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(r),type:"button","aria-pressed":c,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(i,{size:15})}),s.jsx("span",{children:o})]},r)})})})}function ur({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function Bn({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function hn({icon:e,title:t,subtitle:n,children:a}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:n}),a]})}function xA({conversation:e,onCancel:t,onConfirm:n}){const{t:a}=ke(),r=kt(e);return s.jsx(Vt,{children:s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:t,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"card fade-in mobile-compact-dialog relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base md:text-lg font-extrabold",children:a("mobileInbox.hideTitle",{title:r})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:a("mobileInbox.hideDescription")})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:n,className:"btn btn-primary w-full justify-center min-h-[42px]",children:a("mobileInbox.hide")}),s.jsx("button",{onClick:t,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:a("common.cancel")})]})]})]})})}function pr({item:e,type:t,getAvatarText:n,onOpenConversation:a,onRequestHideConversation:r,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:d,onToggleMute:p}){const{t:u}=ke(),m=t==="needs_attention"||t==="task_complete",f=t==="working",g=t==="earlier",k=t==="task_complete",{isReconnecting:h,isConnecting:b}=En(e.conversation),S=kt(e.conversation),x=na(e.conversation),y=sh(e.conversation,{requiresAction:t==="needs_attention"}),C=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":f?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":g?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",v=m?"bg-accent-primary shadow-glow":f?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":g?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",w=g?"text-text-secondary":"text-text-primary",j=g?"text-text-muted":"text-text-secondary",N=g?"text-text-secondary opacity-80":"text-text-muted",A=g?"text-text-muted opacity-80":"text-text-muted",T=!f&&!k,I=eh(e.conversation),P="text-[color:var(--status-warning)]",M=E=>{if(!c)return;E.preventDefault(),E.stopPropagation();const D=c==null?void 0:c(e.conversation);Promise.resolve(D).catch(W=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",W)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${C}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||f?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${v}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(S)}),I&&i&&s.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:E=>{E.preventDefault(),E.stopPropagation(),i(e.conversation)},"aria-label":u("mobileInbox.openMeshGraphFor",{title:S}),title:u("mobileInbox.openLiveMeshGraph"),children:s.jsx(cs,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>a(e.conversation),onContextMenu:M,type:"button",children:[s.jsx("div",{className:"flex items-center gap-2 pr-[124px]",children:s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${w}`,children:S})}),s.jsxs("div",{className:`text-xs font-medium truncate flex items-center ${j}`,children:[s.jsx("span",{className:"truncate",children:x}),s.jsx(qr,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),h?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${P} animate-pulse`,children:u("mobileInbox.reconnectingItem")})]}):b?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:u("mobileInbox.connectingItem")})]}):y==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:P,children:u("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${N}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[T&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${A}`,children:Zp(e.timestamp)}),k&&s.jsx("span",{className:"rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:u("mobileInbox.done")}),p&&s.jsx("button",{type:"button",className:`mobile-inbox-mute-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${d?"border-amber-500/60 bg-amber-500 text-white hover:bg-amber-600":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:E=>{E.preventDefault(),E.stopPropagation(),p()},"aria-label":d?u("mobileInbox.unmute",{title:S}):u("mobileInbox.mute",{title:S}),title:u(d?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:d?s.jsx(Ip,{size:13}):s.jsx(la,{size:13})}),r&&s.jsx("button",{type:"button",className:"mobile-inbox-hide-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:E=>{E.preventDefault(),E.stopPropagation(),r()},"aria-label":u("mobileInbox.hideConversationAria",{title:S}),title:u("mobileInbox.hideConversationTitle"),children:s.jsx(mo,{size:13})}),o&&s.jsx("button",{type:"button",className:"mobile-inbox-stop-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-status-error/30 bg-bg-primary/70 text-status-error transition-colors hover:border-status-error/60 hover:bg-status-error/10",onClick:E=>{E.preventDefault(),E.stopPropagation(),o()},"aria-label":u("mobileInbox.stopSessionAria",{title:S}),title:u("mobileInbox.stopSessionTitle"),children:s.jsx(Dt,{size:13})})]})]})},e.conversation.tabKey)}function lu({count:e,label:t}){return e<=0?null:s.jsxs("span",{className:"inline-flex items-center gap-1.5 text-accent-primary","aria-live":"polite",children:[s.jsxs("span",{className:"relative flex h-2 w-2 shrink-0",children:[s.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-accent-primary/60"}),s.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-accent-primary"})]}),s.jsx("span",{className:"font-semibold",children:t})]})}function vA({section:e,attentionItems:t,unreadItems:n,workingItems:a,completedItems:r,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:p,onOpenConversation:u,onShowAllHidden:m,onHideConversation:f,onOpenMeshGraph:g,onStopCli:k,onOpenNewSession:h,onOpenMachine:b,onOpenSettings:S,onSectionChange:x,wsStatus:y="connected",initialDataLoaded:C=!0,conversationsLoaded:v,isStandalone:w=!1,onCollectChatDebugBundle:j,isConversationMuted:N,onToggleMuteConversation:A}){const{t:T}=ke(),[I,P]=l.useState(null),M=y==="disconnected"||y==="reconnecting"||y==="offline"||y==="auth_failed",E=!M&&!C,D=!M&&!(v??C),W=i.length>0,R=t.length>0||n.length>0||a.length>0||r.length>0,B=T(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),_=w?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",H=w?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",L=l.useCallback(async K=>{const z=kn(K);if(!z)return;const ne=Array.isArray(K.messages)?K.messages:[],ie=_m({activeConv:K,visibleMessages:ne,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:ne.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),Ce=await p(z,"get_chat_debug_bundle",{...wn(K),delivery:"daemon_file",frontendSnapshot:ie}),me=Pa(Ce),O=Fm(me),Y=await $m(O);Y==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ft.showToast(Hm(me,{locatorCopyStatus:Y}),Y==="failed"?"warning":"success")},[d,p]),F=j||L,$=l.useCallback(()=>{I&&(f==null||f(I),P(null))},[I,f]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${_}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:B}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||n.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(la,{size:13}),s.jsx("span",{children:t.length+n.length})]}),s.jsx("button",{onClick:S,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(Ua,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${H}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:M?s.jsx(hn,{icon:s.jsx(ls,{size:32}),title:T(y==="offline"?"mobileInbox.networkOffline":y==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:T(y==="offline"?"mobileInbox.waitingForNetwork":y==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):E?s.jsx(hn,{icon:s.jsx(ls,{size:32}),title:T("mobileInbox.loading"),subtitle:T("mobileInbox.loadingSubtitle")}):i.length===0?s.jsx(hn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:T(w?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:T(w?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!w&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(qh,{})})}):s.jsx(Bn,{children:i.map((K,z)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${z>0?"border-t border-border-subtle/70":""}`,onClick:()=>b(K.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:c(K.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:K.label}),s.jsxs("span",{className:"flex items-center gap-2 text-[11px] font-medium text-text-muted shrink-0",children:[s.jsx(lu,{count:K.generatingCount,label:T("mobileInbox.generatingCount",{count:K.generatingCount})}),K.unread>0?s.jsx("span",{className:"text-accent-primary",children:T("mobileInbox.newCount",{count:K.unread})}):K.total>0?T("mobileInbox.chatCount",{count:K.total}):T("mobileInbox.idle")]})]}),s.jsx("div",{className:"text-xs font-medium text-text-secondary truncate",children:K.subtitle}),K.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[T("mobileInbox.chatCount",{count:K.total}),K.unread>0?T("mobileInbox.unreadSuffix",{count:K.unread}):"",K.generatingCount>0?T("mobileInbox.collapsedGeneratingSuffix",{count:K.generatingCount}):""]}):K.generatingCount>0?s.jsx("div",{className:"text-[13px] text-accent-primary mt-0.5 font-medium",children:T("mobileInbox.generatingCount",{count:K.generatingCount})}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:T("mobileInbox.noActiveChats")})]})]},K.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(ur,{title:T("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(Bn,{children:t.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(pr,{item:K,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:A?()=>A(K.conversation):void 0})},K.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(ur,{title:T("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(Bn,{children:n.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(pr,{item:K,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:A?()=>A(K.conversation):void 0})},K.conversation.tabKey))})]}),e==="chats"&&a.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(ur,{title:T("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(Bn,{children:a.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(pr,{item:K,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:A?()=>A(K.conversation):void 0})},K.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[r.length>0&&s.jsx(ur,{title:T("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),r.length>0?s.jsx(Bn,{children:r.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(pr,{item:K,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:A?()=>A(K.conversation):void 0})},K.conversation.tabKey))}):R?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:T("mobileInbox.allCaughtUp")}):M?s.jsx(hn,{icon:s.jsx(ls,{size:28}),title:T("mobileInbox.connecting"),subtitle:T("mobileInbox.connectingSubtitle")}):D?s.jsx(hn,{icon:s.jsx(ls,{size:28}),title:T("mobileInbox.loading"),subtitle:T("mobileInbox.loadingSubtitle")}):W?s.jsx(hn,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(Is,{size:20})}),title:T("mobileInbox.noConversations"),subtitle:T("paneGroup.newSessionDescription"),children:h&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":T("paneGroup.newSession"),title:T("paneGroup.newSession"),children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:T("paneGroup.newSession")})]})}):s.jsx(hn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:T("mobileInbox.noMachinesConnected"),subtitle:T("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&(()=>{const K=Dx(o);return s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(Bn,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-xs font-bold uppercase tracking-wider text-text-secondary",children:T("mobileInbox.hiddenTabs")}),s.jsx(lu,{count:K,label:T("mobileInbox.generatingCount",{count:K})})]}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[T("mobileInbox.collapsedCount",{count:o.length}),K>0?T("mobileInbox.collapsedGeneratingSuffix",{count:K}):""]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-xs font-semibold text-accent-primary hover:border-border-default",onClick:m,children:T("mobileInbox.restoreAll")})]})})})})()]}),e==="chats"&&h&&R&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:h,"aria-label":T("paneGroup.newSession"),title:T("paneGroup.newSession"),children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),I&&s.jsx(xA,{conversation:I,onCancel:()=>P(null),onConfirm:$}),s.jsx(zh,{section:e,onSectionChange:x})]})}function yA(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function Kh(e){const t=[e.workspace||"Workspace unknown"],n=Mn(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const a=yA(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:a?`Updated ${a}`:"",preview:(e.preview||"").trim()}}function bc({title:e,description:t,currentPath:n,directories:a,busy:r=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:d,onConfirm:p}){const[u,m]=l.useState(n),{t:f}=ke("common");l.useEffect(()=>{m(n)},[n]);const g=QN(n),k=u.trim();return s.jsx(Vt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:c,"aria-label":"Close folder browser",children:s.jsx(Dt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!g||r||d(g)},disabled:!g||r,children:[s.jsx(_l,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:f("machine.workspaceBrowse.currentFolder")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:h=>m(h.target.value),onKeyDown:h=>{h.key!=="Enter"||!k||r||(h.preventDefault(),d(k))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!k||r||d(k)},disabled:!k||r,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:r?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):a.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:a.map(h=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(h.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Tn,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:h.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:h.path})]})]},h.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(k||n),disabled:!k&&!n||r,children:i})]})]})})})}function Ao({title:e,description:t,details:n,workspaceOptions:a,selectedWorkspaceKey:r,onWorkspaceChange:o,confirmLabel:i,busyLabel:c,busy:d=!1,showArgsInput:p,argsValue:u,onArgsChange:m,showModelInput:f,modelValue:g,onModelChange:k,historyProviderNode:h,onConfirm:b,onCancel:S}){const{t:x}=ke("common"),y=i??x("machine.launchConfirm.launch"),C=c??x("machine.launchConfirm.launching"),v=a==null?void 0:a.find(j=>j.key===r),w=s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:S,"aria-label":x("machine.launchConfirm.closeAria"),children:s.jsx(Dt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[a&&a.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:x("machine.launchConfirm.workspace")}),s.jsx("select",{value:r||"",onChange:j=>o(j.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:a.map(j=>s.jsx("option",{value:j.key,children:j.label},j.key))}),(v==null?void 0:v.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v.description})]}),h,n.map(j=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:j.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:j.value})]},`${j.label}:${j.value}`)),f&&k&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:x("machine.launchConfirm.languageModel")}),s.jsx("input",{type:"text",value:g||"",onChange:j=>k(j.target.value),placeholder:x("machine.launchConfirm.autoDetect"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),p&&m&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:x("machine.launchConfirm.cliArgs")}),s.jsx("input",{type:"text",value:u||"",onChange:j=>m(j.target.value),placeholder:x("machine.launchConfirm.cliArgsPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:S,disabled:d,children:x("machine.launchConfirm.cancel")}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:b,disabled:d,children:[s.jsx(Dp,{size:14}),d?C:y]})]})]})});return typeof document>"u"?w:zs.createPortal(w,document.body)}function cu(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Vh(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:a,includeHome:r=!0,homeLabel:o="Home directory",homeDescription:i="Launch without a workspace"}=e,c=[];r&&c.push({key:"__home__",label:o,description:i,workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])c.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${cu(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const d=(n==null?void 0:n.trim())||"",p=d?(t.workspaces||[]).find(u=>u.path===d):null;if(d&&!p&&c.push({key:`custom:${d}`,label:cu(d),description:d,workspaceId:null,workspacePath:d}),a){const u=`saved:${a}`;if(c.some(m=>m.key===u))return{options:c,selectedKey:u}}return p?{options:c,selectedKey:`saved:${p.id}`}:d?{options:c,selectedKey:`custom:${d}`}:{options:c,selectedKey:"__home__"}}function wA(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function kA(e){return[wA(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function SA(e){return e.lastLaunchedAt?za(e.lastLaunchedAt):""}function Yh(e){return{metaText:kA(e),updatedLabel:SA(e)}}function li(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function CA({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:a,onBrowseDirectory:r,onListSavedSessions:o}){var Ie,We,Xe,et;const i=da(),[c,d]=l.useState(!1),p=(((Ie=e.detectedIdes)==null?void 0:Ie.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(J=>({id:J.id,path:J.path,label:J.label})),[e]),m=e.defaultWorkspaceId||null,[f,g]=l.useState(m||((We=u[0])==null?void 0:We.id)||""),[k,h]=l.useState(""),[b,S]=l.useState(""),[x,y]=l.useState([]),[C,v]=l.useState(!1),[w,j]=l.useState(""),[N,A]=l.useState(!1),[T,I]=l.useState(li(p,t.length,n.length)),P=l.useRef(null),[M,E]=l.useState(null),D=l.useRef("__home__"),[W,R]=l.useState("__home__"),[B,_]=l.useState(""),[H,L]=l.useState(""),[F,$]=l.useState(""),[K,z]=l.useState([]),[ne,ie]=l.useState(()=>qt().textQuery),[Ce,me]=l.useState(()=>qt().workspaceQuery),[O,Y]=l.useState(()=>qt().modelQuery),[X,Q]=l.useState(()=>qt().resumableOnly),[ve,he]=l.useState(()=>qt().sortMode),[Z,fe]=l.useState(!1),[V,q]=l.useState(!1),ee=l.useRef(null),pe=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const le=f==="__custom__"?k.trim():((Xe=u.find(J=>J.id===f))==null?void 0:Xe.path)||"",se=f==="__custom__"&&!!le&&a.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(a.message),te=f!=="__custom__"&&((et=u.find(J=>J.id===f))==null?void 0:et.path)||"",ue=l.useMemo(()=>(e.recentLaunches||[]).map(J=>J.workspace),[e]),ye=l.useCallback(async J=>{v(!0),j("");try{const Le=await r(J);S(Le.path),h(Le.path),y(Le.directories)}catch(Le){j(Le instanceof Error?Le.message:"Could not load folder")}finally{v(!1)}},[r]),Me=l.useCallback(()=>{var Le;g("__custom__"),A(!0);const J=hc(e.platform,mc(k.trim(),te,ue,e.defaultWorkspacePath,(Le=u.find($e=>$e.id===m))==null?void 0:Le.path,u.map($e=>$e.path)));ye(J)},[k,m,ye,ue,te,e.platform,u]),re=l.useCallback(J=>{if(J!=null&&J.workspaceId){g(J.workspaceId),h("");return}if(J!=null&&J.workspacePath){g("__custom__"),h(J.workspacePath);return}g(""),h("")},[]),ce=l.useCallback(J=>{if(g(J),J==="__custom__"){Me();return}h("")},[Me]),Ae=l.useCallback(J=>{g("__custom__"),h(J)},[]),be=l.useCallback((J,Le)=>{P.current=Le,D.current=J.selectedWorkspaceKey||"__home__",R(J.selectedWorkspaceKey||"__home__"),_(J.initialArgs||""),L(J.initialModel||""),$(""),z([]);const $e=J.providerType?`${e.id}:${J.providerType}`:null;if(jj(pe.current,$e)){const at=qt();ie(at.textQuery),me(at.workspaceQuery),Y(at.modelQuery),Q(at.resumableOnly),he(at.sortMode)}pe.current=$e,E(J),J.providerType&&o&&(fe(!0),o(J.providerType).then(at=>z(at||[])).catch(at=>console.warn("Failed to load saved sessions",at)).finally(()=>fe(!1)))},[o,e.id]),we=l.useMemo(()=>ih(K,{textQuery:ne,workspaceQuery:Ce,modelQuery:O,resumableOnly:X,sortMode:ve}),[O,X,K,ve,ne,Ce]);l.useEffect(()=>{F&&(we.some(J=>J.providerSessionId===F)||$(""))},[we,F]);const _e=l.useCallback(()=>{P.current&&(q(!0),P.current().finally(()=>{P.current=null,q(!1),E(null)}))},[]),U=l.useCallback(()=>{P.current=null,E(null)},[]),Ne=l.useCallback(J=>{D.current=J,R(J)},[]);return l.useEffect(()=>{var J;ee.current!==e.id&&(ee.current=e.id,g(m||((J=u[0])==null?void 0:J.id)||"__custom__"),h(""),S(""),y([]),j(""),A(!1),ie(qt().textQuery),me(qt().workspaceQuery),Y(qt().modelQuery),Q(qt().resumableOnly),he(qt().sortMode),pe.current=null,I(li(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,u]),l.useEffect(()=>{var J;f!=="__custom__"&&(f&&u.some(Le=>Le.id===f)||g(m||((J=u[0])==null?void 0:J.id)||"__custom__"))},[m,f,u]),l.useEffect(()=>{T==="ide"&&p||T==="cli"&&t.length>0||T==="acp"&&n.length>0||I(li(p,t.length,n.length))},[T,n.length,t.length,p]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:p,workspaceRows:u,defaultWorkspaceId:m,workspaceChoice:f,customWorkspacePath:k,browseCurrentPath:b,browseDirectories:x,browseBusy:C,browseError:w,browseDialogOpen:N,activeLauncherKind:T,launchConfirm:M,launchConfirmWorkspaceKeyRef:D,launchConfirmWorkspaceKey:W,launchConfirmArgs:B,launchConfirmModel:H,launchConfirmResumeId:F,launchConfirmSavedSessions:K,launchConfirmTextFilter:ne,launchConfirmWorkspaceFilter:Ce,launchConfirmModelFilter:O,launchConfirmResumableOnly:X,launchConfirmSortMode:ve,filteredLaunchConfirmSavedSessions:we,launchConfirmSessionsLoading:Z,launchConfirmBusy:V,resolvedWorkspacePath:le,canCreateMissingWorkspace:se,openBrowseDialog:Me,loadBrowsePath:ye,handleWorkspaceChoiceChange:ce,chooseCustomWorkspacePath:Ae,setCustomWorkspacePath:h,setBrowseDialogOpen:A,setActiveLauncherKind:I,openLaunchConfirm:be,handleConfirmLaunch:_e,closeLaunchConfirm:U,setWorkspaceSelectionFromOption:re,setLaunchConfirmWorkspaceKeyAndSync:Ne,setLaunchConfirmArgs:_,setLaunchConfirmModel:L,setLaunchConfirmResumeId:$,setLaunchConfirmTextFilter:ie,setLaunchConfirmWorkspaceFilter:me,setLaunchConfirmModelFilter:Y,setLaunchConfirmResumableOnly:Q,setLaunchConfirmSortMode:he}}function jA({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:a,acpProviders:r,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:d,section:p,showBottomNav:u,onBack:m,onSectionChange:f,onOpenConversation:g,onOpenRecent:k,onOpenMachineDetails:h,onMachineUpgrade:b,onLaunchDetectedIde:S,onAddWorkspace:x,onBrowseDirectory:y,onLaunchWorkspaceProvider:C,onListSavedSessions:v}){const{t:w}=ke("common"),j=R=>R==="ide"?"IDE":R==="cli"?"CLI":"ACP",N=n.slice(0,4),A=t.slice(0,3),T=CA({selectedMachineEntry:e,cliProviders:a,acpProviders:r,machineAction:c,onBrowseDirectory:y,onListSavedSessions:v}),I=l.useMemo(()=>N.map(R=>{const{metaText:B,updatedLabel:_}=Yh(R);return{key:`recent-launch:${R.id}`,primary:R.label,secondary:B,updatedLabel:_,onClick:()=>{const{options:H,selectedKey:L}=Vh({machine:{workspaces:T.workspaceRows,defaultWorkspaceId:T.defaultWorkspaceId},currentWorkspacePath:R.workspace,homeLabel:w("newSession.homeDirectory"),homeDescription:w("newSession.launchWithoutWorkspace")});T.openLaunchConfirm({title:R.kind==="ide"?zr(w,"restart-ide",R.label):R.providerSessionId?ch(w,R.label):zr(w,"start-fresh",R.label),description:R.kind==="ide"?Kr(w,"restart-ide"):R.providerSessionId?dh(w):Kr(w,"start-fresh"),confirmLabel:R.kind==="ide"?Vr(w,"restart-ide"):R.providerSessionId?cl(w,!0):Vr(w,"start-fresh"),busyLabel:R.kind==="ide"?Yr(w,"restart-ide"):R.providerSessionId?lh(w,!0):Yr(w,"start-fresh"),workspaceOptions:H,selectedWorkspaceKey:L,details:[{label:"Mode",value:j(R.kind)},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]},async()=>{const F=H.find($=>$.key===T.launchConfirmWorkspaceKeyRef.current);T.setWorkspaceSelectionFromOption(F),await k({...R,workspace:(F==null?void 0:F.workspacePath)??null})})}}}),[T,k,N,w]),P=l.useMemo(()=>A.map(R=>({key:`recent-chat:${R.conversation.tabKey}`,primary:kt(R.conversation),secondary:QC(R.conversation,{timestampLabel:R.timestamp?Zp(R.timestamp):null}),unread:R.unread,onClick:()=>g(R.conversation)})),[g,A]),M=T.showAllRecent?I:I.slice(0,4),E=I.length>0,D=P.length>0,W=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${W} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx(_l,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:ds(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[D&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:P.map(R=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${R.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:R.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:R.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))})]}),E&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:M.map(R=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:R.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:R.primary}),R.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:R.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))}),I.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>T.setShowAllRecent(R=>!R),children:T.showAllRecent?"Show fewer":`Show ${I.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:b,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:h,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),T.browseDialogOpen&&s.jsx(bc,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:T.browseCurrentPath,directories:T.browseDirectories,busy:T.browseBusy,error:T.browseError,confirmLabel:"Use this folder",onClose:()=>T.setBrowseDialogOpen(!1),onNavigate:R=>{T.loadBrowsePath(R)},onConfirm:R=>{T.chooseCustomWorkspacePath(R),T.setBrowseDialogOpen(!1)}}),T.launchConfirm&&s.jsx(Ao,{title:T.launchConfirm.title,description:T.launchConfirm.description,details:T.launchConfirm.details,workspaceOptions:T.launchConfirm.workspaceOptions,selectedWorkspaceKey:T.launchConfirmWorkspaceKey,onWorkspaceChange:T.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:T.launchConfirm.providerType?cl(w,!!T.launchConfirmResumeId):T.launchConfirm.confirmLabel,busyLabel:T.launchConfirm.providerType?void 0:T.launchConfirm.busyLabel,busy:T.launchConfirmBusy,showArgsInput:T.launchConfirm.showArgsInput,argsValue:T.launchConfirmArgs,onArgsChange:T.setLaunchConfirmArgs,showModelInput:T.launchConfirm.showModelInput,modelValue:T.launchConfirmModel,onModelChange:T.setLaunchConfirmModel,historyProviderNode:T.launchConfirm.providerType&&(T.launchConfirmSessionsLoading||T.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),T.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:oc(w)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:T.launchConfirmTextFilter,onChange:R=>T.setLaunchConfirmTextFilter(R.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmWorkspaceFilter,onChange:R=>T.setLaunchConfirmWorkspaceFilter(R.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmModelFilter,onChange:R=>T.setLaunchConfirmModelFilter(R.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsxs("select",{value:T.launchConfirmSortMode,onChange:R=>T.setLaunchConfirmSortMode(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:T.launchConfirmResumableOnly,onChange:R=>T.setLaunchConfirmResumableOnly(R.target.checked),disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:T.launchConfirmResumeId,onChange:R=>T.setLaunchConfirmResumeId(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Tj(w)}),T.filteredLaunchConfirmSavedSessions.map(R=>s.jsxs("option",{value:R.providerSessionId,disabled:!R.canResume,children:[R.title||R.providerSessionId," ",R.canResume?"":"(workspace missing)"]},R.providerSessionId))]}),!T.launchConfirmSessionsLoading&&T.launchConfirmSavedSessions.length>0&&T.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),T.launchConfirmResumeId&&(()=>{const R=T.filteredLaunchConfirmSavedSessions.find(_=>_.providerSessionId===T.launchConfirmResumeId);if(!R)return null;const B=Kh(R);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:B.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:B.providerSessionId}),s.jsx("div",{className:"mt-1",children:B.metaLine}),B.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:B.updatedLabel}),B.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:B.preview})]})})()]}),onConfirm:T.handleConfirmLaunch,onCancel:T.closeLaunchConfirm}),u&&s.jsx(zh,{section:p,onSectionChange:f})]})}const du=8e3;function NA(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,n=t&&typeof t=="object",a=n&&t.success===!1,r=n&&t.mirrorStale===!0;return!a&&!r?{confirmed:!0}:{confirmed:!1,reason:a&&typeof t.error=="string"?t.error:r?"the coordinator did not confirm the change":"command was rejected"}}function Qh(e,t,n){const a=l.useRef(new Map),[,r]=l.useState(0),o=l.useCallback(()=>r(g=>g+1),[]);l.useEffect(()=>{const g=a.current;if(g.size===0)return;const k=Date.now();let h=!1;for(const[b,S]of g){const x=e.get(b),y=S.muted===void 0||(x?x.muted===S.muted:!1),C=S.hidden===void 0||(x?x.surfaceHidden===S.hidden:!1),v=k-S.at>du;(y&&C||v)&&(g.delete(b),h=!0)}h&&o()},[e,o]),l.useEffect(()=>{if(a.current.size===0)return;const g=setInterval(()=>{const k=a.current,h=Date.now();let b=!1;for(const[S,x]of k)h-x.at>du&&(k.delete(S),b=!0);b&&o(),k.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,k)=>{const h=a.current.get(g);a.current.set(g,{...h,...k,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const k=g.sessionId,h=k?a.current.get(k):void 0;return(h==null?void 0:h.muted)!==void 0?h.muted:rn(g,e).muted??!1},[e]),d=l.useCallback(g=>{const k=g.sessionId,h=k?a.current.get(k):void 0;return(h==null?void 0:h.hidden)!==void 0?h.hidden:rn(g,e).surfaceHidden??!1},[e]),p=l.useCallback((g,k)=>{const h=Vs(g),b=g.sessionId;!h||!b||(i(b,k),t(h,"set_conversation_prefs",{sessionId:b,...k,...ko(g)}).then(S=>{const x=NA(S);x.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",x.reason),a.current.delete(b),o(),n==null||n(`Couldn't update conversation — ${x.reason}`))}).catch(S=>{console.warn("[conversation-prefs] set_conversation_prefs failed",S),a.current.delete(b),o();const x=S instanceof Error?S.message:String(S??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${x}`)}))},[t,i,o,n]),u=l.useCallback(g=>{p(g,{muted:!c(g)})},[p,c]),m=l.useCallback((g,k)=>{p(g,{hidden:k})},[p]),f=l.useCallback(g=>{p(g,{hidden:!d(g)})},[p,d]);return{isMuted:c,isHidden:d,toggleMute:u,setHidden:m,toggleHidden:f}}function Ir(e){return[...e].sort((t,n)=>{const a=n.timestamp-t.timestamp;return a!==0?a:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function AA(e,t=[]){const n=new Map(e.map(r=>[r.conversation.tabKey,r])),a=t.map(r=>n.get(r)).filter(r=>!!r);return a.length===e.length?a:Ir(e)}function TA(e,t=[]){const n=e.filter(i=>i.requiresAction),a=e.filter(i=>i.unread&&!i.requiresAction),r=e.filter(i=>!i.unread&&!i.requiresAction&&i.isWorking),o=e.filter(i=>!i.unread&&!i.requiresAction&&!i.isWorking);return{attentionItems:Ir(n),unreadItems:Ir(a),workingItems:AA(r,t),completedItems:Ir(o)}}function To(e,t){if(!t)return!1;const n=e.filter(a=>a.type==="adhdev-daemon"&&Jh(a)==="Connected");return n.length===0?!0:n.every(a=>a._sessionListAuthoritative===!0)}function Jh(e){var a,r,o;const t=((a=e.p2p)==null?void 0:a.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((r=e.p2p)!=null&&r.available)||!!((o=e.p2p)!=null&&o.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function MA(e,t){if(!e)return[];const n=e.recentLaunches||[];return n.length>0?n.map(a=>({id:a.id,label:a.title||a.providerName||a.providerType,kind:a.kind,providerType:a.providerType,providerSessionId:a.providerSessionId,subtitle:Mn(a.summaryMetadata)||a.workspace||void 0,workspace:a.workspace,summaryMetadata:a.summaryMetadata})):t.filter(a=>a.type!=="adhdev-daemon"&&a.daemonId===e.id).map(a=>{var i;const r=Fa(a)?"cli":Xn(a)?"acp":"ide",o=Mn(a.summaryMetadata);return{id:`${r}:${a.type}:${a.workspace||""}`,label:((i=a.activeChat)==null?void 0:i.title)||(Fa(a)?a.cliName||a.type:Xn(a)&&a.cliName||a.type),kind:r,providerType:a.type,providerSessionId:a.providerSessionId,subtitle:Xn(a)?o||a.workspace||void 0:a.workspace||void 0,workspace:a.workspace||void 0,timestamp:a.lastMessageAt||0}}).sort((a,r)=>r.timestamp-a.timestamp).map(({timestamp:a,...r})=>r)}function PA(e,t,n=[]){const a=new Map;for(const o of t){const i=Vs(o.conversation),c=a.get(i);c?c.push(o):a.set(i,[o])}const r=new Map;for(const o of n){const i=Vs(o),c=r.get(i);c?c.push(o):r.set(i,[o])}return e.map(o=>{const i=a.get(o.id)||[],c=r.get(o.id)||[],d=[...i].sort((h,b)=>b.timestamp-h.timestamp)[0]||null,p=(d==null?void 0:d.conversation)||null,u=sl(o),m=i.filter(h=>h.unread||h.requiresAction).length,f=i.filter(h=>Ha(h.conversation)).length+c.filter(Ha).length,g=Jh(o),k=[o.platform||"machine",g].filter(Boolean);return{id:o.id,label:ds(o,{fallbackId:o.id}),subtitle:k.join(" · "),unread:m,total:i.length,generatingCount:f,latestConversation:p,latestTimestamp:(d==null?void 0:d.timestamp)||0,fallbackActivityAt:u,preview:p?JC(p,Vm(p)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((o,i)=>{const c=o.latestTimestamp||o.fallbackActivityAt||0,d=i.latestTimestamp||i.fallbackActivityAt||0;return d!==c?d-c:o.label.localeCompare(i.label)})}function DA(e){return e==="chat"}function mr(e,t){var n;if(!(typeof window>"u"))try{if(!(!!((n=import.meta.env)!=null&&n.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function IA({conversations:e,machineEntries:t,items:n,selectedConversation:a,selectedTabKey:r,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:k,setScreen:h,setSelectedMachineId:b,setSection:S,setMachineBackTarget:x,resetMachineAction:y}){const C=l.useRef(null),v=l.useCallback(w=>{if(!(w!=null&&w.sessionId))return;const j=rn(w,i),N=Math.max(Date.now(),Nn(w),j.lastUpdated||0);mr("mark_read:start",{tabKey:w.tabKey,sessionId:w.sessionId,displayPrimary:kt(w),inboxBucket:j.inboxBucket,unread:j.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:Nn(w),readAt:N}),c(Vs(w)||w.routeId,"mark_session_seen",{sessionId:w.sessionId,providerSessionId:w.providerSessionId,seenAt:N,completionMarker:j.completionMarker}).then(A=>{mr("mark_read:result",{tabKey:w.tabKey,sessionId:w.sessionId,result:A})}).catch(A=>{mr("mark_read:error",{tabKey:w.tabKey,sessionId:w.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var j;if(!a){DA(o)&&h("inbox"),k(((j=e[0])==null?void 0:j.tabKey)||null),C.current=null;return}if(o!=="chat"){C.current=null;return}const w=`${a.tabKey}:${a.sessionId||""}`;C.current!==w&&(C.current=w,v(a))},[e,v,o,a,h,k]),l.useEffect(()=>{if(!d)return;const w=e.find(j=>j.tabKey===d);w&&(k(w.tabKey),h("chat"),p==null||p())},[e,p,d,h,k]),l.useEffect(()=>{if(!u)return;const w=t.find(j=>j.id===u);w&&(b(w.id),y(),S("machines"),x("inbox"),h("machine"),m==null||m())},[t,m,u,y,x,h,S,b]),l.useEffect(()=>{f&&(S(f),h("inbox"),g==null||g())},[g,f,h,S]),l.useEffect(()=>{const w=n.filter(j=>j.inboxBucket==="task_complete"||j.unread);w.length!==0&&mr("inbox_state",{screen:o,selectedTabKey:r,items:w.map(j=>{const N=rn(j.conversation,i);return{liveState:N,tabKey:j.conversation.tabKey,sessionId:j.conversation.sessionId,displayPrimary:kt(j.conversation),serverBucket:N.inboxBucket,computedBucket:j.inboxBucket,serverUnread:N.unread,computedUnread:j.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:Nn(j.conversation)}})})},[n,i,o,r]),{markConversationRead:v}}function LA(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function uu(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function RA(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function EA({sendDaemonCommand:e,navigate:t,ides:n,conversations:a}){const{launchCli:r}=fo(),[o,i]=l.useState("idle"),[c,d]=l.useState(""),[p,u]=l.useState(null),m=l.useCallback(()=>{i("idle"),d(""),u(null)},[]),f=l.useCallback(async(y,C,v)=>{var w;try{i("loading"),d(`Launching ${C}…`);const j={ideType:C,enableCdp:!0};(w=v==null?void 0:v.workspacePath)!=null&&w.trim()&&(j.workspace=v.workspacePath.trim()),await e(y,"launch_ide",j),i("done"),d(`${C} launch requested`)}catch(j){i("error"),d(j instanceof Error?j.message:"Launch IDE failed"),console.error("Launch IDE failed",j)}},[e]),g=l.useCallback(async(y,C,v)=>{if(C.trim())try{i("loading"),d(v!=null&&v.createIfMissing?"Creating folder…":"Saving workspace…");const w=await e(y,"workspace_add",{path:C.trim(),createIfMissing:(v==null?void 0:v.createIfMissing)===!0});if(w!=null&&w.success){i("done"),d(v!=null&&v.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((w==null?void 0:w.error)||"Could not save workspace")}catch(w){i("error"),d(w instanceof Error?w.message:"Could not save workspace")}},[e]),k=l.useCallback(async y=>{i("loading"),d("Starting daemon upgrade…");const C=n.find(w=>w.id===y||w.daemonId===y),v=await j1(e,y,C);i(v.state),d(v.message)},[n,e]),h=l.useCallback(async(y,C,v,w)=>{var A,T,I;const j=Date.now(),N={machineId:y,kind:C,providerType:v,workspaceId:(w==null?void 0:w.workspaceId)||null,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:j};try{i("loading"),d(`Launching ${v}…`),u(N);const P={cliType:v};(A=w==null?void 0:w.workspacePath)!=null&&A.trim()?P.dir=w.workspacePath.trim():w!=null&&w.workspaceId?P.workspaceId=w.workspaceId:w!=null&&w.useHome&&(P.useHome=!0),w!=null&&w.resumeSessionId&&(P.resumeSessionId=w.resumeSessionId),(T=w==null?void 0:w.args)!=null&&T.trim()&&(P.cliArgs=w.args.trim().split(/\s+/).filter(Boolean)),(I=w==null?void 0:w.model)!=null&&I.trim()&&(P.initialModel=w.model.trim());const M=await r(y,P),E=(M==null?void 0:M.result)||M,D=(E==null?void 0:E.sessionId)||(E==null?void 0:E.id);if(M!=null&&M.success&&D){u(null),i("done"),d(`${v} launched`),t(Wa(D));return}if(M!=null&&M.success){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d((M==null?void 0:M.error)||(E==null?void 0:E.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(P){if(RA(P)){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d(P instanceof Error?P.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),b=l.useCallback(async(y,C)=>{try{const v=await e(y,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),w=(v==null?void 0:v.result)??v;return Array.isArray(w==null?void 0:w.sessions)?w.sessions:[]}catch(v){return console.error("Failed to list saved sessions on mobile:",v),[]}},[e]),S=l.useCallback(async(y,C)=>fc(e,y,C),[e]);l.useEffect(()=>{if(!p)return;const y=uu(p.workspacePath),C=n.find(w=>{var P,M,E,D;if(!w||w.type==="adhdev-daemon"||LA(w.daemonId||w.id)!==p.machineId||(w.transport==="acp"?"acp":w.transport==="pty"?"cli":null)!==p.kind||String(w.agentType||w.type||"")!==p.providerType)return!1;const T=String(w.providerSessionId||"");if(p.resumeSessionId&&T)return T===p.resumeSessionId;if(y){const W=uu(w.workspace||w.runtimeWorkspaceLabel);return W?W===y:!1}return Number(w.lastUpdated||w._lastUpdate||w.timestamp||((D=(E=(M=(P=w.activeChat)==null?void 0:P.messages)==null?void 0:M.at)==null?void 0:E.call(M,-1))==null?void 0:D.timestamp)||0)>=p.startedAt-5e3});if(!C)return;const v=Uh({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:a});v&&(u(null),i("done"),d(`${p.providerType} launched`),t(Wa(v)))},[a,n,t,p]),l.useEffect(()=>{if(!p)return;const y=window.setTimeout(()=>{u(C=>!C||C.startedAt!==p.startedAt?C:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(y)},[p]);const x=l.useCallback(async(y,C)=>{var v;if(C.kind==="ide"&&C.providerType){await f(y,C.providerType,{workspacePath:C.workspace||null});return}if((C.kind==="cli"||C.kind==="acp")&&C.providerType){const w=((v=C.workspace)==null?void 0:v.trim())||"";await h(y,C.kind,C.providerType,{workspacePath:w||null,useHome:!w,resumeSessionId:C.providerSessionId||null})}},[f,h]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:g,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:h,handleListSavedSessions:b,handleBrowseDirectory:S,handleOpenRecent:x}}function _A({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:a,resetMachineAction:r,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:p}){const u=l.useCallback(S=>{o(S.tabKey),i("chat"),a(S)},[a,i,o]),m=l.useCallback(S=>{const x=e.find(y=>y.routeId===S.routeId&&y.streamSource==="native");x&&(o(x.tabKey),i("chat"),a(x))},[e,a,i,o]),f=l.useCallback(()=>{a(t),i("inbox")},[a,t,i]),g=l.useCallback((S,x="inbox")=>{c(S),r(),d("machines"),p(x),i("machine")},[r,p,i,d,c]),k=l.useCallback(S=>{const x=Vs(S);x&&g(x,"chat")},[g]),h=l.useCallback(()=>{r(),i(n)},[n,r,i]),b=l.useCallback(S=>{d(S),i("inbox")},[i,d]);return{openConversation:u,openNativeConversation:m,backFromConversation:f,openMachine:g,openConversationMachine:k,backFromMachine:h,changeMachineSection:b}}function aa(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function HA(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function $A({conversations:e,hiddenConversations:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,onOpenHistory:k,onOpenRemote:h,onStopCli:b,wsStatus:S,isConnected:x,initialDataLoaded:y=!0,onShowAllHiddenConversations:C,onHideConversation:v,onOpenMeshGraph:w,onOpenNewSession:j,liveSessionInboxState:N,setCliViewModeOverrides:A}){const[T,I]=l.useState(()=>{var ce;return((ce=e[0])==null?void 0:ce.tabKey)||null}),[P,M]=l.useState(()=>e[0]?"chat":"inbox"),[E,D]=l.useState("chats"),[W,R]=l.useState(null),[B,_]=l.useState("inbox"),H=l.useRef([]),L=ia(),F="1.0.57",$=l.useMemo(()=>e.find(ce=>ce.tabKey===T)||e[0]||null,[e,T]),K=l.useMemo(()=>$?n.find(ce=>ce.id===$.routeId):void 0,[n,$]),z=l.useMemo(()=>!$||ht($)||!bt($)?null:ca($),[$]),ne=l.useMemo(()=>n.filter(ce=>ce.type==="adhdev-daemon").sort(Kl),[n]),ie=l.useMemo(()=>ne.find(ce=>ce.id===W)||null,[ne,W]),Ce=So({sendDaemonCommand:r,activeConv:$||void 0,setActionLogs:o,isStandalone:i}),me=EA({sendDaemonCommand:r,navigate:L,ides:n,conversations:e}),O=NC(e),Y=l.useMemo(()=>e.map(ce=>{const Ae=P==="chat"&&($==null?void 0:$.tabKey)===ce.tabKey,be=go(ce,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ae}),we=Nn(ce),_e=Vm(ce),U=th(ce,_e);return{conversation:ce,timestamp:we,preview:U,unread:be.unread,requiresAction:be.requiresAction,isWorking:be.isWorking,inboxBucket:be.inboxBucket}}),[e,N,P,$,O]),{markConversationRead:X}=IA({conversations:e,machineEntries:ne,items:Y,selectedConversation:$,selectedTabKey:T,screen:P,liveSessionInboxState:N,sendDaemonCommand:r,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:I,setScreen:M,setSelectedMachineId:R,setSection:D,setMachineBackTarget:_,resetMachineAction:me.resetMachineAction}),Q=_A({conversations:e,selectedConversation:$,machineBackTarget:B,markConversationRead:X,resetMachineAction:me.resetMachineAction,setSelectedTabKey:I,setScreen:M,setSelectedMachineId:R,setSection:D,setMachineBackTarget:_}),{isMuted:ve,toggleMute:he}=Qh(N,r),{attentionItems:Z,unreadItems:fe,workingItems:V,completedItems:q}=l.useMemo(()=>TA(Y,H.current),[Y]);l.useEffect(()=>{H.current=V.map(ce=>ce.conversation.tabKey)},[V]);const ee=l.useMemo(()=>ie?Y.filter(ce=>Vs(ce.conversation)===ie.id):[],[Y,ie]),pe=l.useMemo(()=>MA(ie,n),[n,ie]),le=!!ie&&jo(ie,Js(ie,F)),se=l.useMemo(()=>(ie==null?void 0:ie.availableProviders)||[],[ie]),te=l.useMemo(()=>se.filter(ce=>aa(ce,"cli")).map(ce=>({type:ce.type,displayName:ce.displayName||ce.type,icon:ce.icon})),[se]),ue=l.useMemo(()=>se.filter(ce=>aa(ce,"acp")).map(ce=>({type:ce.type,displayName:ce.displayName||ce.type,icon:ce.icon})),[se]),ye=l.useMemo(()=>PA(ne,Y,t),[Y,ne,t]),Me=l.useMemo(()=>To(n,y),[n,y]),re=l.useCallback(async ce=>{ie&&await me.handleOpenRecent(ie.id,ce)},[me,ie]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:P==="chat"&&$?s.jsx(gA,{selectedConversation:$,isAcp:ht($),isStandalone:i,selectedIdeEntry:K,actionLogs:a,userName:c,isSendingChat:Ce.isSendingChat,sendFeedbackMessage:Ce.sendFeedbackMessage,isFocusingAgent:Ce.isFocusingAgent,handleModalButton:Ce.handleModalButton,handleRelaunch:Ce.handleRelaunch,onBack:Q.backFromConversation,onOpenNativeConversation:Q.openNativeConversation,onOpenMachine:Q.openConversationMachine,onOpenHistory:k,onOpenRemote:h,onOpenMeshGraph:w,onStopCli:b,cliViewMode:z,onSetCliViewMode:async ce=>{await Lh({conversation:$,mode:ce,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:A})},handleSendChat:Ce.handleSendChat,handleForceSendChat:Ce.handleForceSendChat,handleFocusAgent:Ce.handleFocusAgent}):P==="machine"&&ie?s.jsx(jA,{selectedMachineEntry:ie,selectedMachineConversations:ee,selectedMachineRecentLaunches:pe,cliProviders:te,acpProviders:ue,selectedMachineNeedsUpgrade:le,appVersion:F,machineAction:me.machineAction,isStandalone:i,section:E,showBottomNav:B==="inbox",onBack:Q.backFromMachine,onSectionChange:Q.changeMachineSection,onOpenConversation:Q.openConversation,onOpenRecent:re,onOpenMachineDetails:()=>L(`/machines/${ie.id}`),onMachineUpgrade:()=>me.handleMachineUpgrade(ie.id),onLaunchDetectedIde:(ce,Ae)=>me.handleLaunchDetectedIde(ie.id,ce,Ae),onAddWorkspace:(ce,Ae)=>me.handleAddWorkspace(ie.id,ce,Ae),onBrowseDirectory:ce=>me.handleBrowseDirectory(ie.id,ce),onLaunchWorkspaceProvider:(ce,Ae,be)=>me.handleLaunchWorkspaceProvider(ie.id,ce,Ae,be),onListSavedSessions:ce=>me.handleListSavedSessions(ie.id,ce)}):s.jsx(vA,{section:E,attentionItems:Z,unreadItems:fe,workingItems:V,completedItems:q,hiddenConversations:t,machineCards:ye,getAvatarText:HA,actionLogs:a,sendDaemonCommand:r,onOpenConversation:Q.openConversation,onShowAllHidden:C,onHideConversation:v,onOpenMeshGraph:w,onStopCli:b,onOpenNewSession:j,onOpenMachine:Q.openMachine,onOpenSettings:()=>L("/settings"),onSectionChange:D,wsStatus:S,isConnected:x,initialDataLoaded:y,conversationsLoaded:Me,isStandalone:i,isConversationMuted:ve,onToggleMuteConversation:he})})}function ci(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function FA({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:a,onOwnTabDrop:r,onClearPreviewOrder:o}){const i=l.useRef(0),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useCallback(()=>{i.current=0,d(!1),u(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const f=l.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),g=l.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!ci(t,n)){u("merge");return}const S=b.currentTarget.getBoundingClientRect(),x=b.clientX-S.left,y=S.width/3;x<y?u("split-left"):x>y*2?u("split-right"):u("merge")},[t,n]),k=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),u(null))},[]),h=l.useCallback(b=>{i.current=0,d(!1);const S=b.dataTransfer.getData("text/tab-key"),x=S?e.some(C=>C.tabKey===S):!1,y=p;if(u(null),o(),!!S){if(b.preventDefault(),y==="split-left"&&ci(t,n)){n==null||n(S,"split-left");return}if(y==="split-right"&&ci(t,n)){n==null||n(S,"split-right");return}if(x){r(S);return}a==null||a(S)}},[e,p,t,n,a,r,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:f,handleDragOver:g,handleDragLeave:k,handleDrop:h}}function BA(e,t){const n=new Set(t.map(o=>o.tabKey)),a=e.filter(o=>n.has(o)),r=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...a,...r]}function WA({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:a,onTabOrderChange:r}){const[o,i]=l.useState(t??null),[c,d]=l.useState(n??[]),[p,u]=l.useState(null),m=l.useRef(null),f=l.useRef(null),g=l.useRef(a),k=l.useRef(r);l.useEffect(()=>{g.current=a},[a]),l.useEffect(()=>{k.current=r},[r]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(j=>{const N=BA(j,e);return N.length===j.length&&N.every((A,T)=>A===j[T])?j:N})},[e]);const h=l.useMemo(()=>{const j=p??c;if(j.length===0)return e;const N=new Map(j.map((A,T)=>[A,T]));return[...e].sort((A,T)=>{const I=N.get(A.tabKey)??999,P=N.get(T.tabKey)??999;return I-P})},[e,p,c]);l.useEffect(()=>{var N,A;if(h.length===0){o!==null&&(i(null),(N=g.current)==null||N.call(g,null));return}if(o&&h.some(T=>T.tabKey===o))return;const j=h[0].tabKey;j!==o&&(i(j),(A=g.current)==null||A.call(g,j))},[h,o]);const b=l.useMemo(()=>h.find(j=>j.tabKey===o),[h,o]),S=l.useCallback(j=>{var N;i(j),(N=g.current)==null||N.call(g,j)},[]),x=l.useCallback((j,N,A)=>{d(T=>{var E;const I=T.filter(D=>D!==j),P=I.indexOf(N);if(P<0)return T;const M=A==="left"?P:P+1;return I.splice(M,0,j),(E=k.current)==null||E.call(k,I),I}),u(null)},[]),y=l.useCallback((j,N,A)=>{const I=(c.length>0?c:e.map(E=>E.tabKey)).filter(E=>E!==j),P=I.indexOf(N);if(P<0)return;const M=A==="left"?P:P+1;I.splice(M,0,j),m.current=I,u(I)},[c,e]),C=l.useCallback(()=>{var N;const j=m.current;j&&(d(j),(N=k.current)==null||N.call(k,j))},[]),v=l.useCallback(()=>{m.current=null,u(null)},[]),w=l.useCallback(j=>{d(N=>{var T;const A=N.filter(I=>I!==j);return A.push(j),(T=k.current)==null||T.call(k,A),A})},[]);return{activeTabId:o,activeConv:b,sortedConversations:h,previewOrderRef:m,draggingTabRef:f,selectTab:S,handleTabReorder:x,updatePreviewOrder:y,commitPreviewOrder:C,clearPreviewOrder:v,moveTabToEnd:w,setDraggingTabKey:j=>{f.current=j}}}function OA({dropAction:e,canSplit:t}){return s.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),s.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function xc({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:a=!1,suppressGuide:r=!1,onOpenNewSession:o,isLoading:i=!1}){const{t:c}=ke("common");if(r)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});if(i)return s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center gap-3 -mt-8 text-text-muted",children:[s.jsx(ls,{}),s.jsx("p",{className:"text-sm",children:c("paneGroup.loadingSessions")})]});const d=!n&&!a,p=a&&!!o,u=c(a?"paneGroup.noConversations":n?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),m=c(a?"paneGroup.newSessionDescription":n?"paneGroup.daemonDescription":"paneGroup.installDescription");return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:u}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),p&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:c("paneGroup.newSession"),"aria-label":c("paneGroup.newSession"),children:[s.jsx(Wl,{size:14}),s.jsx("span",{children:c("paneGroup.newSession")})]})}),d&&s.jsx(qh,{}),d&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const Xh="adhdev-tab-shortcuts";function Zh(){try{return JSON.parse(localStorage.getItem(Xh)||"{}")}catch{return{}}}function ef({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:a}){const r=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>Zh()),[c,d]=l.useState(null),p=l.useCallback(m=>{const f=[];return m.metaKey&&f.push(r?"⌘":"Meta"),m.ctrlKey&&f.push("Ctrl"),m.altKey&&f.push(r?"⌥":"Alt"),m.shiftKey&&f.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(f.push(m.key.length===1?m.key.toUpperCase():m.key),f.join("+"))},[r]),u=l.useCallback(m=>{i(m);try{localStorage.setItem(Xh,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){d(null);return}const g=p(f);if(!g)return;const k={...o};for(const[h,b]of Object.entries(k))b===g&&delete k[h];k[c]=g,u(k),d(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,u,p]),l.useEffect(()=>{if(!e)return;const m=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[g,k]of Object.entries(o))if(t.includes(g)&&p(f)===k){f.preventDefault(),n(),a(g);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,n,a,p]),{isMac:r,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const di=e=>{e.preventDefault()},UA=l.memo(function({conv:t,isActive:n,isDraggedTab:a,isTaskCompleteUnread:r,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:p,onConversationActivated:u,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:g,onClearPreviewOrder:k,onDragStateReset:h,onDragTabKeyChange:b,onReceiveTab:S,onOpenContextMenu:x,longPressTimer:y,isGroupActive:C}){const v=En(t),w=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",j=v.isReconnecting,N=VC(t),A=YC(t),T=eh(t),I=l.useCallback(H=>{c.current=t.tabKey,b(t.tabKey),H.dataTransfer.setData("text/tab-key",t.tabKey),H.dataTransfer.effectAllowed="move"},[t.tabKey,c,b]),P=l.useCallback(()=>{c.current=null,b(null),g(),k(),h()},[c,b,g,k,h]),M=l.useCallback(H=>{const L=c.current;if(!(!L||L===t.tabKey)&&H.dataTransfer.types.includes("text/tab-key")){H.preventDefault(),H.stopPropagation();const F=H.currentTarget.getBoundingClientRect(),$=H.clientX<F.left+F.width/2?"left":"right";m(L,t.tabKey,$)}},[t.tabKey,c,m]),E=l.useCallback(H=>{H.preventDefault(),H.stopPropagation();const L=H.dataTransfer.getData("text/tab-key");if(L&&L!==t.tabKey){const F=H.currentTarget.getBoundingClientRect(),$=H.clientX<F.left+F.width/2?"left":"right";i.includes(L)?f(L,t.tabKey,$):S&&S(L)}k()},[t.tabKey,i,f,S,k]),D=l.useCallback(H=>{H.stopPropagation(),d(),p(t.tabKey),u(t)},[t,u,d,p]),W=l.useCallback(H=>{H.preventDefault(),x(H.clientX,H.clientY,t.tabKey)},[t.tabKey,x]),R=l.useCallback(H=>{const L=H.touches[0];y.current=setTimeout(()=>{x(L.clientX,L.clientY,t.tabKey)},600)},[t.tabKey,y,x]),B=l.useCallback(()=>{y.current&&clearTimeout(y.current)},[y]),_=["adhdev-dockview-tab",w,n&&"is-active",C&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:_,draggable:!0,onDragStart:I,onDragEnd:P,onDragOver:M,onDrop:E,onClick:D,onContextMenu:W,onTouchStart:R,onTouchEnd:B,onTouchMove:B,style:{position:"relative",cursor:"pointer",opacity:a?.4:void 0},children:[T&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-badge pointer-events-none absolute top-0.5 right-0.5 text-text-muted",title:"Mesh chat","aria-label":"Mesh chat",children:s.jsx(cs,{size:11})}),r&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:v.isGenerating?s.jsx(ls,{size:12,thickness:2,color:"success"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?s.jsx(ls,{size:12,thickness:2}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),N.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:A,"aria-label":A||N.join(" · "),children:N.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:kt(t),children:kt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[j?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Sn(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Sn(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:Sn(t)}),s.jsx(qr,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),o&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${o}`,children:o})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function GA({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:a,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onHideTab:h,isGroupActive:b,allowTabShortcuts:S=!0}){const{t:x}=ke("common"),[y,C]=l.useState(null),v=l.useRef(null),w=l.useRef(null),j=l.useMemo(()=>e.map(E=>E.tabKey),[e]);qa("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(y==null?void 0:y.tabKey)||null});const{isMac:N,tabShortcuts:A,shortcutListening:T,setShortcutListening:I,saveShortcuts:P}=ef({enabled:S,sortedTabKeys:e.map(E=>E.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!y)return;const E=D=>{const W=document.querySelector("[data-pane-context-menu]");W&&W.contains(D.target)||C(null)};return window.addEventListener("mousedown",E,!0),()=>window.removeEventListener("mousedown",E,!0)},[y]),l.useEffect(()=>{const E=w.current;if(!E)return;const D=W=>{Math.abs(W.deltaY)<=Math.abs(W.deltaX)||(W.preventDefault(),E.scrollLeft+=W.deltaY)};return E.addEventListener("wheel",D,{passive:!1}),()=>E.removeEventListener("wheel",D)},[]);const M=l.useCallback((E,D,W)=>{C({x:E,y:D,tabKey:W})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:w,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(E=>s.jsx(UA,{conv:E,isActive:t===E.tabKey,isDraggedTab:r.current===E.tabKey,isTaskCompleteUnread:a.has(E.tabKey),shortcut:S?A[E.tabKey]:void 0,conversationKeys:j,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onOpenContextMenu:M,longPressTimer:v,isGroupActive:b},E.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:x("paneGroup.noTabsInGroup")})]})}),y&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:y.x,top:y.y},children:[S&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:di,onClick:E=>{E.stopPropagation(),I(y.tabKey),C(null)},children:["⌨ ",A[y.tabKey]?`Change shortcut (${A[y.tabKey]})`:"Set shortcut"]}),A[y.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:di,onClick:()=>{const E={...A};delete E[y.tabKey],P(E),C(null)},children:"✕ Remove shortcut"})]}),h&&s.jsxs(s.Fragment,{children:[S&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:di,onClick:()=>{h(y.tabKey),C(null)},children:s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(mo,{size:12}),"Hide from Dashboard"]})})]})]}),S&&T&&s.jsx(Vt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>I(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:E=>E.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",N?"⌘+1":"Ctrl+1",", ",N?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:x("paneGroup.pressEscToCancel")})]})})})]})}function qA({conversations:e,ides:t,clearedTabs:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d=!0,userName:p,groupIndex:u,onFocus:m,isSplitMode:f,numGroups:g,onMoveTab:k,onReceiveTab:h,style:b,onActiveTabChange:S,initialActiveTabId:x,initialTabOrder:y,onTabOrderChange:C,onHideTab:v,isFocused:w,allowTabShortcuts:j=!0,onOpenNewSession:N,liveSessionInboxState:A}){const{sendCommand:T}=St(),I=l.useRef(null),{activeTabId:P,activeConv:M,sortedConversations:E,draggingTabRef:D,selectTab:W,handleTabReorder:R,updatePreviewOrder:B,commitPreviewOrder:_,clearPreviewOrder:H,moveTabToEnd:L,setDraggingTabKey:F}=WA({conversations:e,initialActiveTabId:x,initialTabOrder:y,onActiveTabChange:S,onTabOrderChange:C}),$=So({sendDaemonCommand:r,activeConv:M,setActionLogs:o,isStandalone:i}),{dragOver:K,dropAction:z,resetDragState:ne,handleDragEnter:ie,handleDragOver:Ce,handleDragLeave:me,handleDrop:O}=FA({conversations:e,numGroups:g,onMoveTab:k,onReceiveTab:h,onOwnTabDrop:L,onClearPreviewOrder:H}),Y=M&&!ht(M)&&ca(M)==="terminal",X=l.useMemo(()=>M?t.find(Z=>Z.id===M.routeId):void 0,[t,M]),Q=l.useMemo(()=>M?a.filter(Z=>Z.routeId===M.tabKey):[],[a,M]),ve=l.useMemo(()=>new Set(E.filter(Z=>Lx(Z,A,{isOpenConversation:Z.tabKey===P})).map(Z=>Z.tabKey)),[P,A,E]);qa("PaneGroup",{groupIndex:u,conversationCount:e.length,activeTabId:P,dragOver:K});const he=l.useCallback(Z=>{Z.streamSource==="agent-stream"&&Z.agentType&&T(Z.routeId,Em(),{agentType:Z.agentType,...Z.sessionId&&{targetSessionId:Z.sessionId}}).catch(()=>{})},[T]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:m,style:{...b,outline:K?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(GA,{conversations:E,activeTabId:P,groupIndex:u,numGroups:g,unreadTabKeys:ve,draggingTabRef:D,onFocus:m,onSelectTab:W,onConversationActivated:he,onPreviewReorder:B,onReorderTab:R,onCommitPreviewOrder:_,onClearPreviewOrder:H,onDragStateReset:ne,onDragTabKeyChange:F,onMoveTab:k,onReceiveTab:h,onHideTab:v,isGroupActive:w??!1,allowTabShortcuts:j}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ie,onDragOver:Ce,onDragLeave:me,onDrop:O,children:[K&&s.jsx(OA,{dropAction:z,canSplit:!!(g<4&&k)}),M?s.jsx(gc,{activeConv:M,clearToken:n[M.tabKey]||0,isCliTerminal:!!Y,ideEntry:X,terminalRef:I,handleModalButton:$.handleModalButton,handleRelaunch:$.handleRelaunch,handleSendChat:$.handleSendChat,handleForceSendChat:$.handleForceSendChat,isSendingChat:$.isSendingChat,sendFeedbackMessage:$.sendFeedbackMessage,handleFocusAgent:$.handleFocusAgent,isFocusingAgent:$.isFocusingAgent,actionLogs:Q,userName:p,isInputActive:!f||!!w}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(xc,{conversationsCount:e.length,isSplitMode:f,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N,isLoading:!To(t,d)})})]})]})}function zA({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:a,groupedConvs:r,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,initialDataLoaded:f,userName:g,focusedGroup:k,focusGroup:h,moveTabToGroup:b,splitTabRelative:S,closeGroup:x,handleResizeStart:y,groupActiveTabIds:C,setGroupActiveTab:v,groupTabOrders:w,setGroupTabOrder:j,toggleHiddenTab:N,onOpenNewSession:A,allowTabShortcuts:T=!0,liveSessionInboxState:I}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:r.map((P,M)=>{const E=t&&a.length===n?`${a[M]}%`:void 0;return s.jsxs(Rt.Fragment,{children:[t&&M>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:D=>y(M-1,D),onDoubleClick:()=>x(M),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(qA,{style:t?{flexBasis:E??`${100/n}%`,flexGrow:E?0:1,flexShrink:E?0:1}:void 0,conversations:P,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,initialDataLoaded:f,userName:g,groupIndex:M,isFocused:t&&k===M,onFocus:()=>h(M),isSplitMode:t,numGroups:n,onMoveTab:(D,W)=>{W==="left"&&M>0?b(D,M-1):W==="right"&&M<n-1?b(D,M+1):W==="split-left"&&n<4?S(D,M,"left"):W==="split-right"&&n<4&&S(D,M,"right")},onReceiveTab:D=>b(D,M),onActiveTabChange:D=>v(M,D),initialActiveTabId:C[M],initialTabOrder:w[M],onTabOrderChange:D=>j(M,D),onHideTab:N,onOpenNewSession:A,allowTabShortcuts:T,liveSessionInboxState:I})]},M)})})}const tf="adhdev-dashboard-action-shortcuts",KA=1200,VA=[["toggleHiddenTabs","G H"],["openNewSession","N"],["setActiveTabShortcut","G S"],["selectPreviousGroupTab","G K"],["selectPreviousGroupTab","T ←"],["selectPreviousGroupTab","⌥+["],["selectPreviousGroupTab","Ctrl+Alt+["],["selectNextGroupTab","G J"],["selectNextGroupTab","T →"],["selectNextGroupTab","⌥+]"],["selectNextGroupTab","Ctrl+Alt+]"],["splitActiveTabDown","S ↓"],["splitActiveTabDown","⌘+⌥+-"],["splitActiveTabDown","Ctrl+Alt+-"],["splitActiveTabRight","S →"],["splitActiveTabRight","⌘+⌥+\\"],["splitActiveTabRight","⌘+⌥+="],["splitActiveTabRight","Ctrl+Alt+\\"],["focusLeftPane","F ←"],["focusLeftPane","⌘+⌥+←"],["focusLeftPane","⌘+⌥+["],["focusLeftPane","Ctrl+Alt+←"],["focusRightPane","F →"],["focusRightPane","⌘+⌥+→"],["focusRightPane","⌘+⌥+]"],["focusRightPane","Ctrl+Alt+→"],["focusUpPane","F ↑"],["focusUpPane","⌘+⌥+U"],["focusUpPane","Ctrl+Alt+↑"],["focusDownPane","F ↓"],["focusDownPane","⌘+⌥+J"],["focusDownPane","Ctrl+Alt+↓"],["moveActiveTabToLeftPane","M ←"],["moveActiveTabToLeftPane","⌘+⌥+⇧+←"],["moveActiveTabToLeftPane","⌘+⌥+,"],["moveActiveTabToLeftPane","Ctrl+Alt+Shift+←"],["moveActiveTabToRightPane","M →"],["moveActiveTabToRightPane","⌘+⌥+⇧+→"],["moveActiveTabToRightPane","⌘+⌥+."],["moveActiveTabToRightPane","Ctrl+Alt+Shift+→"],["moveActiveTabToUpPane","M ↑"],["moveActiveTabToUpPane","⌘+⌥+I"],["moveActiveTabToUpPane","Ctrl+Alt+Shift+↑"],["moveActiveTabToDownPane","M ↓"],["moveActiveTabToDownPane","⌘+⌥+K"],["moveActiveTabToDownPane","Ctrl+Alt+Shift+↓"],["triggerPrimaryApprovalAction","⌥+A"],["triggerSecondaryApprovalAction","⌥+D"],["toggleCliView","T"]];function YA(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function gt(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function sf(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:gt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:gt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:gt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:gt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:gt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:gt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:gt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:gt("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:gt("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:gt("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:gt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:gt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:gt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:gt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:gt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:gt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:gt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:gt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:gt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:gt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:gt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:gt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:gt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:gt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:gt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:gt("toggleCliView",e)}]}function bl(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function eo(e){const t=Object.fromEntries(sf(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(tf)||"{}"),a={...t,...n};for(const[r,o]of VA)a[r]===o&&(a[r]=t[r]);return a}catch{return t}}function nf(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function QA({enabled:e=!0,onTrigger:t}){const n=YA(),[a,r]=l.useState(()=>eo(n)),[o,i]=l.useState(null),[c,d]=l.useState([]),p=l.useRef({parts:[],timer:null}),u=l.useCallback(h=>{const b=[];return h.metaKey&&b.push(n?"⌘":"Meta"),h.ctrlKey&&b.push("Ctrl"),h.altKey&&b.push(n?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&b.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(b.push(nf(h.key)),b.join("+"))},[n]),m=l.useCallback(h=>{r(h);try{localStorage.setItem(tf,JSON.stringify(h))}catch{}},[]);l.useEffect(()=>{const h=eo(n),b=Object.entries(a),S=Object.entries(h);b.length===S.length&&b.every(([x,y])=>h[x]===y)||m(h)},[a,n,m]);const f=l.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),g=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},KA))},[]);l.useEffect(()=>{if(!o)return;const h=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){i(null),d([]);return}const S=u(b);if(!S)return;const y=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(S);if(c.length===0&&y){d([S]);return}const v=[...c,S].slice(0,2).join(" "),w={...a};for(const[j,N]of Object.entries(w))N===v&&delete w[j];w[o]=v,m(w),i(null),d([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[a,u,m,o,c]),l.useEffect(()=>{if(!e||o)return;const h=b=>{if(b.defaultPrevented)return;const S=u(b);if(!S)return;const x=b.metaKey||b.ctrlKey||b.altKey;if(bl(b.target))return;const y=p.current.parts,C=x?[S]:[...y.slice(-1),S].slice(-2),v=C.join(" "),w=C[C.length-1],j=Object.entries(a).filter(([,P])=>!!P),N=j.find(([,P])=>P===v);if(N){b.preventDefault(),f(),t(N[0]);return}if(j.some(([,P])=>P.startsWith(`${v} `))){b.preventDefault(),p.current.parts=C,g();return}const T=j.find(([,P])=>P===w);if(T){b.preventDefault(),f(),t(T[0]);return}if(j.some(([,P])=>P.startsWith(`${w} `))){b.preventDefault(),p.current.parts=[w],g();return}f()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[a,g,e,u,t,f,o]),l.useEffect(()=>()=>f(),[f]);const k=l.useMemo(()=>sf(n),[n]);return{isMac:n,actionDefinitions:k,actionShortcuts:a,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:m}}function JA({isTabInPopout:e,isTabFloating:t,tabShortcut:n,actionShortcuts:a}){const r=[];return e?(t&&r.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:a.dockActiveTab}),r.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:a.dockActiveTab})):t?r.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:a.dockActiveTab}):r.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:a.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:a.popoutActiveTab}),r.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:n?`Change shortcut (${n})`:"Set shortcut",shortcut:a.setActiveTabShortcut}),n&&r.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),r.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:a.hideCurrentTab,tone:"muted"}),r}function af(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function pu({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:a}){return!e||n>0?!1:t?!af(a):!0}function XA({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:af(n)}const rf=1e3,ZA=4;function mu(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function hu(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function eT({detachDelayMs:e=rf,stillnessThresholdPx:t=ZA,onDetach:n,setTimeoutFn:a=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:r=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,d=null,p=null,u=!1;const m=()=>{p!=null&&(r(p),p=null)},f=()=>{m(),c=null},g=()=>{m(),o=null,i=null,c=null,d=null,u=!1},k=()=>{!o||!c||!d||u||p!=null||(p=a(()=>{p=null,!(!o||!c||!d||u)&&mu(d,i)&&(hu(c,d,t)||(u=!0,n({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},h=S=>{if(!(!o||u)){if(!mu(S,i)){d={clientX:S.clientX,clientY:S.clientY},f();return}(!c||hu(c,S,t))&&(m(),c={clientX:S.clientX,clientY:S.clientY}),d={clientX:S.clientX,clientY:S.clientY},k()}},b=S=>{!o||u||(S&&(d={clientX:S.clientX,clientY:S.clientY}),f())};return{startDrag:S=>{m(),o=S.panelId,i=S.selfPanelBounds??null,c=null,d={clientX:S.clientX,clientY:S.clientY},u=!1},markSelfPanel:h,markNonSelfPanel:b,markNoDropTarget:b,markDockTarget:b,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>u,dispose:g}}function tT(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Lr(e){return kt(e)||e.tabKey}function sT(e){return`remote:${e}`}function fs(e){return e.startsWith("remote:")}function fu(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ui(e){var a;const t=e==null?void 0:e.defaultView;if(!t)return;const n=r=>{if(r)try{r.focus({preventScroll:!0})}catch{try{r.focus()}catch{}}};try{t.focus(),n(e==null?void 0:e.body),n(e==null?void 0:e.documentElement),(a=t.requestAnimationFrame)==null||a.call(t,()=>{try{t.focus(),n(e==null?void 0:e.body)}catch{}})}catch{}}function pi(e,t){e.classList.remove(Wi.className,Oi.className),e.classList.add(t==="light"?Wi.className:Oi.className)}function gu(e){return e?Array.from(new Set(e.groups.map(t=>{var n,a;return(a=(n=t.element)==null?void 0:n.ownerDocument)==null?void 0:a.defaultView}).filter(t=>!!t&&t!==window))):[]}function nT(e,t,n){var i;const a=[t];let r;for(const c of a){let d;for(const p of c){const u=e.addPanel({id:p.tabKey,component:"conversation",title:Lr(p),params:{kind:"conversation",tabKey:p.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:r?{position:{referencePanel:r,direction:"right"},inactive:!0}:{}});d||(d=u.id)}r=d??r}return n??((i=t[0])==null?void 0:i.tabKey)??null}function bu(e,t){const n=new Set(t.map(r=>r.tabKey)),a=new Map;for(const r of t)a.set(r.tabKey,(a.get(r.tabKey)||0)+1);for(const r of[...e.panels])fs(r.id)||n.has(r.id)||e.removePanel(r);for(const r of t){const o=e.getPanel(r.tabKey);if(o){(a.get(r.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:r.tabKey,daemonId:r.daemonId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,panelId:o.id}),o.update({params:{tabKey:r.tabKey}}),o.title!==Lr(r)&&o.api.setTitle(Lr(r));continue}e.addPanel({id:r.tabKey,component:"conversation",title:Lr(r),params:{kind:"conversation",tabKey:r.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function xu(e,t,n){var d,p;const a=n?sT(n):null;for(const u of[...e.panels])fs(u.id)&&(!a||u.id!==a)&&e.removePanel(u);if(!n||!a)return;const r=ws(t,n);if(!r&&e.totalPanels===0)return;const o=e.getPanel(a),i=ah(r);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(r==null?void 0:r.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((p=e.panels.find(u=>!fs(u.id)))==null?void 0:p.id);e.addPanel({id:a,component:"remote",title:i,params:{kind:"remote",routeId:n},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function of({doId:e,targetSessionId:t,connState:n,viewMode:a}){const[r,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?Ct.onScreenshot("ide-page",(u,m)=>{if(u!==e)return;const f=new FileReader;f.onload=()=>o(f.result),f.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&o(null)},[n]),l.useEffect(()=>{var u;return e?((u=Ct.onStatus)==null?void 0:u.call(Ct,(m,f)=>{m===e&&f!=null&&f.screenshotUsage&&c(f.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?Ct.get(e):null;if(!(!p||n!=="connected"))return a!=="chat"&&t?p.startScreenshots(t):p.stopScreenshots(t),()=>{p.stopScreenshots(t)}},[a,n,t,e]);const d=l.useCallback(async(p,u)=>{const m=e?Ct.get(e):null;return!m||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(p,u,t)},[e,n,t]);return{connScreenshot:r,screenshotUsage:i,handleRemoteAction:d}}const lf=l.createContext(null);function Mo(){const e=l.useContext(lf);if(!e)throw new Error("DashboardDockviewContext missing");return e}function aT(e){const[,t]=l.useState(0);l.useEffect(()=>{const n=()=>t(r=>r+1),a=[e.api.onDidActiveGroupChange(n),e.api.onDidTitleChange(n),e.api.onDidGroupChange(n),e.containerApi.onDidActivePanelChange(n)];return()=>{for(const r of a)r.dispose()}},[e.api,e.containerApi])}function rT({params:e}){var d;const t=Mo(),n=l.useMemo(()=>ws([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),a=l.useMemo(()=>t.ides.find(p=>p.id===e.routeId),[t.ides,e.routeId]),r=(n==null?void 0:n.daemonId)||((d=n==null?void 0:n.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=of({doId:r,targetSessionId:n?Lm(n):(a==null?void 0:a.sessionId)||(a==null?void 0:a.instanceId),connState:(n==null?void 0:n.connectionState)||"new",viewMode:"remote"});return n?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(Qp,{addLog:()=>{},connState:n.connectionState||"new",connScreenshot:o,screenshotUsage:i,transportType:n.transport,onAction:c})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function oT(){const e=Mo();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(xc,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels,isLoading:!To(e.ides,e.initialDataLoaded)})})}function iT(e){var x,y;aT(e);const t=Mo(),n=l.useCallback(C=>{"button"in C&&C.button!==0||e.api.setActive()},[e.api]),a=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),r=a==null?void 0:a.sessionId,o=l.useCallback(C=>PC(C),[]),i=l.useCallback(()=>MC(r),[r]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const C=ws([...t.conversationsByTabKey.values()],e.params.routeId),v=((x=e.api.group.activePanel)==null?void 0:x.id)===e.api.id,w=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${v?" is-active":""}${w?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(C==null?void 0:C.tabKey)||"",onMouseDown:n,onTouchStart:n,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:C!=null&&C.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:C.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const d=t.conversationsByTabKey.get(e.params.tabKey);if(!d)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const p=((y=e.api.group.activePanel)==null?void 0:y.id)===e.api.id,u=e.api.isGroupActive,m=go(d,t.liveSessionInboxState,{isOpenConversation:p}),f=m.isReconnecting,g=m.isConnecting,k=m.isGenerating||c,h=m.isWaiting,b=m.unread,S=t.tabShortcuts[d.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${u?" is-group-active":""}${f?" is-reconnecting":""}`,title:kt(d),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:C=>{var v;C.preventDefault(),n(C),t.openTabContextMenu({x:C.clientX,y:C.clientY,tabKey:d.tabKey,sourceDocument:((v=C.target)==null?void 0:v.ownerDocument)??document})},children:[b&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:k?s.jsx(ls,{size:12,thickness:2,color:"success"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):g?s.jsx(ls,{size:12,thickness:2}):d.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:kt(d)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Sn(d)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Sn(d)}):s.jsx("span",{children:Sn(d)})})]}),S&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:S,children:S})]})}function hr(e){return e.isActive}function vu(e){return e.isVisible}function lT(e){e.preventDefault()}function cT({params:e,api:t}){var g;const n=Mo(),a=l.useRef(null),[r,o]=l.useState(()=>hr(t)),[i,c]=l.useState(()=>vu(t)),d=n.conversationsByTabKey.get(e.tabKey),p=So({sendDaemonCommand:n.sendDaemonCommand,activeConv:d,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(hr(t)),c(vu(t));const k=[t.onDidActiveChange(h=>o(h.isActive)),t.onDidActiveGroupChange(h=>{if(!hr(t)&&!h.isActive){o(!1);return}o(hr(t))}),t.onDidVisibilityChange(h=>c(h.isVisible))];return()=>{for(const h of k)h.dispose()}},[t]);const u=l.useMemo(()=>d?n.ides.find(k=>k.id===d.routeId):void 0,[n.ides,d]),m=l.useMemo(()=>d?n.actionLogs.filter(k=>k.routeId===d.tabKey):[],[n.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(xc,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels,isLoading:!To(n.ides,n.initialDataLoaded)})});const f=!ht(d)&&ca(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(gc,{activeConv:d,clearToken:n.clearedTabs[d.tabKey]||0,isCliTerminal:f,ideEntry:u,terminalRef:a,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((g=n.scrollToBottomRequest)==null?void 0:g.tabKey)===d.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:r,isVisible:i})})}function dT({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:p,toggleHiddenTab:u,actionShortcuts:m,registerActionHandlers:f,onActiveTabChange:g,onOpenNewSession:k,onRequestScrollToBottom:h,requestedActiveTabKey:b,requestedRemoteIdeId:S,onRequestedActiveTabConsumed:x,scrollToBottomRequest:y,liveSessionInboxState:C,layoutProfile:v}){var $e,at,rt;const{theme:w}=Rs(),{sendCommand:j}=St(),N=l.useRef(null),A=l.useRef(null),T=l.useRef(null),I=l.useRef(!1),P=l.useRef(!1),M=l.useRef(!1),E=l.useRef(null),D=l.useRef([]),[W,R]=l.useState(null),[B,_]=l.useState(0),H=l.useRef(typeof window>"u"?{}:TN(v)),L=l.useMemo(()=>new Map(e.map(G=>[G.tabKey,G])),[e]),F=l.useMemo(()=>{const G=N.current;return G?G.groups.some(oe=>{try{const de=oe.model.location.type;return de!=="floating"&&de!=="popout"?!1:oe.panels.some(xe=>L.has(xe.id))}catch{return!1}}):!1},[L,B,e]),$=l.useCallback(()=>{var G;(G=N.current)==null||G.focus()},[]),K=l.useCallback((G,oe)=>{h==null||h(G,oe)},[h]),z=l.useCallback(G=>{const oe=document,de=G.document;for(const Ee of oe.querySelectorAll('link[rel="stylesheet"]')){const Je=de.createElement("link");Je.rel="stylesheet",Je.href=Ee.href,Ee.crossOrigin&&(Je.crossOrigin=Ee.crossOrigin),de.head.appendChild(Je)}for(const Ee of oe.querySelectorAll("style")){const Je=de.createElement("style");Je.textContent=Ee.textContent,de.head.appendChild(Je)}const xe=[];for(const Ee of oe.styleSheets)try{for(const Je of Ee.cssRules)Je instanceof CSSStyleRule&&(Je.selectorText===":root"||Je.selectorText==="html")&&xe.push(Je.cssText)}catch{}if(xe.length>0){const Ee=de.createElement("style");Ee.textContent=xe.join(`
66
66
  `),de.head.appendChild(Ee)}const Se=oe.documentElement.getAttribute("data-theme");Se&&de.documentElement.setAttribute("data-theme",Se),de.documentElement.style.colorScheme=Se==="light"?"light":"dark",de.body.className=oe.body.className;const Pe=oe.documentElement.getAttribute("style");Pe&&de.documentElement.setAttribute("style",Pe);const He=de.getElementById("dv-popout-window");He instanceof HTMLElement&&(He.classList.add("adhdev-dockview"),pi(He,w))},[w]),ne=l.useCallback(()=>{var oe;const G=N.current;if(G)for(const de of G.groups)try{const xe=(oe=de.element)==null?void 0:oe.ownerDocument;if(!xe||xe===document)continue;const Se=xe.getElementById("dv-popout-window");Se instanceof HTMLElement&&(Se.classList.add("adhdev-dockview"),pi(Se,w));const Pe=document.documentElement.getAttribute("data-theme");Pe&&xe.documentElement.setAttribute("data-theme",Pe),xe.documentElement.style.colorScheme=Pe==="light"?"light":"dark",xe.body.className=document.body.className;const He=document.documentElement.getAttribute("style");He?xe.documentElement.setAttribute("style",He):xe.documentElement.removeAttribute("style")}catch{}},[w]),ie=l.useCallback(G=>{const oe=N.current;if(!oe)return;const de=oe.getPanel(G);de&&oe.addPopoutGroup(de,{popoutUrl:"/popout.html",onDidOpen:({window:xe})=>{z(xe),Z();const Se=L.get(G);xe.document.title=Se?`${kt(Se)} — ADHDev`:"ADHDev — Popout"}})},[L,z]),Ce=l.useCallback(G=>{const oe=N.current,de=oe==null?void 0:oe.getPanel(G);if(!oe||!de)return;const xe=oe.groups.filter(Se=>{var Pe;try{return((Pe=Se.element)==null?void 0:Pe.ownerDocument)===document}catch{return!0}});xe.length>0?de.api.moveTo({group:xe[0],position:"center"}):de.api.moveTo({position:"center"}),de.api.setActive()},[]),me=l.useCallback(G=>{var xe;const oe=N.current;if(!oe)return!1;const de=oe.getPanel(G);if(!de)return!1;try{return((xe=de.group.element)==null?void 0:xe.ownerDocument)!==document}catch{return!1}},[]),O=l.useCallback(G=>{me(G)&&Ce(G),u(G)},[me,Ce,u]),Y=l.useCallback(G=>{const oe=N.current,de=oe==null?void 0:oe.getPanel(G);!oe||!de||oe.addFloatingGroup(de,{width:600,height:500})},[]),X=l.useCallback(G=>{var de;const oe=(de=N.current)==null?void 0:de.getPanel(G);if(!oe)return!1;try{return oe.group.model.location.type==="floating"}catch{return!1}},[]),Q=l.useCallback(()=>{var oe,de;const G=(de=(oe=N.current)==null?void 0:oe.activePanel)==null?void 0:de.id;return!G||fs(G)?null:L.has(G)?G:null},[L]),ve=l.useCallback(G=>{const oe=N.current,de=oe==null?void 0:oe.getPanel(G);if(!oe||!de)return;const xe=oe.groups.filter(Se=>{try{return Se.model.location.type==="grid"}catch{return!0}});xe.length>0?de.api.moveTo({group:xe[0],position:"center"}):de.api.moveTo({position:"center"}),de.api.setActive()},[]),he=l.useCallback(()=>{var Pe;const G=N.current;if(!G)return;const de=G.groups.filter(He=>{var Ee;try{return((Ee=He.element)==null?void 0:Ee.ownerDocument)===document&&He.model.location.type==="grid"}catch{return!1}})[0]||null,xe=[...G.panels];for(const He of xe){const Ee=(Pe=He.group.element)==null?void 0:Pe.ownerDocument,Je=He.group.model.location.type;Ee===document&&Je==="grid"||(de&&de.id!==He.group.id?He.api.moveTo({group:de,position:"center"}):He.api.moveTo({position:"center"}))}const Se=G.activePanel;Se&&(Se.group.model.openPanel(Se),Se.api.setActive()),ui(document)},[]),Z=l.useCallback(()=>{var oe,de;const G=N.current;if(G)for(const xe of G.groups){const Se=(oe=xe.element)==null?void 0:oe.ownerDocument;if(!Se||Se===document)continue;const Pe=Se.getElementById("dv-popout-window");if(!(Pe instanceof HTMLElement))continue;let He=null,Ee=Se.title||"ADHDev",Je="Popout workspace";const st=xe.activePanel;if(st)if(He=st.id,fs(st.id)){const Be=((de=st.params)==null?void 0:de.routeId)||st.id.slice(7),ge=ws([...L.values()],Be);Ee=ah(ge),Je=ge!=null&&ge.machineName?`Remote view · ${ge.machineName}`:"Remote view"}else{const Be=L.get(st.id);Ee=Be?kt(Be):st.title||st.id,Je=Be?Sn(Be):"Dockview panel"}Se.title=`${Ee} — ADHDev`;const Ze=Array.from(Se.querySelectorAll("#adhdev-popout-header"));for(const Be of Ze)Be.remove();const Ue=Se.createElement("div");Ue.id="adhdev-popout-header",Se.body.appendChild(Ue),Ue.setAttribute("style",["position:absolute","top:0","left:0","right:0","height:52px","display:flex","align-items:center","justify-content:space-between","gap:12px","padding:0 14px","box-sizing:border-box","background:var(--surface-secondary)","border-bottom:1px solid var(--border-subtle)","z-index:5","backdrop-filter:blur(14px)"].join(";")),Ue.innerHTML=`
67
67
  <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
68
68
  <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
@@ -85,7 +85,7 @@ The machine's IDE, workspace and provider settings are kept.`,confirmLabel:o("ma
85
85
  `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono text-[10px] select-text ${a.textPrimary}`,children:XM(M.sessionId)}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${Au(M,a.isDark)}`,children:Zs(M)})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${a.textMuted}`,children:[s.jsx("span",{className:"truncate",children:M.providerType||n("meshGraph.panel.providerUnknown")}),s.jsx("span",{children:D}),s.jsx("span",{children:Tu(E)}),M.difficulty&&s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0 text-[8px] font-semibold uppercase tracking-[0.1em] ${QM(M.difficulty,a.isDark)}`,children:xr(M.difficulty,n)})]}),M.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${a.textMuted}`,children:M.statusNote})]},M.sessionId)}),w.length>Wn&&s.jsx("div",{className:`text-[9px] ${a.textMuted}`,title:I.join(`
86
86
  `),children:n("meshGraph.panel.moreChats",{count:w.length-Wn})})]})]}),u&&C&&s.jsx("div",{className:`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${a.isDark?"border-cyan-400/15 bg-cyan-500/8 text-cyan-50/90":"border-sky-300 bg-sky-50 text-sky-700"}`,style:zM,children:C})]}),s.jsx(Ns,{type:"source",position:o==="TB"?$t.Bottom:$t.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const nP={meshNode:sP},aP=8;function rP(e){if(e.length<2)return null;if(e.length===2){const[p,u]=e;return{d:`M ${p.x},${p.y} L ${u.x},${u.y}`,labelX:(p.x+u.x)/2,labelY:(p.y+u.y)/2}}const t=aP,n=[`M ${e[0].x},${e[0].y}`];for(let p=1;p<e.length-1;p+=1){const u=e[p-1],m=e[p],f=e[p+1],g=Math.sign(m.x-u.x),k=Math.sign(m.y-u.y),h=Math.sign(f.x-m.x),b=Math.sign(f.y-m.y),S=Math.hypot(m.x-u.x,m.y-u.y),x=Math.hypot(f.x-m.x,f.y-m.y),y=Math.min(t,S/2,x/2);if(y<1||g===h&&k===b){n.push(`L ${m.x},${m.y}`);continue}const C=m.x-g*y,v=m.y-k*y,w=m.x+h*y,j=m.y+b*y;n.push(`L ${C},${v}`),n.push(`Q ${m.x},${m.y} ${w},${j}`)}const a=e[e.length-1];n.push(`L ${a.x},${a.y}`);let r=0;const o=[0];for(let p=1;p<e.length;p+=1)r+=Math.hypot(e[p].x-e[p-1].x,e[p].y-e[p-1].y),o.push(r);const i=r/2;let c=e[0].x,d=e[0].y;for(let p=1;p<e.length;p+=1)if(o[p]>=i){const u=o[p]-o[p-1],m=u===0?0:(i-o[p-1])/u;c=e[p-1].x+(e[p].x-e[p-1].x)*m,d=e[p-1].y+(e[p].y-e[p-1].y)*m;break}return{d:n.join(" "),labelX:c,labelY:d}}function oP(e){var o,i;const t=(o=e.data)==null?void 0:o.routePoints;if(t&&t.length>=2){const c=rP(t);if(c)return[c.d,c.labelX,c.labelY]}const n={sourceX:e.sourceX,sourceY:e.sourceY,sourcePosition:e.sourcePosition,targetX:e.targetX,targetY:e.targetY,targetPosition:e.targetPosition},a=(i=e.data)==null?void 0:i.graphEdge;if(!a){const c=$c(n);return[c[0],c[1],c[2]]}let r;return a.type==="parentBranch"?r=$g(n):a.type==="worktreeLink"||a.type==="submoduleLink"||a.type==="cloneLink"?r=Hg(n):r=$c(n),[r[0],r[1],r[2]]}function iP(e,t){const n="nodrag nopan rounded-md border px-2 py-1 text-[10px] font-semibold shadow-sm";switch(e.type){case"orphanLink":return t?`${n} border-orange-400/35 bg-orange-500/14 text-orange-100`:`${n} border-orange-300 bg-orange-50 text-orange-700`;case"submoduleLink":return t?`${n} border-violet-400/30 bg-violet-500/14 text-violet-100`:`${n} border-violet-300 bg-violet-50 text-violet-700`;case"sessionLink":return t?`${n} border-emerald-400/30 bg-emerald-500/14 text-emerald-100`:`${n} border-emerald-300 bg-emerald-50 text-emerald-700`;case"cloneLink":return t?`${n} border-teal-400/30 bg-teal-500/14 text-teal-100`:`${n} border-teal-300 bg-teal-50 text-teal-700`;default:return t?`${n} border-sky-400/25 bg-slate-950/78 text-sky-100`:`${n} border-sky-300 bg-white/95 text-sky-700`}}function lP(e){var c;const t=l.useContext(kc),n=(c=e.data)==null?void 0:c.graphEdge,[a,r,o]=oP(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(Lg,{id:e.id,path:a,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&n&&s.jsx(Rg,{children:s.jsx("div",{className:iP(n,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${r}px, ${o}px)`,pointerEvents:"none",maxWidth:RT.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const cP={meshEdge:lP};async function dP(e,t,n,a,r){const o=await wf(e,n,a,r);return Bf(e,o,t,n)}async function uP(e,t=Es("dark"),n=!1,a="LR"){const r=await wf(e,n,a);return Bf(e,r,t,n)}function Bf(e,t,n,a=!1){const r=new Set(t.nodes.map(p=>p.id)),o=t.nodes.map(p=>({id:p.id,type:p.type,position:p.position,data:{graphNode:p.graphNode,compact:a},selected:p.selected,draggable:p.draggable,selectable:p.selectable})),i=e.edges.filter(p=>r.has(p.source)&&r.has(p.target)),c=hP(i),d=i.map(p=>{var u;return{id:p.id,source:p.source,target:p.target,label:c.has(p.id)?p.label:void 0,type:"meshEdge",data:{graphEdge:p,routePoints:(u=t.edgeRoutes.get(p.id))==null?void 0:u.points},animated:p.type==="orphanLink",markerEnd:p.direction==="directed"?{type:xp.ArrowClosed,width:p.type==="submoduleLink"?16:18,height:p.type==="submoduleLink"?16:18,color:yl(p)}:void 0,style:{stroke:yl(p),strokeWidth:p.type==="orphanLink"?2.25:p.type==="submoduleLink"?1.7:p.type==="worktreeLink"?1.8:p.type==="cloneLink"?1.6:2,strokeDasharray:p.type==="orphanLink"?"5 4":p.type==="submoduleLink"?"4 3":p.type==="cloneLink"?"6 3":void 0},labelStyle:{fill:n.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:n.edgeLabelBackgroundColor,fillOpacity:1,stroke:n.edgeLabelBorderColor},labelBgPadding:[6,4],labelBgBorderRadius:7}});return{nodes:o,edges:d}}const pP=3,mP=2;function Mu(e){switch(e.type){case"orphanLink":return 5;case"parentBranch":return 4;case"submoduleLink":return 3;case"cloneLink":return 2;case"worktreeLink":return 1;case"sessionLink":return 0;default:return 0}}function hP(e){const t=new Set,n=new Map;for(const a of e){if(!a.label)continue;const r=n.get(a.source);r?r.push(a):n.set(a.source,[a])}for(const a of n.values()){if(a.length<pP){for(const o of a)t.add(o.id);continue}const r=[...a].sort((o,i)=>{const c=Mu(i)-Mu(o);return c!==0?c:o.id.localeCompare(i.id)});for(const o of r.slice(0,mP))t.add(o.id)}return t}function yl(e){switch(e.type){case"parentBranch":return"#38bdf8";case"worktreeLink":return"#a78bfa";case"sessionLink":return"#34d399";case"orphanLink":return"#f97316";case"submoduleLink":return"#c084fc";case"cloneLink":return"#2dd4bf";default:return"#64748b"}}function fP(e){const t=e.data.graphNode;if(t.locality==="local")return"#38bdf8";switch(t.health){case"online":return"#34d399";case"dirty":return"#fbbf24";case"degraded":case"offline":return"#fb7185";case"wrong_branch":return"#a78bfa";default:return"#94a3b8"}}function gP(e){const t=e.data.graphNode;return["mesh-minimap-node",`mesh-minimap-node--${t.type}`,`mesh-minimap-node--${t.health}`,t.isOrphan?"mesh-minimap-node--attention":null,t.dirty?"mesh-minimap-node--dirty":null,t.outOfSync?"mesh-minimap-node--out-of-sync":null].filter(Boolean).join(" ")}function bP({data:e,viewportKey:t}){const n=Eg(),a=_g(),r=l.useRef(null),o=l.useMemo(()=>bf(e),[e]),i=l.useMemo(()=>TT(e),[e]);return l.useEffect(()=>{if(!n||e.nodes.length===0||r.current===t)return;let c=!1;const d=requestAnimationFrame(()=>{if(c)return;const p=e.nodes.length>8&&i.length>0&&i.length<e.nodes.length;a.fitView({nodes:p?i.map(u=>({id:u})):void 0,padding:p?.24:.2,maxZoom:1,duration:260}),r.current=t});return()=>{c=!0,cancelAnimationFrame(d)}},[e.nodes.length,i,o,n,a,t]),null}const xP=12,vP=["parentBranch","cloneLink","worktreeLink","submoduleLink","sessionLink","orphanLink"],yP={parentBranch:"meshGraph.legendEdge.parentBranch",cloneLink:"meshGraph.legendEdge.cloneLink",worktreeLink:"meshGraph.legendEdge.worktreeLink",submoduleLink:"meshGraph.legendEdge.submoduleLink",sessionLink:"meshGraph.legendEdge.sessionLink",orphanLink:"meshGraph.legendEdge.orphanLink"},wP={orphanLink:"5 4",submoduleLink:"4 3",cloneLink:"6 3"};function kP(e){return e>=16?"min-h-[720px]":e>=10?"min-h-[580px]":"min-h-[460px]"}function SP({data:e,selectedNodeId:t=null,directionPref:n,onNodeClick:a,onEdgeClick:r,onNodeHoverChange:o,onEdgeHoverChange:i}){const{t:c}=ke("common"),{theme:d}=Rs(),p=l.useMemo(()=>Es(d),[d]),u=l.useMemo(()=>YT(e),[e]),m=l.useMemo(()=>QT(e),[e]),f=l.useRef(null),[g,k]=l.useState({width:0,height:0}),h=g.width>0&&g.width<GM,b=e.nodes.length>=UM||h,[S]=l.useState("LR"),x=n??S,y=l.useMemo(()=>n==="LR"||n==="TB"?n:h?"TB":x==="auto"?HT(e):x,[x,n,u,e,h]),C=e.nodes.length>=xP,[v,w]=l.useState({nodes:[],edges:[],pass:"estimated"}),j=l.useMemo(()=>`${MT(e,g.width,g.height)}::${y}`,[u,e,g.height,g.width,y]),N=l.useMemo(()=>{const M=new Set(e.nodes.filter(E=>E.type==="worktreeNode"||E.type==="orphanNode").map(E=>E.machineId||E.machineLabel||""));return M.delete(""),M.size>1},[e.nodes]),A=l.useMemo(()=>{const M=new Set;for(const E of e.edges)M.add(E.type);return vP.filter(E=>M.has(E))},[e.edges]),[T,I]=l.useState(!0);l.useEffect(()=>{const M=setTimeout(()=>I(!1),5e3);return()=>clearTimeout(M)},[]),l.useEffect(()=>{let M=!1;return uP(e,p,b,y).then(E=>{if(M)return;w({...E,pass:"estimated"});const D=requestAnimationFrame(()=>{if(M)return;const W=f.current;if(!W)return;const R=new Map;for(const B of E.nodes){const _=W.querySelector(`.react-flow__node[data-id="${CSS.escape(B.id)}"]`);_&&_.offsetHeight>0&&R.set(B.id,_.offsetHeight)}R.size!==0&&dP(e,p,b,y,R).then(B=>{M||w({...B,pass:"measured"})})});return()=>cancelAnimationFrame(D)}),()=>{M=!0}},[e,m,p,b,y]);const P=l.useMemo(()=>v.nodes.map(M=>({...M,selected:M.id===t})),[v.nodes,t]);return l.useEffect(()=>{const M=f.current;if(!M)return;const E=()=>{const W=Math.max(0,Math.round(M.clientWidth)),R=Math.max(0,Math.round(M.clientHeight));k(B=>B.width===W&&B.height===R?B:{width:W,height:R})};E();const D=typeof ResizeObserver=="function"?new ResizeObserver(()=>E()):null;return D==null||D.observe(M),window.addEventListener("resize",E),()=>{D==null||D.disconnect(),window.removeEventListener("resize",E)}},[]),s.jsx(kc.Provider,{value:p,children:s.jsx(Ef.Provider,{value:b,children:s.jsx(_f.Provider,{value:y,children:s.jsx(Hf.Provider,{value:N,children:s.jsxs("div",{ref:f,className:`${p.graphShellClass} ${kP(e.nodes.length)}`,style:{height:"100%"},children:[s.jsx("div",{className:`pointer-events-none absolute left-1/2 top-2 z-10 -translate-x-1/2 px-3 py-1 text-[10px] transition-opacity duration-700 ${p.graphStatChipClass} ${T?"opacity-100":"opacity-0"}`,"aria-hidden":!T,children:c("meshGraph.obs.panHint")}),A.length>0&&s.jsx("div",{className:`pointer-events-none absolute right-3 top-2 z-10 flex flex-wrap items-center justify-end gap-x-2.5 gap-y-1 rounded-xl border px-2.5 py-1.5 text-[9px] ${p.isDark?"border-white/10 bg-slate-950/75 text-slate-300":"border-slate-200 bg-white/90 text-slate-600"}`,children:A.map(M=>s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("svg",{width:"16",height:"4","aria-hidden":!0,children:s.jsx("line",{x1:"0",y1:"2",x2:"16",y2:"2",stroke:yl({type:M}),strokeWidth:"2",strokeDasharray:wP[M]})}),c(yP[M])]},M))}),s.jsx("div",{className:"w-full min-w-0 flex-1",style:{height:"100%"},children:s.jsxs(hp,{nodes:P,edges:v.edges,nodeTypes:nP,edgeTypes:cP,minZoom:.18,maxZoom:1.35,fitView:!0,fitViewOptions:{padding:.2,maxZoom:1},nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(M,E)=>a==null?void 0:a(E.data.graphNode),onEdgeClick:(M,E)=>{var W;const D=(W=E.data)==null?void 0:W.graphEdge;D&&(r==null||r(D))},onNodeMouseEnter:(M,E)=>o==null?void 0:o(E.data.graphNode),onNodeMouseLeave:()=>o==null?void 0:o(null),onEdgeMouseEnter:(M,E)=>{var D;return i==null?void 0:i(((D=E.data)==null?void 0:D.graphEdge)??null)},onEdgeMouseLeave:()=>i==null?void 0:i(null),className:"h-full w-full",colorMode:p.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(bP,{data:e,viewportKey:`${j}::${v.pass}`}),s.jsx(fp,{className:p.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),C&&s.jsx(Ig,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:fP,nodeClassName:gP,nodeStrokeWidth:3,className:p.isDark?"overflow-hidden rounded-xl border border-white/10 bg-slate-950/85":"overflow-hidden rounded-xl border border-slate-200 bg-white/95"}),s.jsx(gp,{variant:bp.Dots,gap:18,size:1.2,color:p.graphBackgroundDotColor})]})})]})})})})})}function CP(e){if(!Array.isArray(e))return[];const t=new Set,n=[];for(const a of e){const r=typeof a=="string"?a.trim():"";!r||t.has(r)||(t.add(r),n.push(r))}return n}function jP(e){return e==="completed"?"satisfied":e==="failed"||e==="cancelled"?"failed":"waiting"}const Po=30,no=50;function Wf(e,t=Po){const n=Array.isArray(e)?e.filter(d=>d&&typeof d.id=="string"&&d.id):[],a=new Map(n.map(d=>[d.id,d])),r=new Set,o=[];for(const d of n)(d.status==="pending"||d.status==="assigned")&&(r.add(d.id),o.push(d.id));for(;o.length>0;){const d=a.get(o.pop());if(!(!d||!Array.isArray(d.dependsOn)))for(const p of d.dependsOn)typeof p=="string"&&a.has(p)&&!r.has(p)&&(r.add(p),o.push(p))}const i=n.filter(d=>!r.has(d.id)&&d.status!=="pending"&&d.status!=="assigned").sort((d,p)=>String(p.updatedAt||p.createdAt||"").localeCompare(String(d.updatedAt||d.createdAt||"")));for(const d of i.slice(0,Math.max(0,t)))r.add(d.id);const c=n.filter(d=>r.has(d.id));return{tasks:c,hiddenCount:n.length-c.length}}function NP(e){const t=Array.isArray(e)?e.filter(p=>p&&typeof p.id=="string"&&p.id):[],n=new Map(t.map(p=>[p.id,p.status])),a=[],r=[],o=new Set;let i=0,c=0;const d={pending:0,assigned:0,completed:0,failed:0,cancelled:0};for(const p of t){const u=CP(p.dependsOn),m=[],f=[],g=[];for(const h of u){if(!n.has(h)){f.push(h),p.status==="pending"&&g.push(h);continue}m.push(h),r.push({id:`dep:${h}->${p.id}`,source:h,target:p.id,state:jP(n.get(h))}),p.status==="pending"&&n.get(h)!=="completed"&&g.push(h)}const k=typeof p.blockedReason=="string"&&p.blockedReason.length>0;k&&(c+=1),g.length>0&&(i+=1),typeof p.missionId=="string"&&p.missionId&&o.add(p.missionId),p.status in d&&(d[p.status]+=1),a.push({id:p.id,task:p,dependsOn:m,missingDeps:f,waitingOn:g,blocked:k})}return{nodes:a,edges:r,stats:{total:a.length,edges:r.length,pending:d.pending,assigned:d.assigned,completed:d.completed,failed:d.failed,cancelled:d.cancelled,waiting:i,blocked:c,missions:o.size}}}const AP="You are one independent member of a multi-agent cross-verification quorum";function TP(e){var a,r;const t=(e??"").trim();if(!t)return"";if(!t.startsWith(AP))return t;const n=(r=(a=t.match(/\n## Question\n([\s\S]*?)(?:\n## |$)/))==null?void 0:a[1])==null?void 0:r.trim().replace(/\s+/g," ");return n?`MAGI cross-verify — ${n}`:"MAGI cross-verification task"}function Sc(e){let t=e??"";return t?(t=t.replace(/^```[^\n]*\n?/gm,""),t=t.replace(/^#{1,6}\s+/gm,""),t=t.replace(/^\s*(?:[-*+]|\d+[.)])\s+/gm,""),t=t.replace(/^>\s?/gm,""),t=t.replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g,"$2"),t=t.replace(/(^|\W)[*_](?=\S)([^*_\n]*\S)[*_](?=\W|$)/g,"$1$2"),t=t.replace(/`([^`\n]*)`/g,"$1"),t=t.replace(/[ \t]{2,}/g," "),t=t.replace(/\n{3,}/g,`
87
87
 
88
- `),t.trim()):""}function In(e){return Sc(TP(e))}const MP=new mp,Of=236,PP=96;function DP(e){const t=(e.task.message??"").length,n=Math.max(1,Math.min(3,Math.ceil(t/34))),a=e.waitingOn.length>0||e.blocked||e.missingDeps.length>0?22:0;return PP+(n-1)*15+a}const Pu={pending:{dark:"border-slate-400/30 bg-slate-500/10 text-slate-200",light:"border-slate-300 bg-slate-50 text-slate-700",dot:"bg-slate-400"},assigned:{dark:"border-sky-400/40 bg-sky-500/10 text-sky-100",light:"border-sky-300 bg-sky-50 text-sky-800",dot:"bg-sky-400",pulse:!0},completed:{dark:"border-emerald-400/40 bg-emerald-500/10 text-emerald-100",light:"border-emerald-300 bg-emerald-50 text-emerald-800",dot:"bg-emerald-400"},failed:{dark:"border-rose-400/40 bg-rose-500/10 text-rose-100",light:"border-rose-300 bg-rose-50 text-rose-800",dot:"bg-rose-400"},cancelled:{dark:"border-slate-500/25 bg-slate-600/10 text-slate-400",light:"border-slate-200 bg-slate-100 text-slate-400",dot:"bg-slate-500"}},yi={satisfied:{dark:"#34d399",light:"#059669",animated:!1},waiting:{dark:"#fbbf24",light:"#d97706",dash:"6 4",animated:!0},failed:{dark:"#fb7185",light:"#e11d48",dash:"3 4",animated:!1}},IP={overflowWrap:"anywhere",wordBreak:"break-word",display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"};function LP({data:e}){const{t}=ke("common"),{dagNode:n,theme:a,selected:r}=e,o=n.task,i=Pu[o.status]??Pu.pending,c=a.isDark?i.dark:i.light,d=a.isDark?"rounded-full border border-white/10 bg-white/[0.06] px-1.5 py-px text-[9px] text-slate-300":"rounded-full border border-slate-200 bg-white/80 px-1.5 py-px text-[9px] text-slate-500";return s.jsxs("div",{className:`rounded-2xl border px-3 py-2.5 shadow-sm transition-shadow ${c} ${r?a.isDark?"ring-2 ring-cyan-300/60":"ring-2 ring-sky-400/70":""}`,style:{width:Of},children:[s.jsx(Ns,{type:"target",position:$t.Left,className:"!h-2 !w-2 !border-0 !bg-transparent"}),s.jsx(Ns,{type:"source",position:$t.Right,className:"!h-2 !w-2 !border-0 !bg-transparent"}),s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${i.dot} ${i.pulse?"animate-pulse":""}`,"aria-hidden":!0}),s.jsx("span",{className:"truncate text-[10px] font-semibold uppercase tracking-wide opacity-80",children:o.status})]}),s.jsx("span",{className:`shrink-0 font-mono text-[9px] ${a.isDark,"text-slate-400"}`,title:o.id,children:o.id.slice(0,8)})]}),s.jsx("div",{className:`mt-1.5 text-[11px] leading-[15px] ${o.status==="cancelled"?"opacity-60":""}`,style:IP,title:In(o.message),children:In(o.message)}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1",children:[o.difficulty&&s.jsx("span",{className:d,children:o.difficulty}),o.priority&&o.priority!=="normal"&&s.jsx("span",{className:d,children:o.priority}),(o.taskMode==="live_debug_readonly"||o.readonly)&&s.jsx("span",{className:d,children:"read-only"}),o.missionId&&s.jsxs("span",{className:`${d} inline-flex items-center gap-1`,title:o.missionId,children:[s.jsx($p,{size:8}),o.missionId.slice(0,10)]}),n.waitingOn.length>0&&s.jsx("span",{className:a.isDark?"rounded-full border border-amber-400/25 bg-amber-500/10 px-1.5 py-px text-[9px] text-amber-200":"rounded-full border border-amber-300 bg-amber-50 px-1.5 py-px text-[9px] text-amber-700",title:n.waitingOn.join(", "),children:t("meshGraph.taskDag.waitsOn",{count:n.waitingOn.length})}),n.blocked&&s.jsx("span",{className:a.isDark?"rounded-full border border-rose-400/25 bg-rose-500/10 px-1.5 py-px text-[9px] text-rose-200":"rounded-full border border-rose-300 bg-rose-50 px-1.5 py-px text-[9px] text-rose-700",title:o.blockedReason,children:t("meshGraph.taskDag.blocked")}),n.missingDeps.length>0&&s.jsx("span",{className:d,title:n.missingDeps.join(", "),children:t("meshGraph.taskDag.missingDeps",{count:n.missingDeps.length})})]})]})}const RP={taskNode:LP};async function EP(e){const t={id:"task-dag-root",layoutOptions:{"elk.algorithm":"layered","elk.direction":"RIGHT","elk.edgeRouting":"SPLINES","elk.spacing.nodeNode":"46","elk.layered.spacing.nodeNodeBetweenLayers":"120","elk.layered.layering.strategy":"NETWORK_SIMPLEX","elk.layered.nodePlacement.strategy":"NETWORK_SIMPLEX","elk.layered.crossingMinimization.strategy":"LAYER_SWEEP","elk.layered.considerModelOrder.strategy":"NODES_AND_EDGES","elk.layered.cycleBreaking.strategy":"GREEDY","elk.randomSeed":"1"},children:e.nodes.map(r=>({id:r.id,width:Of,height:DP(r)})),edges:e.edges.map(r=>({id:r.id,sources:[r.source],targets:[r.target]}))},n=await MP.layout(t),a=new Map;for(const r of n.children??[])a.set(r.id,{x:r.x??0,y:r.y??0});return a}function _P({tasks:e,emptyMessage:t,compact:n=!1}){const{t:a}=ke("common"),{theme:r}=Rs(),o=l.useMemo(()=>Es(r),[r]),[i,c]=l.useState(Po),d=l.useMemo(()=>Wf(e,n?Number.POSITIVE_INFINITY:i),[e,i,n]),p=l.useMemo(()=>NP(d.tasks),[d.tasks]),u=l.useMemo(()=>p.nodes.map(C=>`${C.id}:${C.task.status}:${C.dependsOn.join("+")}:${C.waitingOn.length}:${C.blocked?1:0}`).join("|"),[p]),[m,f]=l.useState(null),[g,k]=l.useState(null);l.useEffect(()=>{let C=!1;if(p.nodes.length===0){k(null);return}return EP(p).then(v=>{C||k(v)}).catch(()=>{C||k(null)}),()=>{C=!0}},[u]);const h=l.useMemo(()=>g?p.nodes.filter(C=>g.has(C.id)).map(C=>({id:C.id,type:"taskNode",position:g.get(C.id),data:{dagNode:C,theme:o,selected:m===C.id},draggable:!1,selectable:!0})):[],[p,o,g,m]),b=l.useMemo(()=>g?p.edges.map(C=>{const v=yi[C.state],w=o.isDark?v.dark:v.light;return{id:C.id,source:C.source,target:C.target,type:"smoothstep",animated:v.animated,style:{stroke:w,strokeWidth:1.6,...v.dash?{strokeDasharray:v.dash}:{}},markerEnd:{type:xp.ArrowClosed,color:w,width:14,height:14}}}):[],[p,o,g]),S=m?p.nodes.find(C=>C.id===m)??null:null,x=l.useCallback((C,v)=>{f(w=>w===v.id?null:v.id)},[]);if(p.nodes.length===0)return s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:t??a("meshGraph.taskDag.empty")});const y=(C,v="default")=>{const w=v==="warn"?o.isDark?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700":v==="danger"?o.isDark?"border-rose-400/25 bg-rose-500/10 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700":v==="info"?o.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700":o.isDark?"border-white/10 bg-white/[0.05] text-slate-300":"border-slate-200 bg-white/85 text-slate-600";return s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] ${w}`,children:C})};return s.jsxs("div",{className:"relative h-full min-h-[320px] w-full",style:{minHeight:320},children:[s.jsxs(hp,{className:"h-full w-full",nodes:h,edges:b,nodeTypes:RP,onNodeClick:x,onPaneClick:()=>f(null),fitView:!0,fitViewOptions:{padding:.18,maxZoom:1},minZoom:.2,maxZoom:1.6,nodesConnectable:!1,nodesDraggable:!1,proOptions:{hideAttribution:!0},colorMode:o.isDark?"dark":"light",children:[s.jsx(gp,{variant:bp.Dots,gap:22,size:1}),s.jsx(fp,{showInteractive:!1,position:"bottom-left"})]}),!n&&s.jsxs("div",{className:"pointer-events-none absolute left-3 top-3 z-10 flex flex-wrap items-center gap-1.5",children:[d.hiddenCount>0&&s.jsxs(s.Fragment,{children:[y(a("meshGraph.taskDag.hiddenTasks",{count:d.hiddenCount})),s.jsx("button",{type:"button",onClick:()=>c(C=>C+no),className:`pointer-events-auto rounded-full border px-2 py-0.5 text-[10px] font-medium transition-colors ${o.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200 hover:bg-sky-500/20":"border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100"}`,children:a("meshGraph.taskDag.loadMore",{count:Math.min(no,d.hiddenCount)})})]}),y(a("meshGraph.taskDag.statsTasks",{count:p.stats.total})),p.stats.edges>0&&y(a("meshGraph.taskDag.statsEdges",{count:p.stats.edges}),"info"),p.stats.missions>0&&y(a("meshGraph.taskDag.statsMissions",{count:p.stats.missions}),"info"),p.stats.waiting>0&&y(a("meshGraph.taskDag.statsWaiting",{count:p.stats.waiting}),"warn"),p.stats.blocked>0&&y(a("meshGraph.taskDag.statsBlocked",{count:p.stats.blocked}),"danger")]}),s.jsx("div",{className:`pointer-events-none absolute bottom-3 right-3 z-10 flex items-center gap-2.5 rounded-xl border px-2.5 py-1.5 text-[10px] ${o.isDark?"border-white/10 bg-slate-950/80 text-slate-300":"border-slate-200 bg-white/90 text-slate-600"}`,children:["satisfied","waiting","failed"].map(C=>s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"inline-block h-0.5 w-4 rounded",style:{backgroundColor:o.isDark?yi[C].dark:yi[C].light},"aria-hidden":!0}),a(`meshGraph.taskDag.legend.${C}`)]},C))}),S&&s.jsxs("div",{className:`absolute right-3 top-3 z-20 w-72 max-w-[calc(100%-24px)] overflow-y-auto rounded-2xl border p-3.5 shadow-xl backdrop-blur ${o.isDark?"border-white/10 bg-slate-950/95 text-slate-200":"border-slate-200 bg-white/95 text-slate-700"}`,style:{maxHeight:"calc(100% - 24px)"},children:[s.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[s.jsx("span",{className:`text-[10px] font-semibold uppercase tracking-wide ${o.isDark,"text-slate-400"}`,children:a("meshGraph.taskDag.selectedTask")}),s.jsx("button",{type:"button",onClick:()=>f(null),"aria-label":"Close task detail",className:o.isDark?"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 hover:bg-white/[0.08]":"rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 hover:bg-slate-50",children:"✕"})]}),s.jsx("div",{className:"mb-2 font-mono text-[10px] opacity-70",title:S.task.id,children:S.task.id.slice(0,8)}),s.jsx("div",{className:"mb-2 whitespace-pre-wrap text-[11px] leading-4",children:In(S.task.message)}),s.jsxs("div",{className:"flex flex-wrap gap-1.5 text-[10px]",children:[y(S.task.status,S.task.status==="failed"?"danger":S.task.status==="assigned"?"info":"default"),S.task.difficulty&&y(S.task.difficulty),S.task.missionId&&y(S.task.missionId,"info"),S.task.assignedNodeId&&y(`@ ${S.task.assignedNodeId.slice(0,14)}`)]}),S.waitingOn.length>0&&s.jsxs("div",{className:"mt-2 text-[10px]",children:[s.jsxs("span",{className:"font-semibold",children:[a("meshGraph.taskDag.waitsOn",{count:S.waitingOn.length}),":"]}),s.jsx("span",{className:"ml-1 font-mono opacity-80",children:S.waitingOn.map(C=>C.slice(0,8)).join(", ")})]}),S.task.blockedReason&&s.jsx("div",{className:`mt-2 rounded-lg border px-2 py-1.5 text-[10px] ${o.isDark?"border-rose-400/25 bg-rose-500/10 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:S.task.blockedReason})]})]})}const HP={assigned:0,pending:1,failed:2,completed:3,cancelled:4};function Du(e){return HP[e]??5}function fn(e){return String(e.updatedAt||e.createdAt||"")}function Uf(e){return typeof e.blockedReason=="string"&&e.blockedReason.length>0}function Iu(e){const t={total:0,assigned:0,pending:0,completed:0,failed:0,cancelled:0,blocked:0};for(const n of e)t.total+=1,n.status==="assigned"?t.assigned+=1:n.status==="pending"?t.pending+=1:n.status==="completed"?t.completed+=1:n.status==="failed"?t.failed+=1:n.status==="cancelled"&&(t.cancelled+=1),n.status==="pending"&&Uf(n)&&(t.blocked+=1);return t}function $P(e){const t=new Map;for(const n of(e==null?void 0:e.missions)??[]){if(!n||typeof n.id!="string"||!n.id)continue;const a=n,r=typeof a.goal=="string"&&a.goal?a.goal:typeof a.goalPreview=="string"?a.goalPreview:"";t.set(n.id,{title:typeof n.title=="string"?n.title:"",status:typeof n.status=="string"?n.status:"",goal:r})}return t}function FP(e,t,n=Po){const a=Wf(e,n),r=a.tasks,o=new Set(r.map(m=>m.id)),i=$P(t),c=new Map;for(const m of r){const f=typeof m.missionId=="string"&&m.missionId?m.missionId:null,g=c.get(f);g?g.push(m):c.set(f,[m])}const d=[];for(const[m,f]of c){const g=[...f].sort((S,x)=>{const y=Du(S.status)-Du(x.status);return y!==0?y:fn(x).localeCompare(fn(S))}),k=m?i.get(m):void 0;let h="",b=!1;for(const S of f){const x=fn(S);x>h&&(h=x),!b&&Array.isArray(S.dependsOn)&&S.dependsOn.some(y=>typeof y=="string"&&o.has(y))&&(b=!0)}d.push({missionId:m,title:(k==null?void 0:k.title)||null,missionStatus:(k==null?void 0:k.status)||null,goal:(k==null?void 0:k.goal)||null,tasks:g,counts:Iu(f),hasDependencies:b,lastActivityAt:h})}d.sort((m,f)=>{const g=(f.counts.assigned>0?1:0)-(m.counts.assigned>0?1:0);return g!==0?g:f.lastActivityAt.localeCompare(m.lastActivityAt)});const p=r.filter(m=>m.status==="assigned").sort((m,f)=>fn(f).localeCompare(fn(m))),u=r.filter(m=>m.status==="failed"||m.status==="pending"&&Uf(m)).sort((m,f)=>fn(f).localeCompare(fn(m)));return{running:p,attention:u,groups:d,hiddenCount:a.hiddenCount,counts:Iu(r)}}function As(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function wi(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function BP(e){const t=As(e.taskId);if(t)return t;const n=e.payload;return n?As(n.taskId):void 0}function WP(e){const t=e.payload,n=t&&typeof t=="object"?t.routingDecision:void 0;if(!n||typeof n!="object"||Array.isArray(n))return null;const a=n,r=Array.isArray(a.intraNodeLosers)?a.intraNodeLosers.length:0,o=Array.isArray(a.skippedCandidates)?a.skippedCandidates.length:0,i={providerType:As(a.resolvedProviderType),model:As(a.resolvedModel),thinkingLevel:As(a.resolvedThinkingLevel),source:As(a.source),transport:As(a.transport),fitnessScore:wi(a.fitnessScore),selectedNodeId:As(a.selectedNodeId),reason:As(a.reason),intraNodeLoserCount:r+(wi(a.intraNodeLosersOmitted)??0)||void 0,skippedCount:o+(wi(a.skippedCandidatesOmitted)??0)||void 0,dispatchedAt:As(e.timestamp)};return i.model||i.providerType||i.source?i:null}function OP(e){var a;const t=new Map,n=(a=e==null?void 0:e.ledger)==null?void 0:a.entries;if(!Array.isArray(n))return t;for(const r of n){if(!r||r.kind!=="task_dispatched")continue;const o=BP(r);if(!o)continue;const i=WP(r);if(!i)continue;const c=t.get(o);if(c){const d=Date.parse(c.dispatchedAt||""),p=Date.parse(i.dispatchedAt||"");if(Number.isFinite(d)&&Number.isFinite(p)&&p<d)continue}t.set(o,i)}return t}function ki(e){return e?[e.providerType,e.model,e.thinkingLevel].filter(Boolean).join(" · "):""}const Lu={assigned:"bg-sky-400 animate-pulse",pending:"bg-slate-400",completed:"bg-emerald-400",failed:"bg-rose-400",cancelled:"bg-slate-500"},UP={active:{dark:"border-emerald-400/30 bg-emerald-500/10 text-emerald-200",light:"border-emerald-300 bg-emerald-50 text-emerald-700"},paused:{dark:"border-amber-400/30 bg-amber-500/10 text-amber-200",light:"border-amber-300 bg-amber-50 text-amber-700"},completed:{dark:"border-white/10 bg-white/[0.05] text-slate-300",light:"border-slate-200 bg-slate-50 text-slate-500"},abandoned:{dark:"border-white/10 bg-white/[0.04] text-slate-400",light:"border-slate-200 bg-slate-50 text-slate-400"}};function GP(e){const t=Date.parse(e.updatedAt||e.createdAt||"");return Number.isFinite(t)?t:0}function Ru(e){switch(e){case"assigned":return"meshGraph.tasksView.status.running";case"pending":return"meshGraph.tasksView.status.queued";case"completed":return"meshGraph.tasksView.status.done";case"failed":return"meshGraph.tasksView.status.failed";case"cancelled":return"meshGraph.tasksView.status.cancelled";default:return"meshGraph.tasksView.status.queued"}}function qP(e){const t=new Map;for(const n of e.nodes??[]){if(!(n!=null&&n.nodeId))continue;const a=n.machineLabel||n.nodeId.slice(0,12),r=n.isLocalWorktree&&typeof n.worktreeBranch=="string"&&n.worktreeBranch?` · ${n.worktreeBranch}`:"";t.set(n.nodeId,`${a}${r}`)}return t}function zt({theme:e,children:t,tone:n="default",title:a}){const r=n==="info"?e.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700":n==="warn"?e.isDark?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700":n==="danger"?e.isDark?"border-rose-400/25 bg-rose-500/10 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700":n==="good"?e.isDark?"border-emerald-400/25 bg-emerald-500/10 text-emerald-200":"border-emerald-300 bg-emerald-50 text-emerald-700":e.isDark?"border-white/10 bg-white/[0.05] text-slate-300":"border-slate-200 bg-white/85 text-slate-600";return s.jsx("span",{title:a,className:`inline-flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] leading-none ${r}`,children:t})}function zP({theme:e,group:t}){const{counts:n}=t;if(n.total===0)return null;const a=r=>`${r/n.total*100}%`;return s.jsx("div",{className:`h-1.5 w-full overflow-hidden rounded-full ${e.isDark?"bg-white/[0.07]":"bg-slate-200/80"}`,children:s.jsxs("div",{className:"flex h-full",children:[s.jsx("div",{className:"h-full bg-emerald-400/85",style:{width:a(n.completed)}}),s.jsx("div",{className:"h-full bg-rose-400/85",style:{width:a(n.failed)}}),s.jsx("div",{className:`h-full ${e.isDark?"bg-slate-500/50":"bg-slate-400/50"}`,style:{width:a(n.cancelled)}}),s.jsx("div",{className:"h-full animate-pulse bg-sky-400/80",style:{width:a(n.assigned)}})]})})}function wl({task:e,theme:t,nodeLabels:n,routing:a,expanded:r,onToggle:o,actions:i,onFocusNode:c}){const{t:d}=ke("common"),[p,u]=l.useState(null),m=In(e.message),f=typeof e.blockedReason=="string"&&e.blockedReason.length>0,g=e.assignedNodeId?n.get(e.assignedNodeId)??e.assignedNodeId.slice(0,12):null,k=e.status==="cancelled"||e.status==="completed";return s.jsxs("div",{className:`rounded-xl transition-colors ${r?t.isDark?"bg-white/[0.04]":"bg-slate-100/70":""}`,children:[s.jsxs("button",{type:"button",onClick:o,className:`flex w-full items-center gap-2.5 rounded-xl px-2.5 py-2 text-left ${t.isDark?"hover:bg-white/[0.04]":"hover:bg-slate-100/70"}`,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${Lu[e.status]??Lu.pending}`,"aria-hidden":!0}),s.jsx("span",{className:`min-w-0 flex-1 truncate text-[12px] leading-5 ${k?t.textSecondary:t.textPrimary}`,title:m,children:m||e.id}),e.status==="failed"&&s.jsx(zt,{theme:t,tone:"danger",children:d(Ru(e.status))}),f&&s.jsx(zt,{theme:t,tone:"warn",children:d("meshGraph.tasksView.status.blocked")}),(a==null?void 0:a.model)&&s.jsx("span",{className:"hidden sm:contents",children:s.jsx(zt,{theme:t,title:ki(a),children:a.model})}),e.status==="assigned"&&g&&s.jsx(zt,{theme:t,tone:"info",title:e.assignedNodeId??void 0,children:g}),s.jsx("span",{className:`shrink-0 text-[10px] tabular-nums ${t.textSecondary}`,children:za(GP(e))})]}),r&&s.jsxs("div",{className:"px-2.5 pb-2.5 pt-0.5",children:[s.jsx("div",{className:`whitespace-pre-wrap text-[11px] leading-4.5 ${t.textSecondary}`,children:m}),s.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:[s.jsx(zt,{theme:t,tone:e.status==="failed"?"danger":e.status==="assigned"?"info":e.status==="completed"?"good":"default",children:d(Ru(e.status))}),e.difficulty&&s.jsx(zt,{theme:t,children:e.difficulty}),e.priority&&e.priority!=="normal"&&s.jsx(zt,{theme:t,children:e.priority}),(e.taskMode==="live_debug_readonly"||e.readonly)&&s.jsx(zt,{theme:t,children:d("meshGraph.tasksView.readOnly")}),g&&s.jsxs(zt,{theme:t,title:e.assignedNodeId??void 0,children:["@ ",g]}),s.jsx("span",{className:`font-mono text-[9px] ${t.textSecondary} opacity-70`,title:e.id,children:e.id.slice(0,8)})]}),a&&s.jsxs("div",{className:`mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-[10px] ${t.textSecondary}`,children:[ki(a)&&s.jsxs("span",{children:[s.jsxs("span",{className:t.textMuted,children:[d("meshGraph.tasksView.routingRan")," "]}),ki(a)]}),(a.source||a.transport)&&s.jsxs("span",{children:[s.jsxs("span",{className:t.textMuted,children:[d("meshGraph.tasksView.routingFrom")," "]}),[a.source,a.transport].filter(Boolean).join(" · ")]})]}),a&&(typeof a.fitnessScore=="number"||a.reason||a.intraNodeLoserCount||a.skippedCount)&&s.jsxs("details",{className:"mt-1.5",children:[s.jsx("summary",{className:`cursor-pointer list-none text-[10px] ${t.textMuted} [&::-webkit-details-marker]:hidden`,children:d("meshGraph.tasksView.routingWhy")}),s.jsxs("div",{className:`mt-1 flex flex-col gap-0.5 text-[10px] leading-4 ${t.textSecondary}`,children:[typeof a.fitnessScore=="number"&&s.jsxs("div",{children:[s.jsxs("span",{className:t.textMuted,children:[d("meshGraph.tasksView.routingFitness")," "]}),a.fitnessScore]}),a.reason&&s.jsxs("div",{children:[s.jsxs("span",{className:t.textMuted,children:[d("meshGraph.tasksView.routingReason")," "]}),a.reason]}),!!a.intraNodeLoserCount&&s.jsx("div",{children:d("meshGraph.tasksView.routingLosers",{count:a.intraNodeLoserCount})}),!!a.skippedCount&&s.jsx("div",{children:d("meshGraph.tasksView.routingSkipped",{count:a.skippedCount})})]})]}),f&&s.jsx("div",{className:`mt-2 rounded-lg border px-2 py-1.5 text-[10px] ${t.isDark?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:e.blockedReason}),(i||c&&e.assignedNodeId)&&s.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:[i&&(e.status==="failed"||e.status==="cancelled")&&s.jsx(Si,{theme:t,tone:"info",busy:i.busyTaskId===e.id,armed:p==="requeue",label:d("meshGraph.tasksView.actionRequeue"),confirmLabel:d("meshGraph.tasksView.actionConfirm"),onClick:()=>{if(p!=="requeue"){u("requeue");return}u(null),i.run("requeue",e.id)}}),i&&(e.status==="pending"||e.status==="assigned")&&s.jsx(Si,{theme:t,tone:"danger",busy:i.busyTaskId===e.id,armed:p==="cancel",label:d("meshGraph.tasksView.actionCancel"),confirmLabel:d("meshGraph.tasksView.actionConfirm"),onClick:()=>{if(p!=="cancel"){u("cancel");return}u(null),i.run("cancel",e.id)}}),c&&e.assignedNodeId&&s.jsx(Si,{theme:t,tone:"default",label:d("meshGraph.tasksView.actionViewNode"),onClick:()=>c(e.assignedNodeId)})]})]})]})}function Si({theme:e,tone:t,label:n,confirmLabel:a,armed:r,busy:o,onClick:i}){const c=t==="danger"?e.isDark?"border-rose-400/30 bg-rose-500/10 text-rose-200 hover:bg-rose-500/20":"border-rose-300 bg-rose-50 text-rose-700 hover:bg-rose-100":t==="info"?e.isDark?"border-sky-400/30 bg-sky-500/10 text-sky-200 hover:bg-sky-500/20":"border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100":e.isDark?"border-white/10 bg-white/[0.05] text-slate-300 hover:bg-white/[0.1]":"border-slate-200 bg-white text-slate-600 hover:bg-slate-100";return s.jsx("button",{type:"button",disabled:o,onClick:i,className:`rounded-full border px-2.5 py-1 text-[10px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-45 ${c} ${r?"ring-1 ring-current":""}`,children:r&&a?a:n})}function KP({group:e,theme:t,nodeLabels:n,routingIndex:a,expandedTaskId:r,onToggleTask:o,actions:i,onFocusNode:c}){const{t:d}=ke("common"),p=e.counts.assigned>0||e.counts.pending>0||e.counts.failed>0,[u,m]=l.useState(null),[f,g]=l.useState(!1),[k,h]=l.useState(!1),b=u??p,S=e.title||(e.missionId?e.missionId.slice(0,24):d("meshGraph.tasksView.adhocTitle")),x=e.missionStatus?UP[e.missionStatus]:null,y=e.goal?In(e.goal):"";return s.jsxs("section",{className:`rounded-2xl border ${t.isDark?"border-white/10 bg-slate-950/40":"border-slate-200 bg-white/90"}`,children:[s.jsxs("button",{type:"button",onClick:()=>m(C=>C===null?!p:!C),"aria-expanded":b,className:"flex w-full flex-col gap-2 rounded-2xl px-3.5 py-3 text-left",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`shrink-0 transition-transform ${b?"rotate-90":""} ${t.textSecondary}`,"aria-hidden":!0,children:"›"}),e.missionId&&s.jsx($p,{size:11,className:`shrink-0 ${t.isDark,"text-slate-400"}`}),s.jsx("span",{className:`min-w-0 flex-1 truncate text-[12.5px] font-semibold ${t.textPrimary}`,title:e.missionId??void 0,children:S}),e.missionStatus&&x&&s.jsx("span",{className:`inline-flex shrink-0 items-center rounded-full border px-2 py-0.5 text-[9px] leading-none font-medium uppercase tracking-wide ${t.isDark?x.dark:x.light}`,children:d(`meshGraph.tasksView.missionStatus.${e.missionStatus}`,{defaultValue:e.missionStatus})}),e.counts.assigned>0&&s.jsx(zt,{theme:t,tone:"info",children:d("meshGraph.tasksView.chipRunning",{count:e.counts.assigned})}),e.counts.failed>0&&s.jsx(zt,{theme:t,tone:"danger",children:d("meshGraph.tasksView.chipFailed",{count:e.counts.failed})}),e.counts.blocked>0&&s.jsx(zt,{theme:t,tone:"warn",children:d("meshGraph.tasksView.chipBlocked",{count:e.counts.blocked})}),s.jsx("span",{className:`shrink-0 text-[10px] tabular-nums ${t.textSecondary}`,children:d("meshGraph.tasksView.progress",{done:e.counts.completed,total:e.counts.total})})]}),s.jsx(zP,{theme:t,group:e})]}),b&&s.jsxs("div",{className:"flex flex-col gap-0.5 px-1.5 pb-2",children:[(e.hasDependencies||y)&&s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 px-1 pb-1",children:[y&&s.jsx("button",{type:"button",onClick:()=>h(C=>!C),className:`rounded-full border px-2.5 py-1 text-[10px] font-medium transition-colors ${t.isDark?"border-white/10 bg-white/[0.05] text-slate-300 hover:bg-white/[0.1]":"border-slate-200 bg-white text-slate-600 hover:bg-slate-100"}`,children:d(k?"meshGraph.tasksView.hideGoal":"meshGraph.tasksView.showGoal")}),e.hasDependencies&&s.jsx("button",{type:"button",onClick:()=>g(C=>!C),className:`rounded-full border px-2.5 py-1 text-[10px] font-medium transition-colors ${t.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200 hover:bg-sky-500/20":"border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100"}`,children:d(f?"meshGraph.tasksView.hideGraph":"meshGraph.tasksView.showGraph")})]}),k&&y&&s.jsx("div",{className:`mx-1 mb-1 whitespace-pre-wrap rounded-xl border px-3 py-2 text-[11px] leading-4.5 ${t.isDark?"border-white/10 bg-white/[0.03] text-slate-300":"border-slate-200 bg-slate-50 text-slate-600"}`,children:y}),f&&e.hasDependencies?s.jsx("div",{className:`mx-1 mb-1 h-[300px] overflow-hidden rounded-xl border ${t.isDark?"border-white/10":"border-slate-200"}`,children:s.jsx(_P,{tasks:e.tasks,compact:!0})}):e.tasks.map(C=>s.jsx(wl,{task:C,theme:t,nodeLabels:n,routing:a.get(C.id),expanded:r===C.id,onToggle:()=>o(C.id),actions:i,onFocusNode:c},C.id))]})]})}function VP({tasks:e,status:t,emptyMessage:n,daemonId:a,sendDaemonCommand:r,onQueueMutated:o,onFocusNode:i}){const{t:c}=ke("common"),{theme:d}=Rs(),p=l.useMemo(()=>Es(d),[d]),[u,m]=l.useState(Po),[f,g]=l.useState(null),[k,h]=l.useState(null),[b,S]=l.useState(null),x=l.useMemo(()=>FP(e,t,u),[e,t,u]),y=l.useMemo(()=>qP(t),[t]),C=l.useMemo(()=>OP(t),[t]),v=N=>g(A=>A===N?null:N),w=!!(r&&a&&t.meshId),j=l.useMemo(()=>w?{busyTaskId:k,error:b,run:async(N,A)=>{if(!(!r||!a)){h(A),S(null);try{const I=await r(a,N==="cancel"?"cancel_mesh_queue_task":"requeue_mesh_queue_task",{meshId:t.meshId,taskId:A}),P=(I==null?void 0:I.result)??I;if(P&&P.success===!1){S(typeof P.error=="string"?P.error:c("meshGraph.tasksView.actionFailed"));return}o==null||o()}catch(T){S(T instanceof Error?T.message:c("meshGraph.tasksView.actionFailed"))}finally{h(null)}}}}:null,[w,k,b,r,a,t.meshId,o,c]);return x.counts.total===0?s.jsx("div",{className:`flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm ${p.textSecondary}`,children:n??c("meshGraph.taskDag.empty")}):s.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-1 pr-1.5",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 px-0.5",children:[x.counts.assigned>0&&s.jsx(zt,{theme:p,tone:"info",children:c("meshGraph.tasksView.chipRunning",{count:x.counts.assigned})}),x.counts.pending>0&&s.jsx(zt,{theme:p,children:c("meshGraph.tasksView.chipQueued",{count:x.counts.pending})}),x.counts.failed>0&&s.jsx(zt,{theme:p,tone:"danger",children:c("meshGraph.tasksView.chipFailed",{count:x.counts.failed})}),s.jsx(zt,{theme:p,tone:"good",children:c("meshGraph.tasksView.chipDone",{count:x.counts.completed})}),s.jsx("span",{className:`text-[10px] ${p.textSecondary}`,children:c("meshGraph.taskDag.statsMissions",{count:x.groups.filter(N=>N.missionId).length})}),s.jsx("span",{className:"flex-1"}),x.hiddenCount>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`text-[10px] ${p.textSecondary}`,children:c("meshGraph.taskDag.hiddenTasks",{count:x.hiddenCount})}),s.jsx("button",{type:"button",onClick:()=>m(N=>N+no),className:`rounded-full border px-2 py-0.5 text-[10px] font-medium transition-colors ${p.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200 hover:bg-sky-500/20":"border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100"}`,children:c("meshGraph.taskDag.loadMore",{count:Math.min(no,x.hiddenCount)})})]})]}),x.running.length>0&&s.jsxs("section",{className:`rounded-2xl border p-3 ${p.isDark?"border-sky-400/20 bg-sky-500/[0.06]":"border-sky-200 bg-sky-50/60"}`,children:[s.jsx("div",{className:`mb-1.5 px-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${p.isDark?"text-sky-200/90":"text-sky-700"}`,children:c("meshGraph.tasksView.runningTitle")}),s.jsx("div",{className:"flex flex-col gap-0.5",children:x.running.map(N=>s.jsx(wl,{task:N,theme:p,nodeLabels:y,routing:C.get(N.id),expanded:f===N.id,onToggle:()=>v(N.id),actions:j,onFocusNode:i},N.id))})]}),x.attention.length>0&&s.jsxs("section",{className:`rounded-2xl border p-3 ${p.isDark?"border-rose-400/20 bg-rose-500/[0.05]":"border-rose-200 bg-rose-50/60"}`,children:[s.jsx("div",{className:`mb-1.5 px-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${p.isDark?"text-rose-200/90":"text-rose-700"}`,children:c("meshGraph.tasksView.attentionTitle")}),s.jsx("div",{className:"flex flex-col gap-0.5",children:x.attention.map(N=>s.jsx(wl,{task:N,theme:p,nodeLabels:y,routing:C.get(N.id),expanded:f===N.id,onToggle:()=>v(N.id),actions:j,onFocusNode:i},`attention-${N.id}`))})]}),b&&s.jsx("div",{className:`rounded-xl border px-3 py-2 text-[11px] ${p.isDark?"border-rose-400/25 bg-rose-500/10 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:b}),x.groups.map(N=>s.jsx(KP,{group:N,theme:p,nodeLabels:y,routingIndex:C,expandedTaskId:f,onToggleTask:v,actions:j,onFocusNode:i},N.missionId??"__adhoc__"))]})}function YP(e,t){const n=a=>{a.key==="Escape"&&(a.stopPropagation(),t())};return e.addEventListener("keydown",n,!0),()=>e.removeEventListener("keydown",n,!0)}function QP(e,t){if(e==null||!Number.isFinite(e))return null;const n=t-e;if(!Number.isFinite(n)||n<0)return null;const a=Math.floor(n/1e3);if(a<60)return`${a}s`;const r=Math.floor(a/60);return r<60?`${r}m`:`${Math.floor(r/60)}h ${String(r%60).padStart(2,"0")}m`}function JP(e){return`${e.state??""} ${e.chatStatus??""} ${e.lifecycle??""}`.toLowerCase()}function XP(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const a=n.activeSessionDetails;if(Array.isArray(a))for(const r of a)r!=null&&r.sessionId&&JP(r).includes("approval")&&t.push({nodeId:n.nodeId,sessionId:r.sessionId,providerType:r.providerType,machineLabel:n.machineLabel||n.nodeId,detail:r.statusNote??r.title??null})}return t}function ZP({approvals:e,nodes:t,onResolve:n,hideWhenEmpty:a=!0,nowMs:r}){const{t:o}=ke(),i=r??Date.now(),c=l.useMemo(()=>e??XP(t),[e,t]),[d,p]=l.useState({});if(a&&c.length===0)return null;const u=(m,f)=>{d[m.sessionId]||(p(g=>({...g,[m.sessionId]:f})),Promise.resolve(n(m.nodeId,m.sessionId,f)).finally(()=>{p(g=>{const k={...g};return delete k[m.sessionId],k})}))};return s.jsxs("div",{className:"rounded-lg border p-3",style:{borderColor:"color-mix(in srgb, var(--status-warning) 40%, transparent)",background:"color-mix(in srgb, var(--status-warning) 8%, transparent)"},children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2 font-black text-xs",style:{color:"var(--status-warning)"},children:[s.jsx(Ls,{size:14}),o("meshGraph.approvals.title"),s.jsxs("span",{className:"opacity-70 font-semibold",children:["(",c.length,")"]})]}),c.length===0?s.jsx("div",{className:"text-[11px] opacity-70",children:o("meshGraph.approvals.empty")}):s.jsx("ul",{className:"flex flex-col gap-2",children:c.map(m=>{const f=d[m.sessionId]??null,g=f!==null,k=QP(m.waitingSince,i);return s.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-md px-2.5 py-2",style:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)"},children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"text-xs font-semibold truncate",children:[m.machineLabel||m.nodeId,m.providerType&&s.jsx("span",{className:"ml-2 opacity-60 font-normal",children:m.providerType}),k&&s.jsx("span",{className:"ml-2 font-bold text-[10px]",style:{color:"var(--status-warning)"},title:o("meshGraph.approvals.waitingFor",{duration:k}),children:k})]}),s.jsx("div",{className:"text-[10px] opacity-60 truncate",children:m.detail?m.detail.replace(/[\n\r]+/g," ").slice(0,120):o("meshGraph.approvals.sessionFallback",{id:m.sessionId})}),m.options&&m.options.length>0&&s.jsx("div",{className:"mt-1 flex flex-wrap gap-1",children:m.options.slice(0,4).map((h,b)=>s.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded opacity-70",style:{background:"color-mix(in srgb, var(--text-muted) 15%, transparent)"},children:h.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().slice(0,32)},`${h}-${b}`))})]}),s.jsxs("div",{className:"flex gap-2 shrink-0",children:[s.jsx("button",{onClick:()=>u(m,"approve"),disabled:g,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 font-extrabold ${g?"cursor-not-allowed opacity-60":"cursor-pointer"}`,style:{color:"var(--status-warning)",background:"var(--surface-primary)"},children:f==="approve"?s.jsx(Ks,{size:12}):o("meshGraph.approvals.approve")}),s.jsx("button",{onClick:()=>u(m,"reject"),disabled:g,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 font-semibold text-white bg-red-500/30 ${g?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:f==="reject"?s.jsx(Ks,{size:12}):o("meshGraph.approvals.reject")})]})]},`${m.nodeId}:${m.sessionId}`)})})]})}const eD=5,tD=40,sD={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function Cc(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function Gf(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const n=t.toLowerCase().replace(/[\s-]+/g,"_");return n.includes("approval")?"awaiting approval":n.includes("generating")||n.includes("running")||n.includes("busy")?"generating":n.includes("idle")||n.includes("ready")||n.includes("waiting_input")?"idle":n.replace(/_/g," ")}function qf(e){return e.includes("approval")?"amber":e.includes("generating")?"sky":e.includes("idle")?"emerald":e.includes("failed")||e.includes("stopped")||e.includes("interrupted")?"rose":"muted"}function nD(e){const t=e.git;if(!t)return e.gitProbePending?"git probe pending":"no git probe";const n=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),a=[];return t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&a.push(`↑${t.ahead??0}/↓${t.behind??0}`),n>0&&a.push(`✎${n}`),t.hasConflicts&&a.push("conflicts"),a.join(" · ")||"clean"}function zf(e){switch(e){case"active":return"emerald";case"paused":return"amber";case"completed":return"sky";case"abandoned":return"rose";default:return"muted"}}function aD(e){switch(e){case"online":return"emerald";case"dirty":return"amber";case"degraded":case"offline":return"rose";case"wrong_branch":return"sky";default:return"muted"}}function Kf(e){switch(e){case"completed":return"emerald";case"failed":return"rose";case"cancelled":return"muted";case"assigned":return"sky";case"pending":return"amber";default:return"muted"}}function jc(e){switch(e){case"easy":return"emerald";case"medium":return"amber";case"difficult":return"rose";default:return"muted"}}function Nc(e,t){switch(e){case"easy":return t("meshGraph.difficulty.easy");case"medium":return t("meshGraph.difficulty.medium");case"difficult":return t("meshGraph.difficulty.difficult");case"freeform":return t("meshGraph.difficulty.freeform");default:return e}}function Eu(e){switch(e){case"assigned":return 0;case"pending":return 1;case"completed":case"failed":case"cancelled":return 2;default:return 3}}function ks(e){if(!e)return null;const t=Date.parse(e);if(!Number.isFinite(t))return null;const n=Math.max(0,Math.floor((Date.now()-t)/1e3));if(n<60)return`${n}s ago`;const a=Math.floor(n/60);if(a<60)return`${a}m ago`;const r=Math.floor(a/60);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function _u(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return null;if(e<1e3)return`${Math.round(e)}ms`;const t=Math.round(e/1e3),n=t%60,a=Math.floor(t/60),r=a%60,o=Math.floor(a/60),i=[];return o>0&&i.push(`${o}h`),r>0&&i.push(`${r}m`),(n>0||i.length===0)&&i.push(`${n}s`),i.join(" ")}function Ac(e){return e.replace(/[_-]+/g," ")}function Vf(e){const t=e.toLowerCase();return t.includes("fail")||t.includes("stall")||t.includes("error")?"rose":t.includes("complete")?"emerald":t.includes("dispatch")||t.includes("launch")||t.includes("assign")?"sky":t.includes("checkpoint")?"amber":"muted"}function Yf(e){if(!e)return null;const t=e.message??e.summary??e.reason??e.title;return typeof t=="string"&&t.trim()?t.trim():null}function rD({status:e,daemonId:t=null,meshId:n=null,sendDaemonCommand:a=null}){var v,w,j,N;const{theme:r}=Rs(),o=l.useMemo(()=>Es(r),[r]),i=((v=e.queue)==null?void 0:v.summary)??null,c=((w=e.queue)==null?void 0:w.tasks)??[],d=((j=e.ledger)==null?void 0:j.summary)??sD,p=((N=e.ledger)==null?void 0:N.entries)??[],u=e.missions??[],m=u.filter(A=>A.status==="active"||A.status==="paused"),f=u.filter(A=>A.status==="completed"||A.status==="abandoned"),g=e.asyncRefineJobs??[],[k,h]=l.useState(null),b=l.useCallback(()=>h(null),[]),S=l.useCallback(async(A,T,I)=>{!t||!a||await a(t,"mesh_approve",{meshId:n??void 0,node_id:A,session_id:T,action:I})},[t,n,a]),x=l.useCallback(A=>{if(!A)return"";const T=e.nodes.find(I=>I.nodeId===A);return(T==null?void 0:T.machineLabel)||A},[e.nodes]),y=l.useMemo(()=>{const A=new Map;for(const T of c)T.assignedSessionId&&T.difficulty&&A.set(T.assignedSessionId,T.difficulty);return A},[c]),C=l.useMemo(()=>{const A=[];for(const T of e.nodes){const I=T.activeSessionDetails&&T.activeSessionDetails.length>0?T.activeSessionDetails:(T.activeSessions??[]).map(P=>({sessionId:P,workspace:T.workspace,isCached:!0}));for(const P of I){const M=y.get(P.sessionId);A.push({node:T,session:M?{...P,difficulty:M}:P})}}return A},[e.nodes,y]);return s.jsxs("div",{className:"flex flex-col gap-3 pb-2",children:[s.jsx(ZP,{nodes:e.nodes,onResolve:S}),s.jsx(gD,{meshTheme:o,liveMissions:m,historyMissions:f,hasMissionField:Array.isArray(e.missions),onSelect:A=>h({kind:"mission",mission:A})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(bD,{meshTheme:o,ledgerSummary:d,entries:p,resolveNodeLabel:x,onSelect:A=>h({kind:"ledger",entry:A})}),s.jsx(xD,{meshTheme:o,queueSummary:i,tasks:c,onSelect:A=>h({kind:"queue",task:A})})]}),s.jsx(yD,{meshTheme:o,nodes:e.nodes}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(wD,{meshTheme:o,entries:C,onSelect:(A,T)=>h({kind:"session",node:A,session:T})}),s.jsx(kD,{meshTheme:o,jobs:g})]}),k&&s.jsx(iD,{meshTheme:o,detail:k,onClose:b,daemonId:t,meshId:n??e.meshId??null,sendDaemonCommand:a,resolveNodeLabel:x})]})}function Ln({meshTheme:e,title:t,count:n,children:a,action:r}){const o=e.isDark;return s.jsxs("div",{className:`flex min-w-0 flex-col overflow-hidden rounded-2xl border p-4 ${o?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,children:[s.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[s.jsx("span",{className:`text-[11px] font-semibold uppercase tracking-[0.14em] ${e.textSecondary}`,children:t}),n!==void 0&&s.jsx("span",{className:`tabular-nums text-[11px] ${e.textMuted}`,children:n}),r&&s.jsx("span",{className:"ml-auto",children:r})]}),a]})}function Ut({meshTheme:e,label:t,tone:n}){const a=e.isDark,r=n==="rose"?a?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700":n==="sky"?a?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700":n==="amber"?a?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700":n==="emerald"?a?"border-emerald-400/25 bg-emerald-500/10 text-emerald-200":"border-emerald-300 bg-emerald-50 text-emerald-700":a?"border-white/10 bg-white/[0.04] text-slate-300":"border-slate-200 bg-slate-50 text-slate-600";return s.jsx("span",{className:`shrink-0 rounded-full border pl-2 pr-[calc(0.5rem-0.14em)] py-0.5 text-[10px] leading-none align-middle font-semibold uppercase tracking-[0.14em] ${r}`,children:t})}function jt({meshTheme:e,label:t,value:n,tone:a}){const r=e.isDark,o=a==="rose"?r?"text-rose-300":"text-rose-600":a==="sky"?r?"text-sky-300":"text-sky-600":a==="amber"?r?"text-amber-300":"text-amber-600":a==="emerald"?r?"text-emerald-300":"text-emerald-600":a==="muted"?e.textMuted:e.textPrimary;return s.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-2 ${r?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[s.jsx("span",{className:`tabular-nums text-base font-semibold leading-none ${o}`,children:n}),s.jsx("span",{className:`mt-1 text-[9px] uppercase tracking-wide ${e.textMuted}`,children:t})]})}function er({meshTheme:e,children:t}){return s.jsx("div",{className:`text-xs ${e.textMuted}`,children:t})}function Do({meshTheme:e,onClick:t,dimmed:n,children:a}){const r=e.isDark,o=t?r?"hover:bg-white/[0.05]":"hover:bg-slate-100/70":"";return s.jsx("button",{type:"button",onClick:t,disabled:!t,className:`flex w-full min-w-0 items-center gap-2 overflow-hidden rounded-md px-1.5 py-1 text-left text-xs transition ${o} ${t?"cursor-pointer":"cursor-default"} ${n?"opacity-55":""}`,children:a})}function Io({meshTheme:e,expanded:t,hiddenCount:n,onToggle:a}){const{t:r}=ke("common");return n<=0?null:s.jsx("button",{type:"button",onClick:a,className:`mt-1 self-start rounded-md px-1.5 py-0.5 text-[11px] font-medium ${e.textSecondary} hover:underline`,children:t?r("mesh.overview.showFewer"):r("mesh.overview.showMore",{count:n})})}function Lo(e,t=eD){const[n,a]=l.useState(!1),r=n?e:e.slice(0,t),o=Math.max(0,e.length-t),i=l.useCallback(()=>a(c=>!c),[]);return{visible:r,hiddenCount:o,expanded:n,toggle:i}}function mt({meshTheme:e,label:t,value:n}){return s.jsxs("div",{className:e.rowClass,children:[s.jsx("span",{className:e.rowLabelClass,children:t}),s.jsx("span",{className:e.rowValueClass,children:n})]})}function oD(e,t){switch(e.kind){case"mission":return{kicker:t("mesh.overview.detailKickerMission"),title:e.mission.title};case"ledger":return{kicker:t("mesh.overview.detailKickerLedger"),title:Ac(e.entry.kind)};case"queue":return{kicker:t("mesh.overview.detailKickerQueue"),title:e.task.id};case"session":return{kicker:t("mesh.overview.detailKickerSession"),title:Cc(e.session.sessionId)}}}function iD({meshTheme:e,detail:t,onClose:n,daemonId:a,meshId:r,sendDaemonCommand:o,resolveNodeLabel:i}){const{t:c}=ke("common");l.useEffect(()=>YP(window,n),[n]);const d=e.isDark,{kicker:p,title:u}=oD(t,c),m=d?"bg-[#030617]/[0.92]":"bg-[rgba(15,23,42,0.82)]",f=d?"border-white/10 bg-slate-950 md:bg-slate-950/98 shadow-[0_28px_120px_rgba(2,6,23,0.5)]":"border-slate-200 bg-white md:bg-white/98 shadow-[0_28px_120px_rgba(148,163,184,0.3)]";return s.jsx(Vt,{children:s.jsx("div",{className:`fixed inset-0 z-[var(--z-modal)] flex items-stretch justify-center p-0 md:items-center md:p-4 ${m}`,role:"dialog","aria-modal":"true",onClick:n,children:s.jsxs("div",{className:`flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden border ${f} md:h-auto md:max-h-[88dvh] md:max-w-[min(640px,calc(100vw-32px))] md:rounded-2xl`,onClick:g=>g.stopPropagation(),children:[s.jsxs("div",{className:`sticky top-0 z-10 flex shrink-0 items-start justify-between gap-3 border-b px-4 pb-3 pt-[calc(12px+env(safe-area-inset-top,0px))] ${d?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:p}),s.jsx("div",{className:`mt-0.5 break-all text-sm font-semibold ${e.textPrimary}`,children:u})]}),s.jsx("button",{type:"button",onClick:n,"aria-label":c("mesh.overview.closeDetail"),className:"-m-1.5 inline-flex h-11 w-11 shrink-0 items-center justify-center",children:s.jsx("span",{className:d?"inline-flex h-8 w-8 items-center justify-center rounded-xl border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white":"inline-flex h-8 w-8 items-center justify-center rounded-xl border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",children:"✕"})})]}),s.jsxs("div",{className:"min-h-0 min-w-0 flex-1 overflow-y-auto px-4 py-4",children:[t.kind==="mission"&&s.jsx(dD,{meshTheme:e,mission:t.mission,daemonId:a,meshId:r,sendDaemonCommand:o}),t.kind==="ledger"&&s.jsx(mD,{meshTheme:e,entry:t.entry,resolveNodeLabel:i}),t.kind==="queue"&&s.jsx(hD,{meshTheme:e,task:t.task}),t.kind==="session"&&s.jsx(fD,{meshTheme:e,node:t.node,session:t.session})]})]})})})}const lD=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function cD(e){const t=lD(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function dD({meshTheme:e,mission:t,daemonId:n,meshId:a,sendDaemonCommand:r}){var v;const{t:o}=ke("common"),i=t.tasks,c="goal"in t&&typeof t.goal=="string"&&t.goal?t.goal:"goalPreview"in t?t.goalPreview:"",d="goalTruncated"in t?t.goalTruncated===!0:!1,[p,u]=l.useState(null),[m,f]=l.useState(!1),[g,k]=l.useState(null),h=d&&!p&&!!n&&!!r,b=l.useCallback(async()=>{if(!(!n||!r)){f(!0),k(null);try{const w=await r(n,"mesh_status",{meshId:a??void 0,verbose:!0}),j=cD(w),A=(Array.isArray(j==null?void 0:j.missions)?j.missions:[]).find(I=>(I==null?void 0:I.id)===t.id),T=typeof(A==null?void 0:A.goal)=="string"&&A.goal?A.goal:null;T?u(T):k("Full goal unavailable")}catch(w){k(w instanceof Error?w.message:"Failed to fetch full mission goal")}finally{f(!1)}}},[n,a,r,t.id]),S=p??c,x=d&&!p,y=t.stats??null,C=((v=y==null?void 0:y.incompleteTaskIds)==null?void 0:v.length)??0;return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Ut,{meshTheme:e,label:t.status,tone:zf(t.status)}),s.jsx(Ut,{meshTheme:e,label:`${i.total} tasks`,tone:"muted"})]}),S&&s.jsxs("div",{className:`max-h-64 overflow-y-auto whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:[Sc(S),x&&!h&&s.jsx("span",{className:e.textMuted,children:" … (truncated)"})]}),g&&s.jsx("div",{className:"text-[11px] text-amber-400",children:g}),h&&s.jsx("button",{type:"button",className:"self-start text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:b,disabled:m,children:o(m?"mesh.overview.loadingGoal":"mesh.overview.showFullGoal")}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5 sm:grid-cols-6",children:[s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statCompleted"),value:i.completed,tone:"emerald"}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statAssigned"),value:i.assigned,tone:i.assigned>0?"sky":void 0}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statPending"),value:i.pending}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statFailed"),value:i.failed,tone:i.failed>0?"rose":void 0}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statBlocked"),value:i.blocked,tone:i.blocked>0?"amber":void 0}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statCancelled"),value:i.cancelled,tone:"muted"})]}),y&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statWallClock"),value:_u(y.wallClockMs)??"—"}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statTotalRuntime"),value:_u(y.totalDurationMs)??"—"}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statRetries"),value:y.retries,tone:y.retries>0?"amber":void 0})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(mt,{meshTheme:e,label:o("mesh.overview.detailLabelMissionId"),value:t.id}),s.jsx(mt,{meshTheme:e,label:o("mesh.overview.detailLabelCreated"),value:ks(t.createdAt)??t.createdAt}),s.jsx(mt,{meshTheme:e,label:o("mesh.overview.detailLabelUpdated"),value:ks(t.updatedAt)??t.updatedAt}),i.lastActivityAt&&s.jsx(mt,{meshTheme:e,label:o("mesh.overview.detailLabelLastActivity"),value:ks(i.lastActivityAt)??i.lastActivityAt}),C>0&&y&&s.jsx(mt,{meshTheme:e,label:o("mesh.overview.detailLabelIncompleteEvidence"),value:s.jsxs("details",{children:[s.jsx("summary",{className:"cursor-pointer select-none",children:o("mesh.overview.incompleteTaskCount_other",{count:C})}),s.jsx("div",{className:"mt-1 flex flex-col gap-0.5 break-all",children:y.incompleteTaskIds.map(w=>s.jsx("span",{className:`font-mono text-[10px] ${e.textMuted}`,children:w},w))})]})})]})]})}function uD(e){const t=e&&typeof e=="object"?e.routingDecision:void 0;return!t||typeof t!="object"||Array.isArray(t)?null:t}function pD({meshTheme:e,routing:t,resolveNodeLabel:n}){var i;const{t:a}=ke("common"),r=[t.resolvedProviderType,t.resolvedModel,t.resolvedThinkingLevel].filter(c=>typeof c=="string"&&!!c).join(" · "),o=t.requiredTagsResult;return s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx("div",{className:`text-[10px] uppercase tracking-wide ${e.textMuted}`,children:a("mesh.overview.routingHeading")}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[t.selectedNodeId&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.routingDevice"),value:n(t.selectedNodeId)}),t.daemonId&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.routingDaemon"),value:t.daemonId}),r&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.routingExecution"),value:r}),(t.source||t.transport)&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.routingVia"),value:[t.source,t.transport].filter(Boolean).join(" · ")}),t.resolvedDifficulty&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.routingDifficulty"),value:t.resolvedDifficulty}),typeof t.fitnessScore=="number"&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.routingFitness"),value:String(t.fitnessScore)}),t.reason&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.routingReason"),value:t.reason}),o&&Array.isArray(o.required)&&o.required.length>0&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.routingRequiredTags"),value:`${o.required.join(", ")}${o.satisfied===!1?` · ${a("mesh.overview.routingTagsUnsatisfied")}${(i=o.missing)!=null&&i.length?`: ${o.missing.join(", ")}`:""}`:""}`})]}),Array.isArray(t.skippedCandidates)&&t.skippedCandidates.length>0&&s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("div",{className:`text-[10px] uppercase tracking-wide ${e.textMuted}`,children:a("mesh.overview.routingSkipped")}),s.jsxs("div",{className:`flex flex-col gap-0.5 text-[11px] leading-4 ${e.textSecondary}`,children:[t.skippedCandidates.map((c,d)=>s.jsxs("div",{children:[s.jsx("span",{children:n(c.nodeId)}),c.reason&&s.jsxs("span",{className:e.textMuted,children:[" — ",c.reason]})]},`${c.nodeId??"node"}-${d}`)),(()=>{const c=t.skippedCandidatesOmitted??t.skippedCandidatesDropped;return typeof c=="number"&&c>0?s.jsx("div",{className:e.textMuted,children:a("mesh.overview.routingSkippedMore",{count:c})}):null})()]})]})]})}function mD({meshTheme:e,entry:t,resolveNodeLabel:n}){const{t:a}=ke("common"),r=Yf(t.payload),o=uD(t.payload);let i="";try{i=JSON.stringify(t.payload??{},null,2)}catch{i=String(t.payload)}return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:s.jsx(Ut,{meshTheme:e,label:Ac(t.kind),tone:Vf(t.kind)})}),r&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:r}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelEntryId"),value:t.id}),s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelWhen"),value:ks(t.timestamp)??t.timestamp}),t.nodeId&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelNode"),value:n(t.nodeId)}),t.sessionId&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelSession"),value:Cc(t.sessionId)}),t.providerType&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelProvider"),value:t.providerType})]}),o&&s.jsx(pD,{meshTheme:e,routing:o,resolveNodeLabel:n}),i&&i!=="{}"&&s.jsxs("div",{children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:a("mesh.overview.detailLabelPayload")}),s.jsx("pre",{className:`max-h-60 max-w-full overflow-auto rounded-lg border p-2 text-[10px] leading-4 ${e.isDark?"border-white/8 bg-black/30 text-slate-300":"border-slate-200 bg-slate-50 text-slate-700"}`,children:i})]})]})}function hD({meshTheme:e,task:t}){const{t:n}=ke("common");return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Ut,{meshTheme:e,label:t.status,tone:Kf(t.status)}),t.difficulty&&s.jsx(Ut,{meshTheme:e,label:Nc(t.difficulty,n),tone:jc(t.difficulty)}),(t.requeueCount??0)>0&&s.jsx(Ut,{meshTheme:e,label:n("mesh.overview.detailLabelRequeued",{count:t.requeueCount}),tone:"amber"})]}),t.message&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:In(t.message)}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(mt,{meshTheme:e,label:n("mesh.overview.detailLabelTaskId"),value:t.id}),s.jsx(mt,{meshTheme:e,label:n("mesh.overview.detailLabelCreated"),value:ks(t.createdAt)??t.createdAt}),s.jsx(mt,{meshTheme:e,label:n("mesh.overview.detailLabelUpdated"),value:ks(t.updatedAt)??t.updatedAt}),(t.assignedNodeId||t.targetNodeId)&&s.jsx(mt,{meshTheme:e,label:n("mesh.overview.detailLabelNode"),value:t.assignedNodeId||t.targetNodeId}),(t.assignedSessionId||t.targetSessionId)&&s.jsx(mt,{meshTheme:e,label:n("mesh.overview.detailLabelSession"),value:Cc(t.assignedSessionId||t.targetSessionId)}),t.cancelReason&&s.jsx(mt,{meshTheme:e,label:n("mesh.overview.detailLabelCancelReason"),value:t.cancelReason}),t.requeueReason&&s.jsx(mt,{meshTheme:e,label:n("mesh.overview.detailLabelRequeueReason"),value:t.requeueReason}),t.autoLaunch&&s.jsx(mt,{meshTheme:e,label:n("mesh.overview.detailLabelAutoLaunch"),value:`${t.autoLaunch.status}${t.autoLaunch.reason?` · ${t.autoLaunch.reason}`:""}`})]})]})}function fD({meshTheme:e,node:t,session:n}){var o,i;const{t:a}=ke("common"),r=Gf(n);return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Ut,{meshTheme:e,label:r,tone:qf(r)}),s.jsx(Ut,{meshTheme:e,label:n.providerType||"provider unknown",tone:"muted"}),n.difficulty&&s.jsx(Ut,{meshTheme:e,label:Nc(n.difficulty,a),tone:jc(n.difficulty)})]}),n.statusNote&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:n.statusNote}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelSessionId"),value:n.sessionId}),s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelNode"),value:t.machineLabel}),s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelWorkspace"),value:n.workspace||t.workspace}),(((o=t.git)==null?void 0:o.branch)??t.worktreeBranch)&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelBranch"),value:((i=t.git)==null?void 0:i.branch)??t.worktreeBranch}),typeof n.role=="string"&&n.role&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelRole"),value:n.role}),(n.startedAt||n.createdAt)&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelStarted"),value:ks(n.startedAt||n.createdAt)??(n.startedAt||n.createdAt)})]})]})}function Ci({meshTheme:e,mission:t,onSelect:n}){const a=t.tasks,r=ks(a.lastActivityAt),o=a.total===0;return s.jsxs(Do,{meshTheme:e,onClick:n,dimmed:o,children:[s.jsx(Ut,{meshTheme:e,label:t.status,tone:zf(t.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate font-medium ${o?e.textSecondary:e.textPrimary}`,children:t.title}),a.total>0&&s.jsxs("span",{className:`shrink-0 tabular-nums text-[11px] ${e.textMuted}`,children:["✓",a.completed,"/",a.total]}),r&&s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:r})]})}function gD({meshTheme:e,liveMissions:t,historyMissions:n,hasMissionField:a,onSelect:r}){const{t:o}=ke("common"),[i,c]=l.useState(!1),[d,p]=l.useState(!1),u=e.isDark,m=l.useMemo(()=>t.filter(b=>b.status==="active"),[t]),f=l.useMemo(()=>t.filter(b=>b.status!=="active"),[t]),g=m.length>0?m:f,k=m.length>0?f:[],h=Lo(g);return s.jsxs(Ln,{meshTheme:e,title:o("mesh.overview.missionCard"),count:t.length||void 0,children:[g.length>0?s.jsxs("div",{className:"flex flex-col gap-0.5",children:[h.visible.map(b=>s.jsx(Ci,{meshTheme:e,mission:b,onSelect:()=>r(b)},b.id)),s.jsx(Io,{meshTheme:e,expanded:h.expanded,hiddenCount:h.hiddenCount,onToggle:h.toggle})]}):s.jsx(er,{meshTheme:e,children:o(a?"mesh.overview.noActiveMissions":"mesh.overview.missionDataUnavailable")}),k.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${u?"border-white/8":"border-slate-200"}`,children:[s.jsxs("button",{type:"button",onClick:()=>p(b=>!b),className:`flex w-full items-center gap-1.5 text-[11px] font-medium ${e.textSecondary}`,children:[s.jsx("span",{className:`inline-block transition-transform ${d?"rotate-90":""}`,children:"▸"}),s.jsx("span",{children:o("mesh.overview.pausedMissions")}),s.jsx("span",{className:`tabular-nums ${e.textMuted}`,children:k.length})]}),d&&s.jsx("div",{className:"mt-2 flex flex-col gap-0.5",children:k.map(b=>s.jsx(Ci,{meshTheme:e,mission:b,onSelect:()=>r(b)},b.id))})]}),n.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${u?"border-white/8":"border-slate-200"}`,children:[s.jsxs("button",{type:"button",onClick:()=>c(b=>!b),className:`flex w-full items-center gap-1.5 text-[11px] font-medium ${e.textSecondary}`,children:[s.jsx("span",{className:`inline-block transition-transform ${i?"rotate-90":""}`,children:"▸"}),s.jsx("span",{children:o("mesh.overview.completedHistory")}),s.jsx("span",{className:`tabular-nums ${e.textMuted}`,children:n.length})]}),i&&s.jsx("div",{className:"mt-2 flex flex-col gap-0.5",children:n.map(b=>s.jsx(Ci,{meshTheme:e,mission:b,onSelect:()=>r(b)},b.id))})]})]})}function bD({meshTheme:e,ledgerSummary:t,entries:n,resolveNodeLabel:a,onSelect:r}){const{t:o}=ke("common"),i=ks(t.lastActivityAt),c=l.useMemo(()=>[...n].reverse(),[n]),d=Lo(c);return s.jsxs(Ln,{meshTheme:e,title:o("mesh.overview.ledgerCard"),action:s.jsx("span",{className:`text-[10px] ${e.textMuted}`,children:o("mesh.overview.ledgerAllTime")}),children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statDispatched"),value:t.taskDispatched}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statCompleted"),value:t.taskCompleted,tone:"emerald"}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statFailed"),value:t.taskFailed,tone:t.taskFailed>0?"rose":void 0}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statStalled"),value:t.taskStalled,tone:t.taskStalled>0?"amber":void 0}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statSessions"),value:t.sessionLaunched}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statCheckpoints"),value:t.checkpointCreated})]}),c.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:o("mesh.overview.recentActivity")}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[d.visible.map(p=>{const u=Yf(p.payload);return s.jsxs(Do,{meshTheme:e,onClick:()=>r(p),children:[s.jsx(Ut,{meshTheme:e,label:Ac(p.kind),tone:Vf(p.kind)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:p.nodeId||void 0,children:u||a(p.nodeId)||p.sessionId||"—"}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:ks(p.timestamp)??""})]},p.id)}),s.jsx(Io,{meshTheme:e,expanded:d.expanded,hiddenCount:d.hiddenCount,onToggle:d.toggle})]})]}),(t.recentFailures>0||i&&c.length===0)&&s.jsxs("div",{className:`mt-2 flex items-center justify-between text-[11px] ${e.textMuted}`,children:[t.recentFailures>0?s.jsx("span",{className:e.isDark?"text-amber-300":"text-amber-600",children:o("mesh.overview.recentFailures",{count:t.recentFailures})}):s.jsx("span",{}),i&&c.length===0&&s.jsx("span",{children:i})]})]})}function xD({meshTheme:e,queueSummary:t,tasks:n,onSelect:a}){const r=l.useMemo(()=>[...n].sort((c,d)=>{const p=Eu(c.status)-Eu(d.status);return p!==0?p:(d.updatedAt||"").localeCompare(c.updatedAt||"")}).slice(0,tD),[n]),o=Lo(r),{t:i}=ke("common");return t?s.jsxs(Ln,{meshTheme:e,title:i("mesh.overview.queueCard"),count:t.active>0?i("mesh.overview.activeCount",{count:t.active}):void 0,children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(jt,{meshTheme:e,label:i("mesh.overview.statPending"),value:t.pending}),s.jsx(jt,{meshTheme:e,label:i("mesh.overview.statAssigned"),value:t.assigned,tone:t.assigned>0?"sky":void 0}),s.jsx(jt,{meshTheme:e,label:i("mesh.overview.statActive"),value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(jt,{meshTheme:e,label:i("mesh.overview.statCompleted"),value:t.completed,tone:"emerald"}),s.jsx(jt,{meshTheme:e,label:i("mesh.overview.statFailed"),value:t.failed,tone:t.failed>0?"rose":void 0}),s.jsx(jt,{meshTheme:e,label:i("mesh.overview.statCancelled"),value:t.cancelled,tone:"muted"})]}),r.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:i("mesh.overview.recentTasks")}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.visible.map(c=>s.jsxs(Do,{meshTheme:e,onClick:()=>a(c),children:[s.jsx(Ut,{meshTheme:e,label:c.status,tone:Kf(c.status)}),c.difficulty&&s.jsx(Ut,{meshTheme:e,label:Nc(c.difficulty,i),tone:jc(c.difficulty)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:c.message||void 0,children:In(c.message)||c.id}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:ks(c.updatedAt)??""})]},c.id)),s.jsx(Io,{meshTheme:e,expanded:o.expanded,hiddenCount:o.hiddenCount,onToggle:o.toggle})]})]})]}):s.jsx(Ln,{meshTheme:e,title:i("mesh.overview.queueCard"),children:s.jsx(er,{meshTheme:e,children:i("mesh.overview.noQueueActivity")})})}function vD(e){return e.autoFastForwardEligible||e.suggestedAction==="auto_fast_forward"?{label:"fast-forward",tone:"sky"}:e.launchBlockedReason?{label:"blocked",tone:"rose"}:null}function yD({meshTheme:e,nodes:t}){const{t:n}=ke("common"),a=e.isDark;return s.jsx(Ln,{meshTheme:e,title:n("mesh.overview.nodesCard"),count:t.length,children:t.length===0?s.jsx(er,{meshTheme:e,children:n("mesh.overview.noNodes")}):s.jsx("div",{className:"flex flex-col gap-1.5",children:t.map(r=>{var d,p,u;const o=(((d=r.activeSessionDetails)==null?void 0:d.length)??0)||(((p=r.activeSessions)==null?void 0:p.length)??0),i=vD(r),c=((u=r.git)==null?void 0:u.branch)??r.worktreeBranch??null;return s.jsxs("div",{className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 overflow-hidden rounded-xl border px-3 py-2 ${a?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx(Ut,{meshTheme:e,label:r.health,tone:aD(r.health)}),s.jsx("span",{className:`min-w-0 max-w-full flex-1 truncate text-sm font-medium ${e.textPrimary}`,title:r.workspace,children:r.machineLabel}),c&&s.jsx("span",{className:`max-w-full truncate font-mono text-[11px] ${e.textSecondary}`,title:c,children:c}),s.jsx("span",{className:`max-w-full truncate font-mono text-[10px] ${e.textMuted}`,children:nD(r)}),o>0&&s.jsxs("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:[o," session",o>1?"s":""]}),typeof r.daemonBuildVersion=="string"&&r.daemonBuildVersion&&s.jsxs("span",{className:`shrink-0 font-mono text-[10px] ${e.textMuted}`,title:"Daemon build version reported by this node",children:["v",r.daemonBuildVersion]}),i&&s.jsx(Ut,{meshTheme:e,label:i.label,tone:i.tone})]},r.nodeId)})})})}function wD({meshTheme:e,entries:t,onSelect:n}){const{t:a}=ke("common"),r=Lo(t);return s.jsx(Ln,{meshTheme:e,title:a("mesh.overview.sessionsCard"),count:t.length||void 0,children:t.length===0?s.jsx(er,{meshTheme:e,children:a("mesh.overview.noActiveSessions")}):s.jsxs("div",{className:"flex flex-col gap-0.5",children:[r.visible.map(({node:o,session:i})=>{const c=Gf(i),d=o.machineLabel||o.nodeId.slice(0,12),p=o.isLocalWorktree&&o.worktreeBranch?` · ${o.worktreeBranch}`:"",u=so(i);return s.jsxs(Do,{meshTheme:e,onClick:()=>n(o,i),children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:i.sessionId,children:[d,p]}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:If(i)}),s.jsx("span",{className:`shrink-0 ${e.textMuted}`,children:i.providerType||"?"}),!u.includes("not reported")&&s.jsx("span",{className:`shrink-0 text-[10px] tabular-nums ${e.textMuted}`,children:u}),s.jsx(Ut,{meshTheme:e,label:c,tone:qf(c)})]},i.sessionId)}),s.jsx(Io,{meshTheme:e,expanded:r.expanded,hiddenCount:r.hiddenCount,onToggle:r.toggle})]})})}function kD({meshTheme:e,jobs:t}){const{t:n}=ke("common"),a=e.isDark,r=t.filter(o=>o.status==="failed").length;return s.jsx(Ln,{meshTheme:e,title:n("mesh.overview.refineCard"),count:t.length||void 0,action:r>0?s.jsx(Ut,{meshTheme:e,label:n("mesh.overview.failedCount",{count:r}),tone:"rose"}):void 0,children:t.length===0?s.jsx(er,{meshTheme:e,children:n("mesh.overview.noRefineJobs")}):s.jsx("div",{className:"flex flex-col gap-1",children:t.slice(0,8).map(o=>{const i=o.status==="failed"&&(o.lastEvent||o.lastLedgerKind)||"";return s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:[o.branch??o.jobId.slice(0,14),o.into?` → ${o.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[10px] font-semibold ${o.status==="failed"?a?"text-rose-300":"text-rose-600":o.status==="running"||o.status==="accepted"?a?"text-sky-300":"text-sky-600":a?"text-emerald-300":"text-emerald-600"}`,children:o.status})]}),i&&s.jsx("div",{className:`truncate pl-1 text-[10px] ${a?"text-rose-200/80":"text-rose-600/90"}`,title:i,children:i})]},o.jobId)})})})}const SD=["node","p2p","session","task","mission","refinery","completion","magi","magiPanel","convergence"];function CD({meshTheme:e,open:t,onToggle:n}){const{t:a}=ke(),r=e.isDark,o="inline-flex h-7 w-7 items-center justify-center rounded-lg border transition",i=t?r?"border-sky-400/40 bg-sky-500/15 text-sky-100":"border-sky-400 bg-sky-100 text-sky-800":r?"border-white/10 bg-white/[0.04] text-slate-400 hover:bg-white/[0.08] hover:text-slate-100":"border-slate-200 bg-white text-slate-400 hover:bg-slate-50 hover:text-slate-700";return s.jsx("button",{type:"button",onClick:n,"aria-label":a("meshGraph.help.toggleAria"),"aria-expanded":t,title:a("meshGraph.help.toggleTitle"),className:`${o} ${i}`,children:s.jsx(gb,{size:15})})}function jD({meshTheme:e,onClose:t}){const{t:n}=ke(),a=e.isDark,r=l.useMemo(()=>SD.map(o=>({term:n(`meshGraph.help.sections.${o}.term`),summary:n(`meshGraph.help.sections.${o}.summary`),details:n(`meshGraph.help.sections.${o}.details`,{returnObjects:!0})})),[n]);return l.useEffect(()=>{const o=i=>{i.key==="Escape"&&t()};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[t]),s.jsxs("div",{className:`shrink-0 rounded-2xl border p-4 ${a?"border-white/10 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,role:"region","aria-label":n("meshGraph.help.regionAria"),children:[s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:n("meshGraph.help.kicker")}),s.jsx("div",{className:`mt-0.5 text-sm font-semibold ${e.textPrimary}`,children:n("meshGraph.help.title")})]}),s.jsx("button",{type:"button",onClick:t,"aria-label":n("meshGraph.help.close"),className:a?"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white":"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",children:s.jsx(Dt,{size:14})})]}),s.jsx("dl",{className:"grid gap-3 sm:grid-cols-2",children:r.map(o=>s.jsxs("div",{className:`rounded-xl border p-3 ${a?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx("dt",{className:`text-xs font-semibold ${e.textPrimary}`,children:o.term}),s.jsx("dd",{className:`mt-1 text-[11px] leading-5 ${e.textSecondary}`,children:o.summary}),o.details&&o.details.length>0&&s.jsx("ul",{className:`mt-1.5 flex flex-col gap-1 text-[11px] leading-5 ${e.textMuted}`,children:o.details.map((i,c)=>s.jsxs("li",{className:"flex gap-1.5",children:[s.jsx("span",{"aria-hidden":!0,className:"select-none",children:"·"}),s.jsx("span",{className:"min-w-0",children:i})]},c))})]},o.term))})]})}const _s=l.createContext(Es("dark"));function ze({label:e,tone:t="default",className:n,title:a}){const r=l.useContext(_s);return s.jsx("span",{title:a,className:`rounded-full border pl-2 pr-[calc(0.5rem-0.16em)] py-0.5 text-[10px] leading-none align-middle uppercase tracking-[0.16em] ${r.badge(t)}${n?` ${n}`:""}`,children:e})}function Ht({label:e,value:t}){const n=l.useContext(_s);return s.jsxs("div",{className:n.rowClass,children:[s.jsx("span",{className:n.rowLabelClass,children:e}),s.jsx("span",{className:n.rowValueClass,children:t})]})}function ND({scheduling:e}){const{t}=ke("common"),n=l.useContext(_s);if(!e)return s.jsx("div",{className:`${n.cardClass} rounded-2xl p-4 text-[12px] ${n.textSecondary}`,children:t("mesh.status.schedulingNotReported")});const a=typeof e.activeWriteAssigned=="number"&&typeof e.maxParallelTasks=="number";return s.jsxs("div",{className:`${n.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${n.textPrimary}`,children:t("mesh.status.schedulingTitle")}),s.jsx(ze,{label:MM[e.strategy]??e.strategy,tone:"info"}),a&&s.jsx(ze,{label:`write ${e.activeWriteAssigned}/${e.maxParallelTasks}`,tone:e.globalWriteCapReached?"warn":"good",title:"Active write (non-readonly) assigned tasks vs the global parallel cap"}),a&&typeof e.activeReadonlyAssigned=="number"&&typeof e.maxReadonlyParallelTasks=="number"&&s.jsx(ze,{label:`readonly ${e.activeReadonlyAssigned}/${e.maxReadonlyParallelTasks}`,tone:e.globalReadonlyCapReached?"warn":"default",title:"Active read-only diagnosis tasks vs their (2× write) cap"})]}),s.jsx("p",{className:`mt-2 text-[11px] ${n.textSecondary}`,children:t("mesh.status.distributionTitle")})]})}function AD({scheduling:e}){return e?s.jsxs(s.Fragment,{children:[s.jsx(ze,{label:`load ${e.load}`,tone:e.load>0?"info":"default",title:"Active assigned tasks on this node"}),typeof e.schedulingPriority=="number"&&e.schedulingPriority!==0&&s.jsx(ze,{label:`priority ${e.schedulingPriority}`,tone:"default",title:"Soft scheduling priority (higher = preferred)"}),(e.providerRoles??[]).map(t=>s.jsx(ze,{label:`${t.providerType} ${t.activeAssigned}${typeof t.maxParallel=="number"?`/${t.maxParallel}`:""}`,tone:t.capReached?"warn":"default",title:"Per-(node, provider) active assignments vs declared maxParallel cap"},t.providerType)),e.capReached&&(e.capReasons??[]).map(t=>s.jsx(ze,{label:PM(t),tone:"warn",title:"Why this node cannot currently claim a new write task"},t))]}):null}function TD({machine:e}){const{t}=ke("common"),n=l.useContext(_s),a=fS(e.reportedAt);return s.jsxs("div",{className:`rounded-xl border p-3 ${n.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${n.textPrimary}`,children:e.label}),e.daemonBuildVersion&&s.jsx(ze,{label:e.daemonBuildVersion,tone:"default",title:"Daemon build version running on this machine"}),e.nodeCount>1&&s.jsx(ze,{label:`${e.nodeCount} nodes`,tone:"default",title:"Mesh nodes (workspaces/worktrees) hosted by this machine — they share this one plan quota"}),a&&s.jsx("span",{className:`text-[10px] ${n.textSecondary}`,title:t("mesh.status.quotaFreshnessHint"),children:a})]}),e.quota.length===0?s.jsx("div",{className:`mt-1.5 text-[11px] ${n.textSecondary}`,children:e.hasReported?t("mesh.status.quotaNotCollected"):t("mesh.status.machineNotReporting")}):s.jsx("div",{className:"mt-2 flex flex-col gap-1.5",children:e.quota.map(({provider:r,quota:o})=>{var u,m;const i=wo(o),c=ln(o.session,void 0,i),d=ln(o.weekly,void 0,i),p=!!(c||d);return s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx("span",{className:`text-[11px] ${n.textPrimary}`,children:Pn(r)}),$a(o)&&s.jsx("span",{className:`text-[10px] ${n.textSecondary}`,title:t("mesh.status.quotaAccountHint"),children:$a(o)}),c&&s.jsx(ze,{label:`5h ${c}`,tone:on(((u=o.session)==null?void 0:u.usedPercent)??NaN),title:"Rolling 5-hour plan window reported by this machine"}),d&&s.jsx(ze,{label:`7d ${d}`,tone:on(((m=o.weekly)==null?void 0:m.usedPercent)??NaN),title:"Rolling 7-day plan window reported by this machine"}),!p&&s.jsx("span",{className:`text-[11px] ${n.textSecondary}`,title:"This machine reported that it could not read this provider's quota",children:ec(o)}),hS(r,o)&&s.jsx("span",{className:`text-[11px] ${n.textSecondary} opacity-80`,children:t("mesh.status.quotaClaudeSetupHint")})]},r)})})]})}function MD({status:e}){const{t}=ke("common"),n=l.useContext(_s),a=AM(e);if(a.length===0)return null;const r=a.filter(i=>i.hasReported),o=a.filter(i=>!i.hasReported);return s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("span",{className:`px-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${n.textSecondary}`,children:t("mesh.status.machinesQuota")}),r.map(i=>s.jsx(TD,{machine:i},i.machineKey)),o.length>0&&s.jsx("div",{className:`rounded-xl border px-3 py-2 text-[11px] ${n.textSecondary} ${n.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:t("mesh.status.machinesNotReporting",{count:o.length,machines:o.map(i=>i.label).join(", ")})})]})}function PD(e,t){var r;if(e.health!=="degraded"&&e.health!=="unknown")return null;if(typeof e.error=="string"&&e.error)return e.error;const n=e.git;if(n&&n.isGitRepo===!1)return t("mesh.status.healthNotGitRepo");if(e.gitProbePending)return t("mesh.status.healthProbePending");const a=(r=e.connection)==null?void 0:r.state;return a&&a!=="connected"&&a!=="self"?t("mesh.status.healthPeerConnection",{state:a}):t("mesh.status.healthNoLiveReport")}function DD({node:e,previewVersion:t}){var S,x,y,C,v;const{t:n}=ke("common"),a=l.useContext(_s),r=PD(e,n),o=((S=e.activeSessionDetails)==null?void 0:S.length)??((x=e.activeSessions)==null?void 0:x.length)??0,i=vl((y=e.git)==null?void 0:y.headCommit),c=e.isLocalWorktree===!0,d=e.worktreeBootstrap,p=e.staleDaemonBuild,u=e.providerVersions&&typeof e.providerVersions=="object"?e.providerVersions:void 0,m=u?Object.entries(u).filter(([,w])=>typeof w=="string"&&w):[],f=typeof e.daemonBuildVersion=="string"&&e.daemonBuildVersion?e.daemonBuildVersion:void 0,g=(C=e.nodeFacts)==null?void 0:C.daemonBuild,k=g!=null&&g.commitShort?`build ${g.version||f||"?"}@${g.commitShort}`:f?`build ${f}`:void 0,h=((g==null?void 0:g.version)||f||"").trim().toLowerCase(),b=!!(h&&t&&h!==t.trim().toLowerCase());return s.jsxs("div",{className:`rounded-xl border p-3 ${a.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${a.textPrimary}`,children:e.machineLabel||e.nodeId}),s.jsx(ze,{label:e.health,tone:Df(e.health)}),c&&s.jsx(ze,{label:n("mesh.status.badgeWorktree"),tone:"info",title:e.worktreeBranch?n("mesh.status.badgeWorktreeBranchTitle",{branch:e.worktreeBranch}):n("mesh.status.badgeWorktreeTitle")}),(d==null?void 0:d.status)&&d.status!=="ready"&&s.jsx(ze,{label:`bootstrap ${d.status}`,tone:"warn",title:n("mesh.status.badgeBootstrapTitle")}),((v=e.connection)==null?void 0:v.state)&&e.connection.state!=="self"&&s.jsx(ze,{label:e.connection.state,tone:e.connection.state==="connected"?"good":"warn",title:n("mesh.status.badgeConnectionTitle")}),o>0&&s.jsx(ze,{label:n("mesh.status.badgeSessions",{count:o}),tone:"default"}),e.autoFastForwardEligible&&s.jsx(ze,{label:n("mesh.status.badgeFastForwardReady"),tone:"info",title:n("mesh.status.badgeFastForwardReadyTitle")}),!!p&&s.jsx(ze,{label:n("mesh.status.badgeStaleBuild"),tone:"warn",title:n("mesh.status.badgeStaleBuildTitle")}),k&&s.jsx(ze,{label:k,tone:p||b?"warn":"default",title:"Daemon build (version@commit) reported by this node — the running daemon's actual code identity"}),b&&s.jsx(ze,{label:`deploy-lag vs ${t}`,tone:"warn",title:n("mesh.status.badgeDeployLagTitle")}),s.jsx(AD,{scheduling:e.scheduling})]}),r&&s.jsx("div",{className:`mt-1.5 truncate text-[11px] ${a.isDark?"text-amber-200/85":"text-amber-700"}`,title:r,children:r}),m.length>0&&s.jsx("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:m.map(([w,j])=>s.jsx(ze,{label:`${w}@${j}`,tone:"info",title:"Detected provider version on this node"},w))}),s.jsxs("div",{className:`mt-1.5 text-[11px] ${a.textSecondary}`,children:[jM(e),i?s.jsxs("span",{className:"ml-2 font-mono opacity-70",children:["@",i]}):null]})]})}function ID({status:e}){const{t}=ke("common"),n=l.useContext(_s),a=e.meshProtocolMetrics,r=Array.isArray(e.providerVersionSkew)?e.providerVersionSkew:[];return!a&&r.length===0?null:s.jsxs("div",{className:`${n.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${n.textPrimary}`,children:t("mesh.status.protocolTitle")}),a&&s.jsx(ze,{label:`v2 ${Math.round(a.v2Ratio*100)}% (${a.v2}/${a.total})`,tone:a.total>0&&a.v2===a.total?"good":"info",title:"Share of pending coordinator events carrying a mesh-protocol-v2 envelope in this drain"}),r.length>0&&s.jsx(ze,{label:`${r.length} provider skew`,tone:"warn",title:"Providers running different versions across nodes"})]}),a&&Object.keys(a.scopes).length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:Object.entries(a.scopes).map(([o,i])=>s.jsx(ze,{label:`${o}: ${i}`,tone:"default",title:"v2 event scope breakdown"},o))}),r.length>0&&s.jsx("div",{className:"mt-2 flex flex-col gap-1.5",children:r.map(o=>s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx("span",{className:`text-[11px] font-semibold ${n.textPrimary}`,children:o.provider}),o.versions.map(i=>s.jsx(ze,{label:`${i.version} · ${i.nodeIds.length} node${i.nodeIds.length===1?"":"s"}`,tone:"default",title:i.nodeIds.join(", ")},i.version))]},o.provider))}),e.providerVersionSkewWarning&&s.jsx("p",{className:`mt-2 text-[11px] ${n.textSecondary}`,children:e.providerVersionSkewWarning})]})}function LD({canonicalStatus:e}){const{t}=ke("common"),n=l.useContext(_s);return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsx(ND,{scheduling:e.scheduling}),s.jsx(ID,{status:e}),s.jsx(MD,{status:e}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("span",{className:`px-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${n.textSecondary}`,children:t("mesh.status.nodesRuntime")}),e.nodes.length===0?s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${n.textSecondary} ${n.isDark?"border-white/10":"border-slate-200"}`,children:t("mesh.status.noNodesReporting")}):e.nodes.map(a=>{var r;return s.jsx(DD,{node:a,previewVersion:typeof((r=e.previewFreshness)==null?void 0:r.previewVersion)=="string"?e.previewFreshness.previewVersion:void 0},a.nodeId)})]})]})}const yr=["provider_quirk","pattern_to_avoid","recovery_lesson"],Hu=240,RD={provider_quirk:"warn",pattern_to_avoid:"danger",recovery_lesson:"good"};function ji(e,t){return e(t==="provider_quirk"?"meshGraph.notes.categoryProviderQuirk":t==="pattern_to_avoid"?"meshGraph.notes.categoryPatternToAvoid":t==="recovery_lesson"?"meshGraph.notes.categoryRecoveryLesson":"meshGraph.notes.categoryUncategorized")}function $u(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleString()}function ED({meshId:e,daemonId:t,sendDaemonCommand:n}){const{t:a}=ke("common"),r=l.useContext(_s),[o,i]=l.useState([]),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,f]=l.useState(!1),[g,k]=l.useState(!1),[h,b]=l.useState(""),[S,x]=l.useState(""),[y,C]=l.useState(new Set),[v,w]=l.useState(null),[j,N]=l.useState(""),[A,T]=l.useState(""),I=!!(n&&t&&e),P=l.useCallback(async()=>{if(!(!n||!t||!e)){d(!0),u(null);try{const L=await n(t,"list_mesh_notes",{meshId:e,tail:100}),F=(L==null?void 0:L.result)??L;if(F&&F.success===!1){u(typeof F.error=="string"?F.error:a("meshGraph.notes.loadFailed")),i([]);return}const $=Array.isArray(F==null?void 0:F.notes)?F.notes:[];i([...$].reverse())}catch(L){u(L instanceof Error?L.message:a("meshGraph.notes.loadFailed")),i([])}finally{d(!1)}}},[n,t,e,a]);l.useEffect(()=>{P()},[P]);const M=l.useCallback(async()=>{if(!n||!t||!e)return;const L=h.trim();if(!(!L||m)){f(!0),u(null);try{const F=await n(t,"record_mesh_note",{meshId:e,text:L,...S?{category:S}:{}}),$=(F==null?void 0:F.result)??F;if($&&$.success===!1){u(typeof $.error=="string"?$.error:a("meshGraph.notes.saveFailed"));return}b(""),x(""),k(!1),await P()}catch(F){u(F instanceof Error?F.message:a("meshGraph.notes.saveFailed"))}finally{f(!1)}}},[n,t,e,h,S,m,P,a]),E=l.useCallback(async L=>{if(!(!n||!t||!e||m)){f(!0),u(null);try{const F=await n(t,"forget_mesh_note",{meshId:e,noteId:L}),$=(F==null?void 0:F.result)??F;if($&&$.success===!1){u(typeof $.error=="string"?$.error:a("meshGraph.notes.deleteFailed"));return}await P()}catch(F){u(F instanceof Error?F.message:a("meshGraph.notes.deleteFailed"))}finally{f(!1)}}},[n,t,e,m,P,a]),D=l.useCallback(L=>{w(L.id),N(L.text),T(yr.includes(L.category)?L.category:"")},[]),W=l.useCallback(()=>{w(null),N(""),T("")},[]),R=l.useCallback(async L=>{if(!n||!t||!e||m)return;const F=j.trim();if(F){f(!0),u(null);try{const $=await n(t,"forget_mesh_note",{meshId:e,noteId:L}),K=($==null?void 0:$.result)??$;if(K&&K.success===!1){u(typeof K.error=="string"?K.error:a("meshGraph.notes.editFailed"));return}const z=await n(t,"record_mesh_note",{meshId:e,text:F,...A?{category:A}:{}}),ne=(z==null?void 0:z.result)??z;if(ne&&ne.success===!1){u(typeof ne.error=="string"?ne.error:a("meshGraph.notes.editFailed"));return}W(),await P()}catch($){u($ instanceof Error?$.message:a("meshGraph.notes.editFailed"))}finally{f(!1)}}},[n,t,e,j,A,m,W,P,a]),B=r.isDark?"rounded-lg border border-white/10 bg-slate-950/40 px-2.5 py-1.5 text-xs text-slate-200":"rounded-lg border border-slate-300 bg-white px-2.5 py-1.5 text-xs text-slate-700",_=r.isDark?"w-full rounded-lg border border-white/10 bg-slate-950/40 px-3 py-2 text-sm text-slate-100 placeholder:text-slate-500":"w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm text-slate-800 placeholder:text-slate-400",H=L=>`rounded-lg border px-2.5 py-1 text-xs font-medium transition disabled:cursor-not-allowed disabled:opacity-45 ${r.actionButton(L)}`;return I?s.jsxs("div",{className:"flex flex-col gap-3",children:[g?s.jsxs("div",{className:`${r.cardClass} rounded-2xl p-4`,children:[s.jsx("div",{className:`mb-2 text-sm font-semibold ${r.textPrimary}`,children:a("meshGraph.notes.addTitle")}),s.jsx("textarea",{value:h,onChange:L=>b(L.target.value),rows:2,placeholder:a("meshGraph.notes.textPlaceholder"),className:_,autoFocus:!0}),s.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[s.jsxs("select",{value:S,onChange:L=>x(L.target.value),className:B,"aria-label":a("meshGraph.notes.categoryLabel"),children:[s.jsx("option",{value:"",children:a("meshGraph.notes.categoryUncategorized")}),yr.map(L=>s.jsx("option",{value:L,children:ji(a,L)},L))]}),s.jsx("button",{type:"button",onClick:()=>{M()},disabled:m||!h.trim(),className:H("success"),children:a("meshGraph.notes.add")}),s.jsx("button",{type:"button",onClick:()=>k(!1),disabled:m,className:H("default"),children:a("meshGraph.notes.cancel")})]})]}):s.jsx("div",{children:s.jsxs("button",{type:"button",onClick:()=>k(!0),className:H("info"),children:["+ ",a("meshGraph.notes.addTitle")]})}),p&&s.jsx("div",{className:r.isDark?"rounded-xl border border-rose-400/20 bg-rose-500/10 px-3 py-2 text-xs text-rose-100":"rounded-xl border border-rose-300 bg-rose-50 px-3 py-2 text-xs text-rose-700",children:p}),s.jsxs("div",{className:`${r.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("div",{className:`text-sm font-semibold ${r.textPrimary}`,children:a("meshGraph.notes.listTitle")}),s.jsx("button",{type:"button",onClick:()=>{P()},disabled:c||m,className:H("default"),children:a("meshGraph.notes.refresh")})]}),c?s.jsx("div",{className:`py-6 text-center text-sm ${r.textMuted}`,children:a("meshGraph.notes.loading")}):o.length===0?s.jsx("div",{className:`py-6 text-center text-sm ${r.textMuted}`,children:a("meshGraph.notes.empty")}):s.jsx("div",{className:"flex flex-col gap-2",children:o.map(L=>s.jsx("div",{className:`rounded-xl border px-3 py-2.5 ${r.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:v===L.id?s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("textarea",{value:j,onChange:F=>N(F.target.value),rows:2,className:_}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("select",{value:A,onChange:F=>T(F.target.value),className:B,"aria-label":a("meshGraph.notes.categoryLabel"),children:[s.jsx("option",{value:"",children:a("meshGraph.notes.categoryUncategorized")}),yr.map(F=>s.jsx("option",{value:F,children:ji(a,F)},F))]}),s.jsx("button",{type:"button",onClick:()=>{R(L.id)},disabled:m||!j.trim(),className:H("success"),children:a("meshGraph.notes.save")}),s.jsx("button",{type:"button",onClick:W,disabled:m,className:H("default"),children:a("meshGraph.notes.cancel")})]})]}):s.jsxs(s.Fragment,{children:[(()=>{const F=Sc(L.text),$=y.has(L.id),K=F.length>Hu,z=!K||$?F:`${F.slice(0,Hu).trimEnd()}…`;return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`whitespace-pre-wrap break-words text-sm ${r.textPrimary}`,children:z}),K&&s.jsx("button",{type:"button",onClick:()=>C(ne=>{const ie=new Set(ne);return ie.has(L.id)?ie.delete(L.id):ie.add(L.id),ie}),className:`mt-1 text-[11px] font-medium ${r.isDark?"text-sky-300 hover:text-sky-200":"text-sky-600 hover:text-sky-700"}`,children:a($?"meshGraph.notes.showLess":"meshGraph.notes.showMore")})]})})(),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx(ze,{label:ji(a,L.category),tone:yr.includes(L.category)?RD[L.category]:"default"}),L.pinned&&s.jsx(ze,{label:a("meshGraph.notes.pinned"),tone:"info"}),$u(L.createdAt)&&s.jsx("span",{className:`text-[11px] ${r.textMuted}`,children:$u(L.createdAt)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{type:"button",onClick:()=>D(L),disabled:m,className:H("info"),children:a("meshGraph.notes.edit")}),s.jsx("button",{type:"button",onClick:()=>{E(L.id)},disabled:m,className:H("default"),children:a("meshGraph.notes.delete")})]})]})]})},L.id))})]})]}):s.jsx("div",{className:`${r.cardClass} rounded-2xl p-4 text-[12px] ${r.textSecondary}`,children:a("meshGraph.notes.unavailable")})}function _D({canonicalStatus:e,queueSummary:t,ledgerSummary:n,isBootstrapMode:a,meshTheme:r,sessionEntries:o,inlineMode:i=!1}){var w;const c=t&&(t.active>0||t.historical>0),d=n.recentFailures>0||n.taskFailed>0,p=(w=e.queue)!=null&&w.tasks?e.queue.tasks.filter(j=>j.status==="failed"||j.status==="cancelled").slice(0,5):[],u=e.asyncRefineJobs,m=(u==null?void 0:u.filter(j=>j.status==="running"||j.status==="accepted"))??[],f=(u==null?void 0:u.filter(j=>j.status==="failed"))??[],g=e.staleDirectWorkSummary,k=g&&g.count>0;if(!c&&!d&&e.nodes.length===0&&!a&&m.length===0&&f.length===0&&!k&&o.length===0)return null;const{t:h}=ke("common"),b=r.isDark,S=`border-t ${b?"border-white/8":"border-slate-200"}`,x=`group w-full rounded-lg border text-xs ${b?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,y=`flex cursor-pointer list-none items-center gap-1.5 px-2.5 py-1.5 [&::-webkit-details-marker]:hidden ${r.textSecondary}`;function C({label:j,value:N,tone:A}){const T=A==="rose"?b?"text-rose-300":"text-rose-600":A==="sky"?b?"text-sky-300":"text-sky-600":A==="amber"?b?"text-amber-300":"text-amber-600":A==="emerald"?b?"text-emerald-300":"text-emerald-600":A==="muted"?r.textMuted:r.textPrimary;return s.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-1.5 ${b?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[s.jsx("span",{className:`tabular-nums text-sm font-semibold leading-none ${T}`,children:N}),s.jsx("span",{className:`mt-0.5 text-[9px] uppercase tracking-wide ${r.textMuted}`,children:j})]})}const v=s.jsxs("div",{className:"flex flex-col gap-3 text-xs",children:[s.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t?s.jsxs(s.Fragment,{children:[s.jsx(C,{label:"Pending",value:t.pending}),s.jsx(C,{label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(C,{label:"Done",value:t.completed,tone:"emerald"}),s.jsx(C,{label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0})]}):s.jsxs(s.Fragment,{children:[s.jsx(C,{label:"Done",value:n.taskCompleted,tone:"emerald"}),s.jsx(C,{label:"Failed",value:n.taskFailed,tone:n.taskFailed>0?"rose":void 0}),s.jsx(C,{label:"Sessions",value:n.sessionLaunched}),s.jsx(C,{label:"Recent↯",value:n.recentFailures,tone:n.recentFailures>0?"amber":"muted"})]})}),t&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(C,{label:"Ledger done",value:n.taskCompleted,tone:"emerald"}),s.jsx(C,{label:"Sessions",value:n.sessionLaunched}),s.jsx(C,{label:"Recent↯",value:n.recentFailures,tone:n.recentFailures>0?"amber":"muted"})]}),n.lastActivityAt&&s.jsxs("div",{className:`flex items-center justify-between ${r.textMuted}`,children:[s.jsx("span",{children:h("meshGraph.health.lastActivity")}),s.jsx("span",{className:"font-mono text-[10px]",children:n.lastActivityAt.slice(5,16)})]}),e.nodes.length>0&&s.jsx("div",{className:`pt-2.5 ${S}`,children:s.jsx("div",{className:"flex flex-col gap-1",children:e.nodes.map(j=>{var M;const N=((M=j.connection)==null?void 0:M.state)??"unknown",A=N==="unknown"||N==="connecting",P=A?"bg-amber-400":N==="failed"||N==="closed"||N==="disconnected"?b?"bg-rose-400":"bg-rose-500":N==="connected"||N==="self"?b?"bg-emerald-400":"bg-emerald-500":b?"bg-slate-500":"bg-slate-400";return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`size-1.5 shrink-0 rounded-full ${P}`}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${r.textSecondary}`,title:j.workspace,children:j.machineLabel}),s.jsx("span",{className:`shrink-0 font-mono text-[10px] ${r.textMuted}`,children:A?"…":N})]},j.nodeId)})})}),u&&u.length>0&&s.jsx("div",{className:`pt-2.5 ${S}`,children:s.jsxs("details",{className:x,children:[s.jsxs("summary",{className:y,children:[s.jsx("span",{className:"flex-1",children:h("meshGraph.health.refineJobs")}),s.jsx("span",{className:`tabular-nums ${b?"text-slate-400":"text-slate-500"}`,children:u.length}),f.length>0&&s.jsxs("span",{className:b?"text-rose-300":"text-rose-600",children:[f.length," failed"]})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:u.slice(0,8).map(j=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${r.textMuted}`,children:[j.branch??j.jobId.slice(0,14),j.into?` → ${j.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${j.status==="failed"?b?"text-rose-300":"text-rose-600":j.status==="running"||j.status==="accepted"?b?"text-sky-300":"text-sky-600":b?"text-emerald-300":"text-emerald-600"}`,children:j.status})]},j.jobId))})]})}),p.length>0&&s.jsx("div",{className:u&&u.length>0?"":`pt-2.5 ${S}`,children:s.jsxs("details",{className:x,children:[s.jsxs("summary",{className:y,children:[s.jsx("span",{className:`flex-1 ${b?"text-rose-300":"text-rose-600"}`,children:h("meshGraph.health.failedTasks")}),s.jsx("span",{className:`tabular-nums ${b?"text-rose-400":"text-rose-500"}`,children:p.length})]}),s.jsx("div",{className:"flex flex-col gap-1 px-2.5 pb-2",children:p.map(j=>s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`font-mono text-[10px] ${r.textMuted}`,children:j.id.slice(0,10)}),j.message&&s.jsx("span",{className:`flex-1 truncate ${b?"text-slate-300":"text-slate-700"}`,children:j.message.slice(0,55)})]}),j.cancelReason&&s.jsx("div",{className:`truncate text-[10px] ${r.textMuted}`,children:j.cancelReason.slice(0,55)})]},j.id))})]})}),k&&s.jsxs("div",{className:`flex items-center justify-between pt-2.5 ${S}`,children:[s.jsx("span",{className:r.textMuted,children:h("meshGraph.health.staleWork")}),s.jsx("span",{className:`tabular-nums ${b?"text-amber-300":"text-amber-600"}`,children:g.count})]}),o.length>0&&s.jsx("div",{className:`pt-2.5 ${S}`,children:s.jsxs("details",{className:x,children:[s.jsxs("summary",{className:y,children:[s.jsx("span",{className:"flex-1",children:h("meshGraph.health.sessions")}),s.jsx("span",{className:`tabular-nums ${b?"text-slate-400":"text-slate-500"}`,children:o.length})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:o.map(j=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${r.textMuted}`,title:j.session.sessionId,children:Lf(j.session.sessionId)}),s.jsx("span",{className:`shrink-0 ${r.textMuted}`,children:j.session.providerType||"?"}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${r.textMuted}`,children:Rr(j.session)})]},j.session.sessionId))})]})})]});return i?v:s.jsxs("details",{className:`rounded-2xl border text-xs ${r.isDark?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsxs("summary",{className:`flex cursor-pointer list-none items-center gap-2 px-4 py-3 font-medium [&::-webkit-details-marker]:hidden ${r.textSecondary}`,children:[s.jsx("span",{className:"flex-1",children:h("meshGraph.health.panelTitle")}),m.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${r.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700"}`,children:[m.length," refining"]}),f.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${r.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[f.length," refine failed"]}),d&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${r.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[n.recentFailures," recent failures"]}),a&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${r.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:"awaiting live data"})]}),v]})}function Qf({meshTheme:e,activeTab:t,onActiveTabChange:n,helpOpen:a,onHelpOpenChange:r}){const{t:o}=ke("common"),i=c=>c?e.isDark?"rounded-lg px-3.5 py-1.5 text-xs font-semibold text-slate-100 bg-white/[0.08] border border-white/12":"rounded-lg px-3.5 py-1.5 text-xs font-semibold text-slate-900 bg-white border border-slate-300 shadow-sm":`rounded-lg px-3.5 py-1.5 text-xs font-medium ${e.textSecondary} border border-transparent hover:bg-white/[0.04]`;return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:`inline-flex w-fit items-center gap-1 rounded-xl border p-1 ${e.isDark?"border-white/10 bg-slate-950/40":"border-slate-200 bg-slate-50"}`,role:"tablist","aria-label":"Mesh view",children:[s.jsx("button",{type:"button",role:"tab","aria-selected":t==="overview",className:i(t==="overview"),onClick:()=>n("overview"),children:o("meshGraph.obs.tabOverview")}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="tasks",className:i(t==="tasks"),onClick:()=>n("tasks"),children:o("meshGraph.obs.tabTasks")}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="status",className:i(t==="status"),onClick:()=>n("status"),children:o("meshGraph.obs.tabStatus")}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="notes",className:i(t==="notes"),onClick:()=>n("notes"),children:o("meshGraph.notes.tab")}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="graph",className:i(t==="graph"),onClick:()=>n("graph"),children:o("meshGraph.obs.tabGraph")})]}),s.jsx(CD,{meshTheme:e,open:a,onToggle:()=>r(!a)})]})}function HD({status:e,emptyMessage:t,daemonId:n=null,sendDaemonCommand:a=null,bootstrapFallback:r,activeTab:o,onActiveTabChange:i,helpOpen:c,onHelpOpenChange:d,hideControls:p=!1,onRequestRefresh:u}){var We,Xe,et;const{t:m}=ke("common"),{theme:f}=Rs(),g=l.useMemo(()=>Es(f),[f]),k=l.useMemo(()=>({merged_to_main:m("meshGraph.obs.convergenceMergedToMain"),pushed_feature_branch_needs_merge:m("meshGraph.obs.convergenceNeedsMerge"),blocked_review:m("meshGraph.obs.convergenceBlockedReview"),cleanup_candidate:m("meshGraph.obs.convergenceCleanup"),not_mergeable:m("meshGraph.obs.convergenceNotMergeable")}),[m]),h=t??m("meshGraph.obs.emptyGraph"),b=l.useMemo(()=>Sm(e),[e]),S=r??OM(b),x=l.useMemo(()=>WM(b),[b]),y=l.useMemo(()=>Pf(b),[x]),[C,v]=l.useState("overview"),[w,j]=l.useState(!1),N=o??C,A=c??w,T=l.useCallback(J=>{i?i(J):v(J)},[i]),I=l.useCallback(J=>{d?d(J):j(J)},[d]),[P,M]=l.useState(!1);l.useEffect(()=>{N==="graph"&&M(!0)},[N]);const[E,D]=l.useState(!1);l.useEffect(()=>{N==="tasks"&&D(!0)},[N]);const W=l.useMemo(()=>{var Le,$e;const J=((Le=b.queue)==null?void 0:Le.tasks)??(($e=b.queue)==null?void 0:$e.items)??null;return Array.isArray(J)?J:[]},[b.queue]),[R,B]=l.useState(null),[_,H]=l.useState(null),[L,F]=l.useState(null),[$,K]=l.useState({}),[z,ne]=l.useState(null),[ie,Ce]=l.useState(null),me=l.useMemo(()=>new Map(b.nodes.map(J=>[J.nodeId,J])),[b.nodes]),O=l.useMemo(()=>new Map(y.nodes.map(J=>[J.id,J])),[y.nodes]),Y=((We=b.queue)==null?void 0:We.summary)??null,X=((Xe=b.ledger)==null?void 0:Xe.summary)??wM,Q=l.useMemo(()=>DM(b),[b]),ve=l.useMemo(()=>{const J=new Map;for(const Le of Q){const $e=Rr(Le.session);J.set($e,(J.get($e)??0)+1)}return[...J.entries()].sort((Le,$e)=>$e[1]-Le[1])},[Q]);l.useEffect(()=>{R&&(O.has(R)||(B(null),F(J=>!J||"nodeId"in J&&J.nodeId===R?null:J)))},[O,R]);const he=R?me.get(R)??null:null,Z=BM(y,R),fe=(L==null?void 0:L.kind)==="edge"&&_?y.edges.find(J=>J.id===_)??null:null,V=fe?y.nodes.find(J=>J.id===fe.source)??null:null,q=fe?y.nodes.find(J=>J.id===fe.target)??null:null;l.useEffect(()=>{var J,Le,$e;if(R)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:b.meshId,selectedNodeId:R,canonicalNode:sS(he),graphNode:Z?{id:Z.id,branch:Z.branch,upstream:Z.upstream,headCommit:Z.submoduleCommit,submoduleCount:((Le=(J=he==null?void 0:he.git)==null?void 0:J.submodules)==null?void 0:Le.length)??0,snapshotCompleteness:Z.snapshotCompleteness,snapshotWarnings:Z.snapshotWarnings,branchConvergence:(($e=Z.branchConvergence)==null?void 0:$e.status)??null}:null})}catch{}},[b.meshId,Z,R,he]);const ee=(L==null?void 0:L.kind)==="session"?Q.find(J=>J.nodeId===L.nodeId&&J.session.sessionId===L.sessionId)??null:null,pe=l.useMemo(()=>Q.filter(J=>J.nodeId===R),[R,Q]),le=_M({coordinatorDaemonId:n,selectedNodeStatus:he,selectedSessionEntry:ee}),se=(le==null?void 0:le.workspace)??null,te=se?$[se]??null:null,ue=RM(he,(te==null?void 0:te.entries)??[]),ye=(Z==null?void 0:Z.daemonId)??(he==null?void 0:he.daemonId)??n??null,Me=!!(Z&&a&&ye&&Z.type!=="submoduleNode"&&Z.behind>0&&Z.ahead===0&&Z.dirtyFiles===0&&!Z.dirty&&!Z.hasConflicts&&Z.upstreamStatus==="fresh"),re=l.useCallback(()=>{B(null),H(null),F(null),ne(null)},[]);l.useEffect(()=>{ne(null)},[R]);const ce=l.useCallback(async()=>{if(!Z||!ye||!a||!Me)return;Ce(Z.id),ne(null);const J=(he==null?void 0:he.workspace)??Z.workspace??"";try{const Le=await a(ye,"fast_forward_mesh_node",{meshId:b.meshId,nodeId:Z.id,workspace:J,updateSubmodules:!0,dryRun:!0,execute:!1}),$e=(Le==null?void 0:Le.result)??Le;if(ne({phase:"dry_run",code:typeof($e==null?void 0:$e.code)=="string"?$e.code:void 0,error:typeof($e==null?void 0:$e.operationError)=="string"?$e.operationError:null,executed:($e==null?void 0:$e.executed)===!0}),!($e!=null&&$e.success)||$e.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${Z.label}?`))return;const rt=await a(ye,"fast_forward_mesh_node",{meshId:b.meshId,nodeId:Z.id,workspace:J,updateSubmodules:!0,dryRun:!1,execute:!0}),G=(rt==null?void 0:rt.result)??rt;ne({phase:"execute",code:typeof(G==null?void 0:G.code)=="string"?G.code:void 0,error:typeof(G==null?void 0:G.operationError)=="string"?G.operationError:null,executed:(G==null?void 0:G.executed)===!0})}catch(Le){ne({phase:"dry_run",error:Le instanceof Error?Le.message:"fast-forward failed"})}finally{Ce(null)}},[Me,b.meshId,Z,ye,a]);l.useEffect(()=>{if(!Z&&!fe)return;const J=Le=>{Le.key==="Escape"&&re()};return window.addEventListener("keydown",J),()=>window.removeEventListener("keydown",J)},[re,fe,Z]),l.useEffect(()=>{if(!le||!a)return;const{daemonId:J,workspace:Le}=le,$e=$[Le];if($e!=null&&$e.loading||$e&&($e.entries.length>0||$e.error))return;let at=!1;return K(rt=>{var G;return{...rt,[Le]:{loading:!0,error:null,entries:((G=rt[Le])==null?void 0:G.entries)??[]}}}),a(J,"git_log",{workspace:Le,limit:5}).then(rt=>{at||K(G=>({...G,[Le]:{loading:!1,error:null,entries:EM(rt)}}))}).catch(rt=>{at||K(G=>({...G,[Le]:{loading:!1,error:rt instanceof Error?rt.message:"git_log failed",entries:[]}}))}),()=>{at=!0}},[$,le,a]);const Ae=[...y.warnings??[],...b.nodes.filter(J=>J.machineStatus&&J.machineStatus!=="online").map(J=>`${J.machineLabel}: ${J.machineStatus}`)],be=y.stats.incompleteSnapshotNodes>0,we=y.stats.followUpNodes>0?m("meshGraph.obs.headlineFollowUp",{count:y.stats.followUpNodes}):m(be?"meshGraph.obs.headlineIncomplete":"meshGraph.obs.headlineConverged"),_e=y.stats.followUpNodes>0?"danger":be?"warn":"good",[U,Ne]=l.useState("auto"),Ie=J=>J?g.isDark?"rounded-md border border-cyan-400/40 bg-cyan-500/15 px-2 py-0.5 text-cyan-100":"rounded-md border border-sky-400 bg-sky-100 px-2 py-0.5 text-sky-800":g.isDark?"rounded-md border border-white/10 bg-white/[0.03] px-2 py-0.5 text-slate-400 hover:text-slate-200":"rounded-md border border-slate-300 bg-white/80 px-2 py-0.5 text-slate-500 hover:text-slate-800";return s.jsx(_s.Provider,{value:g,children:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[!p&&s.jsx("div",{className:"shrink-0 flex items-center justify-end",children:s.jsx(Qf,{meshTheme:g,activeTab:N,onActiveTabChange:T,helpOpen:A,onHelpOpenChange:I})}),A&&s.jsx(jD,{meshTheme:g,onClose:()=>I(!1)}),s.jsx("div",{className:`${N==="overview"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-3 overflow-y-auto`,children:N==="overview"&&s.jsx(rD,{status:b,daemonId:n,meshId:b.meshId,sendDaemonCommand:a})}),s.jsx("div",{className:`${N==="tasks"?"flex":"hidden"} min-h-0 flex-1 flex-col`,children:s.jsx("div",{className:`${g.cardClass} relative flex min-h-0 flex-1 flex-col overflow-hidden rounded-[28px]`,style:{minHeight:420},children:E?s.jsx("div",{className:"absolute inset-0",children:s.jsx(VP,{tasks:W,status:b,daemonId:n,sendDaemonCommand:a,onQueueMutated:u,onFocusNode:J=>{T("graph"),B(J),H(null),F({kind:"node",nodeId:J})}})}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:m("meshGraph.obs.loadingGraph")})})}),s.jsx("div",{className:`${N==="status"?"flex":"hidden"} min-h-0 flex-1 flex-col overflow-y-auto`,children:N==="status"&&s.jsx(LD,{canonicalStatus:b})}),s.jsx("div",{className:`${N==="notes"?"flex":"hidden"} min-h-0 flex-1 flex-col overflow-y-auto`,children:N==="notes"&&s.jsx(ED,{meshId:b.meshId,daemonId:n,sendDaemonCommand:a})}),s.jsx("div",{className:`${N==="graph"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-4`,children:s.jsxs("div",{className:`${g.cardClass} relative flex min-h-0 flex-1 flex-col rounded-[28px]`,style:{minHeight:480},children:[s.jsxs("div",{className:`relative z-30 max-h-[42dvh] overflow-y-auto sm:max-h-none sm:mb-3 sm:overflow-visible shrink-0 flex flex-wrap items-start justify-between gap-2 px-4 pt-3 pb-2.5 border-b ${g.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:`flex w-full min-w-0 basis-full flex-wrap gap-2 text-xs sm:w-auto sm:flex-1 sm:basis-auto ${g.textSecondary}`,children:[s.jsx(ze,{label:we,tone:_e,className:"shrink-0"}),y.stats.blockedReviewNodes>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeBlocked",{count:y.stats.blockedReviewNodes}),title:m("meshGraph.obs.badgeBlockedTitle",{count:y.stats.blockedReviewNodes}),tone:"danger",className:"shrink-0"}),y.stats.notMergeableNodes>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeNotMergeable",{count:y.stats.notMergeableNodes}),tone:"danger",className:"shrink-0"}),y.stats.mergeReadyNodes>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeNeedMerge",{count:y.stats.mergeReadyNodes}),tone:"warn",className:"shrink-0"}),y.stats.cleanupCandidateNodes>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeCleanup",{count:y.stats.cleanupCandidateNodes}),title:m("meshGraph.obs.badgeCleanupTitle",{count:y.stats.cleanupCandidateNodes}),tone:"info",className:"shrink-0"}),y.stats.offlineNodes>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeOffline",{count:y.stats.offlineNodes}),tone:"danger",className:"shrink-0"}),y.stats.incompleteSnapshotNodes>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeIncomplete",{count:y.stats.incompleteSnapshotNodes}),title:m("meshGraph.obs.badgeIncompleteTitle",{count:y.stats.incompleteSnapshotNodes}),tone:"warn",className:"shrink-0"}),y.stats.missingGitSnapshotNodes>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeNoGit",{count:y.stats.missingGitSnapshotNodes}),title:m("meshGraph.obs.badgeNoGitTitle",{count:y.stats.missingGitSnapshotNodes}),tone:"warn",className:"shrink-0"}),y.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeNoSubmod",{count:y.stats.missingSubmoduleSnapshotNodes}),title:m("meshGraph.obs.badgeNoSubmodTitle",{count:y.stats.missingSubmoduleSnapshotNodes}),tone:"warn",className:"shrink-0"}),y.stats.staleGitSnapshotNodes>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeStale",{count:y.stats.staleGitSnapshotNodes}),title:m("meshGraph.obs.badgeStaleTitle",{count:y.stats.staleGitSnapshotNodes}),tone:"warn",className:"shrink-0"}),((Y==null?void 0:Y.active)??0)>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeActiveQueue",{count:(Y==null?void 0:Y.active)??0}),tone:"info",className:"shrink-0 hidden sm:inline-flex"}),s.jsx(ze,{label:m("meshGraph.obs.badgeNodes",{count:y.stats.totalNodes}),tone:"default",className:"shrink-0 hidden sm:inline-flex"}),y.stats.totalActiveSessions>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeAttachedChats",{count:y.stats.totalActiveSessions}),tone:"info",className:"shrink-0 hidden sm:inline-flex"})]}),s.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-2",children:[s.jsxs("div",{className:g.isDark?"flex items-center gap-0.5 rounded-md border border-white/10 bg-slate-950/40 p-0.5 text-[10px]":"flex items-center gap-0.5 rounded-md border border-slate-300 bg-white/70 p-0.5 text-[10px]",role:"group","aria-label":"Graph layout direction",children:[s.jsx("button",{type:"button",onClick:()=>Ne("auto"),className:Ie(U==="auto"),title:m("meshGraph.obs.directionAutoTitle"),children:m("meshGraph.obs.directionAuto")}),s.jsx("button",{type:"button",onClick:()=>Ne("LR"),className:Ie(U==="LR"),title:m("meshGraph.obs.directionLRTitle"),children:"LR"}),s.jsx("button",{type:"button",onClick:()=>Ne("TB"),className:Ie(U==="TB"),title:m("meshGraph.obs.directionTBTitle"),children:"TB"})]}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${g.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${g.textSecondary} [&::-webkit-details-marker]:hidden`,children:(()=>{var $e;const J=(($e=b.asyncRefineJobs)==null?void 0:$e.filter(at=>at.status==="failed").length)??0,Le=X.recentFailures;return J>0?s.jsx("span",{className:g.isDark?"text-rose-300":"text-rose-600",children:m("meshGraph.obs.healthRefineFailed",{count:J})}):Le>0?s.jsx("span",{className:g.isDark?"text-amber-300":"text-amber-600",children:m("meshGraph.obs.healthFailures",{count:Le})}):m("meshGraph.obs.health")})()}),s.jsx("div",{className:`fixed inset-x-4 top-28 z-50 max-h-[70dvh] overflow-y-auto rounded-xl border p-4 shadow-xl backdrop-blur-xl sm:absolute sm:inset-x-auto sm:right-0 sm:top-auto sm:mt-2 sm:w-72 ${g.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsx(_D,{canonicalStatus:b,queueSummary:Y,ledgerSummary:X,isBootstrapMode:S,meshTheme:g,sessionEntries:Q,inlineMode:!0})})]})}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${g.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${g.textSecondary} [&::-webkit-details-marker]:hidden`,children:m("meshGraph.obs.legend")}),s.jsx("div",{className:`fixed inset-x-4 top-28 z-50 max-h-[70dvh] overflow-y-auto rounded-xl border p-3 shadow-xl backdrop-blur-xl sm:absolute sm:inset-x-auto sm:right-0 sm:top-auto sm:mt-2 sm:w-72 sm:max-h-none sm:overflow-visible ${g.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(ze,{label:m("meshGraph.obs.legendDirty",{count:y.stats.dirtyNodes}),tone:y.stats.dirtyNodes>0?"warn":"good"}),s.jsx(ze,{label:m("meshGraph.obs.legendOrphan",{count:y.stats.orphanNodes}),tone:y.stats.orphanNodes>0?"warn":"good"}),s.jsx(ze,{label:m("meshGraph.obs.legendRecentFailures",{count:X.recentFailures}),tone:X.recentFailures>0?"danger":"good"}),ve.length===0?s.jsx(ze,{label:m("meshGraph.obs.legendNoSessionMeta")}):ve.slice(0,2).map(([J,Le])=>s.jsx(ze,{label:`${Le} ${J}`,tone:gi(J)},J))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(ze,{label:m("meshGraph.obs.legendAnchor"),tone:"info"}),s.jsx(ze,{label:m("meshGraph.obs.legendPeerLink"),tone:"default"}),s.jsx(ze,{label:m("meshGraph.obs.legendSubmoduleLink"),tone:"warn"})]}),Ae.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:Ae.map(J=>s.jsx("span",{className:g.isDark?"rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1 text-xs text-amber-100":"rounded-full border border-amber-300 bg-amber-50 px-3 py-1 text-xs text-amber-700",children:J},J))}),s.jsx("div",{className:`text-xs ${g.textMuted}`,children:m("meshGraph.obs.legendClickHint")})]})})]})})]})]}),S&&y.nodes.length>0&&s.jsxs("div",{className:`shrink-0 mx-4 mt-2 flex items-center gap-2 rounded-xl border px-3.5 py-2 text-xs ${g.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full animate-pulse ${g.isDark?"bg-amber-400":"bg-amber-500"}`,"aria-hidden":!0}),s.jsx("span",{children:m("meshGraph.obs.bootstrapBanner")})]}),s.jsxs("div",{className:"relative flex flex-1 min-w-0",style:{minHeight:360},children:[s.jsx("div",{className:"flex-1 min-w-0",children:P?y.nodes.length>0?s.jsx(SP,{data:y,selectedNodeId:R,directionPref:U,onNodeClick:J=>{if((L==null?void 0:L.kind)==="node"&&R===J.id){re();return}H(null),B(J.id),F({kind:"node",nodeId:J.id})},onEdgeClick:J=>{if((L==null?void 0:L.kind)==="edge"&&_===J.id){re();return}B(null),H(J.id),F({kind:"edge",edgeId:J.id})}}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:h}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:m("meshGraph.obs.loadingGraph")})}),Z&&(L==null?void 0:L.kind)==="node"&&s.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${g.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${g.textMuted}`,children:m("meshGraph.obs.selectedNode")}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${g.textPrimary}`,children:Z.label}),s.jsx("div",{className:`mt-0.5 font-mono text-[11px] ${g.textMuted}`,children:Z.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[Z.behind>0&&s.jsx("button",{type:"button",onClick:()=>{ce()},disabled:!Me||ie===Z.id,className:g.isDark?"rounded-full border border-emerald-400/25 bg-emerald-500/10 px-2 py-0.5 text-xs font-semibold text-emerald-100 transition hover:bg-emerald-500/18 disabled:cursor-not-allowed disabled:opacity-45":"rounded-full border border-emerald-300 bg-emerald-50 px-2 py-0.5 text-xs font-semibold text-emerald-700 transition hover:bg-emerald-100 disabled:cursor-not-allowed disabled:opacity-45",children:ie===Z.id?m("meshGraph.obs.checking"):m("meshGraph.obs.heal")}),s.jsx("button",{type:"button",onClick:re,"aria-label":"Close detail panel",className:g.isDark?"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[(()=>{const J=(he==null?void 0:he.health)??Z.health;return J==="unknown"?s.jsx(ze,{label:m("meshGraph.obs.connecting"),tone:"default"}):s.jsx(ze,{label:J,tone:Df(J)})})(),Z.branch&&s.jsx(ze,{label:Z.branch,tone:"default"}),Z.ahead>0&&s.jsx(ze,{label:`ahead ${Z.ahead}`,tone:"warn"}),Z.behind>0&&s.jsx(ze,{label:`behind ${Z.behind}`,tone:"warn"}),Z.dirtyFiles>0&&s.jsx(ze,{label:`${Z.dirtyFiles} dirty`,tone:"warn"}),(he==null?void 0:he.connection)&&he.connection.state!=="unknown"&&s.jsx(ze,{label:HM(he),tone:SM(he.connection)}),((et=he==null?void 0:he.connection)==null?void 0:et.state)==="unknown"&&s.jsx(ze,{label:m("meshGraph.obs.meshConnecting"),tone:"warn"}),pe.length>0&&s.jsx(ze,{label:`${pe.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[Z.machineLabel&&s.jsx(Ht,{label:m("meshGraph.obs.fieldMachine"),value:Z.machineLabel}),Z.locality&&Z.locality!=="unknown"&&s.jsx(Ht,{label:m("meshGraph.obs.fieldLocality"),value:Z.locality}),s.jsx(Ht,{label:m("meshGraph.obs.fieldWorkspace"),value:(he==null?void 0:he.workspace)??Z.workspace}),ue&&s.jsx(Ht,{label:m("meshGraph.obs.fieldHead"),value:ue}),(Z.dirtyFiles>0||Z.ahead>0||Z.behind>0)&&s.jsx(Ht,{label:m("meshGraph.obs.fieldDirtyAheadBehind"),value:`${Z.dirtyFiles}/${Z.ahead}/${Z.behind}`}),pe.length>0&&s.jsx(Ht,{label:m("meshGraph.obs.fieldSessions"),value:String(pe.length)}),Z.upstream&&s.jsx(Ht,{label:m("meshGraph.obs.fieldUpstream"),value:Z.upstream}),(()=>{var Le;const J=((Le=he==null?void 0:he.connection)==null?void 0:Le.source)??$M(Z);return J&&J!=="unknown"?s.jsx(Ht,{label:m("meshGraph.obs.fieldSource"),value:String(J)}):null})(),(()=>{var Le;const J=(Le=he==null?void 0:he.connection)==null?void 0:Le.transport;return J&&J!=="unknown"?s.jsx(Ht,{label:m("meshGraph.obs.fieldTransport"),value:J}):null})(),(()=>{const J=Z.machineId??(he==null?void 0:he.machineId);return J?s.jsx(Ht,{label:m("meshGraph.obs.fieldMachineId"),value:J}):null})(),(()=>{const J=Z.daemonId??(he==null?void 0:he.daemonId);return J?s.jsx(Ht,{label:m("meshGraph.obs.fieldDaemonId"),value:J}):null})()]}),pe.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${g.textMuted}`,children:m("meshGraph.obs.activeSessions")}),s.jsx("div",{className:"flex flex-col gap-1.5",children:pe.map(J=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${g.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono select-text ${g.textMuted}`,title:J.session.sessionId,children:Lf(J.session.sessionId)}),s.jsx(ze,{label:Rr(J.session),tone:gi(Rr(J.session))})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 ${g.textMuted}`,children:[s.jsx("span",{className:"truncate",children:J.session.providerType||m("meshGraph.obs.providerUnknown")}),s.jsx("span",{children:If(J.session)}),s.jsx("span",{children:so(J.session)})]}),J.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${g.textMuted}`,children:J.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${g.textMuted}`,title:J.session.workspace||J.workspace,children:[(J.session.workspace||J.workspace).slice(0,38),J.branch?` · ${J.branch}`:""]})]},J.session.sessionId))})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${g.textMuted}`,children:m("meshGraph.obs.ledger")}),s.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[s.jsx(Ht,{label:m("meshGraph.obs.fieldCompleted"),value:String(X.taskCompleted)}),s.jsx(Ht,{label:m("meshGraph.obs.fieldFailed"),value:s.jsx("span",{className:X.taskFailed>0?g.isDark?"text-rose-300":"text-rose-600":"",children:X.taskFailed})}),s.jsx(Ht,{label:m("meshGraph.obs.fieldLaunched"),value:String(X.sessionLaunched)}),s.jsx(Ht,{label:m("meshGraph.obs.fieldRecentFailures"),value:s.jsx("span",{className:X.recentFailures>0?g.isDark?"text-amber-300":"text-amber-600":"",children:X.recentFailures})})]})]}),(()=>{var $e,at;const J=(($e=b.queue)==null?void 0:$e.tasks)??((at=b.queue)==null?void 0:at.items)??null;if(!Array.isArray(J)||J.length===0)return null;const Le=J.filter(rt=>IM(rt)===R).slice(0,3);return Le.length===0?null:s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${g.textMuted}`,children:m("meshGraph.obs.queueTasks")}),s.jsx("div",{className:"flex flex-col gap-1.5",children:Le.map(rt=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${g.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`font-mono ${g.textMuted}`,children:rt.id.slice(0,12)}),s.jsx(ze,{label:rt.status??"unknown",tone:gi(rt.status)})]}),rt.message&&s.jsx("div",{className:`mt-0.5 truncate ${g.textMuted}`,children:rt.message.slice(0,48)})]},rt.id))})]})})(),Z.snapshotWarnings.length>0&&s.jsxs("div",{className:g.isDark?"mt-3 rounded-xl border border-amber-400/20 bg-amber-500/10 p-3 text-xs text-amber-100":"mt-3 rounded-xl border border-amber-300 bg-amber-50 p-3 text-xs text-amber-800",children:[s.jsx("div",{className:"font-medium",children:m("meshGraph.obs.keyWarning")}),s.jsx("div",{className:"mt-1",children:Z.snapshotWarnings[0]})]}),Z.branchConvergence&&(Z.branchConvergence.reason||Z.branchConvergence.nextStep)&&s.jsxs("div",{className:g.isDark?"mt-3 rounded-xl border border-sky-400/20 bg-sky-500/10 p-3 text-xs text-sky-100":"mt-3 rounded-xl border border-sky-300 bg-sky-50 p-3 text-xs text-sky-800",children:[s.jsx("div",{className:"font-medium",children:m("meshGraph.obs.followUpLabel",{status:k[Z.branchConvergence.status]??Z.branchConvergence.status})}),Z.branchConvergence.reason&&s.jsx("div",{className:"mt-1",children:Z.branchConvergence.reason}),Z.branchConvergence.nextStep&&s.jsx("div",{className:`${Z.branchConvergence.reason?"mt-1.5 pt-1.5 border-t border-sky-400/20":"mt-1"}`,children:Z.branchConvergence.nextStep})]}),z&&s.jsxs("div",{className:g.isDark?"mt-3 rounded-xl border border-emerald-400/20 bg-emerald-500/10 p-3 text-xs text-emerald-100":"mt-3 rounded-xl border border-emerald-300 bg-emerald-50 p-3 text-xs text-emerald-800",children:[s.jsx("div",{className:"font-medium",children:z.phase==="execute"?m("meshGraph.obs.healResult"):m("meshGraph.obs.healPreview")}),s.jsx("div",{className:"mt-1",children:z.code??z.error??m("meshGraph.obs.noResultCode")})]})]}),fe&&(L==null?void 0:L.kind)==="edge"&&s.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${g.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${g.textMuted}`,children:m("meshGraph.obs.selectedEdge")}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${g.textPrimary}`,children:fe.label||ju(fe)}),s.jsx("div",{className:`mt-0.5 break-all font-mono text-[11px] ${g.textMuted}`,children:fe.id})]}),s.jsx("button",{type:"button",onClick:re,"aria-label":"Close detail panel",className:g.isDark?"shrink-0 rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"shrink-0 rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[s.jsx(ze,{label:ju(fe),tone:"default"}),s.jsx(ze,{label:FM(fe),tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(Ht,{label:m("meshGraph.obs.fieldFrom"),value:(V==null?void 0:V.label)??fe.source}),s.jsx(Ht,{label:m("meshGraph.obs.fieldTo"),value:(q==null?void 0:q.label)??fe.target}),s.jsx(Ht,{label:m("meshGraph.obs.fieldLabel"),value:fe.label??"none"})]})]})]})]})})]})})}function At(e){return typeof e=="string"?e.trim():""}function kl(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Tc(...e){const t=new Set;for(const n of e){const a=At(n);a&&t.add(a)}return[...t]}function $D(e,t){var m,f;const n=kl(e==null?void 0:e.settings),a=At((m=e==null?void 0:e.coordinator)==null?void 0:m.meshId)||At(n.meshCoordinatorFor),r=At(n.meshNodeFor),o=!!a||!!r,i=a===t||r===t;if(o&&!i)return null;const c=kl(e==null?void 0:e.activeChat),d=Tc(e==null?void 0:e.id,e==null?void 0:e.sessionId,e==null?void 0:e.session_id,e==null?void 0:e.providerSessionId,e==null?void 0:e.provider_session_id,e==null?void 0:e.targetSessionId,e==null?void 0:e.target_session_id,c.sessionId,c.session_id,c.providerSessionId,c.provider_session_id),p=d[0]||"";if(!p)return null;const u=a===t?At((f=e==null?void 0:e.coordinator)==null?void 0:f.role)||"coordinator":r===t?At(n.meshNodeRole)||"worker":At(e==null?void 0:e.role)||At(n.meshNodeRole)||void 0;return{sessionId:p,aliases:d,meshId:t,nodeId:i&&At(n.meshNodeId)||null,providerType:At(e==null?void 0:e.providerType)||void 0,state:At(e==null?void 0:e.status)||void 0,chatStatus:At(c.status)||void 0,lifecycle:At(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:At(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:At(e==null?void 0:e.runtimeRecoveryState)||void 0,...u?{role:u}:{},...i?{isSelfCoordinator:a===t}:{},workspace:At(e==null?void 0:e.workspace)||null}}function Jf(e,t){var a;return t?(Array.isArray((a=e.status)==null?void 0:a.sessions)?e.status.sessions:[]).map(r=>$D(r,t)).filter(r=>r!==null):[]}function ao(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function FD(e,t){const n=new Set(ao(t));return ao(e).some(a=>n.has(a))}function BD(e,t){const n=t.filter(r=>!!r);return n.length===0?e:[...e.filter(r=>!n.some(o=>FD(r,o))),...n]}function WD(e,t){if(t.length===0)return e;const n=new Map;for(const i of t)for(const c of ao(i))n.set(c,i);let a=!1;const o=(e.nodes??[]).map((i,c)=>{const d=Array.isArray(i.activeSessionDetails)?i.activeSessionDetails:Array.isArray(i.sessions)?i.sessions:[],p=new Map;for(const f of d){const g=Tc(f==null?void 0:f.sessionId,f==null?void 0:f.session_id,f==null?void 0:f.id,f==null?void 0:f.providerSessionId,f==null?void 0:f.provider_session_id),k=g[0]||"";if(!k)continue;const h=g.map(b=>n.get(b)).find(Boolean);h&&(a=!0),p.set(k,h?{...f,sessionId:k,providerType:h.providerType||f.providerType,state:h.state||f.state,chatStatus:h.chatStatus||f.chatStatus,lifecycle:h.lifecycle||f.lifecycle,surfaceKind:h.surfaceKind||f.surfaceKind,recoveryState:h.recoveryState||f.recoveryState,role:h.role||f.role,isSelfCoordinator:h.isSelfCoordinator??f.isSelfCoordinator,workspace:h.workspace||f.workspace}:{...f,sessionId:k})}for(const f of i.activeSessions??[])p.has(f)||p.set(f,{sessionId:f,workspace:i.workspace,isCached:!0});const u=c===0;for(const f of t){if(ao(f).some(b=>p.has(b)))continue;const k=f.nodeId!=null&&f.nodeId===i.nodeId,h=f.isSelfCoordinator&&!f.nodeId&&u;!k&&!h||(a=!0,p.set(f.sessionId,{sessionId:f.sessionId,providerType:f.providerType,state:f.state,chatStatus:f.chatStatus,lifecycle:f.lifecycle,surfaceKind:f.surfaceKind,recoveryState:f.recoveryState,role:f.role,isSelfCoordinator:f.isSelfCoordinator,workspace:f.workspace||i.workspace}))}const m=[...p.values()];return m.length===0?i:{...i,activeSessionDetails:m,activeSessions:m.map(f=>f.sessionId)}});return a?{...e,nodes:o}:e}function OD(e,t){const a=Jf(e,t).map(r=>{var d;const o=(Array.isArray((d=e.status)==null?void 0:d.sessions)?e.status.sessions:[]).find(p=>At(p==null?void 0:p.id)===r.sessionId),i=kl(o==null?void 0:o.activeInteractivePrompt),c=o!=null&&o.meshQueueStats&&typeof o.meshQueueStats=="object"?JSON.stringify(o.meshQueueStats):"";return[r.sessionId,r.providerType??"",r.state??"",r.chatStatus??"",r.lifecycle??"",r.surfaceKind??"",r.recoveryState??"",At(i.status)||At(i.kind)||At(i.type),r.nodeId??"",r.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(r=>!!r).sort();return a.length>0?a.join(`
88
+ `),t.trim()):""}function In(e){return Sc(TP(e))}const MP=new mp,Of=236,PP=96;function DP(e){const t=(e.task.message??"").length,n=Math.max(1,Math.min(3,Math.ceil(t/34))),a=e.waitingOn.length>0||e.blocked||e.missingDeps.length>0?22:0;return PP+(n-1)*15+a}const Pu={pending:{dark:"border-slate-400/30 bg-slate-500/10 text-slate-200",light:"border-slate-300 bg-slate-50 text-slate-700",dot:"bg-slate-400"},assigned:{dark:"border-sky-400/40 bg-sky-500/10 text-sky-100",light:"border-sky-300 bg-sky-50 text-sky-800",dot:"bg-sky-400",pulse:!0},completed:{dark:"border-emerald-400/40 bg-emerald-500/10 text-emerald-100",light:"border-emerald-300 bg-emerald-50 text-emerald-800",dot:"bg-emerald-400"},failed:{dark:"border-rose-400/40 bg-rose-500/10 text-rose-100",light:"border-rose-300 bg-rose-50 text-rose-800",dot:"bg-rose-400"},cancelled:{dark:"border-slate-500/25 bg-slate-600/10 text-slate-400",light:"border-slate-200 bg-slate-100 text-slate-400",dot:"bg-slate-500"}},yi={satisfied:{dark:"#34d399",light:"#059669",animated:!1},waiting:{dark:"#fbbf24",light:"#d97706",dash:"6 4",animated:!0},failed:{dark:"#fb7185",light:"#e11d48",dash:"3 4",animated:!1}},IP={overflowWrap:"anywhere",wordBreak:"break-word",display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"};function LP({data:e}){const{t}=ke("common"),{dagNode:n,theme:a,selected:r}=e,o=n.task,i=Pu[o.status]??Pu.pending,c=a.isDark?i.dark:i.light,d=a.isDark?"rounded-full border border-white/10 bg-white/[0.06] px-1.5 py-px text-[9px] text-slate-300":"rounded-full border border-slate-200 bg-white/80 px-1.5 py-px text-[9px] text-slate-500";return s.jsxs("div",{className:`rounded-2xl border px-3 py-2.5 shadow-sm transition-shadow ${c} ${r?a.isDark?"ring-2 ring-cyan-300/60":"ring-2 ring-sky-400/70":""}`,style:{width:Of},children:[s.jsx(Ns,{type:"target",position:$t.Left,className:"!h-2 !w-2 !border-0 !bg-transparent"}),s.jsx(Ns,{type:"source",position:$t.Right,className:"!h-2 !w-2 !border-0 !bg-transparent"}),s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${i.dot} ${i.pulse?"animate-pulse":""}`,"aria-hidden":!0}),s.jsx("span",{className:"truncate text-[10px] font-semibold uppercase tracking-wide opacity-80",children:o.status})]}),s.jsx("span",{className:`shrink-0 font-mono text-[9px] ${a.isDark,"text-slate-400"}`,title:o.id,children:o.id.slice(0,8)})]}),s.jsx("div",{className:`mt-1.5 text-[11px] leading-[15px] ${o.status==="cancelled"?"opacity-60":""}`,style:IP,title:In(o.message),children:In(o.message)}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1",children:[o.difficulty&&s.jsx("span",{className:d,children:o.difficulty}),o.priority&&o.priority!=="normal"&&s.jsx("span",{className:d,children:o.priority}),(o.taskMode==="live_debug_readonly"||o.readonly)&&s.jsx("span",{className:d,children:"read-only"}),o.missionId&&s.jsxs("span",{className:`${d} inline-flex items-center gap-1`,title:o.missionId,children:[s.jsx($p,{size:8}),o.missionId.slice(0,10)]}),n.waitingOn.length>0&&s.jsx("span",{className:a.isDark?"rounded-full border border-amber-400/25 bg-amber-500/10 px-1.5 py-px text-[9px] text-amber-200":"rounded-full border border-amber-300 bg-amber-50 px-1.5 py-px text-[9px] text-amber-700",title:n.waitingOn.join(", "),children:t("meshGraph.taskDag.waitsOn",{count:n.waitingOn.length})}),n.blocked&&s.jsx("span",{className:a.isDark?"rounded-full border border-rose-400/25 bg-rose-500/10 px-1.5 py-px text-[9px] text-rose-200":"rounded-full border border-rose-300 bg-rose-50 px-1.5 py-px text-[9px] text-rose-700",title:o.blockedReason,children:t("meshGraph.taskDag.blocked")}),n.missingDeps.length>0&&s.jsx("span",{className:d,title:n.missingDeps.join(", "),children:t("meshGraph.taskDag.missingDeps",{count:n.missingDeps.length})})]})]})}const RP={taskNode:LP};async function EP(e){const t={id:"task-dag-root",layoutOptions:{"elk.algorithm":"layered","elk.direction":"RIGHT","elk.edgeRouting":"SPLINES","elk.spacing.nodeNode":"46","elk.layered.spacing.nodeNodeBetweenLayers":"120","elk.layered.layering.strategy":"NETWORK_SIMPLEX","elk.layered.nodePlacement.strategy":"NETWORK_SIMPLEX","elk.layered.crossingMinimization.strategy":"LAYER_SWEEP","elk.layered.considerModelOrder.strategy":"NODES_AND_EDGES","elk.layered.cycleBreaking.strategy":"GREEDY","elk.randomSeed":"1"},children:e.nodes.map(r=>({id:r.id,width:Of,height:DP(r)})),edges:e.edges.map(r=>({id:r.id,sources:[r.source],targets:[r.target]}))},n=await MP.layout(t),a=new Map;for(const r of n.children??[])a.set(r.id,{x:r.x??0,y:r.y??0});return a}function _P({tasks:e,emptyMessage:t,compact:n=!1}){const{t:a}=ke("common"),{theme:r}=Rs(),o=l.useMemo(()=>Es(r),[r]),[i,c]=l.useState(Po),d=l.useMemo(()=>Wf(e,n?Number.POSITIVE_INFINITY:i),[e,i,n]),p=l.useMemo(()=>NP(d.tasks),[d.tasks]),u=l.useMemo(()=>p.nodes.map(C=>`${C.id}:${C.task.status}:${C.dependsOn.join("+")}:${C.waitingOn.length}:${C.blocked?1:0}`).join("|"),[p]),[m,f]=l.useState(null),[g,k]=l.useState(null);l.useEffect(()=>{let C=!1;if(p.nodes.length===0){k(null);return}return EP(p).then(v=>{C||k(v)}).catch(()=>{C||k(null)}),()=>{C=!0}},[u]);const h=l.useMemo(()=>g?p.nodes.filter(C=>g.has(C.id)).map(C=>({id:C.id,type:"taskNode",position:g.get(C.id),data:{dagNode:C,theme:o,selected:m===C.id},draggable:!1,selectable:!0})):[],[p,o,g,m]),b=l.useMemo(()=>g?p.edges.map(C=>{const v=yi[C.state],w=o.isDark?v.dark:v.light;return{id:C.id,source:C.source,target:C.target,type:"smoothstep",animated:v.animated,style:{stroke:w,strokeWidth:1.6,...v.dash?{strokeDasharray:v.dash}:{}},markerEnd:{type:xp.ArrowClosed,color:w,width:14,height:14}}}):[],[p,o,g]),S=m?p.nodes.find(C=>C.id===m)??null:null,x=l.useCallback((C,v)=>{f(w=>w===v.id?null:v.id)},[]);if(p.nodes.length===0)return s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:t??a("meshGraph.taskDag.empty")});const y=(C,v="default")=>{const w=v==="warn"?o.isDark?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700":v==="danger"?o.isDark?"border-rose-400/25 bg-rose-500/10 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700":v==="info"?o.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700":o.isDark?"border-white/10 bg-white/[0.05] text-slate-300":"border-slate-200 bg-white/85 text-slate-600";return s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] ${w}`,children:C})};return s.jsxs("div",{className:"relative h-full min-h-[320px] w-full",style:{minHeight:320},children:[s.jsxs(hp,{className:"h-full w-full",nodes:h,edges:b,nodeTypes:RP,onNodeClick:x,onPaneClick:()=>f(null),fitView:!0,fitViewOptions:{padding:.18,maxZoom:1},minZoom:.2,maxZoom:1.6,nodesConnectable:!1,nodesDraggable:!1,proOptions:{hideAttribution:!0},colorMode:o.isDark?"dark":"light",children:[s.jsx(gp,{variant:bp.Dots,gap:22,size:1}),s.jsx(fp,{showInteractive:!1,position:"bottom-left"})]}),!n&&s.jsxs("div",{className:"pointer-events-none absolute left-3 top-3 z-10 flex flex-wrap items-center gap-1.5",children:[d.hiddenCount>0&&s.jsxs(s.Fragment,{children:[y(a("meshGraph.taskDag.hiddenTasks",{count:d.hiddenCount})),s.jsx("button",{type:"button",onClick:()=>c(C=>C+no),className:`pointer-events-auto rounded-full border px-2 py-0.5 text-[10px] font-medium transition-colors ${o.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200 hover:bg-sky-500/20":"border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100"}`,children:a("meshGraph.taskDag.loadMore",{count:Math.min(no,d.hiddenCount)})})]}),y(a("meshGraph.taskDag.statsTasks",{count:p.stats.total})),p.stats.edges>0&&y(a("meshGraph.taskDag.statsEdges",{count:p.stats.edges}),"info"),p.stats.missions>0&&y(a("meshGraph.taskDag.statsMissions",{count:p.stats.missions}),"info"),p.stats.waiting>0&&y(a("meshGraph.taskDag.statsWaiting",{count:p.stats.waiting}),"warn"),p.stats.blocked>0&&y(a("meshGraph.taskDag.statsBlocked",{count:p.stats.blocked}),"danger")]}),s.jsx("div",{className:`pointer-events-none absolute bottom-3 right-3 z-10 flex items-center gap-2.5 rounded-xl border px-2.5 py-1.5 text-[10px] ${o.isDark?"border-white/10 bg-slate-950/80 text-slate-300":"border-slate-200 bg-white/90 text-slate-600"}`,children:["satisfied","waiting","failed"].map(C=>s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"inline-block h-0.5 w-4 rounded",style:{backgroundColor:o.isDark?yi[C].dark:yi[C].light},"aria-hidden":!0}),a(`meshGraph.taskDag.legend.${C}`)]},C))}),S&&s.jsxs("div",{className:`absolute right-3 top-3 z-20 w-72 max-w-[calc(100%-24px)] overflow-y-auto rounded-2xl border p-3.5 shadow-xl backdrop-blur ${o.isDark?"border-white/10 bg-slate-950/95 text-slate-200":"border-slate-200 bg-white/95 text-slate-700"}`,style:{maxHeight:"calc(100% - 24px)"},children:[s.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[s.jsx("span",{className:`text-[10px] font-semibold uppercase tracking-wide ${o.isDark,"text-slate-400"}`,children:a("meshGraph.taskDag.selectedTask")}),s.jsx("button",{type:"button",onClick:()=>f(null),"aria-label":"Close task detail",className:o.isDark?"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 hover:bg-white/[0.08]":"rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 hover:bg-slate-50",children:"✕"})]}),s.jsx("div",{className:"mb-2 font-mono text-[10px] opacity-70",title:S.task.id,children:S.task.id.slice(0,8)}),s.jsx("div",{className:"mb-2 whitespace-pre-wrap text-[11px] leading-4",children:In(S.task.message)}),s.jsxs("div",{className:"flex flex-wrap gap-1.5 text-[10px]",children:[y(S.task.status,S.task.status==="failed"?"danger":S.task.status==="assigned"?"info":"default"),S.task.difficulty&&y(S.task.difficulty),S.task.missionId&&y(S.task.missionId,"info"),S.task.assignedNodeId&&y(`@ ${S.task.assignedNodeId.slice(0,14)}`)]}),S.waitingOn.length>0&&s.jsxs("div",{className:"mt-2 text-[10px]",children:[s.jsxs("span",{className:"font-semibold",children:[a("meshGraph.taskDag.waitsOn",{count:S.waitingOn.length}),":"]}),s.jsx("span",{className:"ml-1 font-mono opacity-80",children:S.waitingOn.map(C=>C.slice(0,8)).join(", ")})]}),S.task.blockedReason&&s.jsx("div",{className:`mt-2 rounded-lg border px-2 py-1.5 text-[10px] ${o.isDark?"border-rose-400/25 bg-rose-500/10 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:S.task.blockedReason})]})]})}const HP={assigned:0,pending:1,failed:2,completed:3,cancelled:4};function Du(e){return HP[e]??5}function fn(e){return String(e.updatedAt||e.createdAt||"")}function Uf(e){return typeof e.blockedReason=="string"&&e.blockedReason.length>0}function Iu(e){const t={total:0,assigned:0,pending:0,completed:0,failed:0,cancelled:0,blocked:0};for(const n of e)t.total+=1,n.status==="assigned"?t.assigned+=1:n.status==="pending"?t.pending+=1:n.status==="completed"?t.completed+=1:n.status==="failed"?t.failed+=1:n.status==="cancelled"&&(t.cancelled+=1),n.status==="pending"&&Uf(n)&&(t.blocked+=1);return t}function $P(e){const t=new Map;for(const n of(e==null?void 0:e.missions)??[]){if(!n||typeof n.id!="string"||!n.id)continue;const a=n,r=typeof a.goal=="string"&&a.goal?a.goal:typeof a.goalPreview=="string"?a.goalPreview:"";t.set(n.id,{title:typeof n.title=="string"?n.title:"",status:typeof n.status=="string"?n.status:"",goal:r})}return t}function FP(e,t,n=Po){const a=Wf(e,n),r=a.tasks,o=new Set(r.map(m=>m.id)),i=$P(t),c=new Map;for(const m of r){const f=typeof m.missionId=="string"&&m.missionId?m.missionId:null,g=c.get(f);g?g.push(m):c.set(f,[m])}const d=[];for(const[m,f]of c){const g=[...f].sort((S,x)=>{const y=Du(S.status)-Du(x.status);return y!==0?y:fn(x).localeCompare(fn(S))}),k=m?i.get(m):void 0;let h="",b=!1;for(const S of f){const x=fn(S);x>h&&(h=x),!b&&Array.isArray(S.dependsOn)&&S.dependsOn.some(y=>typeof y=="string"&&o.has(y))&&(b=!0)}d.push({missionId:m,title:(k==null?void 0:k.title)||null,missionStatus:(k==null?void 0:k.status)||null,goal:(k==null?void 0:k.goal)||null,tasks:g,counts:Iu(f),hasDependencies:b,lastActivityAt:h})}d.sort((m,f)=>{const g=(f.counts.assigned>0?1:0)-(m.counts.assigned>0?1:0);return g!==0?g:f.lastActivityAt.localeCompare(m.lastActivityAt)});const p=r.filter(m=>m.status==="assigned").sort((m,f)=>fn(f).localeCompare(fn(m))),u=r.filter(m=>m.status==="failed"||m.status==="pending"&&Uf(m)).sort((m,f)=>fn(f).localeCompare(fn(m)));return{running:p,attention:u,groups:d,hiddenCount:a.hiddenCount,counts:Iu(r)}}function As(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function wi(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function BP(e){const t=As(e.taskId);if(t)return t;const n=e.payload;return n?As(n.taskId):void 0}function WP(e){const t=e.payload,n=t&&typeof t=="object"?t.routingDecision:void 0;if(!n||typeof n!="object"||Array.isArray(n))return null;const a=n,r=Array.isArray(a.intraNodeLosers)?a.intraNodeLosers.length:0,o=Array.isArray(a.skippedCandidates)?a.skippedCandidates.length:0,i={providerType:As(a.resolvedProviderType),model:As(a.resolvedModel),thinkingLevel:As(a.resolvedThinkingLevel),source:As(a.source),transport:As(a.transport),fitnessScore:wi(a.fitnessScore),selectedNodeId:As(a.selectedNodeId),reason:As(a.reason),intraNodeLoserCount:r+(wi(a.intraNodeLosersOmitted)??0)||void 0,skippedCount:o+(wi(a.skippedCandidatesOmitted)??0)||void 0,dispatchedAt:As(e.timestamp)};return i.model||i.providerType||i.source?i:null}function OP(e){var a;const t=new Map,n=(a=e==null?void 0:e.ledger)==null?void 0:a.entries;if(!Array.isArray(n))return t;for(const r of n){if(!r||r.kind!=="task_dispatched")continue;const o=BP(r);if(!o)continue;const i=WP(r);if(!i)continue;const c=t.get(o);if(c){const d=Date.parse(c.dispatchedAt||""),p=Date.parse(i.dispatchedAt||"");if(Number.isFinite(d)&&Number.isFinite(p)&&p<d)continue}t.set(o,i)}return t}function ki(e){return e?[e.providerType,e.model,e.thinkingLevel].filter(Boolean).join(" · "):""}const Lu={assigned:"bg-sky-400 animate-pulse",pending:"bg-slate-400",completed:"bg-emerald-400",failed:"bg-rose-400",cancelled:"bg-slate-500"},UP={active:{dark:"border-emerald-400/30 bg-emerald-500/10 text-emerald-200",light:"border-emerald-300 bg-emerald-50 text-emerald-700"},paused:{dark:"border-amber-400/30 bg-amber-500/10 text-amber-200",light:"border-amber-300 bg-amber-50 text-amber-700"},completed:{dark:"border-white/10 bg-white/[0.05] text-slate-300",light:"border-slate-200 bg-slate-50 text-slate-500"},abandoned:{dark:"border-white/10 bg-white/[0.04] text-slate-400",light:"border-slate-200 bg-slate-50 text-slate-400"}};function GP(e){const t=Date.parse(e.updatedAt||e.createdAt||"");return Number.isFinite(t)?t:0}function Ru(e){switch(e){case"assigned":return"meshGraph.tasksView.status.running";case"pending":return"meshGraph.tasksView.status.queued";case"completed":return"meshGraph.tasksView.status.done";case"failed":return"meshGraph.tasksView.status.failed";case"cancelled":return"meshGraph.tasksView.status.cancelled";default:return"meshGraph.tasksView.status.queued"}}function qP(e){const t=new Map;for(const n of e.nodes??[]){if(!(n!=null&&n.nodeId))continue;const a=n.machineLabel||n.nodeId.slice(0,12),r=n.isLocalWorktree&&typeof n.worktreeBranch=="string"&&n.worktreeBranch?` · ${n.worktreeBranch}`:"";t.set(n.nodeId,`${a}${r}`)}return t}function zt({theme:e,children:t,tone:n="default",title:a}){const r=n==="info"?e.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700":n==="warn"?e.isDark?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700":n==="danger"?e.isDark?"border-rose-400/25 bg-rose-500/10 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700":n==="good"?e.isDark?"border-emerald-400/25 bg-emerald-500/10 text-emerald-200":"border-emerald-300 bg-emerald-50 text-emerald-700":e.isDark?"border-white/10 bg-white/[0.05] text-slate-300":"border-slate-200 bg-white/85 text-slate-600";return s.jsx("span",{title:a,className:`inline-flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] leading-none ${r}`,children:t})}function zP({theme:e,group:t}){const{counts:n}=t;if(n.total===0)return null;const a=r=>`${r/n.total*100}%`;return s.jsx("div",{className:`h-1.5 w-full overflow-hidden rounded-full ${e.isDark?"bg-white/[0.07]":"bg-slate-200/80"}`,children:s.jsxs("div",{className:"flex h-full",children:[s.jsx("div",{className:"h-full bg-emerald-400/85",style:{width:a(n.completed)}}),s.jsx("div",{className:"h-full bg-rose-400/85",style:{width:a(n.failed)}}),s.jsx("div",{className:`h-full ${e.isDark?"bg-slate-500/50":"bg-slate-400/50"}`,style:{width:a(n.cancelled)}}),s.jsx("div",{className:"h-full animate-pulse bg-sky-400/80",style:{width:a(n.assigned)}})]})})}function wl({task:e,theme:t,nodeLabels:n,routing:a,expanded:r,onToggle:o,actions:i,onFocusNode:c}){const{t:d}=ke("common"),[p,u]=l.useState(null),m=In(e.message),f=typeof e.blockedReason=="string"&&e.blockedReason.length>0,g=e.assignedNodeId?n.get(e.assignedNodeId)??e.assignedNodeId.slice(0,12):null,k=e.status==="cancelled"||e.status==="completed";return s.jsxs("div",{className:`rounded-xl transition-colors ${r?t.isDark?"bg-white/[0.04]":"bg-slate-100/70":""}`,children:[s.jsxs("button",{type:"button",onClick:o,className:`flex w-full items-center gap-2.5 rounded-xl px-2.5 py-2 text-left ${t.isDark?"hover:bg-white/[0.04]":"hover:bg-slate-100/70"}`,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${Lu[e.status]??Lu.pending}`,"aria-hidden":!0}),s.jsx("span",{className:`min-w-0 flex-1 truncate text-[12px] leading-5 ${k?t.textSecondary:t.textPrimary}`,title:m,children:m||e.id}),e.status==="failed"&&s.jsx(zt,{theme:t,tone:"danger",children:d(Ru(e.status))}),f&&s.jsx(zt,{theme:t,tone:"warn",children:d("meshGraph.tasksView.status.blocked")}),(a==null?void 0:a.model)&&s.jsx("span",{className:"hidden sm:contents",children:s.jsx(zt,{theme:t,title:ki(a),children:a.model})}),e.status==="assigned"&&g&&s.jsx(zt,{theme:t,tone:"info",title:e.assignedNodeId??void 0,children:g}),s.jsx("span",{className:`shrink-0 text-[10px] tabular-nums ${t.textSecondary}`,children:za(GP(e))})]}),r&&s.jsxs("div",{className:"px-2.5 pb-2.5 pt-0.5",children:[s.jsx("div",{className:`whitespace-pre-wrap text-[11px] leading-4.5 ${t.textSecondary}`,children:m}),s.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:[s.jsx(zt,{theme:t,tone:e.status==="failed"?"danger":e.status==="assigned"?"info":e.status==="completed"?"good":"default",children:d(Ru(e.status))}),e.difficulty&&s.jsx(zt,{theme:t,children:e.difficulty}),e.priority&&e.priority!=="normal"&&s.jsx(zt,{theme:t,children:e.priority}),(e.taskMode==="live_debug_readonly"||e.readonly)&&s.jsx(zt,{theme:t,children:d("meshGraph.tasksView.readOnly")}),g&&s.jsxs(zt,{theme:t,title:e.assignedNodeId??void 0,children:["@ ",g]}),s.jsx("span",{className:`font-mono text-[9px] ${t.textSecondary} opacity-70`,title:e.id,children:e.id.slice(0,8)})]}),a&&s.jsxs("div",{className:`mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-[10px] ${t.textSecondary}`,children:[ki(a)&&s.jsxs("span",{children:[s.jsxs("span",{className:t.textMuted,children:[d("meshGraph.tasksView.routingRan")," "]}),ki(a)]}),(a.source||a.transport)&&s.jsxs("span",{children:[s.jsxs("span",{className:t.textMuted,children:[d("meshGraph.tasksView.routingFrom")," "]}),[a.source,a.transport].filter(Boolean).join(" · ")]})]}),a&&(typeof a.fitnessScore=="number"||a.reason||a.intraNodeLoserCount||a.skippedCount)&&s.jsxs("details",{className:"mt-1.5",children:[s.jsx("summary",{className:`cursor-pointer list-none text-[10px] ${t.textMuted} [&::-webkit-details-marker]:hidden`,children:d("meshGraph.tasksView.routingWhy")}),s.jsxs("div",{className:`mt-1 flex flex-col gap-0.5 text-[10px] leading-4 ${t.textSecondary}`,children:[typeof a.fitnessScore=="number"&&s.jsxs("div",{children:[s.jsxs("span",{className:t.textMuted,children:[d("meshGraph.tasksView.routingFitness")," "]}),a.fitnessScore]}),a.reason&&s.jsxs("div",{children:[s.jsxs("span",{className:t.textMuted,children:[d("meshGraph.tasksView.routingReason")," "]}),a.reason]}),!!a.intraNodeLoserCount&&s.jsx("div",{children:d("meshGraph.tasksView.routingLosers",{count:a.intraNodeLoserCount})}),!!a.skippedCount&&s.jsx("div",{children:d("meshGraph.tasksView.routingSkipped",{count:a.skippedCount})})]})]}),f&&s.jsx("div",{className:`mt-2 rounded-lg border px-2 py-1.5 text-[10px] ${t.isDark?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:e.blockedReason}),(i||c&&e.assignedNodeId)&&s.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:[i&&(e.status==="failed"||e.status==="cancelled")&&s.jsx(Si,{theme:t,tone:"info",busy:i.busyTaskId===e.id,armed:p==="requeue",label:d("meshGraph.tasksView.actionRequeue"),confirmLabel:d("meshGraph.tasksView.actionConfirm"),onClick:()=>{if(p!=="requeue"){u("requeue");return}u(null),i.run("requeue",e.id)}}),i&&(e.status==="pending"||e.status==="assigned")&&s.jsx(Si,{theme:t,tone:"danger",busy:i.busyTaskId===e.id,armed:p==="cancel",label:d("meshGraph.tasksView.actionCancel"),confirmLabel:d("meshGraph.tasksView.actionConfirm"),onClick:()=>{if(p!=="cancel"){u("cancel");return}u(null),i.run("cancel",e.id)}}),c&&e.assignedNodeId&&s.jsx(Si,{theme:t,tone:"default",label:d("meshGraph.tasksView.actionViewNode"),onClick:()=>c(e.assignedNodeId)})]})]})]})}function Si({theme:e,tone:t,label:n,confirmLabel:a,armed:r,busy:o,onClick:i}){const c=t==="danger"?e.isDark?"border-rose-400/30 bg-rose-500/10 text-rose-200 hover:bg-rose-500/20":"border-rose-300 bg-rose-50 text-rose-700 hover:bg-rose-100":t==="info"?e.isDark?"border-sky-400/30 bg-sky-500/10 text-sky-200 hover:bg-sky-500/20":"border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100":e.isDark?"border-white/10 bg-white/[0.05] text-slate-300 hover:bg-white/[0.1]":"border-slate-200 bg-white text-slate-600 hover:bg-slate-100";return s.jsx("button",{type:"button",disabled:o,onClick:i,className:`rounded-full border px-2.5 py-1 text-[10px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-45 ${c} ${r?"ring-1 ring-current":""}`,children:r&&a?a:n})}function KP({group:e,theme:t,nodeLabels:n,routingIndex:a,expandedTaskId:r,onToggleTask:o,actions:i,onFocusNode:c}){const{t:d}=ke("common"),p=e.counts.assigned>0||e.counts.pending>0||e.counts.failed>0,[u,m]=l.useState(null),[f,g]=l.useState(!1),[k,h]=l.useState(!1),b=u??p,S=e.title||(e.missionId?e.missionId.slice(0,24):d("meshGraph.tasksView.adhocTitle")),x=e.missionStatus?UP[e.missionStatus]:null,y=e.goal?In(e.goal):"";return s.jsxs("section",{className:`rounded-2xl border ${t.isDark?"border-white/10 bg-slate-950/40":"border-slate-200 bg-white/90"}`,children:[s.jsxs("button",{type:"button",onClick:()=>m(C=>C===null?!p:!C),"aria-expanded":b,className:"flex w-full flex-col gap-2 rounded-2xl px-3.5 py-3 text-left",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`shrink-0 transition-transform ${b?"rotate-90":""} ${t.textSecondary}`,"aria-hidden":!0,children:"›"}),e.missionId&&s.jsx($p,{size:11,className:`shrink-0 ${t.isDark,"text-slate-400"}`}),s.jsx("span",{className:`min-w-0 flex-1 truncate text-[12.5px] font-semibold ${t.textPrimary}`,title:e.missionId??void 0,children:S}),e.missionStatus&&x&&s.jsx("span",{className:`inline-flex shrink-0 items-center rounded-full border px-2 py-0.5 text-[9px] leading-none font-medium uppercase tracking-wide ${t.isDark?x.dark:x.light}`,children:d(`meshGraph.tasksView.missionStatus.${e.missionStatus}`,{defaultValue:e.missionStatus})}),e.counts.assigned>0&&s.jsx(zt,{theme:t,tone:"info",children:d("meshGraph.tasksView.chipRunning",{count:e.counts.assigned})}),e.counts.failed>0&&s.jsx(zt,{theme:t,tone:"danger",children:d("meshGraph.tasksView.chipFailed",{count:e.counts.failed})}),e.counts.blocked>0&&s.jsx(zt,{theme:t,tone:"warn",children:d("meshGraph.tasksView.chipBlocked",{count:e.counts.blocked})}),s.jsx("span",{className:`shrink-0 text-[10px] tabular-nums ${t.textSecondary}`,children:d("meshGraph.tasksView.progress",{done:e.counts.completed,total:e.counts.total})})]}),s.jsx(zP,{theme:t,group:e})]}),b&&s.jsxs("div",{className:"flex flex-col gap-0.5 px-1.5 pb-2",children:[(e.hasDependencies||y)&&s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 px-1 pb-1",children:[y&&s.jsx("button",{type:"button",onClick:()=>h(C=>!C),className:`rounded-full border px-2.5 py-1 text-[10px] font-medium transition-colors ${t.isDark?"border-white/10 bg-white/[0.05] text-slate-300 hover:bg-white/[0.1]":"border-slate-200 bg-white text-slate-600 hover:bg-slate-100"}`,children:d(k?"meshGraph.tasksView.hideGoal":"meshGraph.tasksView.showGoal")}),e.hasDependencies&&s.jsx("button",{type:"button",onClick:()=>g(C=>!C),className:`rounded-full border px-2.5 py-1 text-[10px] font-medium transition-colors ${t.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200 hover:bg-sky-500/20":"border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100"}`,children:d(f?"meshGraph.tasksView.hideGraph":"meshGraph.tasksView.showGraph")})]}),k&&y&&s.jsx("div",{className:`mx-1 mb-1 whitespace-pre-wrap rounded-xl border px-3 py-2 text-[11px] leading-4.5 ${t.isDark?"border-white/10 bg-white/[0.03] text-slate-300":"border-slate-200 bg-slate-50 text-slate-600"}`,children:y}),f&&e.hasDependencies?s.jsx("div",{className:`mx-1 mb-1 h-[300px] overflow-hidden rounded-xl border ${t.isDark?"border-white/10":"border-slate-200"}`,children:s.jsx(_P,{tasks:e.tasks,compact:!0})}):e.tasks.map(C=>s.jsx(wl,{task:C,theme:t,nodeLabels:n,routing:a.get(C.id),expanded:r===C.id,onToggle:()=>o(C.id),actions:i,onFocusNode:c},C.id))]})]})}function VP({tasks:e,status:t,emptyMessage:n,daemonId:a,sendDaemonCommand:r,onQueueMutated:o,onFocusNode:i}){const{t:c}=ke("common"),{theme:d}=Rs(),p=l.useMemo(()=>Es(d),[d]),[u,m]=l.useState(Po),[f,g]=l.useState(null),[k,h]=l.useState(null),[b,S]=l.useState(null),x=l.useMemo(()=>FP(e,t,u),[e,t,u]),y=l.useMemo(()=>qP(t),[t]),C=l.useMemo(()=>OP(t),[t]),v=N=>g(A=>A===N?null:N),w=!!(r&&a&&t.meshId),j=l.useMemo(()=>w?{busyTaskId:k,error:b,run:async(N,A)=>{if(!(!r||!a)){h(A),S(null);try{const I=await r(a,N==="cancel"?"cancel_mesh_queue_task":"requeue_mesh_queue_task",{meshId:t.meshId,taskId:A}),P=(I==null?void 0:I.result)??I;if(P&&P.success===!1){S(typeof P.error=="string"?P.error:c("meshGraph.tasksView.actionFailed"));return}o==null||o()}catch(T){S(T instanceof Error?T.message:c("meshGraph.tasksView.actionFailed"))}finally{h(null)}}}}:null,[w,k,b,r,a,t.meshId,o,c]);return x.counts.total===0?s.jsx("div",{className:`flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm ${p.textSecondary}`,children:n??c("meshGraph.taskDag.empty")}):s.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-1 pr-1.5",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 px-0.5",children:[x.counts.assigned>0&&s.jsx(zt,{theme:p,tone:"info",children:c("meshGraph.tasksView.chipRunning",{count:x.counts.assigned})}),x.counts.pending>0&&s.jsx(zt,{theme:p,children:c("meshGraph.tasksView.chipQueued",{count:x.counts.pending})}),x.counts.failed>0&&s.jsx(zt,{theme:p,tone:"danger",children:c("meshGraph.tasksView.chipFailed",{count:x.counts.failed})}),s.jsx(zt,{theme:p,tone:"good",children:c("meshGraph.tasksView.chipDone",{count:x.counts.completed})}),s.jsx("span",{className:`text-[10px] ${p.textSecondary}`,children:c("meshGraph.taskDag.statsMissions",{count:x.groups.filter(N=>N.missionId).length})}),s.jsx("span",{className:"flex-1"}),x.hiddenCount>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`text-[10px] ${p.textSecondary}`,children:c("meshGraph.taskDag.hiddenTasks",{count:x.hiddenCount})}),s.jsx("button",{type:"button",onClick:()=>m(N=>N+no),className:`rounded-full border px-2 py-0.5 text-[10px] font-medium transition-colors ${p.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200 hover:bg-sky-500/20":"border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100"}`,children:c("meshGraph.taskDag.loadMore",{count:Math.min(no,x.hiddenCount)})})]})]}),x.running.length>0&&s.jsxs("section",{className:`rounded-2xl border p-3 ${p.isDark?"border-sky-400/20 bg-sky-500/[0.06]":"border-sky-200 bg-sky-50/60"}`,children:[s.jsx("div",{className:`mb-1.5 px-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${p.isDark?"text-sky-200/90":"text-sky-700"}`,children:c("meshGraph.tasksView.runningTitle")}),s.jsx("div",{className:"flex flex-col gap-0.5",children:x.running.map(N=>s.jsx(wl,{task:N,theme:p,nodeLabels:y,routing:C.get(N.id),expanded:f===N.id,onToggle:()=>v(N.id),actions:j,onFocusNode:i},N.id))})]}),x.attention.length>0&&s.jsxs("section",{className:`rounded-2xl border p-3 ${p.isDark?"border-rose-400/20 bg-rose-500/[0.05]":"border-rose-200 bg-rose-50/60"}`,children:[s.jsx("div",{className:`mb-1.5 px-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${p.isDark?"text-rose-200/90":"text-rose-700"}`,children:c("meshGraph.tasksView.attentionTitle")}),s.jsx("div",{className:"flex flex-col gap-0.5",children:x.attention.map(N=>s.jsx(wl,{task:N,theme:p,nodeLabels:y,routing:C.get(N.id),expanded:f===N.id,onToggle:()=>v(N.id),actions:j,onFocusNode:i},`attention-${N.id}`))})]}),b&&s.jsx("div",{className:`rounded-xl border px-3 py-2 text-[11px] ${p.isDark?"border-rose-400/25 bg-rose-500/10 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:b}),x.groups.map(N=>s.jsx(KP,{group:N,theme:p,nodeLabels:y,routingIndex:C,expandedTaskId:f,onToggleTask:v,actions:j,onFocusNode:i},N.missionId??"__adhoc__"))]})}function YP(e,t){const n=a=>{a.key==="Escape"&&(a.stopPropagation(),t())};return e.addEventListener("keydown",n,!0),()=>e.removeEventListener("keydown",n,!0)}function QP(e,t){if(e==null||!Number.isFinite(e))return null;const n=t-e;if(!Number.isFinite(n)||n<0)return null;const a=Math.floor(n/1e3);if(a<60)return`${a}s`;const r=Math.floor(a/60);return r<60?`${r}m`:`${Math.floor(r/60)}h ${String(r%60).padStart(2,"0")}m`}function JP(e){return`${e.state??""} ${e.chatStatus??""} ${e.lifecycle??""}`.toLowerCase()}function XP(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const a=n.activeSessionDetails;if(Array.isArray(a))for(const r of a)r!=null&&r.sessionId&&JP(r).includes("approval")&&t.push({nodeId:n.nodeId,sessionId:r.sessionId,providerType:r.providerType,machineLabel:n.machineLabel||n.nodeId,detail:r.statusNote??r.title??null})}return t}function ZP({approvals:e,nodes:t,onResolve:n,hideWhenEmpty:a=!0,nowMs:r}){const{t:o}=ke(),i=r??Date.now(),c=l.useMemo(()=>e??XP(t),[e,t]),[d,p]=l.useState({});if(a&&c.length===0)return null;const u=(m,f)=>{d[m.sessionId]||(p(g=>({...g,[m.sessionId]:f})),Promise.resolve(n(m.nodeId,m.sessionId,f)).finally(()=>{p(g=>{const k={...g};return delete k[m.sessionId],k})}))};return s.jsxs("div",{className:"rounded-lg border p-3",style:{borderColor:"color-mix(in srgb, var(--status-warning) 40%, transparent)",background:"color-mix(in srgb, var(--status-warning) 8%, transparent)"},children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2 font-black text-xs",style:{color:"var(--status-warning)"},children:[s.jsx(Ls,{size:14}),o("meshGraph.approvals.title"),s.jsxs("span",{className:"opacity-70 font-semibold",children:["(",c.length,")"]})]}),c.length===0?s.jsx("div",{className:"text-[11px] opacity-70",children:o("meshGraph.approvals.empty")}):s.jsx("ul",{className:"flex flex-col gap-2",children:c.map(m=>{const f=d[m.sessionId]??null,g=f!==null,k=QP(m.waitingSince,i);return s.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-md px-2.5 py-2",style:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)"},children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"text-xs font-semibold truncate",children:[m.machineLabel||m.nodeId,m.providerType&&s.jsx("span",{className:"ml-2 opacity-60 font-normal",children:m.providerType}),k&&s.jsx("span",{className:"ml-2 font-bold text-[10px]",style:{color:"var(--status-warning)"},title:o("meshGraph.approvals.waitingFor",{duration:k}),children:k})]}),s.jsx("div",{className:"text-[10px] opacity-60 truncate",children:m.detail?m.detail.replace(/[\n\r]+/g," ").slice(0,120):o("meshGraph.approvals.sessionFallback",{id:m.sessionId})}),m.options&&m.options.length>0&&s.jsx("div",{className:"mt-1 flex flex-wrap gap-1",children:m.options.slice(0,4).map((h,b)=>s.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded opacity-70",style:{background:"color-mix(in srgb, var(--text-muted) 15%, transparent)"},children:h.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().slice(0,32)},`${h}-${b}`))})]}),s.jsxs("div",{className:"flex gap-2 shrink-0",children:[s.jsx("button",{onClick:()=>u(m,"approve"),disabled:g,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 font-extrabold ${g?"cursor-not-allowed opacity-60":"cursor-pointer"}`,style:{color:"var(--status-warning)",background:"var(--surface-primary)"},children:f==="approve"?s.jsx(Ks,{size:12}):o("meshGraph.approvals.approve")}),s.jsx("button",{onClick:()=>u(m,"reject"),disabled:g,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 font-semibold text-white bg-red-500/30 ${g?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:f==="reject"?s.jsx(Ks,{size:12}):o("meshGraph.approvals.reject")})]})]},`${m.nodeId}:${m.sessionId}`)})})]})}const eD=5,tD=40,sD={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function Cc(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function Gf(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const n=t.toLowerCase().replace(/[\s-]+/g,"_");return n.includes("approval")?"awaiting approval":n.includes("generating")||n.includes("running")||n.includes("busy")?"generating":n.includes("idle")||n.includes("ready")||n.includes("waiting_input")?"idle":n.replace(/_/g," ")}function qf(e){return e.includes("approval")?"amber":e.includes("generating")?"sky":e.includes("idle")?"emerald":e.includes("failed")||e.includes("stopped")||e.includes("interrupted")?"rose":"muted"}function nD(e){const t=e.git;if(!t)return e.gitProbePending?"git probe pending":"no git probe";const n=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),a=[];return t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&a.push(`↑${t.ahead??0}/↓${t.behind??0}`),n>0&&a.push(`✎${n}`),t.hasConflicts&&a.push("conflicts"),a.join(" · ")||"clean"}function zf(e){switch(e){case"active":return"emerald";case"paused":return"amber";case"completed":return"sky";case"abandoned":return"rose";default:return"muted"}}function aD(e){switch(e){case"online":return"emerald";case"dirty":return"amber";case"degraded":case"offline":return"rose";case"wrong_branch":return"sky";default:return"muted"}}function Kf(e){switch(e){case"completed":return"emerald";case"failed":return"rose";case"cancelled":return"muted";case"assigned":return"sky";case"pending":return"amber";default:return"muted"}}function jc(e){switch(e){case"easy":return"emerald";case"medium":return"amber";case"difficult":return"rose";default:return"muted"}}function Nc(e,t){switch(e){case"easy":return t("meshGraph.difficulty.easy");case"medium":return t("meshGraph.difficulty.medium");case"difficult":return t("meshGraph.difficulty.difficult");case"freeform":return t("meshGraph.difficulty.freeform");default:return e}}function Eu(e){switch(e){case"assigned":return 0;case"pending":return 1;case"completed":case"failed":case"cancelled":return 2;default:return 3}}function ks(e){if(!e)return null;const t=Date.parse(e);if(!Number.isFinite(t))return null;const n=Math.max(0,Math.floor((Date.now()-t)/1e3));if(n<60)return`${n}s ago`;const a=Math.floor(n/60);if(a<60)return`${a}m ago`;const r=Math.floor(a/60);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function _u(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return null;if(e<1e3)return`${Math.round(e)}ms`;const t=Math.round(e/1e3),n=t%60,a=Math.floor(t/60),r=a%60,o=Math.floor(a/60),i=[];return o>0&&i.push(`${o}h`),r>0&&i.push(`${r}m`),(n>0||i.length===0)&&i.push(`${n}s`),i.join(" ")}function Ac(e){return e.replace(/[_-]+/g," ")}function Vf(e){const t=e.toLowerCase();return t.includes("fail")||t.includes("stall")||t.includes("error")?"rose":t.includes("complete")?"emerald":t.includes("dispatch")||t.includes("launch")||t.includes("assign")?"sky":t.includes("checkpoint")?"amber":"muted"}function Yf(e){if(!e)return null;const t=e.message??e.summary??e.reason??e.title;return typeof t=="string"&&t.trim()?t.trim():null}function rD({status:e,daemonId:t=null,meshId:n=null,sendDaemonCommand:a=null}){var v,w,j,N;const{theme:r}=Rs(),o=l.useMemo(()=>Es(r),[r]),i=((v=e.queue)==null?void 0:v.summary)??null,c=((w=e.queue)==null?void 0:w.tasks)??[],d=((j=e.ledger)==null?void 0:j.summary)??sD,p=((N=e.ledger)==null?void 0:N.entries)??[],u=e.missions??[],m=u.filter(A=>A.status==="active"||A.status==="paused"),f=u.filter(A=>A.status==="completed"||A.status==="abandoned"),g=e.asyncRefineJobs??[],[k,h]=l.useState(null),b=l.useCallback(()=>h(null),[]),S=l.useCallback(async(A,T,I)=>{!t||!a||await a(t,"mesh_approve",{meshId:n??void 0,node_id:A,session_id:T,action:I})},[t,n,a]),x=l.useCallback(A=>{if(!A)return"";const T=e.nodes.find(I=>I.nodeId===A);return(T==null?void 0:T.machineLabel)||A},[e.nodes]),y=l.useMemo(()=>{const A=new Map;for(const T of c)T.assignedSessionId&&T.difficulty&&A.set(T.assignedSessionId,T.difficulty);return A},[c]),C=l.useMemo(()=>{const A=[];for(const T of e.nodes){const I=T.activeSessionDetails&&T.activeSessionDetails.length>0?T.activeSessionDetails:(T.activeSessions??[]).map(P=>({sessionId:P,workspace:T.workspace,isCached:!0}));for(const P of I){const M=y.get(P.sessionId);A.push({node:T,session:M?{...P,difficulty:M}:P})}}return A},[e.nodes,y]);return s.jsxs("div",{className:"flex flex-col gap-3 pb-2",children:[s.jsx(ZP,{nodes:e.nodes,onResolve:S}),s.jsx(gD,{meshTheme:o,liveMissions:m,historyMissions:f,hasMissionField:Array.isArray(e.missions),onSelect:A=>h({kind:"mission",mission:A})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(bD,{meshTheme:o,ledgerSummary:d,entries:p,resolveNodeLabel:x,onSelect:A=>h({kind:"ledger",entry:A})}),s.jsx(xD,{meshTheme:o,queueSummary:i,tasks:c,onSelect:A=>h({kind:"queue",task:A})})]}),s.jsx(yD,{meshTheme:o,nodes:e.nodes}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(wD,{meshTheme:o,entries:C,onSelect:(A,T)=>h({kind:"session",node:A,session:T})}),s.jsx(kD,{meshTheme:o,jobs:g})]}),k&&s.jsx(iD,{meshTheme:o,detail:k,onClose:b,daemonId:t,meshId:n??e.meshId??null,sendDaemonCommand:a,resolveNodeLabel:x})]})}function Ln({meshTheme:e,title:t,count:n,children:a,action:r}){const o=e.isDark;return s.jsxs("div",{className:`flex min-w-0 flex-col overflow-hidden rounded-2xl border p-4 ${o?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,children:[s.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[s.jsx("span",{className:`text-[11px] font-semibold uppercase tracking-[0.14em] ${e.textSecondary}`,children:t}),n!==void 0&&s.jsx("span",{className:`tabular-nums text-[11px] ${e.textMuted}`,children:n}),r&&s.jsx("span",{className:"ml-auto",children:r})]}),a]})}function Ut({meshTheme:e,label:t,tone:n}){const a=e.isDark,r=n==="rose"?a?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700":n==="sky"?a?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700":n==="amber"?a?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700":n==="emerald"?a?"border-emerald-400/25 bg-emerald-500/10 text-emerald-200":"border-emerald-300 bg-emerald-50 text-emerald-700":a?"border-white/10 bg-white/[0.04] text-slate-300":"border-slate-200 bg-slate-50 text-slate-600";return s.jsx("span",{className:`shrink-0 rounded-full border pl-2 pr-[calc(0.5rem-0.14em)] py-0.5 text-[10px] leading-none align-middle font-semibold uppercase tracking-[0.14em] ${r}`,children:t})}function jt({meshTheme:e,label:t,value:n,tone:a}){const r=e.isDark,o=a==="rose"?r?"text-rose-300":"text-rose-600":a==="sky"?r?"text-sky-300":"text-sky-600":a==="amber"?r?"text-amber-300":"text-amber-600":a==="emerald"?r?"text-emerald-300":"text-emerald-600":a==="muted"?e.textMuted:e.textPrimary;return s.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-2 ${r?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[s.jsx("span",{className:`tabular-nums text-base font-semibold leading-none ${o}`,children:n}),s.jsx("span",{className:`mt-1 text-[9px] uppercase tracking-wide ${e.textMuted}`,children:t})]})}function er({meshTheme:e,children:t}){return s.jsx("div",{className:`text-xs ${e.textMuted}`,children:t})}function Do({meshTheme:e,onClick:t,dimmed:n,children:a}){const r=e.isDark,o=t?r?"hover:bg-white/[0.05]":"hover:bg-slate-100/70":"";return s.jsx("button",{type:"button",onClick:t,disabled:!t,className:`flex w-full min-w-0 items-center gap-2 overflow-hidden rounded-md px-1.5 py-1 text-left text-xs transition ${o} ${t?"cursor-pointer":"cursor-default"} ${n?"opacity-55":""}`,children:a})}function Io({meshTheme:e,expanded:t,hiddenCount:n,onToggle:a}){const{t:r}=ke("common");return n<=0?null:s.jsx("button",{type:"button",onClick:a,className:`mt-1 self-start rounded-md px-1.5 py-0.5 text-[11px] font-medium ${e.textSecondary} hover:underline`,children:t?r("mesh.overview.showFewer"):r("mesh.overview.showMore",{count:n})})}function Lo(e,t=eD){const[n,a]=l.useState(!1),r=n?e:e.slice(0,t),o=Math.max(0,e.length-t),i=l.useCallback(()=>a(c=>!c),[]);return{visible:r,hiddenCount:o,expanded:n,toggle:i}}function mt({meshTheme:e,label:t,value:n}){return s.jsxs("div",{className:e.rowClass,children:[s.jsx("span",{className:e.rowLabelClass,children:t}),s.jsx("span",{className:e.rowValueClass,children:n})]})}function oD(e,t){switch(e.kind){case"mission":return{kicker:t("mesh.overview.detailKickerMission"),title:e.mission.title};case"ledger":return{kicker:t("mesh.overview.detailKickerLedger"),title:Ac(e.entry.kind)};case"queue":return{kicker:t("mesh.overview.detailKickerQueue"),title:e.task.id};case"session":return{kicker:t("mesh.overview.detailKickerSession"),title:Cc(e.session.sessionId)}}}function iD({meshTheme:e,detail:t,onClose:n,daemonId:a,meshId:r,sendDaemonCommand:o,resolveNodeLabel:i}){const{t:c}=ke("common");l.useEffect(()=>YP(window,n),[n]);const d=e.isDark,{kicker:p,title:u}=oD(t,c),m=d?"bg-[#030617]/[0.92]":"bg-[rgba(15,23,42,0.82)]",f=d?"border-white/10 bg-slate-950 md:bg-slate-950/98 shadow-[0_28px_120px_rgba(2,6,23,0.5)]":"border-slate-200 bg-white md:bg-white/98 shadow-[0_28px_120px_rgba(148,163,184,0.3)]";return s.jsx(Vt,{children:s.jsx("div",{className:`fixed inset-0 z-[var(--z-modal)] flex items-stretch justify-center p-0 md:items-center md:p-4 ${m}`,role:"dialog","aria-modal":"true",onClick:n,children:s.jsxs("div",{className:`flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden border ${f} md:h-auto md:max-h-[88dvh] md:max-w-[min(640px,calc(100vw-32px))] md:rounded-2xl`,onClick:g=>g.stopPropagation(),children:[s.jsxs("div",{className:`sticky top-0 z-10 flex shrink-0 items-start justify-between gap-3 border-b px-4 pb-3 pt-[calc(12px+env(safe-area-inset-top,0px))] ${d?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:p}),s.jsx("div",{className:`mt-0.5 break-all text-sm font-semibold ${e.textPrimary}`,children:u})]}),s.jsx("button",{type:"button",onClick:n,"aria-label":c("mesh.overview.closeDetail"),className:"-m-1.5 inline-flex h-11 w-11 shrink-0 items-center justify-center",children:s.jsx("span",{className:d?"inline-flex h-8 w-8 items-center justify-center rounded-xl border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white":"inline-flex h-8 w-8 items-center justify-center rounded-xl border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",children:"✕"})})]}),s.jsxs("div",{className:"min-h-0 min-w-0 flex-1 overflow-y-auto px-4 py-4",children:[t.kind==="mission"&&s.jsx(dD,{meshTheme:e,mission:t.mission,daemonId:a,meshId:r,sendDaemonCommand:o}),t.kind==="ledger"&&s.jsx(mD,{meshTheme:e,entry:t.entry,resolveNodeLabel:i}),t.kind==="queue"&&s.jsx(hD,{meshTheme:e,task:t.task}),t.kind==="session"&&s.jsx(fD,{meshTheme:e,node:t.node,session:t.session})]})]})})})}const lD=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function cD(e){const t=lD(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function dD({meshTheme:e,mission:t,daemonId:n,meshId:a,sendDaemonCommand:r}){var v;const{t:o}=ke("common"),i=t.tasks,c="goal"in t&&typeof t.goal=="string"&&t.goal?t.goal:"goalPreview"in t?t.goalPreview:"",d="goalTruncated"in t?t.goalTruncated===!0:!1,[p,u]=l.useState(null),[m,f]=l.useState(!1),[g,k]=l.useState(null),h=d&&!p&&!!n&&!!r,b=l.useCallback(async()=>{if(!(!n||!r)){f(!0),k(null);try{const w=await r(n,"mesh_status",{meshId:a??void 0,verbose:!0}),j=cD(w),A=(Array.isArray(j==null?void 0:j.missions)?j.missions:[]).find(I=>(I==null?void 0:I.id)===t.id),T=typeof(A==null?void 0:A.goal)=="string"&&A.goal?A.goal:null;T?u(T):k("Full goal unavailable")}catch(w){k(w instanceof Error?w.message:"Failed to fetch full mission goal")}finally{f(!1)}}},[n,a,r,t.id]),S=p??c,x=d&&!p,y=t.stats??null,C=((v=y==null?void 0:y.incompleteTaskIds)==null?void 0:v.length)??0;return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Ut,{meshTheme:e,label:t.status,tone:zf(t.status)}),s.jsx(Ut,{meshTheme:e,label:`${i.total} tasks`,tone:"muted"})]}),S&&s.jsxs("div",{className:`max-h-64 overflow-y-auto whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:[Sc(S),x&&!h&&s.jsx("span",{className:e.textMuted,children:" … (truncated)"})]}),g&&s.jsx("div",{className:"text-[11px] text-amber-400",children:g}),h&&s.jsx("button",{type:"button",className:"self-start text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:b,disabled:m,children:o(m?"mesh.overview.loadingGoal":"mesh.overview.showFullGoal")}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5 sm:grid-cols-6",children:[s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statCompleted"),value:i.completed,tone:"emerald"}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statAssigned"),value:i.assigned,tone:i.assigned>0?"sky":void 0}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statPending"),value:i.pending}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statFailed"),value:i.failed,tone:i.failed>0?"rose":void 0}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statBlocked"),value:i.blocked,tone:i.blocked>0?"amber":void 0}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statCancelled"),value:i.cancelled,tone:"muted"})]}),y&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statWallClock"),value:_u(y.wallClockMs)??"—"}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statTotalRuntime"),value:_u(y.totalDurationMs)??"—"}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statRetries"),value:y.retries,tone:y.retries>0?"amber":void 0})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(mt,{meshTheme:e,label:o("mesh.overview.detailLabelMissionId"),value:t.id}),s.jsx(mt,{meshTheme:e,label:o("mesh.overview.detailLabelCreated"),value:ks(t.createdAt)??t.createdAt}),s.jsx(mt,{meshTheme:e,label:o("mesh.overview.detailLabelUpdated"),value:ks(t.updatedAt)??t.updatedAt}),i.lastActivityAt&&s.jsx(mt,{meshTheme:e,label:o("mesh.overview.detailLabelLastActivity"),value:ks(i.lastActivityAt)??i.lastActivityAt}),C>0&&y&&s.jsx(mt,{meshTheme:e,label:o("mesh.overview.detailLabelIncompleteEvidence"),value:s.jsxs("details",{children:[s.jsx("summary",{className:"cursor-pointer select-none",children:o("mesh.overview.incompleteTaskCount_other",{count:C})}),s.jsx("div",{className:"mt-1 flex flex-col gap-0.5 break-all",children:y.incompleteTaskIds.map(w=>s.jsx("span",{className:`font-mono text-[10px] ${e.textMuted}`,children:w},w))})]})})]})]})}function uD(e){const t=e&&typeof e=="object"?e.routingDecision:void 0;return!t||typeof t!="object"||Array.isArray(t)?null:t}function pD({meshTheme:e,routing:t,resolveNodeLabel:n}){var i;const{t:a}=ke("common"),r=[t.resolvedProviderType,t.resolvedModel,t.resolvedThinkingLevel].filter(c=>typeof c=="string"&&!!c).join(" · "),o=t.requiredTagsResult;return s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx("div",{className:`text-[10px] uppercase tracking-wide ${e.textMuted}`,children:a("mesh.overview.routingHeading")}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[t.selectedNodeId&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.routingDevice"),value:n(t.selectedNodeId)}),t.daemonId&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.routingDaemon"),value:t.daemonId}),r&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.routingExecution"),value:r}),(t.source||t.transport)&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.routingVia"),value:[t.source,t.transport].filter(Boolean).join(" · ")}),t.resolvedDifficulty&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.routingDifficulty"),value:t.resolvedDifficulty}),typeof t.fitnessScore=="number"&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.routingFitness"),value:String(t.fitnessScore)}),t.reason&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.routingReason"),value:t.reason}),o&&Array.isArray(o.required)&&o.required.length>0&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.routingRequiredTags"),value:`${o.required.join(", ")}${o.satisfied===!1?` · ${a("mesh.overview.routingTagsUnsatisfied")}${(i=o.missing)!=null&&i.length?`: ${o.missing.join(", ")}`:""}`:""}`})]}),Array.isArray(t.skippedCandidates)&&t.skippedCandidates.length>0&&s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("div",{className:`text-[10px] uppercase tracking-wide ${e.textMuted}`,children:a("mesh.overview.routingSkipped")}),s.jsxs("div",{className:`flex flex-col gap-0.5 text-[11px] leading-4 ${e.textSecondary}`,children:[t.skippedCandidates.map((c,d)=>s.jsxs("div",{children:[s.jsx("span",{children:n(c.nodeId)}),c.reason&&s.jsxs("span",{className:e.textMuted,children:[" — ",c.reason]})]},`${c.nodeId??"node"}-${d}`)),(()=>{const c=t.skippedCandidatesOmitted??t.skippedCandidatesDropped;return typeof c=="number"&&c>0?s.jsx("div",{className:e.textMuted,children:a("mesh.overview.routingSkippedMore",{count:c})}):null})()]})]})]})}function mD({meshTheme:e,entry:t,resolveNodeLabel:n}){const{t:a}=ke("common"),r=Yf(t.payload),o=uD(t.payload);let i="";try{i=JSON.stringify(t.payload??{},null,2)}catch{i=String(t.payload)}return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:s.jsx(Ut,{meshTheme:e,label:Ac(t.kind),tone:Vf(t.kind)})}),r&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:r}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelEntryId"),value:t.id}),s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelWhen"),value:ks(t.timestamp)??t.timestamp}),t.nodeId&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelNode"),value:n(t.nodeId)}),t.sessionId&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelSession"),value:Cc(t.sessionId)}),t.providerType&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelProvider"),value:t.providerType})]}),o&&s.jsx(pD,{meshTheme:e,routing:o,resolveNodeLabel:n}),i&&i!=="{}"&&s.jsxs("div",{children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:a("mesh.overview.detailLabelPayload")}),s.jsx("pre",{className:`max-h-60 max-w-full overflow-auto rounded-lg border p-2 text-[10px] leading-4 ${e.isDark?"border-white/8 bg-black/30 text-slate-300":"border-slate-200 bg-slate-50 text-slate-700"}`,children:i})]})]})}function hD({meshTheme:e,task:t}){const{t:n}=ke("common");return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Ut,{meshTheme:e,label:t.status,tone:Kf(t.status)}),t.difficulty&&s.jsx(Ut,{meshTheme:e,label:Nc(t.difficulty,n),tone:jc(t.difficulty)}),(t.requeueCount??0)>0&&s.jsx(Ut,{meshTheme:e,label:n("mesh.overview.detailLabelRequeued",{count:t.requeueCount}),tone:"amber"})]}),t.message&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:In(t.message)}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(mt,{meshTheme:e,label:n("mesh.overview.detailLabelTaskId"),value:t.id}),s.jsx(mt,{meshTheme:e,label:n("mesh.overview.detailLabelCreated"),value:ks(t.createdAt)??t.createdAt}),s.jsx(mt,{meshTheme:e,label:n("mesh.overview.detailLabelUpdated"),value:ks(t.updatedAt)??t.updatedAt}),(t.assignedNodeId||t.targetNodeId)&&s.jsx(mt,{meshTheme:e,label:n("mesh.overview.detailLabelNode"),value:t.assignedNodeId||t.targetNodeId}),(t.assignedSessionId||t.targetSessionId)&&s.jsx(mt,{meshTheme:e,label:n("mesh.overview.detailLabelSession"),value:Cc(t.assignedSessionId||t.targetSessionId)}),t.cancelReason&&s.jsx(mt,{meshTheme:e,label:n("mesh.overview.detailLabelCancelReason"),value:t.cancelReason}),t.requeueReason&&s.jsx(mt,{meshTheme:e,label:n("mesh.overview.detailLabelRequeueReason"),value:t.requeueReason}),t.autoLaunch&&s.jsx(mt,{meshTheme:e,label:n("mesh.overview.detailLabelAutoLaunch"),value:`${t.autoLaunch.status}${t.autoLaunch.reason?` · ${t.autoLaunch.reason}`:""}`})]})]})}function fD({meshTheme:e,node:t,session:n}){var o,i;const{t:a}=ke("common"),r=Gf(n);return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Ut,{meshTheme:e,label:r,tone:qf(r)}),s.jsx(Ut,{meshTheme:e,label:n.providerType||"provider unknown",tone:"muted"}),n.difficulty&&s.jsx(Ut,{meshTheme:e,label:Nc(n.difficulty,a),tone:jc(n.difficulty)})]}),n.statusNote&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:n.statusNote}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelSessionId"),value:n.sessionId}),s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelNode"),value:t.machineLabel}),s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelWorkspace"),value:n.workspace||t.workspace}),(((o=t.git)==null?void 0:o.branch)??t.worktreeBranch)&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelBranch"),value:((i=t.git)==null?void 0:i.branch)??t.worktreeBranch}),typeof n.role=="string"&&n.role&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelRole"),value:n.role}),(n.startedAt||n.createdAt)&&s.jsx(mt,{meshTheme:e,label:a("mesh.overview.detailLabelStarted"),value:ks(n.startedAt||n.createdAt)??(n.startedAt||n.createdAt)})]})]})}function Ci({meshTheme:e,mission:t,onSelect:n}){const a=t.tasks,r=ks(a.lastActivityAt),o=a.total===0;return s.jsxs(Do,{meshTheme:e,onClick:n,dimmed:o,children:[s.jsx(Ut,{meshTheme:e,label:t.status,tone:zf(t.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate font-medium ${o?e.textSecondary:e.textPrimary}`,children:t.title}),a.total>0&&s.jsxs("span",{className:`shrink-0 tabular-nums text-[11px] ${e.textMuted}`,children:["✓",a.completed,"/",a.total]}),r&&s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:r})]})}function gD({meshTheme:e,liveMissions:t,historyMissions:n,hasMissionField:a,onSelect:r}){const{t:o}=ke("common"),[i,c]=l.useState(!1),[d,p]=l.useState(!1),u=e.isDark,m=l.useMemo(()=>t.filter(b=>b.status==="active"),[t]),f=l.useMemo(()=>t.filter(b=>b.status!=="active"),[t]),g=m.length>0?m:f,k=m.length>0?f:[],h=Lo(g);return s.jsxs(Ln,{meshTheme:e,title:o("mesh.overview.missionCard"),count:t.length||void 0,children:[g.length>0?s.jsxs("div",{className:"flex flex-col gap-0.5",children:[h.visible.map(b=>s.jsx(Ci,{meshTheme:e,mission:b,onSelect:()=>r(b)},b.id)),s.jsx(Io,{meshTheme:e,expanded:h.expanded,hiddenCount:h.hiddenCount,onToggle:h.toggle})]}):s.jsx(er,{meshTheme:e,children:o(a?"mesh.overview.noActiveMissions":"mesh.overview.missionDataUnavailable")}),k.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${u?"border-white/8":"border-slate-200"}`,children:[s.jsxs("button",{type:"button",onClick:()=>p(b=>!b),className:`flex w-full items-center gap-1.5 text-[11px] font-medium ${e.textSecondary}`,children:[s.jsx("span",{className:`inline-block transition-transform ${d?"rotate-90":""}`,children:"▸"}),s.jsx("span",{children:o("mesh.overview.pausedMissions")}),s.jsx("span",{className:`tabular-nums ${e.textMuted}`,children:k.length})]}),d&&s.jsx("div",{className:"mt-2 flex flex-col gap-0.5",children:k.map(b=>s.jsx(Ci,{meshTheme:e,mission:b,onSelect:()=>r(b)},b.id))})]}),n.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${u?"border-white/8":"border-slate-200"}`,children:[s.jsxs("button",{type:"button",onClick:()=>c(b=>!b),className:`flex w-full items-center gap-1.5 text-[11px] font-medium ${e.textSecondary}`,children:[s.jsx("span",{className:`inline-block transition-transform ${i?"rotate-90":""}`,children:"▸"}),s.jsx("span",{children:o("mesh.overview.completedHistory")}),s.jsx("span",{className:`tabular-nums ${e.textMuted}`,children:n.length})]}),i&&s.jsx("div",{className:"mt-2 flex flex-col gap-0.5",children:n.map(b=>s.jsx(Ci,{meshTheme:e,mission:b,onSelect:()=>r(b)},b.id))})]})]})}function bD({meshTheme:e,ledgerSummary:t,entries:n,resolveNodeLabel:a,onSelect:r}){const{t:o}=ke("common"),i=ks(t.lastActivityAt),c=l.useMemo(()=>[...n].reverse(),[n]),d=Lo(c);return s.jsxs(Ln,{meshTheme:e,title:o("mesh.overview.ledgerCard"),action:s.jsx("span",{className:`text-[10px] ${e.textMuted}`,children:o("mesh.overview.ledgerAllTime")}),children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statDispatched"),value:t.taskDispatched}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statCompleted"),value:t.taskCompleted,tone:"emerald"}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statFailed"),value:t.taskFailed,tone:t.taskFailed>0?"rose":void 0}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statStalled"),value:t.taskStalled,tone:t.taskStalled>0?"amber":void 0}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statSessions"),value:t.sessionLaunched}),s.jsx(jt,{meshTheme:e,label:o("mesh.overview.statCheckpoints"),value:t.checkpointCreated})]}),c.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:o("mesh.overview.recentActivity")}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[d.visible.map(p=>{const u=Yf(p.payload);return s.jsxs(Do,{meshTheme:e,onClick:()=>r(p),children:[s.jsx(Ut,{meshTheme:e,label:Ac(p.kind),tone:Vf(p.kind)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:p.nodeId||void 0,children:u||a(p.nodeId)||p.sessionId||"—"}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:ks(p.timestamp)??""})]},p.id)}),s.jsx(Io,{meshTheme:e,expanded:d.expanded,hiddenCount:d.hiddenCount,onToggle:d.toggle})]})]}),(t.recentFailures>0||i&&c.length===0)&&s.jsxs("div",{className:`mt-2 flex items-center justify-between text-[11px] ${e.textMuted}`,children:[t.recentFailures>0?s.jsx("span",{className:e.isDark?"text-amber-300":"text-amber-600",children:o("mesh.overview.recentFailures",{count:t.recentFailures})}):s.jsx("span",{}),i&&c.length===0&&s.jsx("span",{children:i})]})]})}function xD({meshTheme:e,queueSummary:t,tasks:n,onSelect:a}){const r=l.useMemo(()=>[...n].sort((c,d)=>{const p=Eu(c.status)-Eu(d.status);return p!==0?p:(d.updatedAt||"").localeCompare(c.updatedAt||"")}).slice(0,tD),[n]),o=Lo(r),{t:i}=ke("common");return t?s.jsxs(Ln,{meshTheme:e,title:i("mesh.overview.queueCard"),count:t.active>0?i("mesh.overview.activeCount",{count:t.active}):void 0,children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(jt,{meshTheme:e,label:i("mesh.overview.statPending"),value:t.pending}),s.jsx(jt,{meshTheme:e,label:i("mesh.overview.statAssigned"),value:t.assigned,tone:t.assigned>0?"sky":void 0}),s.jsx(jt,{meshTheme:e,label:i("mesh.overview.statActive"),value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(jt,{meshTheme:e,label:i("mesh.overview.statCompleted"),value:t.completed,tone:"emerald"}),s.jsx(jt,{meshTheme:e,label:i("mesh.overview.statFailed"),value:t.failed,tone:t.failed>0?"rose":void 0}),s.jsx(jt,{meshTheme:e,label:i("mesh.overview.statCancelled"),value:t.cancelled,tone:"muted"})]}),r.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:i("mesh.overview.recentTasks")}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.visible.map(c=>s.jsxs(Do,{meshTheme:e,onClick:()=>a(c),children:[s.jsx(Ut,{meshTheme:e,label:c.status,tone:Kf(c.status)}),c.difficulty&&s.jsx(Ut,{meshTheme:e,label:Nc(c.difficulty,i),tone:jc(c.difficulty)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:c.message||void 0,children:In(c.message)||c.id}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:ks(c.updatedAt)??""})]},c.id)),s.jsx(Io,{meshTheme:e,expanded:o.expanded,hiddenCount:o.hiddenCount,onToggle:o.toggle})]})]})]}):s.jsx(Ln,{meshTheme:e,title:i("mesh.overview.queueCard"),children:s.jsx(er,{meshTheme:e,children:i("mesh.overview.noQueueActivity")})})}function vD(e){return e.autoFastForwardEligible||e.suggestedAction==="auto_fast_forward"?{label:"fast-forward",tone:"sky"}:e.launchBlockedReason?{label:"blocked",tone:"rose"}:null}function yD({meshTheme:e,nodes:t}){const{t:n}=ke("common"),a=e.isDark;return s.jsx(Ln,{meshTheme:e,title:n("mesh.overview.nodesCard"),count:t.length,children:t.length===0?s.jsx(er,{meshTheme:e,children:n("mesh.overview.noNodes")}):s.jsx("div",{className:"flex flex-col gap-1.5",children:t.map(r=>{var d,p,u;const o=(((d=r.activeSessionDetails)==null?void 0:d.length)??0)||(((p=r.activeSessions)==null?void 0:p.length)??0),i=vD(r),c=((u=r.git)==null?void 0:u.branch)??r.worktreeBranch??null;return s.jsxs("div",{className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 overflow-hidden rounded-xl border px-3 py-2 ${a?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx(Ut,{meshTheme:e,label:r.health,tone:aD(r.health)}),s.jsx("span",{className:`min-w-0 max-w-full flex-1 truncate text-sm font-medium ${e.textPrimary}`,title:r.workspace,children:r.machineLabel}),c&&s.jsx("span",{className:`max-w-full truncate font-mono text-[11px] ${e.textSecondary}`,title:c,children:c}),s.jsx("span",{className:`max-w-full truncate font-mono text-[10px] ${e.textMuted}`,children:nD(r)}),o>0&&s.jsxs("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:[o," session",o>1?"s":""]}),typeof r.daemonBuildVersion=="string"&&r.daemonBuildVersion&&s.jsxs("span",{className:`shrink-0 font-mono text-[10px] ${e.textMuted}`,title:"Daemon build version reported by this node",children:["v",r.daemonBuildVersion]}),i&&s.jsx(Ut,{meshTheme:e,label:i.label,tone:i.tone})]},r.nodeId)})})})}function wD({meshTheme:e,entries:t,onSelect:n}){const{t:a}=ke("common"),r=Lo(t);return s.jsx(Ln,{meshTheme:e,title:a("mesh.overview.sessionsCard"),count:t.length||void 0,children:t.length===0?s.jsx(er,{meshTheme:e,children:a("mesh.overview.noActiveSessions")}):s.jsxs("div",{className:"flex flex-col gap-0.5",children:[r.visible.map(({node:o,session:i})=>{const c=Gf(i),d=o.machineLabel||o.nodeId.slice(0,12),p=o.isLocalWorktree&&o.worktreeBranch?` · ${o.worktreeBranch}`:"",u=so(i);return s.jsxs(Do,{meshTheme:e,onClick:()=>n(o,i),children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:i.sessionId,children:[d,p]}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:If(i)}),s.jsx("span",{className:`shrink-0 ${e.textMuted}`,children:i.providerType||"?"}),!u.includes("not reported")&&s.jsx("span",{className:`shrink-0 text-[10px] tabular-nums ${e.textMuted}`,children:u}),s.jsx(Ut,{meshTheme:e,label:c,tone:qf(c)})]},i.sessionId)}),s.jsx(Io,{meshTheme:e,expanded:r.expanded,hiddenCount:r.hiddenCount,onToggle:r.toggle})]})})}function kD({meshTheme:e,jobs:t}){const{t:n}=ke("common"),a=e.isDark,r=t.filter(o=>o.status==="failed").length;return s.jsx(Ln,{meshTheme:e,title:n("mesh.overview.refineCard"),count:t.length||void 0,action:r>0?s.jsx(Ut,{meshTheme:e,label:n("mesh.overview.failedCount",{count:r}),tone:"rose"}):void 0,children:t.length===0?s.jsx(er,{meshTheme:e,children:n("mesh.overview.noRefineJobs")}):s.jsx("div",{className:"flex flex-col gap-1",children:t.slice(0,8).map(o=>{const i=o.status==="failed"&&(o.lastEvent||o.lastLedgerKind)||"";return s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:[o.branch??o.jobId.slice(0,14),o.into?` → ${o.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[10px] font-semibold ${o.status==="failed"?a?"text-rose-300":"text-rose-600":o.status==="running"||o.status==="accepted"?a?"text-sky-300":"text-sky-600":a?"text-emerald-300":"text-emerald-600"}`,children:o.status})]}),i&&s.jsx("div",{className:`truncate pl-1 text-[10px] ${a?"text-rose-200/80":"text-rose-600/90"}`,title:i,children:i})]},o.jobId)})})})}const SD=["node","p2p","session","task","mission","refinery","completion","magi","magiPanel","convergence"];function CD({meshTheme:e,open:t,onToggle:n}){const{t:a}=ke(),r=e.isDark,o="inline-flex h-7 w-7 items-center justify-center rounded-lg border transition",i=t?r?"border-sky-400/40 bg-sky-500/15 text-sky-100":"border-sky-400 bg-sky-100 text-sky-800":r?"border-white/10 bg-white/[0.04] text-slate-400 hover:bg-white/[0.08] hover:text-slate-100":"border-slate-200 bg-white text-slate-400 hover:bg-slate-50 hover:text-slate-700";return s.jsx("button",{type:"button",onClick:n,"aria-label":a("meshGraph.help.toggleAria"),"aria-expanded":t,title:a("meshGraph.help.toggleTitle"),className:`${o} ${i}`,children:s.jsx(gb,{size:15})})}function jD({meshTheme:e,onClose:t}){const{t:n}=ke(),a=e.isDark,r=l.useMemo(()=>SD.map(o=>({term:n(`meshGraph.help.sections.${o}.term`),summary:n(`meshGraph.help.sections.${o}.summary`),details:n(`meshGraph.help.sections.${o}.details`,{returnObjects:!0})})),[n]);return l.useEffect(()=>{const o=i=>{i.key==="Escape"&&t()};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[t]),s.jsxs("div",{className:`shrink-0 rounded-2xl border p-4 ${a?"border-white/10 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,role:"region","aria-label":n("meshGraph.help.regionAria"),children:[s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:n("meshGraph.help.kicker")}),s.jsx("div",{className:`mt-0.5 text-sm font-semibold ${e.textPrimary}`,children:n("meshGraph.help.title")})]}),s.jsx("button",{type:"button",onClick:t,"aria-label":n("meshGraph.help.close"),className:a?"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white":"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",children:s.jsx(Dt,{size:14})})]}),s.jsx("dl",{className:"grid gap-3 sm:grid-cols-2",children:r.map(o=>s.jsxs("div",{className:`rounded-xl border p-3 ${a?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx("dt",{className:`text-xs font-semibold ${e.textPrimary}`,children:o.term}),s.jsx("dd",{className:`mt-1 text-[11px] leading-5 ${e.textSecondary}`,children:o.summary}),o.details&&o.details.length>0&&s.jsx("ul",{className:`mt-1.5 flex flex-col gap-1 text-[11px] leading-5 ${e.textMuted}`,children:o.details.map((i,c)=>s.jsxs("li",{className:"flex gap-1.5",children:[s.jsx("span",{"aria-hidden":!0,className:"select-none",children:"·"}),s.jsx("span",{className:"min-w-0",children:i})]},c))})]},o.term))})]})}const _s=l.createContext(Es("dark"));function ze({label:e,tone:t="default",className:n,title:a}){const r=l.useContext(_s);return s.jsx("span",{title:a,className:`rounded-full border pl-2 pr-[calc(0.5rem-0.16em)] py-0.5 text-[10px] leading-none align-middle uppercase tracking-[0.16em] ${r.badge(t)}${n?` ${n}`:""}`,children:e})}function Ht({label:e,value:t}){const n=l.useContext(_s);return s.jsxs("div",{className:n.rowClass,children:[s.jsx("span",{className:n.rowLabelClass,children:e}),s.jsx("span",{className:n.rowValueClass,children:t})]})}function ND({scheduling:e}){const{t}=ke("common"),n=l.useContext(_s);if(!e)return s.jsx("div",{className:`${n.cardClass} rounded-2xl p-4 text-xs ${n.textSecondary}`,children:t("mesh.status.schedulingNotReported")});const a=typeof e.activeWriteAssigned=="number"&&typeof e.maxParallelTasks=="number";return s.jsxs("div",{className:`${n.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-xs font-semibold ${n.textPrimary}`,children:t("mesh.status.schedulingTitle")}),s.jsx(ze,{label:MM[e.strategy]??e.strategy,tone:"info"}),a&&s.jsx(ze,{label:`write ${e.activeWriteAssigned}/${e.maxParallelTasks}`,tone:e.globalWriteCapReached?"warn":"good",title:"Active write (non-readonly) assigned tasks vs the global parallel cap"}),a&&typeof e.activeReadonlyAssigned=="number"&&typeof e.maxReadonlyParallelTasks=="number"&&s.jsx(ze,{label:`readonly ${e.activeReadonlyAssigned}/${e.maxReadonlyParallelTasks}`,tone:e.globalReadonlyCapReached?"warn":"default",title:"Active read-only diagnosis tasks vs their (2× write) cap"})]}),s.jsx("p",{className:`mt-2 text-[11px] ${n.textSecondary}`,children:t("mesh.status.distributionTitle")})]})}function AD({scheduling:e}){return e?s.jsxs(s.Fragment,{children:[s.jsx(ze,{label:`load ${e.load}`,tone:e.load>0?"info":"default",title:"Active assigned tasks on this node"}),typeof e.schedulingPriority=="number"&&e.schedulingPriority!==0&&s.jsx(ze,{label:`priority ${e.schedulingPriority}`,tone:"default",title:"Soft scheduling priority (higher = preferred)"}),(e.providerRoles??[]).map(t=>s.jsx(ze,{label:`${t.providerType} ${t.activeAssigned}${typeof t.maxParallel=="number"?`/${t.maxParallel}`:""}`,tone:t.capReached?"warn":"default",title:"Per-(node, provider) active assignments vs declared maxParallel cap"},t.providerType)),e.capReached&&(e.capReasons??[]).map(t=>s.jsx(ze,{label:PM(t),tone:"warn",title:"Why this node cannot currently claim a new write task"},t))]}):null}function TD({machine:e}){const{t}=ke("common"),n=l.useContext(_s),a=fS(e.reportedAt);return s.jsxs("div",{className:`rounded-xl border p-3 ${n.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-xs font-semibold ${n.textPrimary}`,children:e.label}),e.daemonBuildVersion&&s.jsx(ze,{label:e.daemonBuildVersion,tone:"default",title:"Daemon build version running on this machine"}),e.nodeCount>1&&s.jsx(ze,{label:`${e.nodeCount} nodes`,tone:"default",title:"Mesh nodes (workspaces/worktrees) hosted by this machine — they share this one plan quota"}),a&&s.jsx("span",{className:`text-[10px] ${n.textSecondary}`,title:t("mesh.status.quotaFreshnessHint"),children:a})]}),e.quota.length===0?s.jsx("div",{className:`mt-1.5 text-[11px] ${n.textSecondary}`,children:e.hasReported?t("mesh.status.quotaNotCollected"):t("mesh.status.machineNotReporting")}):s.jsx("div",{className:"mt-2 flex flex-col gap-1.5",children:e.quota.map(({provider:r,quota:o})=>{var u,m;const i=wo(o),c=ln(o.session,void 0,i),d=ln(o.weekly,void 0,i),p=!!(c||d);return s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx("span",{className:`text-[11px] ${n.textPrimary}`,children:Pn(r)}),$a(o)&&s.jsx("span",{className:`text-[10px] ${n.textSecondary}`,title:t("mesh.status.quotaAccountHint"),children:$a(o)}),c&&s.jsx(ze,{label:`5h ${c}`,tone:on(((u=o.session)==null?void 0:u.usedPercent)??NaN),title:"Rolling 5-hour plan window reported by this machine"}),d&&s.jsx(ze,{label:`7d ${d}`,tone:on(((m=o.weekly)==null?void 0:m.usedPercent)??NaN),title:"Rolling 7-day plan window reported by this machine"}),!p&&s.jsx("span",{className:`text-[11px] ${n.textSecondary}`,title:"This machine reported that it could not read this provider's quota",children:ec(o)}),hS(r,o)&&s.jsx("span",{className:`text-[11px] ${n.textSecondary} opacity-80`,children:t("mesh.status.quotaClaudeSetupHint")})]},r)})})]})}function MD({status:e}){const{t}=ke("common"),n=l.useContext(_s),a=AM(e);if(a.length===0)return null;const r=a.filter(i=>i.hasReported),o=a.filter(i=>!i.hasReported);return s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("span",{className:`px-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${n.textSecondary}`,children:t("mesh.status.machinesQuota")}),r.map(i=>s.jsx(TD,{machine:i},i.machineKey)),o.length>0&&s.jsx("div",{className:`rounded-xl border px-3 py-2 text-[11px] ${n.textSecondary} ${n.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:t("mesh.status.machinesNotReporting",{count:o.length,machines:o.map(i=>i.label).join(", ")})})]})}function PD(e,t){var r;if(e.health!=="degraded"&&e.health!=="unknown")return null;if(typeof e.error=="string"&&e.error)return e.error;const n=e.git;if(n&&n.isGitRepo===!1)return t("mesh.status.healthNotGitRepo");if(e.gitProbePending)return t("mesh.status.healthProbePending");const a=(r=e.connection)==null?void 0:r.state;return a&&a!=="connected"&&a!=="self"?t("mesh.status.healthPeerConnection",{state:a}):t("mesh.status.healthNoLiveReport")}function DD({node:e,previewVersion:t}){var S,x,y,C,v;const{t:n}=ke("common"),a=l.useContext(_s),r=PD(e,n),o=((S=e.activeSessionDetails)==null?void 0:S.length)??((x=e.activeSessions)==null?void 0:x.length)??0,i=vl((y=e.git)==null?void 0:y.headCommit),c=e.isLocalWorktree===!0,d=e.worktreeBootstrap,p=e.staleDaemonBuild,u=e.providerVersions&&typeof e.providerVersions=="object"?e.providerVersions:void 0,m=u?Object.entries(u).filter(([,w])=>typeof w=="string"&&w):[],f=typeof e.daemonBuildVersion=="string"&&e.daemonBuildVersion?e.daemonBuildVersion:void 0,g=(C=e.nodeFacts)==null?void 0:C.daemonBuild,k=g!=null&&g.commitShort?`build ${g.version||f||"?"}@${g.commitShort}`:f?`build ${f}`:void 0,h=((g==null?void 0:g.version)||f||"").trim().toLowerCase(),b=!!(h&&t&&h!==t.trim().toLowerCase());return s.jsxs("div",{className:`rounded-xl border p-3 ${a.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-xs font-semibold ${a.textPrimary}`,children:e.machineLabel||e.nodeId}),s.jsx(ze,{label:e.health,tone:Df(e.health)}),c&&s.jsx(ze,{label:n("mesh.status.badgeWorktree"),tone:"info",title:e.worktreeBranch?n("mesh.status.badgeWorktreeBranchTitle",{branch:e.worktreeBranch}):n("mesh.status.badgeWorktreeTitle")}),(d==null?void 0:d.status)&&d.status!=="ready"&&s.jsx(ze,{label:`bootstrap ${d.status}`,tone:"warn",title:n("mesh.status.badgeBootstrapTitle")}),((v=e.connection)==null?void 0:v.state)&&e.connection.state!=="self"&&s.jsx(ze,{label:e.connection.state,tone:e.connection.state==="connected"?"good":"warn",title:n("mesh.status.badgeConnectionTitle")}),o>0&&s.jsx(ze,{label:n("mesh.status.badgeSessions",{count:o}),tone:"default"}),e.autoFastForwardEligible&&s.jsx(ze,{label:n("mesh.status.badgeFastForwardReady"),tone:"info",title:n("mesh.status.badgeFastForwardReadyTitle")}),!!p&&s.jsx(ze,{label:n("mesh.status.badgeStaleBuild"),tone:"warn",title:n("mesh.status.badgeStaleBuildTitle")}),k&&s.jsx(ze,{label:k,tone:p||b?"warn":"default",title:"Daemon build (version@commit) reported by this node — the running daemon's actual code identity"}),b&&s.jsx(ze,{label:`deploy-lag vs ${t}`,tone:"warn",title:n("mesh.status.badgeDeployLagTitle")}),s.jsx(AD,{scheduling:e.scheduling})]}),r&&s.jsx("div",{className:`mt-1.5 truncate text-[11px] ${a.isDark?"text-amber-200/85":"text-amber-700"}`,title:r,children:r}),m.length>0&&s.jsx("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:m.map(([w,j])=>s.jsx(ze,{label:`${w}@${j}`,tone:"info",title:"Detected provider version on this node"},w))}),s.jsxs("div",{className:`mt-1.5 text-[11px] ${a.textSecondary}`,children:[jM(e),i?s.jsxs("span",{className:"ml-2 font-mono opacity-70",children:["@",i]}):null]})]})}function ID({status:e}){const{t}=ke("common"),n=l.useContext(_s),a=e.meshProtocolMetrics,r=Array.isArray(e.providerVersionSkew)?e.providerVersionSkew:[];return!a&&r.length===0?null:s.jsxs("div",{className:`${n.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-xs font-semibold ${n.textPrimary}`,children:t("mesh.status.protocolTitle")}),a&&s.jsx(ze,{label:`v2 ${Math.round(a.v2Ratio*100)}% (${a.v2}/${a.total})`,tone:a.total>0&&a.v2===a.total?"good":"info",title:"Share of pending coordinator events carrying a mesh-protocol-v2 envelope in this drain"}),r.length>0&&s.jsx(ze,{label:`${r.length} provider skew`,tone:"warn",title:"Providers running different versions across nodes"})]}),a&&Object.keys(a.scopes).length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:Object.entries(a.scopes).map(([o,i])=>s.jsx(ze,{label:`${o}: ${i}`,tone:"default",title:"v2 event scope breakdown"},o))}),r.length>0&&s.jsx("div",{className:"mt-2 flex flex-col gap-1.5",children:r.map(o=>s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx("span",{className:`text-[11px] font-semibold ${n.textPrimary}`,children:o.provider}),o.versions.map(i=>s.jsx(ze,{label:`${i.version} · ${i.nodeIds.length} node${i.nodeIds.length===1?"":"s"}`,tone:"default",title:i.nodeIds.join(", ")},i.version))]},o.provider))}),e.providerVersionSkewWarning&&s.jsx("p",{className:`mt-2 text-[11px] ${n.textSecondary}`,children:e.providerVersionSkewWarning})]})}function LD({canonicalStatus:e}){const{t}=ke("common"),n=l.useContext(_s);return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsx(ND,{scheduling:e.scheduling}),s.jsx(ID,{status:e}),s.jsx(MD,{status:e}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("span",{className:`px-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${n.textSecondary}`,children:t("mesh.status.nodesRuntime")}),e.nodes.length===0?s.jsx("div",{className:`rounded-xl border p-3 text-xs ${n.textSecondary} ${n.isDark?"border-white/10":"border-slate-200"}`,children:t("mesh.status.noNodesReporting")}):e.nodes.map(a=>{var r;return s.jsx(DD,{node:a,previewVersion:typeof((r=e.previewFreshness)==null?void 0:r.previewVersion)=="string"?e.previewFreshness.previewVersion:void 0},a.nodeId)})]})]})}const yr=["provider_quirk","pattern_to_avoid","recovery_lesson"],Hu=240,RD={provider_quirk:"warn",pattern_to_avoid:"danger",recovery_lesson:"good"};function ji(e,t){return e(t==="provider_quirk"?"meshGraph.notes.categoryProviderQuirk":t==="pattern_to_avoid"?"meshGraph.notes.categoryPatternToAvoid":t==="recovery_lesson"?"meshGraph.notes.categoryRecoveryLesson":"meshGraph.notes.categoryUncategorized")}function $u(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleString()}function ED({meshId:e,daemonId:t,sendDaemonCommand:n}){const{t:a}=ke("common"),r=l.useContext(_s),[o,i]=l.useState([]),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,f]=l.useState(!1),[g,k]=l.useState(!1),[h,b]=l.useState(""),[S,x]=l.useState(""),[y,C]=l.useState(new Set),[v,w]=l.useState(null),[j,N]=l.useState(""),[A,T]=l.useState(""),I=!!(n&&t&&e),P=l.useCallback(async()=>{if(!(!n||!t||!e)){d(!0),u(null);try{const L=await n(t,"list_mesh_notes",{meshId:e,tail:100}),F=(L==null?void 0:L.result)??L;if(F&&F.success===!1){u(typeof F.error=="string"?F.error:a("meshGraph.notes.loadFailed")),i([]);return}const $=Array.isArray(F==null?void 0:F.notes)?F.notes:[];i([...$].reverse())}catch(L){u(L instanceof Error?L.message:a("meshGraph.notes.loadFailed")),i([])}finally{d(!1)}}},[n,t,e,a]);l.useEffect(()=>{P()},[P]);const M=l.useCallback(async()=>{if(!n||!t||!e)return;const L=h.trim();if(!(!L||m)){f(!0),u(null);try{const F=await n(t,"record_mesh_note",{meshId:e,text:L,...S?{category:S}:{}}),$=(F==null?void 0:F.result)??F;if($&&$.success===!1){u(typeof $.error=="string"?$.error:a("meshGraph.notes.saveFailed"));return}b(""),x(""),k(!1),await P()}catch(F){u(F instanceof Error?F.message:a("meshGraph.notes.saveFailed"))}finally{f(!1)}}},[n,t,e,h,S,m,P,a]),E=l.useCallback(async L=>{if(!(!n||!t||!e||m)){f(!0),u(null);try{const F=await n(t,"forget_mesh_note",{meshId:e,noteId:L}),$=(F==null?void 0:F.result)??F;if($&&$.success===!1){u(typeof $.error=="string"?$.error:a("meshGraph.notes.deleteFailed"));return}await P()}catch(F){u(F instanceof Error?F.message:a("meshGraph.notes.deleteFailed"))}finally{f(!1)}}},[n,t,e,m,P,a]),D=l.useCallback(L=>{w(L.id),N(L.text),T(yr.includes(L.category)?L.category:"")},[]),W=l.useCallback(()=>{w(null),N(""),T("")},[]),R=l.useCallback(async L=>{if(!n||!t||!e||m)return;const F=j.trim();if(F){f(!0),u(null);try{const $=await n(t,"forget_mesh_note",{meshId:e,noteId:L}),K=($==null?void 0:$.result)??$;if(K&&K.success===!1){u(typeof K.error=="string"?K.error:a("meshGraph.notes.editFailed"));return}const z=await n(t,"record_mesh_note",{meshId:e,text:F,...A?{category:A}:{}}),ne=(z==null?void 0:z.result)??z;if(ne&&ne.success===!1){u(typeof ne.error=="string"?ne.error:a("meshGraph.notes.editFailed"));return}W(),await P()}catch($){u($ instanceof Error?$.message:a("meshGraph.notes.editFailed"))}finally{f(!1)}}},[n,t,e,j,A,m,W,P,a]),B=r.isDark?"rounded-lg border border-white/10 bg-slate-950/40 px-2.5 py-1.5 text-xs text-slate-200":"rounded-lg border border-slate-300 bg-white px-2.5 py-1.5 text-xs text-slate-700",_=r.isDark?"w-full rounded-lg border border-white/10 bg-slate-950/40 px-3 py-2 text-sm text-slate-100 placeholder:text-slate-500":"w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm text-slate-800 placeholder:text-slate-400",H=L=>`rounded-lg border px-2.5 py-1 text-xs font-medium transition disabled:cursor-not-allowed disabled:opacity-45 ${r.actionButton(L)}`;return I?s.jsxs("div",{className:"flex flex-col gap-3",children:[g?s.jsxs("div",{className:`${r.cardClass} rounded-2xl p-4`,children:[s.jsx("div",{className:`mb-2 text-sm font-semibold ${r.textPrimary}`,children:a("meshGraph.notes.addTitle")}),s.jsx("textarea",{value:h,onChange:L=>b(L.target.value),rows:2,placeholder:a("meshGraph.notes.textPlaceholder"),className:_,autoFocus:!0}),s.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[s.jsxs("select",{value:S,onChange:L=>x(L.target.value),className:B,"aria-label":a("meshGraph.notes.categoryLabel"),children:[s.jsx("option",{value:"",children:a("meshGraph.notes.categoryUncategorized")}),yr.map(L=>s.jsx("option",{value:L,children:ji(a,L)},L))]}),s.jsx("button",{type:"button",onClick:()=>{M()},disabled:m||!h.trim(),className:H("success"),children:a("meshGraph.notes.add")}),s.jsx("button",{type:"button",onClick:()=>k(!1),disabled:m,className:H("default"),children:a("meshGraph.notes.cancel")})]})]}):s.jsx("div",{children:s.jsxs("button",{type:"button",onClick:()=>k(!0),className:H("info"),children:["+ ",a("meshGraph.notes.addTitle")]})}),p&&s.jsx("div",{className:r.isDark?"rounded-xl border border-rose-400/20 bg-rose-500/10 px-3 py-2 text-xs text-rose-100":"rounded-xl border border-rose-300 bg-rose-50 px-3 py-2 text-xs text-rose-700",children:p}),s.jsxs("div",{className:`${r.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("div",{className:`text-sm font-semibold ${r.textPrimary}`,children:a("meshGraph.notes.listTitle")}),s.jsx("button",{type:"button",onClick:()=>{P()},disabled:c||m,className:H("default"),children:a("meshGraph.notes.refresh")})]}),c?s.jsx("div",{className:`py-6 text-center text-sm ${r.textMuted}`,children:a("meshGraph.notes.loading")}):o.length===0?s.jsx("div",{className:`py-6 text-center text-sm ${r.textMuted}`,children:a("meshGraph.notes.empty")}):s.jsx("div",{className:"flex flex-col gap-2",children:o.map(L=>s.jsx("div",{className:`rounded-xl border px-3 py-2.5 ${r.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:v===L.id?s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("textarea",{value:j,onChange:F=>N(F.target.value),rows:2,className:_}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("select",{value:A,onChange:F=>T(F.target.value),className:B,"aria-label":a("meshGraph.notes.categoryLabel"),children:[s.jsx("option",{value:"",children:a("meshGraph.notes.categoryUncategorized")}),yr.map(F=>s.jsx("option",{value:F,children:ji(a,F)},F))]}),s.jsx("button",{type:"button",onClick:()=>{R(L.id)},disabled:m||!j.trim(),className:H("success"),children:a("meshGraph.notes.save")}),s.jsx("button",{type:"button",onClick:W,disabled:m,className:H("default"),children:a("meshGraph.notes.cancel")})]})]}):s.jsxs(s.Fragment,{children:[(()=>{const F=Sc(L.text),$=y.has(L.id),K=F.length>Hu,z=!K||$?F:`${F.slice(0,Hu).trimEnd()}…`;return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`whitespace-pre-wrap break-words text-sm ${r.textPrimary}`,children:z}),K&&s.jsx("button",{type:"button",onClick:()=>C(ne=>{const ie=new Set(ne);return ie.has(L.id)?ie.delete(L.id):ie.add(L.id),ie}),className:`mt-1 text-[11px] font-medium ${r.isDark?"text-sky-300 hover:text-sky-200":"text-sky-600 hover:text-sky-700"}`,children:a($?"meshGraph.notes.showLess":"meshGraph.notes.showMore")})]})})(),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx(ze,{label:ji(a,L.category),tone:yr.includes(L.category)?RD[L.category]:"default"}),L.pinned&&s.jsx(ze,{label:a("meshGraph.notes.pinned"),tone:"info"}),$u(L.createdAt)&&s.jsx("span",{className:`text-[11px] ${r.textMuted}`,children:$u(L.createdAt)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{type:"button",onClick:()=>D(L),disabled:m,className:H("info"),children:a("meshGraph.notes.edit")}),s.jsx("button",{type:"button",onClick:()=>{E(L.id)},disabled:m,className:H("default"),children:a("meshGraph.notes.delete")})]})]})]})},L.id))})]})]}):s.jsx("div",{className:`${r.cardClass} rounded-2xl p-4 text-[12px] ${r.textSecondary}`,children:a("meshGraph.notes.unavailable")})}function _D({canonicalStatus:e,queueSummary:t,ledgerSummary:n,isBootstrapMode:a,meshTheme:r,sessionEntries:o,inlineMode:i=!1}){var w;const c=t&&(t.active>0||t.historical>0),d=n.recentFailures>0||n.taskFailed>0,p=(w=e.queue)!=null&&w.tasks?e.queue.tasks.filter(j=>j.status==="failed"||j.status==="cancelled").slice(0,5):[],u=e.asyncRefineJobs,m=(u==null?void 0:u.filter(j=>j.status==="running"||j.status==="accepted"))??[],f=(u==null?void 0:u.filter(j=>j.status==="failed"))??[],g=e.staleDirectWorkSummary,k=g&&g.count>0;if(!c&&!d&&e.nodes.length===0&&!a&&m.length===0&&f.length===0&&!k&&o.length===0)return null;const{t:h}=ke("common"),b=r.isDark,S=`border-t ${b?"border-white/8":"border-slate-200"}`,x=`group w-full rounded-lg border text-xs ${b?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,y=`flex cursor-pointer list-none items-center gap-1.5 px-2.5 py-1.5 [&::-webkit-details-marker]:hidden ${r.textSecondary}`;function C({label:j,value:N,tone:A}){const T=A==="rose"?b?"text-rose-300":"text-rose-600":A==="sky"?b?"text-sky-300":"text-sky-600":A==="amber"?b?"text-amber-300":"text-amber-600":A==="emerald"?b?"text-emerald-300":"text-emerald-600":A==="muted"?r.textMuted:r.textPrimary;return s.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-1.5 ${b?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[s.jsx("span",{className:`tabular-nums text-sm font-semibold leading-none ${T}`,children:N}),s.jsx("span",{className:`mt-0.5 text-[9px] uppercase tracking-wide ${r.textMuted}`,children:j})]})}const v=s.jsxs("div",{className:"flex flex-col gap-3 text-xs",children:[s.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t?s.jsxs(s.Fragment,{children:[s.jsx(C,{label:"Pending",value:t.pending}),s.jsx(C,{label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(C,{label:"Done",value:t.completed,tone:"emerald"}),s.jsx(C,{label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0})]}):s.jsxs(s.Fragment,{children:[s.jsx(C,{label:"Done",value:n.taskCompleted,tone:"emerald"}),s.jsx(C,{label:"Failed",value:n.taskFailed,tone:n.taskFailed>0?"rose":void 0}),s.jsx(C,{label:"Sessions",value:n.sessionLaunched}),s.jsx(C,{label:"Recent↯",value:n.recentFailures,tone:n.recentFailures>0?"amber":"muted"})]})}),t&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(C,{label:"Ledger done",value:n.taskCompleted,tone:"emerald"}),s.jsx(C,{label:"Sessions",value:n.sessionLaunched}),s.jsx(C,{label:"Recent↯",value:n.recentFailures,tone:n.recentFailures>0?"amber":"muted"})]}),n.lastActivityAt&&s.jsxs("div",{className:`flex items-center justify-between ${r.textMuted}`,children:[s.jsx("span",{children:h("meshGraph.health.lastActivity")}),s.jsx("span",{className:"font-mono text-[10px]",children:n.lastActivityAt.slice(5,16)})]}),e.nodes.length>0&&s.jsx("div",{className:`pt-2.5 ${S}`,children:s.jsx("div",{className:"flex flex-col gap-1",children:e.nodes.map(j=>{var M;const N=((M=j.connection)==null?void 0:M.state)??"unknown",A=N==="unknown"||N==="connecting",P=A?"bg-amber-400":N==="failed"||N==="closed"||N==="disconnected"?b?"bg-rose-400":"bg-rose-500":N==="connected"||N==="self"?b?"bg-emerald-400":"bg-emerald-500":b?"bg-slate-500":"bg-slate-400";return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`size-1.5 shrink-0 rounded-full ${P}`}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${r.textSecondary}`,title:j.workspace,children:j.machineLabel}),s.jsx("span",{className:`shrink-0 font-mono text-[10px] ${r.textMuted}`,children:A?"…":N})]},j.nodeId)})})}),u&&u.length>0&&s.jsx("div",{className:`pt-2.5 ${S}`,children:s.jsxs("details",{className:x,children:[s.jsxs("summary",{className:y,children:[s.jsx("span",{className:"flex-1",children:h("meshGraph.health.refineJobs")}),s.jsx("span",{className:`tabular-nums ${b?"text-slate-400":"text-slate-500"}`,children:u.length}),f.length>0&&s.jsxs("span",{className:b?"text-rose-300":"text-rose-600",children:[f.length," failed"]})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:u.slice(0,8).map(j=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${r.textMuted}`,children:[j.branch??j.jobId.slice(0,14),j.into?` → ${j.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${j.status==="failed"?b?"text-rose-300":"text-rose-600":j.status==="running"||j.status==="accepted"?b?"text-sky-300":"text-sky-600":b?"text-emerald-300":"text-emerald-600"}`,children:j.status})]},j.jobId))})]})}),p.length>0&&s.jsx("div",{className:u&&u.length>0?"":`pt-2.5 ${S}`,children:s.jsxs("details",{className:x,children:[s.jsxs("summary",{className:y,children:[s.jsx("span",{className:`flex-1 ${b?"text-rose-300":"text-rose-600"}`,children:h("meshGraph.health.failedTasks")}),s.jsx("span",{className:`tabular-nums ${b?"text-rose-400":"text-rose-500"}`,children:p.length})]}),s.jsx("div",{className:"flex flex-col gap-1 px-2.5 pb-2",children:p.map(j=>s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`font-mono text-[10px] ${r.textMuted}`,children:j.id.slice(0,10)}),j.message&&s.jsx("span",{className:`flex-1 truncate ${b?"text-slate-300":"text-slate-700"}`,children:j.message.slice(0,55)})]}),j.cancelReason&&s.jsx("div",{className:`truncate text-[10px] ${r.textMuted}`,children:j.cancelReason.slice(0,55)})]},j.id))})]})}),k&&s.jsxs("div",{className:`flex items-center justify-between pt-2.5 ${S}`,children:[s.jsx("span",{className:r.textMuted,children:h("meshGraph.health.staleWork")}),s.jsx("span",{className:`tabular-nums ${b?"text-amber-300":"text-amber-600"}`,children:g.count})]}),o.length>0&&s.jsx("div",{className:`pt-2.5 ${S}`,children:s.jsxs("details",{className:x,children:[s.jsxs("summary",{className:y,children:[s.jsx("span",{className:"flex-1",children:h("meshGraph.health.sessions")}),s.jsx("span",{className:`tabular-nums ${b?"text-slate-400":"text-slate-500"}`,children:o.length})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:o.map(j=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${r.textMuted}`,title:j.session.sessionId,children:Lf(j.session.sessionId)}),s.jsx("span",{className:`shrink-0 ${r.textMuted}`,children:j.session.providerType||"?"}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${r.textMuted}`,children:Rr(j.session)})]},j.session.sessionId))})]})})]});return i?v:s.jsxs("details",{className:`rounded-2xl border text-xs ${r.isDark?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsxs("summary",{className:`flex cursor-pointer list-none items-center gap-2 px-4 py-3 font-medium [&::-webkit-details-marker]:hidden ${r.textSecondary}`,children:[s.jsx("span",{className:"flex-1",children:h("meshGraph.health.panelTitle")}),m.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${r.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700"}`,children:[m.length," refining"]}),f.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${r.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[f.length," refine failed"]}),d&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${r.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[n.recentFailures," recent failures"]}),a&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${r.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:"awaiting live data"})]}),v]})}function Qf({meshTheme:e,activeTab:t,onActiveTabChange:n,helpOpen:a,onHelpOpenChange:r}){const{t:o}=ke("common"),i=c=>c?e.isDark?"rounded-lg px-3.5 py-1.5 text-xs font-semibold text-slate-100 bg-white/[0.08] border border-white/12":"rounded-lg px-3.5 py-1.5 text-xs font-semibold text-slate-900 bg-white border border-slate-300 shadow-sm":`rounded-lg px-3.5 py-1.5 text-xs font-medium ${e.textSecondary} border border-transparent hover:bg-white/[0.04]`;return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:`inline-flex w-fit items-center gap-1 rounded-xl border p-1 ${e.isDark?"border-white/10 bg-slate-950/40":"border-slate-200 bg-slate-50"}`,role:"tablist","aria-label":"Mesh view",children:[s.jsx("button",{type:"button",role:"tab","aria-selected":t==="overview",className:i(t==="overview"),onClick:()=>n("overview"),children:o("meshGraph.obs.tabOverview")}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="tasks",className:i(t==="tasks"),onClick:()=>n("tasks"),children:o("meshGraph.obs.tabTasks")}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="status",className:i(t==="status"),onClick:()=>n("status"),children:o("meshGraph.obs.tabStatus")}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="notes",className:i(t==="notes"),onClick:()=>n("notes"),children:o("meshGraph.notes.tab")}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="graph",className:i(t==="graph"),onClick:()=>n("graph"),children:o("meshGraph.obs.tabGraph")})]}),s.jsx(CD,{meshTheme:e,open:a,onToggle:()=>r(!a)})]})}function HD({status:e,emptyMessage:t,daemonId:n=null,sendDaemonCommand:a=null,bootstrapFallback:r,activeTab:o,onActiveTabChange:i,helpOpen:c,onHelpOpenChange:d,hideControls:p=!1,onRequestRefresh:u}){var We,Xe,et;const{t:m}=ke("common"),{theme:f}=Rs(),g=l.useMemo(()=>Es(f),[f]),k=l.useMemo(()=>({merged_to_main:m("meshGraph.obs.convergenceMergedToMain"),pushed_feature_branch_needs_merge:m("meshGraph.obs.convergenceNeedsMerge"),blocked_review:m("meshGraph.obs.convergenceBlockedReview"),cleanup_candidate:m("meshGraph.obs.convergenceCleanup"),not_mergeable:m("meshGraph.obs.convergenceNotMergeable")}),[m]),h=t??m("meshGraph.obs.emptyGraph"),b=l.useMemo(()=>Sm(e),[e]),S=r??OM(b),x=l.useMemo(()=>WM(b),[b]),y=l.useMemo(()=>Pf(b),[x]),[C,v]=l.useState("overview"),[w,j]=l.useState(!1),N=o??C,A=c??w,T=l.useCallback(J=>{i?i(J):v(J)},[i]),I=l.useCallback(J=>{d?d(J):j(J)},[d]),[P,M]=l.useState(!1);l.useEffect(()=>{N==="graph"&&M(!0)},[N]);const[E,D]=l.useState(!1);l.useEffect(()=>{N==="tasks"&&D(!0)},[N]);const W=l.useMemo(()=>{var Le,$e;const J=((Le=b.queue)==null?void 0:Le.tasks)??(($e=b.queue)==null?void 0:$e.items)??null;return Array.isArray(J)?J:[]},[b.queue]),[R,B]=l.useState(null),[_,H]=l.useState(null),[L,F]=l.useState(null),[$,K]=l.useState({}),[z,ne]=l.useState(null),[ie,Ce]=l.useState(null),me=l.useMemo(()=>new Map(b.nodes.map(J=>[J.nodeId,J])),[b.nodes]),O=l.useMemo(()=>new Map(y.nodes.map(J=>[J.id,J])),[y.nodes]),Y=((We=b.queue)==null?void 0:We.summary)??null,X=((Xe=b.ledger)==null?void 0:Xe.summary)??wM,Q=l.useMemo(()=>DM(b),[b]),ve=l.useMemo(()=>{const J=new Map;for(const Le of Q){const $e=Rr(Le.session);J.set($e,(J.get($e)??0)+1)}return[...J.entries()].sort((Le,$e)=>$e[1]-Le[1])},[Q]);l.useEffect(()=>{R&&(O.has(R)||(B(null),F(J=>!J||"nodeId"in J&&J.nodeId===R?null:J)))},[O,R]);const he=R?me.get(R)??null:null,Z=BM(y,R),fe=(L==null?void 0:L.kind)==="edge"&&_?y.edges.find(J=>J.id===_)??null:null,V=fe?y.nodes.find(J=>J.id===fe.source)??null:null,q=fe?y.nodes.find(J=>J.id===fe.target)??null:null;l.useEffect(()=>{var J,Le,$e;if(R)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:b.meshId,selectedNodeId:R,canonicalNode:sS(he),graphNode:Z?{id:Z.id,branch:Z.branch,upstream:Z.upstream,headCommit:Z.submoduleCommit,submoduleCount:((Le=(J=he==null?void 0:he.git)==null?void 0:J.submodules)==null?void 0:Le.length)??0,snapshotCompleteness:Z.snapshotCompleteness,snapshotWarnings:Z.snapshotWarnings,branchConvergence:(($e=Z.branchConvergence)==null?void 0:$e.status)??null}:null})}catch{}},[b.meshId,Z,R,he]);const ee=(L==null?void 0:L.kind)==="session"?Q.find(J=>J.nodeId===L.nodeId&&J.session.sessionId===L.sessionId)??null:null,pe=l.useMemo(()=>Q.filter(J=>J.nodeId===R),[R,Q]),le=_M({coordinatorDaemonId:n,selectedNodeStatus:he,selectedSessionEntry:ee}),se=(le==null?void 0:le.workspace)??null,te=se?$[se]??null:null,ue=RM(he,(te==null?void 0:te.entries)??[]),ye=(Z==null?void 0:Z.daemonId)??(he==null?void 0:he.daemonId)??n??null,Me=!!(Z&&a&&ye&&Z.type!=="submoduleNode"&&Z.behind>0&&Z.ahead===0&&Z.dirtyFiles===0&&!Z.dirty&&!Z.hasConflicts&&Z.upstreamStatus==="fresh"),re=l.useCallback(()=>{B(null),H(null),F(null),ne(null)},[]);l.useEffect(()=>{ne(null)},[R]);const ce=l.useCallback(async()=>{if(!Z||!ye||!a||!Me)return;Ce(Z.id),ne(null);const J=(he==null?void 0:he.workspace)??Z.workspace??"";try{const Le=await a(ye,"fast_forward_mesh_node",{meshId:b.meshId,nodeId:Z.id,workspace:J,updateSubmodules:!0,dryRun:!0,execute:!1}),$e=(Le==null?void 0:Le.result)??Le;if(ne({phase:"dry_run",code:typeof($e==null?void 0:$e.code)=="string"?$e.code:void 0,error:typeof($e==null?void 0:$e.operationError)=="string"?$e.operationError:null,executed:($e==null?void 0:$e.executed)===!0}),!($e!=null&&$e.success)||$e.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${Z.label}?`))return;const rt=await a(ye,"fast_forward_mesh_node",{meshId:b.meshId,nodeId:Z.id,workspace:J,updateSubmodules:!0,dryRun:!1,execute:!0}),G=(rt==null?void 0:rt.result)??rt;ne({phase:"execute",code:typeof(G==null?void 0:G.code)=="string"?G.code:void 0,error:typeof(G==null?void 0:G.operationError)=="string"?G.operationError:null,executed:(G==null?void 0:G.executed)===!0})}catch(Le){ne({phase:"dry_run",error:Le instanceof Error?Le.message:"fast-forward failed"})}finally{Ce(null)}},[Me,b.meshId,Z,ye,a]);l.useEffect(()=>{if(!Z&&!fe)return;const J=Le=>{Le.key==="Escape"&&re()};return window.addEventListener("keydown",J),()=>window.removeEventListener("keydown",J)},[re,fe,Z]),l.useEffect(()=>{if(!le||!a)return;const{daemonId:J,workspace:Le}=le,$e=$[Le];if($e!=null&&$e.loading||$e&&($e.entries.length>0||$e.error))return;let at=!1;return K(rt=>{var G;return{...rt,[Le]:{loading:!0,error:null,entries:((G=rt[Le])==null?void 0:G.entries)??[]}}}),a(J,"git_log",{workspace:Le,limit:5}).then(rt=>{at||K(G=>({...G,[Le]:{loading:!1,error:null,entries:EM(rt)}}))}).catch(rt=>{at||K(G=>({...G,[Le]:{loading:!1,error:rt instanceof Error?rt.message:"git_log failed",entries:[]}}))}),()=>{at=!0}},[$,le,a]);const Ae=[...y.warnings??[],...b.nodes.filter(J=>J.machineStatus&&J.machineStatus!=="online").map(J=>`${J.machineLabel}: ${J.machineStatus}`)],be=y.stats.incompleteSnapshotNodes>0,we=y.stats.followUpNodes>0?m("meshGraph.obs.headlineFollowUp",{count:y.stats.followUpNodes}):m(be?"meshGraph.obs.headlineIncomplete":"meshGraph.obs.headlineConverged"),_e=y.stats.followUpNodes>0?"danger":be?"warn":"good",[U,Ne]=l.useState("auto"),Ie=J=>J?g.isDark?"rounded-md border border-cyan-400/40 bg-cyan-500/15 px-2 py-0.5 text-cyan-100":"rounded-md border border-sky-400 bg-sky-100 px-2 py-0.5 text-sky-800":g.isDark?"rounded-md border border-white/10 bg-white/[0.03] px-2 py-0.5 text-slate-400 hover:text-slate-200":"rounded-md border border-slate-300 bg-white/80 px-2 py-0.5 text-slate-500 hover:text-slate-800";return s.jsx(_s.Provider,{value:g,children:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[!p&&s.jsx("div",{className:"shrink-0 flex items-center justify-end",children:s.jsx(Qf,{meshTheme:g,activeTab:N,onActiveTabChange:T,helpOpen:A,onHelpOpenChange:I})}),A&&s.jsx(jD,{meshTheme:g,onClose:()=>I(!1)}),s.jsx("div",{className:`${N==="overview"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-3 overflow-y-auto`,children:N==="overview"&&s.jsx(rD,{status:b,daemonId:n,meshId:b.meshId,sendDaemonCommand:a})}),s.jsx("div",{className:`${N==="tasks"?"flex":"hidden"} min-h-0 flex-1 flex-col`,children:s.jsx("div",{className:`${g.cardClass} relative flex min-h-0 flex-1 flex-col overflow-hidden rounded-[28px]`,style:{minHeight:420},children:E?s.jsx("div",{className:"absolute inset-0",children:s.jsx(VP,{tasks:W,status:b,daemonId:n,sendDaemonCommand:a,onQueueMutated:u,onFocusNode:J=>{T("graph"),B(J),H(null),F({kind:"node",nodeId:J})}})}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:m("meshGraph.obs.loadingGraph")})})}),s.jsx("div",{className:`${N==="status"?"flex":"hidden"} min-h-0 flex-1 flex-col overflow-y-auto`,children:N==="status"&&s.jsx(LD,{canonicalStatus:b})}),s.jsx("div",{className:`${N==="notes"?"flex":"hidden"} min-h-0 flex-1 flex-col overflow-y-auto`,children:N==="notes"&&s.jsx(ED,{meshId:b.meshId,daemonId:n,sendDaemonCommand:a})}),s.jsx("div",{className:`${N==="graph"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-4`,children:s.jsxs("div",{className:`${g.cardClass} relative flex min-h-0 flex-1 flex-col rounded-[28px]`,style:{minHeight:480},children:[s.jsxs("div",{className:`relative z-30 max-h-[42dvh] overflow-y-auto sm:max-h-none sm:mb-3 sm:overflow-visible shrink-0 flex flex-wrap items-start justify-between gap-2 px-4 pt-3 pb-2.5 border-b ${g.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:`flex w-full min-w-0 basis-full flex-wrap gap-2 text-xs sm:w-auto sm:flex-1 sm:basis-auto ${g.textSecondary}`,children:[s.jsx(ze,{label:we,tone:_e,className:"shrink-0"}),y.stats.blockedReviewNodes>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeBlocked",{count:y.stats.blockedReviewNodes}),title:m("meshGraph.obs.badgeBlockedTitle",{count:y.stats.blockedReviewNodes}),tone:"danger",className:"shrink-0"}),y.stats.notMergeableNodes>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeNotMergeable",{count:y.stats.notMergeableNodes}),tone:"danger",className:"shrink-0"}),y.stats.mergeReadyNodes>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeNeedMerge",{count:y.stats.mergeReadyNodes}),tone:"warn",className:"shrink-0"}),y.stats.cleanupCandidateNodes>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeCleanup",{count:y.stats.cleanupCandidateNodes}),title:m("meshGraph.obs.badgeCleanupTitle",{count:y.stats.cleanupCandidateNodes}),tone:"info",className:"shrink-0"}),y.stats.offlineNodes>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeOffline",{count:y.stats.offlineNodes}),tone:"danger",className:"shrink-0"}),y.stats.incompleteSnapshotNodes>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeIncomplete",{count:y.stats.incompleteSnapshotNodes}),title:m("meshGraph.obs.badgeIncompleteTitle",{count:y.stats.incompleteSnapshotNodes}),tone:"warn",className:"shrink-0"}),y.stats.missingGitSnapshotNodes>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeNoGit",{count:y.stats.missingGitSnapshotNodes}),title:m("meshGraph.obs.badgeNoGitTitle",{count:y.stats.missingGitSnapshotNodes}),tone:"warn",className:"shrink-0"}),y.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeNoSubmod",{count:y.stats.missingSubmoduleSnapshotNodes}),title:m("meshGraph.obs.badgeNoSubmodTitle",{count:y.stats.missingSubmoduleSnapshotNodes}),tone:"warn",className:"shrink-0"}),y.stats.staleGitSnapshotNodes>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeStale",{count:y.stats.staleGitSnapshotNodes}),title:m("meshGraph.obs.badgeStaleTitle",{count:y.stats.staleGitSnapshotNodes}),tone:"warn",className:"shrink-0"}),((Y==null?void 0:Y.active)??0)>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeActiveQueue",{count:(Y==null?void 0:Y.active)??0}),tone:"info",className:"shrink-0 hidden sm:inline-flex"}),s.jsx(ze,{label:m("meshGraph.obs.badgeNodes",{count:y.stats.totalNodes}),tone:"default",className:"shrink-0 hidden sm:inline-flex"}),y.stats.totalActiveSessions>0&&s.jsx(ze,{label:m("meshGraph.obs.badgeAttachedChats",{count:y.stats.totalActiveSessions}),tone:"info",className:"shrink-0 hidden sm:inline-flex"})]}),s.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-2",children:[s.jsxs("div",{className:g.isDark?"flex items-center gap-0.5 rounded-md border border-white/10 bg-slate-950/40 p-0.5 text-[10px]":"flex items-center gap-0.5 rounded-md border border-slate-300 bg-white/70 p-0.5 text-[10px]",role:"group","aria-label":"Graph layout direction",children:[s.jsx("button",{type:"button",onClick:()=>Ne("auto"),className:Ie(U==="auto"),title:m("meshGraph.obs.directionAutoTitle"),children:m("meshGraph.obs.directionAuto")}),s.jsx("button",{type:"button",onClick:()=>Ne("LR"),className:Ie(U==="LR"),title:m("meshGraph.obs.directionLRTitle"),children:"LR"}),s.jsx("button",{type:"button",onClick:()=>Ne("TB"),className:Ie(U==="TB"),title:m("meshGraph.obs.directionTBTitle"),children:"TB"})]}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${g.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${g.textSecondary} [&::-webkit-details-marker]:hidden`,children:(()=>{var $e;const J=(($e=b.asyncRefineJobs)==null?void 0:$e.filter(at=>at.status==="failed").length)??0,Le=X.recentFailures;return J>0?s.jsx("span",{className:g.isDark?"text-rose-300":"text-rose-600",children:m("meshGraph.obs.healthRefineFailed",{count:J})}):Le>0?s.jsx("span",{className:g.isDark?"text-amber-300":"text-amber-600",children:m("meshGraph.obs.healthFailures",{count:Le})}):m("meshGraph.obs.health")})()}),s.jsx("div",{className:`fixed inset-x-4 top-28 z-50 max-h-[70dvh] overflow-y-auto rounded-xl border p-4 shadow-xl backdrop-blur-xl sm:absolute sm:inset-x-auto sm:right-0 sm:top-auto sm:mt-2 sm:w-72 ${g.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsx(_D,{canonicalStatus:b,queueSummary:Y,ledgerSummary:X,isBootstrapMode:S,meshTheme:g,sessionEntries:Q,inlineMode:!0})})]})}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${g.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${g.textSecondary} [&::-webkit-details-marker]:hidden`,children:m("meshGraph.obs.legend")}),s.jsx("div",{className:`fixed inset-x-4 top-28 z-50 max-h-[70dvh] overflow-y-auto rounded-xl border p-3 shadow-xl backdrop-blur-xl sm:absolute sm:inset-x-auto sm:right-0 sm:top-auto sm:mt-2 sm:w-72 sm:max-h-none sm:overflow-visible ${g.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(ze,{label:m("meshGraph.obs.legendDirty",{count:y.stats.dirtyNodes}),tone:y.stats.dirtyNodes>0?"warn":"good"}),s.jsx(ze,{label:m("meshGraph.obs.legendOrphan",{count:y.stats.orphanNodes}),tone:y.stats.orphanNodes>0?"warn":"good"}),s.jsx(ze,{label:m("meshGraph.obs.legendRecentFailures",{count:X.recentFailures}),tone:X.recentFailures>0?"danger":"good"}),ve.length===0?s.jsx(ze,{label:m("meshGraph.obs.legendNoSessionMeta")}):ve.slice(0,2).map(([J,Le])=>s.jsx(ze,{label:`${Le} ${J}`,tone:gi(J)},J))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(ze,{label:m("meshGraph.obs.legendAnchor"),tone:"info"}),s.jsx(ze,{label:m("meshGraph.obs.legendPeerLink"),tone:"default"}),s.jsx(ze,{label:m("meshGraph.obs.legendSubmoduleLink"),tone:"warn"})]}),Ae.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:Ae.map(J=>s.jsx("span",{className:g.isDark?"rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1 text-xs text-amber-100":"rounded-full border border-amber-300 bg-amber-50 px-3 py-1 text-xs text-amber-700",children:J},J))}),s.jsx("div",{className:`text-xs ${g.textMuted}`,children:m("meshGraph.obs.legendClickHint")})]})})]})})]})]}),S&&y.nodes.length>0&&s.jsxs("div",{className:`shrink-0 mx-4 mt-2 flex items-center gap-2 rounded-xl border px-3.5 py-2 text-xs ${g.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full animate-pulse ${g.isDark?"bg-amber-400":"bg-amber-500"}`,"aria-hidden":!0}),s.jsx("span",{children:m("meshGraph.obs.bootstrapBanner")})]}),s.jsxs("div",{className:"relative flex flex-1 min-w-0",style:{minHeight:360},children:[s.jsx("div",{className:"flex-1 min-w-0",children:P?y.nodes.length>0?s.jsx(SP,{data:y,selectedNodeId:R,directionPref:U,onNodeClick:J=>{if((L==null?void 0:L.kind)==="node"&&R===J.id){re();return}H(null),B(J.id),F({kind:"node",nodeId:J.id})},onEdgeClick:J=>{if((L==null?void 0:L.kind)==="edge"&&_===J.id){re();return}B(null),H(J.id),F({kind:"edge",edgeId:J.id})}}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:h}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:m("meshGraph.obs.loadingGraph")})}),Z&&(L==null?void 0:L.kind)==="node"&&s.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${g.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${g.textMuted}`,children:m("meshGraph.obs.selectedNode")}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${g.textPrimary}`,children:Z.label}),s.jsx("div",{className:`mt-0.5 font-mono text-[11px] ${g.textMuted}`,children:Z.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[Z.behind>0&&s.jsx("button",{type:"button",onClick:()=>{ce()},disabled:!Me||ie===Z.id,className:g.isDark?"rounded-full border border-emerald-400/25 bg-emerald-500/10 px-2 py-0.5 text-xs font-semibold text-emerald-100 transition hover:bg-emerald-500/18 disabled:cursor-not-allowed disabled:opacity-45":"rounded-full border border-emerald-300 bg-emerald-50 px-2 py-0.5 text-xs font-semibold text-emerald-700 transition hover:bg-emerald-100 disabled:cursor-not-allowed disabled:opacity-45",children:ie===Z.id?m("meshGraph.obs.checking"):m("meshGraph.obs.heal")}),s.jsx("button",{type:"button",onClick:re,"aria-label":"Close detail panel",className:g.isDark?"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[(()=>{const J=(he==null?void 0:he.health)??Z.health;return J==="unknown"?s.jsx(ze,{label:m("meshGraph.obs.connecting"),tone:"default"}):s.jsx(ze,{label:J,tone:Df(J)})})(),Z.branch&&s.jsx(ze,{label:Z.branch,tone:"default"}),Z.ahead>0&&s.jsx(ze,{label:`ahead ${Z.ahead}`,tone:"warn"}),Z.behind>0&&s.jsx(ze,{label:`behind ${Z.behind}`,tone:"warn"}),Z.dirtyFiles>0&&s.jsx(ze,{label:`${Z.dirtyFiles} dirty`,tone:"warn"}),(he==null?void 0:he.connection)&&he.connection.state!=="unknown"&&s.jsx(ze,{label:HM(he),tone:SM(he.connection)}),((et=he==null?void 0:he.connection)==null?void 0:et.state)==="unknown"&&s.jsx(ze,{label:m("meshGraph.obs.meshConnecting"),tone:"warn"}),pe.length>0&&s.jsx(ze,{label:`${pe.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[Z.machineLabel&&s.jsx(Ht,{label:m("meshGraph.obs.fieldMachine"),value:Z.machineLabel}),Z.locality&&Z.locality!=="unknown"&&s.jsx(Ht,{label:m("meshGraph.obs.fieldLocality"),value:Z.locality}),s.jsx(Ht,{label:m("meshGraph.obs.fieldWorkspace"),value:(he==null?void 0:he.workspace)??Z.workspace}),ue&&s.jsx(Ht,{label:m("meshGraph.obs.fieldHead"),value:ue}),(Z.dirtyFiles>0||Z.ahead>0||Z.behind>0)&&s.jsx(Ht,{label:m("meshGraph.obs.fieldDirtyAheadBehind"),value:`${Z.dirtyFiles}/${Z.ahead}/${Z.behind}`}),pe.length>0&&s.jsx(Ht,{label:m("meshGraph.obs.fieldSessions"),value:String(pe.length)}),Z.upstream&&s.jsx(Ht,{label:m("meshGraph.obs.fieldUpstream"),value:Z.upstream}),(()=>{var Le;const J=((Le=he==null?void 0:he.connection)==null?void 0:Le.source)??$M(Z);return J&&J!=="unknown"?s.jsx(Ht,{label:m("meshGraph.obs.fieldSource"),value:String(J)}):null})(),(()=>{var Le;const J=(Le=he==null?void 0:he.connection)==null?void 0:Le.transport;return J&&J!=="unknown"?s.jsx(Ht,{label:m("meshGraph.obs.fieldTransport"),value:J}):null})(),(()=>{const J=Z.machineId??(he==null?void 0:he.machineId);return J?s.jsx(Ht,{label:m("meshGraph.obs.fieldMachineId"),value:J}):null})(),(()=>{const J=Z.daemonId??(he==null?void 0:he.daemonId);return J?s.jsx(Ht,{label:m("meshGraph.obs.fieldDaemonId"),value:J}):null})()]}),pe.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${g.textMuted}`,children:m("meshGraph.obs.activeSessions")}),s.jsx("div",{className:"flex flex-col gap-1.5",children:pe.map(J=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${g.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono select-text ${g.textMuted}`,title:J.session.sessionId,children:Lf(J.session.sessionId)}),s.jsx(ze,{label:Rr(J.session),tone:gi(Rr(J.session))})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 ${g.textMuted}`,children:[s.jsx("span",{className:"truncate",children:J.session.providerType||m("meshGraph.obs.providerUnknown")}),s.jsx("span",{children:If(J.session)}),s.jsx("span",{children:so(J.session)})]}),J.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${g.textMuted}`,children:J.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${g.textMuted}`,title:J.session.workspace||J.workspace,children:[(J.session.workspace||J.workspace).slice(0,38),J.branch?` · ${J.branch}`:""]})]},J.session.sessionId))})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${g.textMuted}`,children:m("meshGraph.obs.ledger")}),s.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[s.jsx(Ht,{label:m("meshGraph.obs.fieldCompleted"),value:String(X.taskCompleted)}),s.jsx(Ht,{label:m("meshGraph.obs.fieldFailed"),value:s.jsx("span",{className:X.taskFailed>0?g.isDark?"text-rose-300":"text-rose-600":"",children:X.taskFailed})}),s.jsx(Ht,{label:m("meshGraph.obs.fieldLaunched"),value:String(X.sessionLaunched)}),s.jsx(Ht,{label:m("meshGraph.obs.fieldRecentFailures"),value:s.jsx("span",{className:X.recentFailures>0?g.isDark?"text-amber-300":"text-amber-600":"",children:X.recentFailures})})]})]}),(()=>{var $e,at;const J=(($e=b.queue)==null?void 0:$e.tasks)??((at=b.queue)==null?void 0:at.items)??null;if(!Array.isArray(J)||J.length===0)return null;const Le=J.filter(rt=>IM(rt)===R).slice(0,3);return Le.length===0?null:s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${g.textMuted}`,children:m("meshGraph.obs.queueTasks")}),s.jsx("div",{className:"flex flex-col gap-1.5",children:Le.map(rt=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${g.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`font-mono ${g.textMuted}`,children:rt.id.slice(0,12)}),s.jsx(ze,{label:rt.status??"unknown",tone:gi(rt.status)})]}),rt.message&&s.jsx("div",{className:`mt-0.5 truncate ${g.textMuted}`,children:rt.message.slice(0,48)})]},rt.id))})]})})(),Z.snapshotWarnings.length>0&&s.jsxs("div",{className:g.isDark?"mt-3 rounded-xl border border-amber-400/20 bg-amber-500/10 p-3 text-xs text-amber-100":"mt-3 rounded-xl border border-amber-300 bg-amber-50 p-3 text-xs text-amber-800",children:[s.jsx("div",{className:"font-medium",children:m("meshGraph.obs.keyWarning")}),s.jsx("div",{className:"mt-1",children:Z.snapshotWarnings[0]})]}),Z.branchConvergence&&(Z.branchConvergence.reason||Z.branchConvergence.nextStep)&&s.jsxs("div",{className:g.isDark?"mt-3 rounded-xl border border-sky-400/20 bg-sky-500/10 p-3 text-xs text-sky-100":"mt-3 rounded-xl border border-sky-300 bg-sky-50 p-3 text-xs text-sky-800",children:[s.jsx("div",{className:"font-medium",children:m("meshGraph.obs.followUpLabel",{status:k[Z.branchConvergence.status]??Z.branchConvergence.status})}),Z.branchConvergence.reason&&s.jsx("div",{className:"mt-1",children:Z.branchConvergence.reason}),Z.branchConvergence.nextStep&&s.jsx("div",{className:`${Z.branchConvergence.reason?"mt-1.5 pt-1.5 border-t border-sky-400/20":"mt-1"}`,children:Z.branchConvergence.nextStep})]}),z&&s.jsxs("div",{className:g.isDark?"mt-3 rounded-xl border border-emerald-400/20 bg-emerald-500/10 p-3 text-xs text-emerald-100":"mt-3 rounded-xl border border-emerald-300 bg-emerald-50 p-3 text-xs text-emerald-800",children:[s.jsx("div",{className:"font-medium",children:z.phase==="execute"?m("meshGraph.obs.healResult"):m("meshGraph.obs.healPreview")}),s.jsx("div",{className:"mt-1",children:z.code??z.error??m("meshGraph.obs.noResultCode")})]})]}),fe&&(L==null?void 0:L.kind)==="edge"&&s.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${g.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${g.textMuted}`,children:m("meshGraph.obs.selectedEdge")}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${g.textPrimary}`,children:fe.label||ju(fe)}),s.jsx("div",{className:`mt-0.5 break-all font-mono text-[11px] ${g.textMuted}`,children:fe.id})]}),s.jsx("button",{type:"button",onClick:re,"aria-label":"Close detail panel",className:g.isDark?"shrink-0 rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"shrink-0 rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[s.jsx(ze,{label:ju(fe),tone:"default"}),s.jsx(ze,{label:FM(fe),tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(Ht,{label:m("meshGraph.obs.fieldFrom"),value:(V==null?void 0:V.label)??fe.source}),s.jsx(Ht,{label:m("meshGraph.obs.fieldTo"),value:(q==null?void 0:q.label)??fe.target}),s.jsx(Ht,{label:m("meshGraph.obs.fieldLabel"),value:fe.label??"none"})]})]})]})]})})]})})}function At(e){return typeof e=="string"?e.trim():""}function kl(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Tc(...e){const t=new Set;for(const n of e){const a=At(n);a&&t.add(a)}return[...t]}function $D(e,t){var m,f;const n=kl(e==null?void 0:e.settings),a=At((m=e==null?void 0:e.coordinator)==null?void 0:m.meshId)||At(n.meshCoordinatorFor),r=At(n.meshNodeFor),o=!!a||!!r,i=a===t||r===t;if(o&&!i)return null;const c=kl(e==null?void 0:e.activeChat),d=Tc(e==null?void 0:e.id,e==null?void 0:e.sessionId,e==null?void 0:e.session_id,e==null?void 0:e.providerSessionId,e==null?void 0:e.provider_session_id,e==null?void 0:e.targetSessionId,e==null?void 0:e.target_session_id,c.sessionId,c.session_id,c.providerSessionId,c.provider_session_id),p=d[0]||"";if(!p)return null;const u=a===t?At((f=e==null?void 0:e.coordinator)==null?void 0:f.role)||"coordinator":r===t?At(n.meshNodeRole)||"worker":At(e==null?void 0:e.role)||At(n.meshNodeRole)||void 0;return{sessionId:p,aliases:d,meshId:t,nodeId:i&&At(n.meshNodeId)||null,providerType:At(e==null?void 0:e.providerType)||void 0,state:At(e==null?void 0:e.status)||void 0,chatStatus:At(c.status)||void 0,lifecycle:At(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:At(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:At(e==null?void 0:e.runtimeRecoveryState)||void 0,...u?{role:u}:{},...i?{isSelfCoordinator:a===t}:{},workspace:At(e==null?void 0:e.workspace)||null}}function Jf(e,t){var a;return t?(Array.isArray((a=e.status)==null?void 0:a.sessions)?e.status.sessions:[]).map(r=>$D(r,t)).filter(r=>r!==null):[]}function ao(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function FD(e,t){const n=new Set(ao(t));return ao(e).some(a=>n.has(a))}function BD(e,t){const n=t.filter(r=>!!r);return n.length===0?e:[...e.filter(r=>!n.some(o=>FD(r,o))),...n]}function WD(e,t){if(t.length===0)return e;const n=new Map;for(const i of t)for(const c of ao(i))n.set(c,i);let a=!1;const o=(e.nodes??[]).map((i,c)=>{const d=Array.isArray(i.activeSessionDetails)?i.activeSessionDetails:Array.isArray(i.sessions)?i.sessions:[],p=new Map;for(const f of d){const g=Tc(f==null?void 0:f.sessionId,f==null?void 0:f.session_id,f==null?void 0:f.id,f==null?void 0:f.providerSessionId,f==null?void 0:f.provider_session_id),k=g[0]||"";if(!k)continue;const h=g.map(b=>n.get(b)).find(Boolean);h&&(a=!0),p.set(k,h?{...f,sessionId:k,providerType:h.providerType||f.providerType,state:h.state||f.state,chatStatus:h.chatStatus||f.chatStatus,lifecycle:h.lifecycle||f.lifecycle,surfaceKind:h.surfaceKind||f.surfaceKind,recoveryState:h.recoveryState||f.recoveryState,role:h.role||f.role,isSelfCoordinator:h.isSelfCoordinator??f.isSelfCoordinator,workspace:h.workspace||f.workspace}:{...f,sessionId:k})}for(const f of i.activeSessions??[])p.has(f)||p.set(f,{sessionId:f,workspace:i.workspace,isCached:!0});const u=c===0;for(const f of t){if(ao(f).some(b=>p.has(b)))continue;const k=f.nodeId!=null&&f.nodeId===i.nodeId,h=f.isSelfCoordinator&&!f.nodeId&&u;!k&&!h||(a=!0,p.set(f.sessionId,{sessionId:f.sessionId,providerType:f.providerType,state:f.state,chatStatus:f.chatStatus,lifecycle:f.lifecycle,surfaceKind:f.surfaceKind,recoveryState:f.recoveryState,role:f.role,isSelfCoordinator:f.isSelfCoordinator,workspace:f.workspace||i.workspace}))}const m=[...p.values()];return m.length===0?i:{...i,activeSessionDetails:m,activeSessions:m.map(f=>f.sessionId)}});return a?{...e,nodes:o}:e}function OD(e,t){const a=Jf(e,t).map(r=>{var d;const o=(Array.isArray((d=e.status)==null?void 0:d.sessions)?e.status.sessions:[]).find(p=>At(p==null?void 0:p.id)===r.sessionId),i=kl(o==null?void 0:o.activeInteractivePrompt),c=o!=null&&o.meshQueueStats&&typeof o.meshQueueStats=="object"?JSON.stringify(o.meshQueueStats):"";return[r.sessionId,r.providerType??"",r.state??"",r.chatStatus??"",r.lifecycle??"",r.surfaceKind??"",r.recoveryState??"",At(i.status)||At(i.kind)||At(i.type),r.nodeId??"",r.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(r=>!!r).sort();return a.length>0?a.join(`
89
89
  `):null}function Xf({status:e,daemonId:t,extraDaemonIds:n,meshId:a,sendData:r,extraLiveSessions:o=[]}){const[i,c]=l.useState(new Map),d=l.useRef(new Map),p=l.useMemo(()=>{const g=new Set;if(t&&g.add(t),n)for(const k of n)k&&g.add(k);return[...g].sort()},[t,n]),u=p.join(",");l.useEffect(()=>{d.current=new Map,c(new Map)},[t,a]),l.useEffect(()=>{if(!a||!r||p.length===0)return;const g=p.map(k=>ys.subscribe({sendData:r},k,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${k}`,params:{includeSessions:!0}},h=>{if(h.topic!=="daemon.metadata")return;const b=OD(h,a);if(b===(d.current.get(k)??null))return;d.current.set(k,b);const S=Jf(h,a);c(x=>{const y=new Map(x);return y.set(k,S),y})}));return()=>{for(const k of g)k()}},[u,a,r]);const m=l.useMemo(()=>{const g=[];for(const k of i.values())g.push(...k);return g},[i]),f=l.useMemo(()=>BD(m,o),[o,m]);return l.useMemo(()=>e?WD(e,f):null,[f,e])}const Fu=[1500,4e3,9e3];function UD(e){var t,n,a,r,o,i;return!!(((t=e.git)==null?void 0:t.isGitRepo)===!0||(n=e.git)!=null&&n.branch||(a=e.git)!=null&&a.upstream||(r=e.git)!=null&&r.headCommit||(o=e.git)!=null&&o.workspace||(i=e.git)!=null&&i.repoRoot)}function GD(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>{var n;return UD(t)?!1:t.gitProbePending||((n=t.connection)==null?void 0:n.state)==="connecting"?!0:t.machineStatus==="online"||t.launchReady===!0})}function qD(e){return!Number.isInteger(e)||e<0?Fu[0]:Fu[e]??null}const Ni=new Map;function zD(e,t){return!e||!t?null:`${e}::${t}`}function KD(e,t){var o,i,c,d;if(!t||!e.sessionId)return null;const n=((o=e.coordinator)==null?void 0:o.meshId)??(typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),a=typeof((c=e.settings)==null?void 0:c.meshNodeFor)=="string"?e.settings.meshNodeFor:null;if(n!==t&&a!==t)return null;const r=typeof((d=e.settings)==null?void 0:d.meshNodeId)=="string"?e.settings.meshNodeId:null;return{sessionId:e.sessionId,aliases:Tc(e.sessionId,e.providerSessionId,e.historySessionId,e.nativeSessionId),meshId:t,nodeId:r,providerType:e.agentType,state:e.status,chatStatus:e.status,role:n===t?"coordinator":"worker",isSelfCoordinator:n===t,workspace:e.workspacePath??null}}function Zf({activeConv:e,sendDaemonCommand:t,onClose:n}){var ne,ie,Ce,me,O,Y;const a=((ne=e.coordinator)==null?void 0:ne.meshId)??(typeof((ie=e.settings)==null?void 0:ie.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),r=e.daemonId??null,o=zD(r,a),i=o?Ni.get(o)??null:null,{t:c}=ke("common"),d=Ql(),{sendData:p}=St(),{theme:u}=Rs(),m=l.useMemo(()=>Es(u),[u]),[f,g]=l.useState("overview"),[k,h]=l.useState(!1),b=l.useMemo(()=>KD(e,a),[e.agentType,(Ce=e.coordinator)==null?void 0:Ce.meshId,e.sessionId,(me=e.settings)==null?void 0:me.meshCoordinatorFor,(O=e.settings)==null?void 0:O.meshNodeFor,(Y=e.settings)==null?void 0:Y.meshNodeId,e.status,e.workspacePath,a]),[S,x]=l.useState(i),[y,C]=l.useState(!1),[v,w]=l.useState(!1),[j,N]=l.useState(!1),[A,T]=l.useState(null),[I,P]=l.useState((i==null?void 0:i.refreshedAt)??null),M=l.useRef(i!==null),E=l.useRef(!1),D=l.useRef(!1),W=l.useRef(!0),R=l.useRef(0),B=l.useRef(null);l.useEffect(()=>{M.current=S!==null},[S]);const _=l.useCallback(()=>{B.current!==null&&(clearTimeout(B.current),B.current=null)},[]);l.useEffect(()=>{_(),R.current=0;const X=o?Ni.get(o)??null:null;x(X),P((X==null?void 0:X.refreshedAt)??null),M.current=X!==null,D.current=!1,w(!1),T(null)},[o,_]);const H=l.useCallback(async(X=!1,Q=!1)=>{if(!r||!a){T(c("meshGraph.dialog.errorNoMeshId")),x(null);return}if(E.current){X&&(D.current=!0);return}Q||(_(),R.current=0),E.current=!0;const ve=!M.current;C(ve),w(X&&M.current),T(null);try{const he=d!=null&&d.loadMeshStatus?await d.loadMeshStatus(r,a,{refresh:X,retryProfile:Q?"interactive":"settled"}):await t(r,"mesh_status",{meshId:a,refresh:X}),Z=Xl(he);if(!Z){T(c("meshGraph.dialog.errorUnexpectedPayload"));return}if(o&&Ni.set(o,Z),x(Z),M.current=!0,P(Z.refreshedAt||new Date().toISOString()),GD(Z.nodes)){const fe=qD(R.current);fe!==null&&W.current&&(R.current+=1,B.current=setTimeout(()=>{W.current&&H(!0,!0)},fe))}else R.current=0}catch(he){T(he instanceof Error?he.message:"Failed to load live mesh status")}finally{E.current=!1,C(!1),w(!1),D.current&&W.current&&(D.current=!1,window.setTimeout(()=>{W.current&&H(!0)},0))}},[o,_,r,a,d,t]);l.useEffect(()=>(W.current=!0,R.current=0,(async()=>(await H(!1,!0),W.current&&B.current===null&&!E.current&&H(!0,!0)))(),()=>{W.current=!1,_()}),[H,_]),l.useEffect(()=>{const X=Q=>{Q.key==="Escape"&&n()};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[n]),l.useEffect(()=>{const Q=window.setInterval(()=>{document.hidden||E.current||H(!0,!0)},45e3);return()=>window.clearInterval(Q)},[H]);const L=(S==null?void 0:S.meshName)||a||"Repo Mesh",F=l.useMemo(()=>b?[b]:[],[b]),$=Xf({status:S,daemonId:r,meshId:a,sendData:p,extraLiveSessions:F}),K=I?new Date(I).toLocaleTimeString():null,z=l.useMemo(()=>c(y?"meshGraph.dialog.loadingStatus":"meshGraph.dialog.noGraph"),[y,c]);return s.jsx("div",{className:m.dialogOverlayClass,onClick:n,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:m.dialogShellClass,onClick:X=>X.stopPropagation(),children:[s.jsxs("div",{className:`relative ${m.dialogHeaderClass}`,children:[s.jsx("button",{type:"button",onClick:n,className:`absolute right-4 top-[calc(16px+env(safe-area-inset-top,0px))] z-10 md:right-5 md:top-1/2 md:-translate-y-1/2 ${m.dialogCloseButtonClass}`,"aria-label":"Close mesh graph",children:s.jsx(Dt,{size:16})}),s.jsx("div",{className:"min-w-0 flex-1 pr-12 md:pr-0",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-400/20 bg-sky-500/12 text-sky-200 shadow-[0_12px_30px_rgba(14,165,233,0.18)]",children:s.jsx(cs,{size:18})}),s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("h2",{className:m.dialogTitleClass,children:L}),s.jsx("span",{className:m.dialogKickerClass,children:c("meshGraph.dialog.kicker")}),s.jsx("button",{type:"button",onClick:()=>N(X=>!X),"aria-expanded":j,"aria-label":c(j?"meshGraph.dialog.hideDetails":"meshGraph.dialog.showDetails"),className:"btn btn-secondary btn-sm rounded-lg px-1.5 py-1 md:hidden",title:c(j?"meshGraph.dialog.hideDetails":"meshGraph.dialog.showDetails"),children:s.jsx(uo,{size:14})})]}),s.jsxs("p",{className:`${m.dialogSubtitleClass} ${j?"block":"hidden"} md:block`,children:[kt(e),e.workspaceName?` · ${e.workspaceName}`:"",S!=null&&S.repoIdentity?` · ${S.repoIdentity}`:"",K?` · ${c("meshGraph.dialog.refreshedAt",{time:K})}`:"",!v&&S?` · ${c(p&&!A?"meshGraph.dialog.liveMetadata":"meshGraph.dialog.metadataUnavailable")}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end md:pr-12",children:[s.jsx(Qf,{meshTheme:m,activeTab:f,onActiveTabChange:g,helpOpen:k,onHelpOpenChange:h}),s.jsx("button",{type:"button",onClick:()=>{H(!0)},disabled:y||v,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:c("meshGraph.dialog.refreshTitle"),children:c(y||v?"meshGraph.dialog.refreshing":"meshGraph.dialog.refresh")})]})]}),A&&s.jsx("div",{className:m.isDark?"shrink-0 border-b border-rose-400/20 bg-rose-500/12 px-4 py-2 text-sm text-rose-200 md:px-5":"shrink-0 border-b border-rose-300 bg-rose-50 px-4 py-2 text-sm text-rose-700 md:px-5",children:A}),s.jsx("div",{className:m.dialogBodyClass,children:$?s.jsx(HD,{status:$,emptyMessage:z,daemonId:r,sendDaemonCommand:t,activeTab:f,onActiveTabChange:g,helpOpen:k,onHelpOpenChange:h,hideControls:!0,onRequestRefresh:()=>{H(!0)}}):s.jsx("div",{className:m.dialogEmptyClass,children:z})})]})})}function VD(e,t){const{sendCommand:n}=St(),[a,r]=l.useState(null),[o,i]=l.useState(!1);l.useEffect(()=>{if(!e||!t){r(null);return}i(!0),n(e,"git_remote_url",{workspace:t}).then(d=>{const p=(d==null?void 0:d.result)??d;r(typeof(p==null?void 0:p.remoteUrl)=="string"?p.remoteUrl:null)}).catch(()=>{r(null)}).finally(()=>i(!1))},[e,t,n]);const c=YD(a);return{remoteUrl:a,githubUrl:c,loading:o}}function YD(e){if(!e)return null;const t=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(t)return`https://github.com/${t[1]}`;const n=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return n?`https://github.com/${n[1]}`:null}const eg=5e3;function QD(e){return`git:${e}`}function JD({workspace:e,includeDiffSummary:t=!1,intervalMs:n=eg}){return{type:"subscribe",topic:"workspace.git",key:QD(e),params:{workspace:e,includeDiffSummary:t,intervalMs:n}}}function Mc(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Rn(e,t){if(e instanceof Error)return e.message;if(e&&typeof e=="object"){const n=e;if(typeof n.error=="string"&&n.error.trim())return n.error;if(typeof n.message=="string"&&n.message.trim())return n.message}return t}function XD(e){const t=Mc(e);return(t==null?void 0:t.success)===!1?{status:null,error:Rn(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Rn(t,"Git status response did not include status")}}function ZD(e){const t=Mc(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Rn(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Rn(t,"Git diff summary response did not include diffSummary")}}function Ai(e){return e===void 0||typeof e=="boolean"}function eI(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Ai(t.binary)&&Ai(t.truncated)&&Ai(t.staged)}function tI(e){const t=Mc(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Rn(t,"Git file diff request failed")}:eI(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Rn(t,"Git file diff response did not include a valid diff object")}}function sI({daemonId:e,workspace:t,enabled:n=!0,includeDiffSummary:a=!1,intervalMs:r=eg}){const{sendCommand:o,sendData:i}=St(),c=typeof t=="string"?t.trim():"",d=!!(n&&e&&c),[p,u]=l.useState(null),[m,f]=l.useState(null),[g,k]=l.useState(!1),[h,b]=l.useState(null),S=l.useCallback(async()=>{if(!(!d||!e||!c)){k(!0),b(null);try{const y=XD(await o(e,"git_status",{workspace:c}));if(y.error){u(null),f(null),b(y.error);return}if(u(y.status),!a){f(null);return}const C=ZD(await o(e,"git_diff_summary",{workspace:c}));if(C.error){f(null),b(C.error);return}f(C.diffSummary)}catch(y){b(Rn(y,"Git status request failed"))}finally{k(!1)}}},[d,e,a,o,c]),x=l.useMemo(()=>c?JD({workspace:c,includeDiffSummary:a,intervalMs:r}):null,[a,r,c]);return l.useEffect(()=>{if(!d||!e||!c||!x){u(null),f(null),k(!1),b(null);return}const y=i?ys.subscribe({sendData:i},e,x,C=>{var v,w;C.workspace===c&&(u(C.status),f(C.diffSummary??null),b(((v=C.status)==null?void 0:v.error)||((w=C.diffSummary)==null?void 0:w.error)||null),k(!1))},{retryIntervalMs:1e3}):null;return S(),()=>{y==null||y()}},[d,e,S,x,i,c]),{status:p,diffSummary:m,loading:g,error:h,refresh:S}}const nI={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},aI={added:"text-status-online",modified:"text-orange-400",deleted:"text-status-error",renamed:"text-accent-primary",copied:"text-accent-primary",untracked:"text-text-muted",conflict:"text-status-error font-bold"};function Bu(e){return e.split("/").pop()??e}function rI(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function oI({files:e,truncated:t,onFileClick:n,selectedPath:a,className:r=""}){const{t:o}=ke("common");return e.length===0?s.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:"No changed files."}):s.jsxs("div",{className:`flex flex-col ${r}`,children:[s.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(i=>{const c=a===i.path,d=nI[i.status]??"?",p=aI[i.status]??"text-text-muted",u=rI(i.path),m=Bu(i.path),f=i.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-status-online align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${c?"bg-surface-elevated":""}`,onClick:()=>n==null?void 0:n(i),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${p}`,title:i.status,children:d}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[u&&s.jsxs("span",{className:"text-text-secondary",children:[u,"/"]}),s.jsx("span",{className:"text-text-primary",children:m}),i.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",Bu(i.oldPath)]}),f]}),!i.binary&&(i.insertions>0||i.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[i.insertions>0&&s.jsxs("span",{className:"text-status-online",children:["+",i.insertions]}),i.insertions>0&&i.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),i.deletions>0&&s.jsxs("span",{className:"text-status-error",children:["-",i.deletions]})]}),i.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:o("git.changeList.binaryBadge")})]},`${i.path}-${i.staged?"S":"U"}`)})}),t&&s.jsx("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:s.jsx(Fg,{i18nKey:"git.changeList.truncatedNote",ns:"common",components:{code:s.jsx("code",{className:"font-mono"})}})})]})}function iI(e,t){let n="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?n="bg-status-online/10 text-status-online":e.startsWith("-")&&!e.startsWith("---")?n="bg-status-error/10 text-status-error":e.startsWith("@@")?n="text-accent-primary":(e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ "))&&(n="text-text-secondary"),s.jsx("div",{className:`px-3 ${n}`,children:s.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},t)}function lI({diff:e,binary:t,truncated:n,loading:a,error:r,className:o=""}){const i=l.useRef(null);if(l.useEffect(()=>{i.current&&(i.current.scrollTop=0)},[e]),a)return s.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${o}`,children:"Loading diff…"});if(r)return s.jsx("div",{className:`px-3 py-4 text-xs text-status-error ${o}`,children:r});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"No diff available."});const c=e.split(`
90
90
  `);return s.jsxs("div",{ref:i,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((d,p)=>iI(d,p))}),n&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary border-t border-border/30",children:["Diff truncated — run ",s.jsx("code",{className:"font-mono",children:"git diff"})," locally for full output."]})]})}function cI(e,t){const n=[`Branch: ${e||"unknown"}`];n.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const a={};for(const r of t.files)a[r.status]||(a[r.status]=[]),a[r.status].push(r.path);for(const[r,o]of Object.entries(a))n.push(`${r}: ${o.slice(0,5).join(", ")}${o.length>5?` (+${o.length-5} more)`:""}`);return n.join(`
91
91
  `)}function tg({daemonId:e,workspace:t,onClose:n}){const{t:a}=ke("common"),{sendCommand:r}=St(),{status:o,diffSummary:i,loading:c,error:d,refresh:p}=sI({daemonId:e,workspace:t,includeDiffSummary:!0}),[u,m]=l.useState(null),[f,g]=l.useState(null),[k,h]=l.useState(""),[b,S]=l.useState(!1),[x,y]=l.useState(!1),[C,v]=l.useState(null),[w,j]=l.useState(null),{githubUrl:N}=VD(e,t),A=l.useCallback(async D=>{if(!((u==null?void 0:u.path)===D.path&&!u.loading)){m({path:D.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const W=await r(e,"git_diff_file",{workspace:t,path:D.path,staged:D.staged}),R=tI(W);if(R.error||!R.diff){m({path:D.path,diff:"",binary:!1,truncated:!1,loading:!1,error:R.error??"Failed to load diff"});return}m({path:D.path,diff:R.diff.diff,binary:R.diff.binary??!1,truncated:R.diff.truncated??!1,loading:!1,error:null})}catch(W){const R=W instanceof Error?W.message:"Failed to load diff";m({path:D.path,diff:"",binary:!1,truncated:!1,loading:!1,error:R})}}},[e,r,u,t]),T=l.useCallback(D=>{h(""),S(!1),v(null),j(null),g(D)},[]),I=l.useCallback(()=>{g(null),v(null),y(!1)},[]),P=l.useCallback(async()=>{var D,W,R;if(f){y(!0),v(null);try{let B;f==="checkpoint"?B=await r(e,"git_checkpoint",{workspace:t,message:k,includeUntracked:b}):f==="stash"?B=await r(e,"git_stash_push",{workspace:t,message:k,includeUntracked:b}):f==="stash_pop"?B=await r(e,"git_stash_pop",{workspace:t}):f==="checkout_files"&&u&&(B=await r(e,"git_checkout_files",{workspace:t,paths:[u.path]}));const _=(B==null?void 0:B.result)??B;if((_==null?void 0:_.success)===!1||_!=null&&_.error){v((_==null?void 0:_.error)??"Action failed"),y(!1);return}f==="checkpoint"?j(`Checkpoint created: ${((W=(D=_==null?void 0:_.checkpoint)==null?void 0:D.commit)==null?void 0:W.slice(0,7))??"done"}`):f==="stash"?j(`Stashed as ${((R=_==null?void 0:_.stash)==null?void 0:R.stashRef)??"stash@{0}"}`):f==="stash_pop"?j("Stash restored"):(j("File reverted"),m(null)),g(null),await p()}catch(B){v(B instanceof Error?B.message:"Action failed")}finally{y(!1)}}},[f,r,e,t,k,b,u,p]),M=!!(o!=null&&o.hasConflicts);l.useEffect(()=>{const D=W=>{W.key==="Escape"&&(f?I():n())};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[f,I,n]);const E=o?o.staged+o.modified+o.untracked+o.deleted+o.renamed:null;return s.jsx(Vt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/60 px-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] pt-[calc(16px+env(safe-area-inset-top,0px))]",onClick:D=>{D.target===D.currentTarget&&n()},children:s.jsxs("div",{className:"relative flex h-[80dvh] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-2rem)] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(o==null?void 0:o.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),N&&s.jsx("a",{href:`${N}/tree/${(o==null?void 0:o.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-accent-primary underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:p,disabled:c,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),s.jsx("button",{type:"button",onClick:n,className:"-m-1.5 flex h-11 w-11 shrink-0 items-center justify-center rounded text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(Dt,{className:"h-4 w-4"})})]}),o&&s.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[o.headCommit&&s.jsxs("span",{title:o.headMessage??void 0,children:[s.jsx("span",{className:"font-mono",children:o.headCommit.slice(0,7)}),o.headMessage&&s.jsx("span",{className:"ml-1 truncate",children:o.headMessage.slice(0,60)})]}),o.ahead>0&&s.jsxs("span",{className:"text-orange-400",children:["↑",o.ahead," ahead"]}),o.behind>0&&s.jsxs("span",{className:"text-orange-400",children:["↓",o.behind," behind"]}),o.staged>0&&s.jsxs("span",{className:"text-status-online",children:[o.staged," staged"]}),o.modified>0&&s.jsxs("span",{children:[o.modified," modified"]}),o.untracked>0&&s.jsxs("span",{children:[o.untracked," untracked"]}),o.deleted>0&&s.jsxs("span",{className:"text-status-error",children:[o.deleted," deleted"]}),o.stashCount>0&&s.jsxs("span",{children:[o.stashCount," stashed"]}),o.hasConflicts&&s.jsx("span",{className:"font-bold text-status-error",children:a("git.statusDialog.conflicts")}),E===0&&!o.error&&s.jsx("span",{className:"text-status-online",children:a("git.statusDialog.clean")}),i&&i.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[i.files.length," file",i.files.length!==1?"s":"",i.totalInsertions>0&&s.jsxs("span",{className:"text-status-online",children:[" +",i.totalInsertions]}),i.totalDeletions>0&&s.jsxs("span",{className:"text-status-error",children:[" -",i.totalDeletions]})]})]}),d&&s.jsx("div",{className:"shrink-0 border-b border-border/50 bg-status-error/10 px-4 py-2 text-xs text-status-error",children:d}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[c&&!i&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),i&&s.jsx(oI,{files:i.files,truncated:i.truncated,selectedPath:(u==null?void 0:u.path)??null,onFileClick:A}),!c&&!i&&!d&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:u?s.jsx(lI,{diff:u.diff,binary:u.binary,truncated:u.truncated,loading:u.loading,error:u.error,className:"h-full"}):s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),w&&s.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-status-online/10 px-4 py-2 text-xs text-status-online flex items-center justify-between",children:[s.jsx("span",{children:w}),s.jsx("button",{onClick:()=>j(null),className:"ml-2 text-status-online hover:text-text-primary",children:"×"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[s.jsx("button",{onClick:()=>T("checkpoint"),disabled:M,title:M?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),s.jsx("button",{onClick:()=>T("stash"),disabled:M,title:M?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),s.jsx("button",{onClick:()=>T("stash_pop"),disabled:M||!(o!=null&&o.stashCount),title:M?"Resolve conflicts before restoring a stash":o!=null&&o.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),s.jsx("button",{onClick:()=>T("checkout_files"),disabled:!u,title:u?`Revert changes to ${u.path}`:"Select a file to revert",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkout selected"}),i&&i.files.length>0&&s.jsx("button",{onClick:()=>{const D=cI((o==null?void 0:o.branch)??null,i);navigator.clipboard.writeText(D),j("Copied to clipboard"),setTimeout(()=>j(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),f&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[f==="checkpoint"&&"Create checkpoint commit",f==="stash"&&"Stash changes",f==="stash_pop"&&"Restore latest stash?",f==="checkout_files"&&`Revert changes to ${(u==null?void 0:u.path)??"file"}?`]}),(f==="checkpoint"||f==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:k,onChange:D=>h(D.target.value),maxLength:200,placeholder:"Message (required)",className:"rounded border border-border bg-surface-secondary px-2 py-1 text-xs text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-border",autoFocus:!0}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:b,onChange:D=>S(D.target.checked)}),"Include untracked files"]})]}),C&&s.jsx("p",{className:"text-xs text-status-error",children:C}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:I,disabled:x,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),s.jsx("button",{onClick:P,disabled:x||(f==="checkpoint"||f==="stash")&&!k.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:x?"Working…":"Confirm"})]})]})})]})})})}function dI({isMobile:e,showMobileChatMode:t,visibleConversationCount:n}){const[a,r]=l.useState(!1),[o,i]=l.useState(!1),[c,d]=l.useState(!1),[p,u]=l.useState(!1),[m,f]=l.useState(!1),[g,k]=l.useState("quickstart"),[h,b]=l.useState("workspace"),S=l.useMemo(()=>!t&&!e,[t,e]),x=l.useCallback(N=>{r(N),N&&i(!1)},[]),y=l.useCallback(N=>{i(N),N&&r(!1)},[]),C=l.useCallback(()=>{k(n===0?"quickstart":"shortcuts"),b("workspace"),d(!0),r(!1),i(!1)},[n]),v=l.useCallback(()=>{d(!1)},[]),w=l.useCallback(()=>{u(!0)},[]),j=l.useCallback(()=>{u(!1)},[]);return l.useEffect(()=>{if(!S){f(!1);return}f(!0);const N=window.setTimeout(()=>{f(!1)},1e4);return()=>window.clearTimeout(N)},[S]),{inboxOpen:a,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:p,guideNudgeVisible:m,guideTab:g,shortcutSection:h,isDesktopDashboard:S,setGuideTab:k,setShortcutSection:b,handleInboxOpenChange:x,handleHiddenOpenChange:y,handleOpenShortcutHelp:C,closeShortcutHelp:v,openNewSession:w,closeNewSession:j}}function uI(e){switch(e.id){case"triggerPrimaryApprovalAction":case"triggerSecondaryApprovalAction":case"triggerTertiaryApprovalAction":return"approvals";case"splitActiveTabRight":case"splitActiveTabDown":case"focusLeftPane":case"focusRightPane":case"focusUpPane":case"focusDownPane":case"moveActiveTabToLeftPane":case"moveActiveTabToRightPane":case"moveActiveTabToUpPane":case"moveActiveTabToDownPane":return"panes";default:return"workspace"}}function pI(e){return e instanceof Error?e.message:String(e||"")}function mI(e){const t=pI(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function hI({showMobileChatMode:e,isMobile:t,activeConv:n,wsStatus:a,isConnected:r,onOpenHistory:o,onOpenRemote:i,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:p,mobileChatConversations:u,hiddenConversations:m,ides:f,actionLogs:g,sendDaemonCommand:k,setActionLogs:h,setCliViewModeOverrides:b,isStandalone:S,initialDataLoaded:x,userName:y,requestedMobileTabKey:C,onRequestedMobileTabConsumed:v,requestedMachineId:w,onRequestedMachineConsumed:j,requestedMobileSection:N,onRequestedMobileSectionConsumed:A,containerRef:T,isSplitMode:I,numGroups:P,groupSizes:M,groupedConvs:E,clearedTabs:D,focusedGroup:W,focusGroup:R,moveTabToGroup:B,splitTabRelative:_,closeGroup:H,handleResizeStart:L,groupActiveTabIds:F,setGroupActiveTab:$,groupTabOrders:K,setGroupTabOrder:z,toggleHiddenTab:ne,visibleConversations:ie,requestedDesktopTabKey:Ce,onRequestedDesktopTabConsumed:me,onDesktopActiveTabChange:O,onRequestScrollToBottom:Y,onHideConversation:X,onShowHiddenConversation:Q,onShowAllHiddenConversations:ve,scrollToBottomRequest:he,machineEntries:Z,layoutProfile:fe,onBrowseMachineDirectory:V,onSaveMachineWorkspace:q,onLaunchMachineIde:ee,onLaunchMachineProvider:pe,onListMachineMeshes:le,onLaunchMeshCoordinator:se,onListMachineSavedSessions:te,notifications:ue,notificationUnreadCount:ye,liveSessionInboxState:Me,onMarkNotificationRead:re,onMarkNotificationUnread:ce,onDeleteNotification:Ae}){const{t:be}=ke(),we=Rt.useRef(null),{inboxOpen:_e,hiddenOpen:U,shortcutHelpOpen:Ne,newSessionOpen:Ie,guideNudgeVisible:We,guideTab:Xe,shortcutSection:et,isDesktopDashboard:J,setGuideTab:Le,setShortcutSection:$e,handleInboxOpenChange:at,handleHiddenOpenChange:rt,handleOpenShortcutHelp:G,closeShortcutHelp:oe,openNewSession:de,closeNewSession:xe}=dI({isMobile:t,showMobileChatMode:e,visibleConversationCount:ie.length}),[Se,Pe]=Rt.useState(null),[He,Ee]=Rt.useState(null),Je=Rt.useCallback((Re,tt)=>{Pe({daemonId:Re,workspace:tt})},[]),st=Rt.useCallback(Re=>{Ee(Re)},[]),Ze=Rt.useCallback(Re=>{var tt;zs.flushSync(()=>{Q(Re)}),(tt=we.current)==null||tt.restoreHiddenTabToSavedLocation(Re.tabKey)},[Q]),Ue=Rt.useCallback(Re=>{var It;const tt=u.find(pt=>el(pt,Re))||m.find(pt=>el(pt,Re));tt&&(m.some(pt=>pt.tabKey===tt.tabKey)&&Ze(tt),O(tt.tabKey),(It=we.current)==null||It.activateConversationTab(tt.tabKey),Y(tt.tabKey,"notification-open")),re(Re.id),at(!1)},[Ze,m,u,O,re,Y]),Qe=Rt.useCallback(()=>{var tt;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((tt=we.current)==null||tt.resetAllPanelsToMain(),rt(!1))},[rt]),nt=Rt.useCallback(async Re=>{var _t;if(!n)return;const tt=(_t=n.modalButtons)==null?void 0:_t[Re];if(!tt)return;const It=kn(n);if(!It)return;const pt=tt.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Yt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(pt);try{await k(It,"resolve_action",{button:tt,action:Yt?"approve":"reject",buttonIndex:Re,...wn(n)})}catch(Qt){mI(Qt)||console.error("[Shortcut approval] Failed:",Qt)}},[n,k]),{isMac:Be,actionDefinitions:ge,actionShortcuts:je,shortcutListening:Te,shortcutListeningDraft:Fe,setShortcutListening:Ge,setShortcutListeningDraft:dt,saveShortcuts:Ve}=QA({enabled:J&&!Ne,onTrigger:Re=>{var tt,It,pt,Yt,_t,Qt,Cs,$s,ms,ss,Ys,Fs,Oe,lt,es,ns;if(Re==="openShortcutHelp"){G();return}if(Re==="openNewSession"){de();return}if(Re==="hideCurrentTab"){n&&X(n);return}if(Re==="toggleHiddenTabs"){rt(!U);return}if(Re==="openHistoryForActiveTab"){n&&!ht(n)&&o(n);return}if(Re==="openRemoteForActiveTab"){n&&!bt(n)&&!ht(n)&&i(n);return}if(Re==="splitActiveTabRight"){(tt=we.current)==null||tt.splitActiveTabRight();return}if(Re==="splitActiveTabDown"){(It=we.current)==null||It.splitActiveTabDown();return}if(Re==="floatActiveTab"){(pt=we.current)==null||pt.floatActiveTab();return}if(Re==="popoutActiveTab"){(Yt=we.current)==null||Yt.popoutActiveTab();return}if(Re==="dockActiveTab"){(_t=we.current)==null||_t.dockActiveTab();return}if(Re==="focusLeftPane"){(Qt=we.current)==null||Qt.focusLeftPane();return}if(Re==="focusRightPane"){(Cs=we.current)==null||Cs.focusRightPane();return}if(Re==="focusUpPane"){($s=we.current)==null||$s.focusUpPane();return}if(Re==="focusDownPane"){(ms=we.current)==null||ms.focusDownPane();return}if(Re==="moveActiveTabToLeftPane"){(ss=we.current)==null||ss.moveActiveTabToLeftPane();return}if(Re==="moveActiveTabToRightPane"){(Ys=we.current)==null||Ys.moveActiveTabToRightPane();return}if(Re==="moveActiveTabToUpPane"){(Fs=we.current)==null||Fs.moveActiveTabToUpPane();return}if(Re==="moveActiveTabToDownPane"){(Oe=we.current)==null||Oe.moveActiveTabToDownPane();return}if(Re==="triggerPrimaryApprovalAction"){nt(0);return}if(Re==="triggerSecondaryApprovalAction"){nt(1);return}if(Re==="triggerTertiaryApprovalAction"){nt(2);return}if(Re==="setActiveTabShortcut"){(lt=we.current)==null||lt.setShortcutForActiveTab();return}if(Re==="selectPreviousGroupTab"){(es=we.current)==null||es.activatePreviousTabInGroup();return}if(Re==="selectNextGroupTab"){(ns=we.current)==null||ns.activateNextTabInGroup();return}!n||!bt(n)||ht(n)||Re==="toggleCliView"&&p(d==="chat"?"terminal":"chat")}}),ut=Rt.useCallback(()=>{oe(),Ge(null),dt([])},[oe,Ge,dt]),Kt=Rt.useMemo(()=>et==="all"?ge:ge.filter(Re=>uI(Re)===et),[ge,et]),Et=Rt.useMemo(()=>[gt("triggerPrimaryApprovalAction",Be),gt("triggerSecondaryApprovalAction",Be),gt("triggerTertiaryApprovalAction",Be)].filter(Boolean).join(" / "),[Be]),ps=Be?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",Zt=Rt.useCallback(()=>{const Re=Object.fromEntries(ge.map(tt=>[tt.id,""]));Ve(Re)},[ge,Ve]),Hs=Rt.useCallback(()=>{if(typeof window<"u"&&!window.confirm(be("dashboard.guide.shortcuts.resetConfirm")))return;const Re=Object.fromEntries(ge.map(tt=>[tt.id,tt.defaultShortcut]));Ve(Re)},[ge,Ve,be]);return Rt.useEffect(()=>{const Re=tt=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?tt.metaKey&&tt.key.toLowerCase()==="w":tt.ctrlKey&&tt.key.toLowerCase()==="w")&&(tt.preventDefault(),n&&X&&X(n))};return window.addEventListener("keydown",Re),()=>window.removeEventListener("keydown",Re)},[n,X]),Rt.useEffect(()=>{if(!Ne||Te)return;const Re=tt=>{tt.key==="Escape"&&(tt.preventDefault(),ut())};return window.addEventListener("keydown",Re,!0),()=>window.removeEventListener("keydown",Re,!0)},[ut,Ne,Te]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(Cj,{activeConv:n,wsStatus:a,isConnected:r,conversations:ie,hiddenConversations:m,onOpenHistory:o,onHideConversation:X,onShowConversation:Ze,onShowAllHidden:ve,onResetPanelsToMain:Qe,notifications:ue,notificationUnreadCount:ye,onOpenNotification:Ue,onMarkNotificationRead:re,onMarkNotificationUnread:ce,onDeleteNotification:Ae,inboxOpen:_e,onInboxOpenChange:at,hiddenOpen:U,onHiddenOpenChange:rt,onOpenNewSession:t?void 0:de,onOpenDashboardGuide:G,guideNudgeVisible:We,actionShortcuts:je,onOpenRemote:()=>{!n||bt(n)||ht(n)||i(n)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:p,onOpenGitDialog:Je,onOpenMeshGraph:st}),e?s.jsx($A,{conversations:u,hiddenConversations:m,ides:f,actionLogs:g,sendDaemonCommand:k,setActionLogs:h,setCliViewModeOverrides:b,isStandalone:S,userName:y,requestedActiveTabKey:C,onRequestedActiveTabConsumed:v,requestedMachineId:w,onRequestedMachineConsumed:j,requestedMobileSection:N,onRequestedMobileSectionConsumed:A,onOpenHistory:o,onOpenRemote:i,onStopCli:c,wsStatus:a,isConnected:r,initialDataLoaded:x,onShowAllHiddenConversations:ve,onHideConversation:X,onOpenMeshGraph:st,onOpenNewSession:de,liveSessionInboxState:Me}):t?s.jsx(zA,{containerRef:T,isSplitMode:I,numGroups:P,groupSizes:M,groupedConvs:E,clearedTabs:D,ides:f,actionLogs:g,sendDaemonCommand:k,setActionLogs:h,isStandalone:S,hasRegisteredMachines:Z.length>0,initialDataLoaded:x,userName:y,focusedGroup:W,focusGroup:R,moveTabToGroup:B,splitTabRelative:_,closeGroup:H,handleResizeStart:L,groupActiveTabIds:F,setGroupActiveTab:$,groupTabOrders:K,setGroupTabOrder:z,toggleHiddenTab:ne,onOpenNewSession:de,allowTabShortcuts:!1,liveSessionInboxState:Me}):s.jsx(dT,{visibleConversations:ie,clearedTabs:D,ides:f,actionLogs:g,sendDaemonCommand:k,setActionLogs:h,isStandalone:S,hasRegisteredMachines:Z.length>0,initialDataLoaded:x,userName:y,toggleHiddenTab:ne,actionShortcuts:je,registerActionHandlers:Re=>{we.current=Re},onActiveTabChange:O,requestedActiveTabKey:Ce,onRequestedActiveTabConsumed:me,onRequestScrollToBottom:Y,scrollToBottomRequest:he,onOpenNewSession:de,liveSessionInboxState:Me,layoutProfile:fe}),Ie&&s.jsx(NT,{machines:Z,ides:f,onClose:xe,onBrowseDirectory:V,onSaveWorkspace:q,onLaunchIde:ee,onLaunchProvider:pe,onListMeshes:le,onLaunchMeshCoordinator:se,onListSavedSessions:te}),He&&s.jsx(Zf,{activeConv:He,sendDaemonCommand:k,onClose:()=>Ee(null)}),Se&&s.jsx(tg,{daemonId:Se.daemonId,workspace:Se.workspace,onClose:()=>Pe(null)}),Ne&&s.jsx(Vt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:ut,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",onClick:Re=>Re.stopPropagation(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:be("dashboard.guide.title")}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:be("dashboard.guide.subtitle")})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:ut,"aria-label":be("dashboard.guide.close"),children:s.jsx(Dt,{size:14})})]}),s.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:be("dashboard.guide.tabs.overview")},{id:"quickstart",label:be("dashboard.guide.tabs.quickstart")},{id:"shortcuts",label:be("dashboard.guide.tabs.shortcuts")}].map(Re=>s.jsx("button",{type:"button",className:`btn btn-sm ${Xe===Re.id?"btn-primary":"btn-secondary"}`,onClick:()=>Le(Re.id),children:Re.label},Re.id))}),Xe==="overview"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:be("dashboard.guide.overview.whatLivesWhere.title")}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:be("dashboard.guide.overview.whatLivesWhere.tabsLabel")})," ",be("dashboard.guide.overview.whatLivesWhere.tabsText")]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:be("dashboard.guide.overview.whatLivesWhere.hiddenLabel")})," ",be("dashboard.guide.overview.whatLivesWhere.hiddenText")]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:be("dashboard.guide.overview.whatLivesWhere.inboxLabel")})," ",be("dashboard.guide.overview.whatLivesWhere.inboxText")]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:be("dashboard.guide.overview.whatLivesWhere.cliToggleLabel")})," ",be("dashboard.guide.overview.whatLivesWhere.cliToggleText")]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:be("dashboard.guide.overview.usefulFlows.title")}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:be("dashboard.guide.overview.usefulFlows.reviewLabel")})," ",be("dashboard.guide.overview.usefulFlows.reviewText")]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:be("dashboard.guide.overview.usefulFlows.clutterLabel")})," ",be("dashboard.guide.overview.usefulFlows.clutterText")]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:be("dashboard.guide.overview.usefulFlows.splitLabel")})," ",be("dashboard.guide.overview.usefulFlows.splitText")]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:be("dashboard.guide.overview.usefulFlows.detachedLabel")})," ",be("dashboard.guide.overview.usefulFlows.detachedText")]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:be("dashboard.guide.overview.usefulFlows.dockingLabel")})," ",be("dashboard.guide.overview.usefulFlows.dockingText")]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:be("dashboard.guide.overview.usefulFlows.perTabLabel")})," ",be("dashboard.guide.overview.usefulFlows.perTabText")]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:be("dashboard.guide.overview.usefulFlows.approvalLabel")})," ",be("dashboard.guide.overview.usefulFlows.approvalText",{keys:Et})]})]})]})]}),Xe==="quickstart"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:be("dashboard.guide.quickstart.desktop.title")}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," ",be("dashboard.guide.quickstart.desktop.step1")]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," ",be("dashboard.guide.quickstart.desktop.step2")]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," ",be("dashboard.guide.quickstart.desktop.step3")]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," ",be("dashboard.guide.quickstart.desktop.step4")]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:be("dashboard.guide.quickstart.mobile.title")}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," ",be("dashboard.guide.quickstart.mobile.step1")]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," ",be("dashboard.guide.quickstart.mobile.step2")]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," ",be("dashboard.guide.quickstart.mobile.step3")]})]})]})]}),Xe==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:be("dashboard.guide.shortcuts.sections.all")},{id:"workspace",label:be("dashboard.guide.shortcuts.sections.workspace")},{id:"panes",label:be("dashboard.guide.shortcuts.sections.panes")},{id:"approvals",label:be("dashboard.guide.shortcuts.sections.approvals")}].map(Re=>s.jsx("button",{type:"button",className:`btn btn-sm ${et===Re.id?"btn-primary":"btn-secondary"}`,onClick:()=>$e(Re.id),children:Re.label},Re.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Zt,children:be("dashboard.guide.shortcuts.disableAll")}),s.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:Hs,children:be("dashboard.guide.shortcuts.resetToDefaults")})]})]}),s.jsx("div",{className:"space-y-2",children:Kt.map(Re=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Te===Re.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:be(`dashboard.shortcutDefs.${Re.id}.label`,Re.label)}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:be(`dashboard.shortcutDefs.${Re.id}.description`,Re.description)}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:[be("dashboard.guide.shortcuts.default")," ",s.jsx("span",{className:"font-mono",children:Re.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-surface-secondary border border-border-subtle min-w-[72px] text-center",children:Te===Re.id?Fe.length>0?`${Fe.join(" ")} ...`:be("dashboard.guide.shortcuts.listening"):je[Re.id]||be("dashboard.guide.shortcuts.off")}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Ge(Re.id),dt([])},children:Te===Re.id?be("dashboard.guide.shortcuts.setListening"):be("dashboard.guide.shortcuts.set")}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const tt={...je};tt[Re.id]="",Ve(tt)},children:be("dashboard.guide.shortcuts.disable")})]})]})},Re.id))}),s.jsx("div",{className:"text-[11px] text-text-muted mt-4",children:be("dashboard.guide.shortcuts.footer",{keys:ps})})]})]})})})]})}const fI=[{icon:ho,title:"Welcome to ADHDev",desc:"Drive any local CLI coding agent — Claude Code, Codex, Gemini — straight from your browser or phone. The agents keep running on your machine; you control them from the web.",visual:_p},{icon:Is,title:"Real-time chat",desc:"See what your AI agent is doing in real-time. Send messages, approve or reject actions — all from your browser or phone.",visual:Eb},{icon:Fl,title:"Watch and steer, live",desc:"Follow each agent's session in real time and steer it as it works — switch sessions, take screenshots, and (for IDE sessions) view and control the screen over a P2P connection.",visual:Hp},{icon:Ki,title:"Orchestrate your agents",desc:"Repo Mesh (Cloud Pro) lets one coordinator hand work to agents across many machines — parallel git worktrees, automatic branch convergence, and cross-checking the same repo from several angles.",visual:Ki}],gI={icon:ho,title:"Get started",desc:"Run this on any machine you want to drive, then sign in — the daemon pairs itself to your dashboard automatically.",code:"curl -fsSL https://adhf.dev/install | sh"},bI={icon:ho,title:"You're all set",desc:"This dashboard is already connected to your local daemon. Start a session from the Dashboard tab, or add more providers under Machines → Providers.",visual:Ga};function xI({onClose:e,standalone:t=!1}){const[n,a]=l.useState(0),r=[...fI,t?bI:gI],o=r[n],i=n===r.length-1;return l.useEffect(()=>{const c=d=>{d.key==="Escape"&&e()};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[e]),s.jsx(Vt,{children:s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:"var(--z-modal)",background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",padding:"calc(16px + env(safe-area-inset-top, 0px)) 16px calc(16px + env(safe-area-inset-bottom, 0px))",animation:"fadeIn 0.3s ease-out"},onClick:c=>{c.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",maxHeight:"calc(100dvh - env(safe-area-inset-top, 0px) - env(safe-area-inset-bottom, 0px) - 32px)",overflowY:"auto",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,"aria-label":"Close onboarding",className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",style:{minWidth:44,minHeight:44,margin:-6,display:"inline-flex",alignItems:"center",justifyContent:"center"},children:s.jsx(Dt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:r.map((c,d)=>s.jsx("div",{style:{width:d===n?24:8,height:8,borderRadius:4,background:d===n?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},d))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:(()=>{const c=o.visual||o.icon;return s.jsx(c,{size:44})})()}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx(o.icon,{size:18})," ",o.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:o.desc}),o.code&&s.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),o.code]}),i&&s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"Learn more in the docs →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>i?e():a(c=>c+1),className:"btn btn-primary",children:i?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
@@ -116,6 +116,6 @@ The newest runtime for each provider session will be kept and older duplicates w
116
116
  from { opacity: 0; transform: translateX(40px); }
117
117
  to { opacity: 1; transform: translateX(0); }
118
118
  }
119
- `})]})}function OL({daemonIds:e,meshId:t,sendData:n,onRevisionAdvance:a}){const r=l.useRef(new Map),o=l.useRef(a);o.current=a;const i=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{r.current=new Map},[i,t]),l.useEffect(()=>{if(!t||!n)return;const c=[...new Set(e.filter(Boolean))];if(c.length===0)return;const d=c.map(p=>ys.subscribe({sendData:n},p,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${p}`,params:{includeSessions:!0}},u=>{if(u.topic!=="daemon.metadata")return;const m=u.meshStateRevisions;if(!m)return;const f=m[t]??m["*"];if(typeof f!="number")return;const g=r.current.get(p);r.current.set(p,f),g!==void 0&&f>g&&o.current()}));return()=>{for(const p of d)p()}},[i,t,n])}const rg={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},og=l.createContext(null);function UL(){const e=l.useContext(og);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}const ro="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function Cl({workspaces:e,value:t,onChange:n,autoFocus:a}){const{t:r}=ke("common"),[o,i]=l.useState(!1),c=new Set(e.map(p=>p.path)),d=o?"__custom":c.has(t)?t:"";return e.length===0||o?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("input",{type:"text",className:ro,value:t,autoFocus:a,placeholder:r("setupWizard.machines.workspacePlaceholder"),onChange:p=>n(p.target.value)}),e.length>0&&s.jsx("button",{type:"button",className:"self-start text-[10px] text-accent-primary hover:underline",onClick:()=>i(!1),children:r("setupWizard.machines.pickFromKnown")})]}):s.jsxs("select",{className:ro,value:d,onChange:p=>{p.target.value==="__custom"?(i(!0),n("")):n(p.target.value)},children:[s.jsx("option",{value:"",children:r("setupWizard.machines.workspaceSelectPlaceholder")}),e.map(p=>s.jsx("option",{value:p.path,children:p.label||p.path},p.path)),s.jsx("option",{value:"__custom",children:r("setupWizard.machines.workspaceCustom")})]})}function oo(e){var t;return!!(e!=null&&e.success)&&((t=e==null?void 0:e.plan)==null?void 0:t.kind)!==void 0&&e.plan.kind!=="create_mesh_and_onboard"}function ig(e,t){const[n,a]=l.useState(!1),r=l.useRef(null);return l.useEffect(()=>(e?r.current=setTimeout(()=>a(!0),t):a(!1),()=>{r.current&&clearTimeout(r.current)}),[e,t]),e&&n}function lg({plan:e,loading:t}){var i,c,d;const{t:n}=ke("common"),a=ig(t,250);let r=null,o="text-[11px] text-text-muted";return a?r=n("setupWizard.machines.planChecking"):(e==null?void 0:e.success)===!1?(o="text-[11px] text-red-400",r=s.jsxs(s.Fragment,{children:[e.error,e.action?` ${e.action}`:""]})):oo(e)?(o="text-[11px] text-amber-400",r=((i=e.plan)==null?void 0:i.summary)||n("setupWizard.machines.planExists")):e&&(o="text-[11px] text-emerald-400",r=n("setupWizard.machines.planOk",{identity:((c=e.discovery)==null?void 0:c.repoIdentity)||((d=e.discovery)==null?void 0:d.repoRoot)||""})),s.jsx("p",{className:`${o} min-h-[1.4em]`,children:r})}function GL(e){var t;return e.creating||e.planLoading||!e.name.trim()||e.showDaemonPicker&&!e.daemonId||((t=e.plan)==null?void 0:t.success)===!1||oo(e.plan)?!0:e.workspace.trim()?!1:!e.repoRemoteUrl.trim()&&!e.repoIdentity.trim()}function cg(e){var E,D;const{variant:t="page",showDaemonPicker:n,daemons:a,daemonLabel:r,name:o,onNameChange:i,daemonId:c,onDaemonIdChange:d,workspace:p,onWorkspaceChange:u,workspaces:m,plan:f,planLoading:g,repoRemoteUrl:k,onRepoRemoteUrlChange:h,repoIdentity:b,onRepoIdentityChange:S,manualOpen:x,onManualOpenChange:y,creating:C,warning:v,onCreate:w,onCancel:j}=e,{t:N}=ke("common"),A=GL({creating:C,planLoading:g,plan:f,name:o,workspace:p,showDaemonPicker:n,daemonId:c,repoRemoteUrl:k,repoIdentity:b}),T=ig(g,250),I=x||!!k.trim()||!!b.trim(),P=n&&a.length>0&&s.jsxs("select",{className:t==="wizard"?ro:"input w-full",value:c,onChange:W=>d(W.target.value),children:[s.jsx("option",{value:"",children:N("setupWizard.machines.machineSelectPlaceholder")}),a.map(W=>s.jsx("option",{value:W.id,children:r(W)},W.id))]}),M=I?s.jsxs(s.Fragment,{children:[s.jsx(Tt,{label:N("repoMesh.list.remoteUrl"),hint:N("repoMesh.list.remoteUrlHint"),children:s.jsx(xs,{value:k,onChange:W=>h(W.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(Tt,{label:N("repoMesh.list.repoIdentity"),hint:N("repoMesh.list.repoIdentityHint"),children:s.jsx(xs,{value:b,onChange:W=>S(W.target.value),placeholder:"github.com/user/repo"})})]}):s.jsx("button",{type:"button",className:"self-start text-xs text-text-muted hover:text-text-primary underline underline-offset-2 mb-3 bg-transparent border-none cursor-pointer p-0",onClick:()=>y(!0),children:N("repoMesh.list.advancedIdentityToggle")});return t==="wizard"?s.jsxs("div",{className:"flex flex-col gap-2.5 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:N("setupWizard.machines.meshName")}),s.jsx("input",{type:"text",className:ro,value:o,onChange:W=>i(W.target.value)})]}),n&&a.length>1&&s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:N("setupWizard.machines.machine")}),P]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:N("setupWizard.machines.workspace")}),s.jsx(Cl,{workspaces:m,value:p,onChange:u})]}),s.jsx(lg,{plan:f,loading:g}),v&&s.jsx("p",{className:"text-[11px] text-amber-400",children:v}),s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:w,disabled:A,children:N(C?"setupWizard.machines.creating":"setupWizard.machines.create")})})]}):s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:N("repoMesh.list.createTitle")}),n&&s.jsx(Tt,{label:N("repoMesh.list.createOnMachine"),hint:N("repoMesh.list.createOnMachineHint"),children:a.length===0?s.jsx("select",{className:"input w-full",disabled:!0,children:s.jsx("option",{value:"",children:N("repoMesh.list.noConnectedDaemon")})}):P}),s.jsx(Tt,{label:N("repoMesh.list.workspace"),hint:N("repoMesh.list.workspaceHint"),children:s.jsx(Cl,{workspaces:m,value:p,onChange:u})}),(T||f)&&s.jsx(Mt,{variant:(f==null?void 0:f.success)===!1?"error":oo(f)?"warning":"info",className:"mb-4",children:T?N("setupWizard.machines.planChecking"):(f==null?void 0:f.success)===!1?`${(f==null?void 0:f.code)||"onboarding_blocked"}: ${(f==null?void 0:f.error)||"Git discovery failed"} ${(f==null?void 0:f.action)||""}`:oo(f)?((E=f.plan)==null?void 0:E.summary)||N("setupWizard.machines.planExists"):`${((D=f.plan)==null?void 0:D.summary)||"Git repository detected."} No changes will be made until you click Create.`}),s.jsx(Tt,{label:N("repoMesh.list.name"),children:s.jsx(xs,{value:o,onChange:W=>i(W.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx("div",{className:"flex flex-col",children:M}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:w,disabled:A,children:N(C?"repoMesh.list.creating":"repoMesh.list.create")}),j&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:j,disabled:C,children:N("repoMesh.list.cancel")})]})]})}function qL({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("polyline",{points:"1 20 1 14 7 14"}),s.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function zL({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"6",cy:"18",r:"3"}),s.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function KL({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"3 6 5 6 21 6"}),s.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})}function VL({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function YL({status:e}){const n={online:{color:"#22c55e",label:"Online"},dirty:{color:"#f59e0b",label:"Dirty",title:"Workspace has uncommitted changes"},offline:{color:"#6b7280",label:"Offline"},degraded:{color:"#ef4444",label:"Degraded",title:"P2P connection to this node is down or timed out — often transient. Wait and retry, or re-establish the node's connection."},enabled:{color:"#22c55e",label:"Enabled"},pending:{color:"#a855f7",label:"Pending"},assigned:{color:"#3b82f6",label:"Assigned"},completed:{color:"#22c55e",label:"Completed"},failed:{color:"#ef4444",label:"Failed"},unknown:{color:"#6b7280",label:"Unknown"}}[e]||{color:"#6b7280",label:e};return s.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-md",style:{background:n.color+"15",color:n.color,border:`1px solid ${n.color}25`},title:n.title,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:n.color}}),n.label]})}function QL(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function JL({meshes:e,loading:t,error:n,onDismissError:a,daemons:r,features:o,showCreate:i,onToggleCreate:c,createName:d,onCreateNameChange:p,createRepoIdentity:u,onCreateRepoIdentityChange:m,createRepoRemoteUrl:f,onCreateRepoRemoteUrlChange:g,newMeshDaemonId:k,onNewMeshDaemonIdChange:h,newMeshWorkspace:b,onNewMeshWorkspaceChange:S,createPickerWorkspaces:x,createOnboardingPlan:y,createPlanLoading:C,creating:v,createWarning:w,onDismissCreateWarning:j,onSelectMesh:N,onCreate:A,onCancelCreate:T}){const{t:I}=ke("common"),P=o.maxMeshes!=null&&e.length>=o.maxMeshes,[M,E]=l.useState(!1);return s.jsxs(Ja,{icon:s.jsx(cs,{}),title:I("repoMesh.list.title"),subtitle:I("repoMesh.list.count",{count:e.length}),widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,disabled:P,title:P?I("repoMesh.list.meshLimitReached",{max:o.maxMeshes}):void 0,children:I("repoMesh.list.createMesh")}),children:[P&&s.jsx(Mt,{variant:"info",className:"mb-4",children:I("repoMesh.list.meshLimitBanner",{max:o.maxMeshes})}),n&&s.jsx(Mt,{variant:"error",onDismiss:a,className:"mb-4",children:n}),w&&s.jsx(Mt,{variant:"warning",onDismiss:j,className:"mb-4",children:w}),i&&s.jsx(xt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:s.jsx(cg,{variant:"page",showDaemonPicker:o.createDaemonPicker,daemons:r,daemonLabel:QL,name:d,onNameChange:p,daemonId:k,onDaemonIdChange:h,workspace:b,onWorkspaceChange:S,workspaces:x,plan:y,planLoading:C,repoRemoteUrl:f,onRepoRemoteUrlChange:g,repoIdentity:u,onRepoIdentityChange:m,manualOpen:M,onManualOpenChange:E,creating:v,onCreate:A,onCancel:T})}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:I("repoMesh.list.loading")}):e.length===0?s.jsx(Xa,{icon:s.jsx(cs,{}),title:I("repoMesh.list.emptyTitle"),description:r.length>0?I("repoMesh.list.emptyWithDaemons"):I("repoMesh.list.emptyNoDaemons"),action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!r.length,onClick:c,children:I("repoMesh.list.createFirst")})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(D=>{var W;return s.jsx("button",{type:"button",onClick:()=>N(D.id),className:"w-full text-left bg-bg-glass border border-border-subtle rounded-xl px-5 py-4 transition-colors hover:border-border-default hover:bg-bg-secondary/70",children:s.jsxs("div",{className:"flex justify-between items-start",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(cs,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:D.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:D.repoIdentity||D.repo_identity||I("repoMesh.list.noRepoIdentity")}),(D.defaultBranch||D.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(zL,{size:11}),D.defaultBranch||D.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(D.createdAt||D.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((W=D.nodes)==null?void 0:W.length)??D.nodeCount??0," ",I("repoMesh.list.nodesSuffix")]})]})]})},D.id)})})]})}function XL(e){const t=new Map;for(const n of e)n!=null&&n.id&&t.set(n.id,cn(n.availableProviders||[]));return t}function ZL(e,t){const n=String(e.daemon_id||e.daemonId||"");return n&&t.has(n)?t.get(n):!n&&t.size===1?[...t.values()][0]:[]}function e2(e,t){const n=new Map;for(const c of t)c!=null&&c.id&&n.set(c.id,Array.isArray(c.availableProviders)?c.availableProviders:[]);const a=new Set,r=[];let o=0,i=0;for(const c of Array.isArray(e)?e:[]){const d=String((c==null?void 0:c.daemon_id)||(c==null?void 0:c.daemonId)||""),p=d?n.get(d):n.size===1?[...n.values()][0]:void 0;if(!p||p.length===0){i++;continue}o++;for(const u of p){const m=String((u==null?void 0:u.type)||(u==null?void 0:u.id)||"").trim();!m||a.has(m)||(a.add(m),r.push(u))}}return r.sort((c,d)=>String((c==null?void 0:c.type)||(c==null?void 0:c.id)||"").localeCompare(String((d==null?void 0:d.type)||(d==null?void 0:d.id)||""))),{providers:r,reportedNodeCount:o,unreportedNodeCount:i}}function t2(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},n=new Set,a=[],r=o=>{const i=typeof o=="string"?o.trim():"";!i||n.has(i)||(n.add(i),a.push(i))};for(const o of im(t.slots))r(o.provider);if(Array.isArray(t.providerPriority))for(const o of t.providerPriority)r(o);return a}function s2(e){var d,p;const t=e,n=[],a=Array.isArray(t.capabilities)?t.capabilities:[];for(const u of a){const m=typeof u=="string"?u.trim():"";m&&n.push({tag:m,custom:!0})}const r=(((d=t.userOverrides)==null?void 0:d.platform)||t.reportedPlatform||"").toString().trim(),o=(((p=t.userOverrides)==null?void 0:p.arch)||t.reportedArch||"").toString().trim();r&&n.push({tag:`os=${r}`,custom:!1}),o&&n.push({tag:`arch=${o}`,custom:!1});for(const u of t2(t.policy))n.push({tag:`provider=${u}`,custom:!1});const i=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";t.isLocalWorktree===!0&&i&&n.push({tag:`worktree=${i}`,custom:!1});const c=new Set;return n.filter(u=>c.has(u.tag)?!1:(c.add(u.tag),!0))}const n2=["","low","medium","high"],a2={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function Zu(e){return{provider:e.provider||"",model:e.model||"",thinkingLevel:e.thinkingLevel||"",difficulty:Array.isArray(e.difficulty)?e.difficulty:[],capability:Array.isArray(e.capability)?e.capability:[],maxParallel:e.maxParallel!=null?String(e.maxParallel):""}}function ep(e){const t=e.provider.trim();if(!t)return null;const n=e.model.trim(),a=e.thinkingLevel.trim()||void 0,r=Number(e.maxParallel),o=Number.isFinite(r)&&r>0?Math.floor(r):void 0;return{provider:t,...n?{model:n}:{},...a?{thinkingLevel:a}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...o!==void 0?{maxParallel:o}:{}}}function r2(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const gn="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function o2({slots:e,availableProviders:t,saving:n,onSave:a}){const{t:r}=ke("common"),[o,i]=l.useState(()=>e.map(Zu)),c=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{i(e.map(Zu))},[c]);const d=l.useMemo(()=>[...new Set(t.map(x=>x.type).filter(Boolean))],[t]),p=l.useMemo(()=>bh(t),[t]),u=l.useMemo(()=>{const x=o.map(ep).filter(Boolean);return JSON.stringify(x)!==JSON.stringify(e)},[o,e]),m=(x,y)=>i(C=>C.map((v,w)=>w===x?{...v,...y}:v)),f=(x,y)=>i(C=>C.map((v,w)=>{var A;if(w!==x)return v;const j=((A=p.get(y))==null?void 0:A.models)??[],N=!v.model||j.length===0||j.includes(v.model);return{...v,provider:y,...N?{}:{model:""}}})),g=x=>i(y=>y.filter((C,v)=>v!==x)),k=()=>i(x=>[...x,r2()]),h=(x,y)=>i(C=>{const v=x+y;if(v<0||v>=C.length)return C;const w=[...C];return[w[x],w[v]]=[w[v],w[x]],w}),b=(x,y)=>i(C=>C.map((v,w)=>{if(w!==x)return v;const j=v.difficulty.includes(y);return{...v,difficulty:j?v.difficulty.filter(N=>N!==y):[...v.difficulty,y]}})),S=()=>a(o.map(ep).filter(Boolean));return s.jsxs("div",{className:"flex flex-col gap-2",onClick:x=>x.stopPropagation(),children:[o.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:r("repoMesh.slotEditor.empty")}),o.map((x,y)=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-2.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[s.jsxs("span",{className:"text-[11px] font-semibold text-text-muted",children:["#",y+1]}),s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:y===0,onClick:()=>h(y,-1),title:r("repoMesh.slotEditor.moveUp"),children:"↑"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:y===o.length-1,onClick:()=>h(y,1),title:r("repoMesh.slotEditor.moveDown"),children:"↓"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-status-error/30 text-status-error hover:bg-status-error/10",onClick:()=>g(y),"aria-label":r("repoMesh.slotEditor.removeSlot"),children:s.jsx(Dt,{size:12})})]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.provider")}),d.length>0?s.jsxs("select",{className:gn,value:x.provider,onChange:C=>f(y,C.target.value),children:[s.jsx("option",{value:"",children:r("repoMesh.slotEditor.select")}),d.map(C=>s.jsx("option",{value:C,children:C},C)),x.provider&&!d.includes(x.provider)&&s.jsx("option",{value:x.provider,children:x.provider})]}):s.jsx("input",{className:gn,value:x.provider,placeholder:"claude-cli",onChange:C=>m(y,{provider:C.target.value})})]}),(()=>{var N;const C=p.get(x.provider),v=(C==null?void 0:C.models)??[],w=(N=C==null?void 0:C.thinking)!=null&&N.length?["",...C.thinking]:n2,j=!!x.model&&v.length>0&&!v.includes(x.model);return s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.model")}),v.length>0&&!j?s.jsxs("select",{className:gn,value:v.includes(x.model)?x.model:"",onChange:A=>m(y,{model:A.target.value==="__custom__"?" ":A.target.value}),children:[s.jsx("option",{value:"",children:r("repoMesh.slotEditor.providerDefault")}),v.map(A=>s.jsx("option",{value:A,children:A},A)),s.jsx("option",{value:"__custom__",children:r("repoMesh.slotEditor.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:gn,value:x.model.trim(),placeholder:x.provider?`${x.provider} model`:r("repoMesh.slotEditor.modelPlaceholder"),onChange:A=>m(y,{model:A.target.value})}),v.length>0&&s.jsx("button",{type:"button",className:"self-start bg-transparent border-none cursor-pointer p-0 text-[10px] text-text-muted hover:underline",onClick:()=>m(y,{model:""}),children:r("repoMesh.slotEditor.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.thinking")}),s.jsx("select",{className:gn,value:x.thinkingLevel,onChange:A=>m(y,{thinkingLevel:A.target.value}),children:w.map(A=>s.jsx("option",{value:A,children:A||r("repoMesh.slotEditor.thinkingDefault")},A||"_default"))})]})]})})()]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.difficulty")}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:om.map(C=>{const v=x.difficulty.includes(C);return s.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${v?"border-accent-primary/60 bg-accent-primary/15 text-accent-primary":"border-border-subtle bg-bg-primary/60 text-text-muted hover:text-text-primary"}`,onClick:()=>b(y,C),children:a2[C]},C)})})]}),s.jsxs("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.capabilityTags")}),s.jsx("input",{className:gn,value:x.capability.join(", "),placeholder:"worktree, os=darwin",onChange:C=>m(y,{capability:C.target.value.split(",").map(v=>v.trim()).filter(Boolean)})})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.maxParallel")}),s.jsx("input",{type:"number",inputMode:"numeric",min:1,className:gn,value:x.maxParallel,placeholder:r("repoMesh.slotEditor.maxParallelPlaceholder"),onChange:C=>m(y,{maxParallel:C.target.value})})]})]})]},y)),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1",onClick:k,children:[s.jsx(Wl,{size:13})," ",r("repoMesh.slotEditor.addSlot")]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:S,disabled:!!n||!u,children:r(n?"repoMesh.slotEditor.saving":"repoMesh.slotEditor.saveSlots")})]})]})}function i2(e){const t=e.capabilities;return Array.isArray(t)?t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean):[]}const l2=["os=","arch=","provider=","worktree=","converge="];function c2({node:e,saving:t,onSave:n}){const{t:a}=ke("common"),r=l.useMemo(()=>s2(e).filter(h=>!h.custom),[e]),o=l.useMemo(()=>i2(e),[e]),[i,c]=l.useState(o),[d,p]=l.useState(""),u=JSON.stringify(i)!==JSON.stringify(o),f=(h=>{const b=h.trim();return b?/\s/.test(b)?a("repoMesh.tagEditor.noSpaces"):l2.some(S=>b.toLowerCase().startsWith(S))?a("repoMesh.tagEditor.reservedPrefix"):i.includes(b)?a("repoMesh.tagEditor.alreadyAdded"):null:null})(d);function g(){const h=d.trim();!h||f||(c(b=>[...b,h]),p(""))}function k(h){c(b=>b.filter(S=>S!==h))}return s.jsxs("div",{className:"mt-2",onClick:h=>h.stopPropagation(),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wide text-text-muted mr-1",children:a("repoMesh.tagEditor.routingTags")}),r.map(h=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 font-mono text-[10px] text-text-muted",title:a("repoMesh.tagEditor.autoDerivedTitle"),children:h.tag},h.tag)),i.map(h=>s.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 font-mono text-[10px] text-accent-primary",title:a("repoMesh.tagEditor.customTagTitle"),children:[h,s.jsx("button",{type:"button",className:"text-accent-primary/70 hover:text-accent-primary bg-transparent border-none cursor-pointer p-0 leading-none",onClick:()=>k(h),disabled:t,"aria-label":a("repoMesh.tagEditor.remove",{tag:h}),children:"×"})]},h))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:h=>p(h.target.value),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),g())},placeholder:a("repoMesh.tagEditor.addPlaceholder"),disabled:t,className:"min-w-[12rem] flex-1 px-2 py-1 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:g,disabled:t||!d.trim()||!!f,children:a("repoMesh.tagEditor.add")}),u&&s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>n(i),disabled:t,children:a(t?"repoMesh.tagEditor.saving":"repoMesh.tagEditor.saveTags")})]}),f&&s.jsx("div",{className:"mt-1 text-[11px] text-amber-400",children:f}),i.length===0&&r.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:a("repoMesh.tagEditor.empty")})]})}function d2(e,t){const n=t;return[...Array.isArray(n==null?void 0:n.cliSessions)?n.cliSessions:[],...Array.isArray(n==null?void 0:n.acpSessions)?n.acpSessions:[],...Array.isArray(n==null?void 0:n.sessions)?n.sessions:[]].filter(r=>{var o;return((o=r==null?void 0:r.settings)==null?void 0:o.meshNodeId)===e.id||(r==null?void 0:r.workspace)===e.workspace}).map(r=>{var o;return{id:r.sessionId||r.id||r.instanceId||"unknown",provider:r.providerType||r.cliType||r.acpType||r.type||"unknown",status:r.status||((o=r.activeChat)==null?void 0:o.status)||"unknown"}})}function u2(e,t){var n;return(e==null?void 0:e.ownerName)||(e==null?void 0:e.userName)||((n=e==null?void 0:e.user)==null?void 0:n.name)||t||"You"}function tp({nodes:e,meshQueue:t,activeDaemon:n,daemons:a,userName:r,features:o,providersByDaemonId:i,savingNodeSlotsId:c,onUpdateNodeSlots:d,savingNodeCapabilitiesId:p,onUpdateNodeCapabilities:u,nodeSystemPromptDrafts:m,onNodeSystemPromptDraftChange:f,savingNodeSystemPromptId:g,onSaveNodeSystemPrompt:k,selectedNodeId:h,onSelectNode:b,onRemoveNode:S}){const{t:x}=ke("common");return e.length===0?s.jsx(Xa,{icon:s.jsx(Tn,{}),title:x("repoMesh.nodeList.emptyTitle"),description:x("repoMesh.nodeList.emptyDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:e.map(y=>{var A;const C=f2(y),v=p2(y,t),w=d2(y,n),j=h===y.id,N=y.status||y.machine_status||(v.length>0||w.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${o.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${j?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:o.addNodeDaemonPicker?void 0:"button",tabIndex:o.addNodeDaemonPicker?void 0:0,onClick:o.addNodeDaemonPicker?void 0:()=>b(j?null:y.id),onKeyDown:o.addNodeDaemonPicker?void 0:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),b(j?null:y.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[o.addNodeDaemonPicker?s.jsx("span",{className:"font-semibold text-sm text-text-primary truncate",children:y.machine_label||y.machine_nickname||y.hostname||y.workspace}):s.jsx("span",{className:"text-sm font-medium",children:y.workspace.split("/").pop()}),o.addNodeDaemonPicker&&s.jsx(YL,{status:N}),o.addNodeDaemonPicker&&s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:x("repoMesh.nodeList.setupInventory")})]}),o.addNodeDaemonPicker&&s.jsx("div",{className:"text-[11px] text-text-muted",children:x("repoMesh.nodeList.ownerMachine",{owner:u2(a.find(T=>T.id===String(y.daemon_id||"")),r),machine:y.machine_label||y.daemon_id||y.workspace})}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:y.workspace}),s.jsx(c2,{node:y,saving:p===y.id,onSave:T=>u(y,T)}),o.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:x("repoMesh.nodeList.liveDetailGraphOwned")}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:T=>T.stopPropagation(),children:[s.jsx(Tt,{label:x("repoMesh.nodeList.slotsLabel"),hint:x("repoMesh.nodeList.slotsHint"),children:s.jsx(o2,{slots:Array.isArray((A=y.policy)==null?void 0:A.slots)?y.policy.slots:[],availableProviders:ZL(y,i),saving:c===y.id,onSave:T=>d(y,T)})}),o.nodeInstruction&&s.jsxs(Tt,{label:x("repoMesh.nodeList.nodeInstruction"),hint:x("repoMesh.nodeList.nodeInstructionHint"),children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:m[y.id]??"",onChange:T=>{const I=T.target.value;f(y.id,I)},onClick:T=>T.stopPropagation(),disabled:g===y.id,placeholder:x("repoMesh.nodeList.nodeInstructionPlaceholder")}),s.jsx("div",{className:"mt-2 flex items-center gap-2",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:T=>{T.stopPropagation(),k(y)},disabled:g===y.id,children:g===y.id?x("repoMesh.nodeList.saving"):x("repoMesh.nodeList.saveInstruction")})})]})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${o.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:T=>{T.stopPropagation(),S(y.id)},title:x("repoMesh.nodeList.removeNode"),children:s.jsx(KL,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:T=>T.stopPropagation(),children:[s.jsxs("summary",{className:"cursor-pointer select-none text-[12px] text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[s.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," ",x("repoMesh.nodeList.details")]}),s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:x("repoMesh.nodeList.nodeId")})," ",s.jsx("span",{className:"font-mono break-all",children:y.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:x("repoMesh.nodeList.launchReady")})," ",s.jsx("span",{className:C.configured?"text-green-400":"text-amber-400",children:C.configured?x("repoMesh.nodeList.launchReadyYes"):x("repoMesh.nodeList.launchReadyNo")})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:x("repoMesh.nodeList.repoRoot")})," ",s.jsx("span",{className:"font-mono break-all",children:y.repoRoot||y.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:x("repoMesh.nodeList.activeSessionsLabel")})," ",w.length]}),o.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:x("repoMesh.nodeList.added")})," ",new Date(y.created_at||y.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:x("repoMesh.nodeList.activeQueueAssignments")}),v.length===0?s.jsx("div",{children:x("repoMesh.nodeList.noActiveAssignment")}):s.jsx("ul",{className:"m-0 pl-4",children:v.map(T=>s.jsx("li",{className:"font-mono",children:m2(T)},T.id))})]}),w.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:x("repoMesh.nodeList.activeSessions")}),s.jsx("ul",{className:"m-0 pl-4",children:w.map(T=>s.jsxs("li",{className:"font-mono",children:[T.provider," / ",T.status," / ",T.id]},T.id))})]})]})]})]},y.id)})})}function p2(e,t){return t.filter(n=>n.status!=="assigned"?!1:(n.assignedNodeId||n.nodeId)===e.id)}function m2(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",n=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${n}`}function h2(e){var r,o;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set,a=t.map(i=>typeof i=="string"?i.trim():"").filter(Boolean).filter(i=>n.has(i)?!1:(n.add(i),!0));return a.length?a:G0((o=e.policy)==null?void 0:o.slots)}function f2(e){const t=h2(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"No provider configured on this node — task launch is blocked until a capability slot or provider priority is set."}}function jl(e){return e.isLocalWorktree===!0}function io(e){return e&&(e.machineNickname||e.nickname||e.hostname||(e.id?Rf(e.id):void 0))||"Unknown"}function g2(e){return String(e.daemon_id||e.daemonId||"")}function b2(e,t){const n=new Map(t.map(o=>[o.id,o])),a=[],r=new Map;for(const o of e){const i=g2(o);r.has(i)||(r.set(i,[]),a.push(i)),r.get(i).push(o)}return a.map(o=>{const i=r.get(o),c=o?n.get(o):void 0,d=i[0],p=o?c?io(c):(d==null?void 0:d.machine_label)||(d==null?void 0:d.machine_nickname)||(d==null?void 0:d.hostname)||o:io(c),u=(c==null?void 0:c.status)==="online",m=i.reduce((f,g)=>{var k;return f+(Array.isArray((k=g.policy)==null?void 0:k.slots)?g.policy.slots.length:0)},0);return{key:o,label:p,online:u,nodes:i,slotCount:m}})}function x2({groups:e,activeKey:t,onChange:n}){const{t:a}=ke("common");return s.jsx("div",{className:"flex items-center gap-1 px-1 border-b border-border-subtle mb-4 overflow-x-auto",role:"tablist","aria-label":a("repoMesh.nodeList.machineTabsLabel"),children:e.map(r=>{const o=r.key===t;return s.jsxs("button",{type:"button",role:"tab","aria-selected":o,onClick:()=>n(r.key),className:`flex items-center gap-2 px-3 py-2.5 text-[13px] font-medium border-b-2 -mb-px transition-colors cursor-pointer whitespace-nowrap ${o?"border-accent text-accent":"border-transparent text-text-muted hover:text-text-secondary"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${r.online?"bg-green-400":"bg-neutral-500"}`}),s.jsx("span",{className:"truncate max-w-[160px]",children:r.label}),s.jsx("span",{className:"text-[11px] text-text-muted font-normal",children:a("repoMesh.nodeList.machineTabCounts",{nodes:r.nodes.length,slots:r.slotCount})})]},r.key)})})}function v2({nodes:e,meshQueue:t,activeDaemon:n,daemons:a,selectedMeshId:r,userName:o,features:i,coordinatorDaemonId:c,availableCliProviders:d,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:b,selectedNodeId:S,onSelectNode:x,showAddNode:y,onShowAddNode:C,onCancelAddNode:v,nodeWorkspace:w,onNodeWorkspaceChange:j,nodeProviderPriority:N,onNodeProviderPriorityChange:A,nodeDaemonId:T,onNodeDaemonIdChange:I,nodeCustomPath:P,onNodeCustomPathChange:M,nodePickerWorkspaces:E,nodePickerProviders:D,nodeOnboardingPlan:W,nodePlanLoading:R,attachableDaemons:B,onAddNode:_,onRemoveNode:H}){var Ce,me,O;const{t:L}=ke("common"),F=l.useMemo(()=>XL(a),[a]),$=l.useMemo(()=>e.filter(Y=>!jl(Y)),[e]),K=l.useMemo(()=>i.addNodeDaemonPicker?b2($,a):[],[i.addNodeDaemonPicker,$,a]),[z,ne]=l.useState(null),ie=K.some(Y=>Y.key===z)?z:((Ce=K[0])==null?void 0:Ce.key)??"";return s.jsxs(xt,{title:i.addNodeDaemonPicker?L("repoMesh.nodeList.title",{count:$.length}):L("repoMesh.nodeList.titleNoCount"),description:i.addNodeDaemonPicker?L("repoMesh.nodeList.descriptionCloud"):L("repoMesh.nodeList.descriptionStandalone"),children:[i.addNodeDaemonPicker&&s.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:L("repoMesh.nodeList.daemonCandidates")}),s.jsx("div",{className:"text-[12px] text-text-muted",children:L("repoMesh.nodeList.daemonCandidatesHint")})]}),s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:L("repoMesh.nodeList.available",{count:B.length})})]}),a.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:L("repoMesh.nodeList.noDaemonsAvailable")}):B.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:L("repoMesh.nodeList.allDaemonsAttached")}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:B.map(Y=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors min-w-0 ${Y.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{I(Y.id),j(""),M(!1),A(Dn(cn(Y.availableProviders||[]))),C()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate min-w-0",children:io(Y)}),Y.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary shrink-0",children:L("repoMesh.nodeList.selectedHost")})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:Y.id}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:L("repoMesh.nodeList.workspacesDetected",{count:(Y.workspaces||[]).length})})]},Y.id))})]}),!y&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:C,children:[s.jsx(VL,{size:13})," ",i.addNodeDaemonPicker?L("repoMesh.nodeList.attachMachine"):L("repoMesh.nodeList.addNode")]}),y&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:i.addNodeDaemonPicker?L("repoMesh.nodeList.attachMachineTitle"):L("repoMesh.nodeList.addNodeTitle")}),s.jsx("button",{onClick:()=>{v(),I(""),M(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(Dt,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(Tt,{label:L("repoMesh.nodeList.machine"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:T,onChange:Y=>{var X;I(Y.target.value),j(""),M(!1),A(Dn(cn(((X=a.find(Q=>Q.id===Y.target.value))==null?void 0:X.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:L("repoMesh.nodeList.selectMachine")}),a.map(Y=>s.jsx("option",{value:Y.id,children:io(Y)},Y.id))]})}),(i.addNodeDaemonPicker?T:!0)&&s.jsx(Tt,{label:L("repoMesh.nodeList.workspacePath"),children:i.addNodeDaemonPicker&&!P&&E.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:E.map(Y=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${w===Y.path?"border-accent-primary bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-primary hover:bg-violet-500/10 text-text-primary"}`,onClick:()=>j(Y.path),children:[s.jsx("span",{className:"font-medium block truncate",children:Y.label||Y.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:Y.path})]},Y.id||Y.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{M(!0),j("")},children:L("repoMesh.nodeList.enterCustomPath")})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(xs,{value:w,onChange:Y=>j(Y.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:Y=>{Y.key==="Enter"&&_()}}),E.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{M(!1),j("")},children:L("repoMesh.nodeList.pickFromSaved")})]}):(()=>{var Q;const Y=Array.isArray(n==null?void 0:n.workspaces)?n.workspaces:[],X=`mesh-add-node-workspaces-${r||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(xs,{value:w,onChange:ve=>j(ve.target.value),placeholder:((Q=Y[0])==null?void 0:Q.path)||"/Users/dev/projects/myapp",list:Y.length>0?X:void 0,autoFocus:!0}),Y.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:X,children:Y.map(ve=>s.jsx("option",{value:ve.path,children:ve.label||ve.path},ve.id||ve.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:Y.slice(0,6).map(ve=>s.jsx("button",{type:"button",onClick:()=>j(ve.path),className:"text-[11px] px-2 py-0.5 rounded-full border border-border-subtle hover:border-accent-primary/50 text-text-muted hover:text-text-primary transition-colors bg-transparent cursor-pointer",title:ve.path,children:ve.label||ve.path.split("/").filter(Boolean).pop()||ve.path},ve.id||ve.path))})]})]})})()})}),(R||W)&&s.jsx(Mt,{variant:(W==null?void 0:W.success)===!1?"error":"info",className:"mb-4",children:R?"Inspecting Git repository (read-only)…":W!=null&&W.success?`${((me=W.plan)==null?void 0:me.summary)||"Compatible Git workspace detected."} Adding remains an explicit action.`:`${(W==null?void 0:W.code)||"onboarding_blocked"}: ${(W==null?void 0:W.error)||"Git discovery failed"} ${(W==null?void 0:W.action)||""}`}),s.jsx(Tt,{label:L("repoMesh.nodeList.preferredTools"),hint:L("repoMesh.nodeList.preferredToolsHint"),children:s.jsx(Yj,{value:N,availableProviders:i.addNodeDaemonPicker?D:d,onChange:A})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:_,disabled:R||(W==null?void 0:W.success)===!1||!w.trim()||i.addNodeDaemonPicker&&!T,className:"btn btn-primary btn-sm",children:L("repoMesh.nodeList.add")}),s.jsx("button",{onClick:()=>{v(),I(""),M(!1)},className:"btn btn-secondary btn-sm",children:L("repoMesh.nodeList.cancel")})]})]}),$.length===0?s.jsx(Xa,{icon:s.jsx(Tn,{}),title:L("repoMesh.nodeList.emptyTitle"),description:L("repoMesh.nodeList.emptyDescription")}):i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[K.length>1&&s.jsx(x2,{groups:K,activeKey:ie,onChange:ne}),s.jsx(tp,{nodes:((O=K.find(Y=>Y.key===ie))==null?void 0:O.nodes)||$,meshQueue:t,activeDaemon:n,daemons:a,userName:o,features:i,providersByDaemonId:F,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:b,selectedNodeId:S,onSelectNode:x,onRemoveNode:H})]}):s.jsx(tp,{nodes:$,meshQueue:t,activeDaemon:n,daemons:a,userName:o,features:i,providersByDaemonId:F,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:b,selectedNodeId:S,onSelectNode:x,onRemoveNode:H})]})}const y2=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],w2=[{kind:"rca",labelKey:"meshGraph.magiKind.kindRca",hint:"rca"},{kind:"design",labelKey:"meshGraph.magiKind.kindDesign",hint:"design"},{kind:"claim_audit",labelKey:"meshGraph.magiKind.kindClaimAudit",hint:"claim_audit"},{kind:"freeform",labelKey:"meshGraph.magiKind.kindFreeform",hint:"freeform"}];function k2(){return{nodeId:"",provider:"",model:"",n:""}}function sp(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function S2(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function C2(e){const t=[];for(let n=0;n<e.length;n++){const a=e[n],r=a.provider.trim();if(!r)return{error:{code:"provider_required",slot:n+1}};const o=a.nodeId.trim(),i=a.model.trim(),c=a.n.trim();let d;if(c){const p=Number(c);if(!Number.isFinite(p)||p<1)return{error:{code:"replica_min",slot:n+1}};d=Math.floor(p)}t.push({provider:r,...o?{nodeId:o}:{},...i?{model:i}:{},...d!==void 0?{n:d}:{}})}return t.length===0?{error:{code:"no_slot"}}:{slots:t}}function j2({status:e,daemonId:t,sendDaemonCommand:n,availableProviders:a}){const{t:r}=ke(),{theme:o}=Rs(),i=l.useMemo(()=>Es(o),[o]),c=l.useMemo(()=>bh(a),[a]),[d,p]=l.useState({}),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState({}),[b,S]=l.useState(null),x=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map($=>({nodeId:$.nodeId,machineLabel:$.machineLabel,providers:$.providers,providerPriority:$.providerPriority,isLocalWorktree:$.isLocalWorktree,worktreeBranch:$.worktreeBranch})),[e==null?void 0:e.nodes]),y=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map($=>$.nodeId),[e==null?void 0:e.nodes]),C=l.useMemo(()=>new Set(x.filter(jl).map($=>$.nodeId)),[x]),v=l.useMemo(()=>Object.fromEntries(x.filter(jl).map($=>[$.nodeId,$.worktreeBranch])),[x]),w=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map($=>[$.nodeId,$.machineLabel||$.nodeId])),[e==null?void 0:e.nodes]),j=l.useMemo(()=>{const $={};for(const K of x)$[K.nodeId]=sp(K);return $},[x]),N=l.useMemo(()=>{const $=[...new Set(x.flatMap(sp).filter(Boolean))];return[...new Set([...$,...y2])].sort()},[x]),A=!!t&&!!n,T=$=>$&&typeof $=="object"&&"result"in $?$.result:$,I=e==null?void 0:e.meshId,P=l.useCallback(async()=>{if(!(!t||!n)){m(!0),g(null);try{const $=await n(t,"magi_kind_panel_list",{...I?{meshId:I}:{}}),K=T($);if((K==null?void 0:K.success)===!1)throw new Error(K.error||r("meshGraph.magiKind.errorLoad"));p(K!=null&&K.kindPanels&&typeof K.kindPanels=="object"?K.kindPanels:{}),h({})}catch($){g(($==null?void 0:$.message)||r("meshGraph.magiKind.errorLoad"))}finally{m(!1)}}},[t,n,I,r]);l.useEffect(()=>{P()},[P]);const M=l.useCallback($=>{if(k[$])return k[$];const K=d[$];return K?K.map(S2):[]},[k,d]),E=($,K)=>{h(z=>({...z,[$]:K}))},D=($,K,z)=>{const ne=M($);E($,ne.map((ie,Ce)=>Ce===K?{...ie,...z}:ie))},W=$=>{E($,[...M($),k2()])},R=($,K)=>{E($,M($).filter((z,ne)=>ne!==K))},B=l.useCallback(async $=>{if(!t||!n)return;const K=C2(M($));if("error"in K){const z=K.error,ne=z.code==="provider_required"?r("meshGraph.magiKind.errorSlotProvider",{slot:z.slot}):z.code==="replica_min"?r("meshGraph.magiKind.errorSlotReplica",{slot:z.slot}):r("meshGraph.magiKind.errorNoSlot");g(`${$}: ${ne}`);return}S($),g(null);try{const z=await n(t,"magi_kind_panel_set",{kind:$,slots:K.slots,...I?{meshId:I}:{}}),ne=T(z);if((ne==null?void 0:ne.success)===!1)throw new Error(ne.error||r("meshGraph.magiKind.errorSave"));await P()}catch(z){g((z==null?void 0:z.message)||r("meshGraph.magiKind.errorSave"))}finally{S(null)}},[t,n,M,P,I,r]),_=l.useCallback(async $=>{if(!(!t||!n)&&confirm(r("meshGraph.magiKind.removeConfirm",{kind:$}))){S($),g(null);try{const K=await n(t,"magi_kind_panel_remove",{kind:$,...I?{meshId:I}:{}}),z=T(K);if((z==null?void 0:z.success)===!1)throw new Error(z.error||r("meshGraph.magiKind.errorRemove"));await P()}catch(K){g((K==null?void 0:K.message)||r("meshGraph.magiKind.errorRemove"))}finally{S(null)}}},[t,n,P,I,r]),H=`w-full rounded-lg border px-2.5 py-1.5 text-xs ${i.isDark?"border-white/10 bg-slate-950/40 text-slate-100 placeholder:text-slate-500":"border-slate-300 bg-white text-slate-900 placeholder:text-slate-400"}`,L="btn btn-primary btn-sm",F="btn btn-secondary btn-sm";return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("p",{className:`text-[12px] ${i.textSecondary}`,children:r("meshGraph.magiKind.intro")}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:F,onClick:()=>void P(),disabled:u||!A,children:r(u?"meshGraph.magiKind.loading":"meshGraph.magiKind.refresh")})})]}),!A&&s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${i.textSecondary} ${i.isDark?"border-white/10":"border-slate-200"}`,children:r("meshGraph.magiKind.connectPrompt")}),f&&s.jsx("div",{className:"rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-[12px] text-rose-300",children:f}),s.jsx("div",{className:"flex flex-col gap-3",children:w2.map(({kind:$,labelKey:K,hint:z})=>{const ne=M($),ie=!!d[$],Ce=b===$;return s.jsxs("div",{className:`${i.cardClass} rounded-2xl p-4 flex flex-col gap-3`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[13px] font-semibold ${i.textPrimary}`,children:r(K)}),s.jsx("span",{className:`font-mono text-[10px] ${i.textMuted}`,children:z}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${ie?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:ie?r("meshGraph.magiKind.agentCount",{count:d[$].length}):r("meshGraph.magiKind.off")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[ne.length===0&&s.jsx("div",{className:`rounded-xl border p-2.5 text-[11px] ${i.textSecondary} ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:r("meshGraph.magiKind.noAgents")}),ne.map((me,O)=>{const Y=me.nodeId?j[me.nodeId]??[]:[],X=me.nodeId&&Y.length?Y:N;return s.jsxs("div",{className:`rounded-xl border p-2.5 grid grid-cols-1 sm:grid-cols-[1fr_1fr_1fr_auto_auto] gap-x-2 gap-y-1 items-start ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:r("meshGraph.magiKind.machine")}),s.jsxs("select",{className:H,value:me.nodeId,onChange:Q=>D($,O,{nodeId:Q.target.value}),title:r("meshGraph.magiKind.machineTitle"),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.anyMachine")}),y.map(Q=>{const ve=C.has(Q),he=ve?r("meshGraph.magiKind.worktreeSuffix",{label:w[Q]??Q,branch:v[Q]||r("meshGraph.magiKind.worktreeUnknownBranch")}):w[Q]??Q;return s.jsx("option",{value:Q,disabled:ve,title:ve?r("meshGraph.magiKind.worktreeDisabledTitle"):void 0,children:he},Q)}),me.nodeId&&!y.includes(me.nodeId)&&s.jsx("option",{value:me.nodeId,children:r("meshGraph.magiKind.offlineSuffix",{label:w[me.nodeId]??me.nodeId})})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:[r("meshGraph.magiKind.provider")," *"]}),s.jsxs("select",{className:H,value:me.provider,onChange:Q=>D($,O,{provider:Q.target.value}),title:r("meshGraph.magiKind.providerTitle"),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.selectProvider")}),X.map(Q=>s.jsx("option",{value:Q,children:Q},Q)),me.provider&&!X.includes(me.provider)&&s.jsx("option",{value:me.provider,children:me.provider})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:r("meshGraph.magiKind.model")}),(()=>{var he;const Q=(me.provider?(he=c.get(me.provider))==null?void 0:he.models:void 0)??[],ve=!!me.model&&Q.length>0&&!Q.includes(me.model);return Q.length>0&&!ve?s.jsxs("select",{className:H,value:Q.includes(me.model)?me.model:"",title:r("meshGraph.magiKind.modelTitle"),onChange:Z=>D($,O,{model:Z.target.value==="__custom__"?" ":Z.target.value}),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.modelDefault")}),Q.map(Z=>s.jsx("option",{value:Z,children:Z},Z)),s.jsx("option",{value:"__custom__",children:r("meshGraph.magiKind.modelCustom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:H,value:me.model.trim(),placeholder:r("meshGraph.magiKind.modelDefault"),title:r("meshGraph.magiKind.modelTitle"),onChange:Z=>D($,O,{model:Z.target.value})}),Q.length>0&&s.jsx("button",{type:"button",className:`self-start bg-transparent border-none cursor-pointer p-0 text-[10px] ${i.textSecondary} hover:underline`,onClick:()=>D($,O,{model:""}),children:r("meshGraph.magiKind.backToModelList")})]})})()]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:r("meshGraph.magiKind.copies")}),s.jsx("input",{className:`${H} sm:w-16`,value:me.n,placeholder:"1",inputMode:"numeric",title:r("meshGraph.magiKind.copiesTitle"),onChange:Q=>D($,O,{n:Q.target.value})})]}),s.jsx("button",{type:"button",className:`${F} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>R($,O),"aria-label":r("meshGraph.magiKind.removeAgent"),title:r("meshGraph.magiKind.removeAgent"),children:"✕"})]},O)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:F,onClick:()=>W($),disabled:!A,children:r("meshGraph.magiKind.addAgent")})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:L,onClick:()=>void B($),disabled:Ce||!A,children:r(Ce?"meshGraph.magiKind.saving":"meshGraph.magiKind.save")}),s.jsx("button",{type:"button",className:F,onClick:()=>void _($),disabled:Ce||!A||!ie,title:r(ie?"meshGraph.magiKind.removeBindingTitle":"meshGraph.magiKind.removeBindingDisabledTitle"),children:r("meshGraph.magiKind.removeBinding")})]})]},$)})})]})}const On={sessionMinRemainingPercent:10,weeklyMinRemainingPercent:15,sessionResetImminentMinutes:5,staleAfterMinutes:30,spreadBonusMax:30,sessionAxisWeeklyHeadroomPercent:40},Nl=60*1e3;function np(e){return e===void 0||!Number.isFinite(e)?"":String(e/Nl)}function Al(e){const t=e??{};return{sessionMinRemainingPercent:t.sessionMinRemainingPercent!==void 0?String(t.sessionMinRemainingPercent):"",weeklyMinRemainingPercent:t.weeklyMinRemainingPercent!==void 0?String(t.weeklyMinRemainingPercent):"",sessionResetImminentMinutes:np(t.sessionResetImminentMs),staleAfterMinutes:np(t.staleAfterMs),spreadBonusMax:t.spreadBonusMax!==void 0?String(t.spreadBonusMax):"",sessionAxisWeeklyHeadroomPercent:t.sessionAxisWeeklyHeadroomPercent!==void 0?String(t.sessionAxisWeeklyHeadroomPercent):""}}function N2(e,t){const n=t.trim();if(!n)return null;const a=Number(n);if(!Number.isFinite(a))return"notANumber";const r=e==="sessionMinRemainingPercent"||e==="weeklyMinRemainingPercent"||e==="sessionAxisWeeklyHeadroomPercent";return r&&(a<0||a>100)?"percentRange":!r&&a<0?"negative":null}function Tl(e){const t={},n=p=>{const u=p.trim();if(!u)return;const m=Number(u);return Number.isFinite(m)?m:void 0},a=n(e.sessionMinRemainingPercent);a!==void 0&&(t.sessionMinRemainingPercent=a);const r=n(e.weeklyMinRemainingPercent);r!==void 0&&(t.weeklyMinRemainingPercent=r);const o=n(e.sessionResetImminentMinutes);o!==void 0&&(t.sessionResetImminentMs=o*Nl);const i=n(e.staleAfterMinutes);i!==void 0&&(t.staleAfterMs=i*Nl);const c=n(e.spreadBonusMax);c!==void 0&&(t.spreadBonusMax=c);const d=n(e.sessionAxisWeeklyHeadroomPercent);return d!==void 0&&(t.sessionAxisWeeklyHeadroomPercent=d),t}const A2="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs",T2="w-full rounded-lg border border-red-500/60 bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function M2({quotaRouting:e,saving:t,error:n,onSave:a}){const{t:r}=ke("common"),[o,i]=l.useState(()=>Al(e)),c=l.useCallback((k,h)=>{i(b=>({...b,[k]:h}))},[]),d=l.useMemo(()=>{const k={};for(const h of Object.keys(o)){const b=N2(h,o[h]);b&&(k[h]=b)}return k},[o]),p=Object.keys(d).length>0,u=l.useMemo(()=>JSON.stringify(Tl(o))!==JSON.stringify(P2(e)),[o,e]),m=l.useCallback(()=>{p||a(Tl(o))},[o,p,a]),f=l.useCallback(()=>{i(Al(null))},[]),g=[{key:"sessionMinRemainingPercent",label:r("setupWizard.quotaPolicy.sessionMin"),hint:r("setupWizard.quotaPolicy.sessionMinHint"),placeholder:On.sessionMinRemainingPercent,unit:"%"},{key:"weeklyMinRemainingPercent",label:r("setupWizard.quotaPolicy.weeklyMin"),hint:r("setupWizard.quotaPolicy.weeklyMinHint"),placeholder:On.weeklyMinRemainingPercent,unit:"%"},{key:"sessionResetImminentMinutes",label:r("setupWizard.quotaPolicy.resetImminent"),hint:r("setupWizard.quotaPolicy.resetImminentHint"),placeholder:On.sessionResetImminentMinutes,unit:r("setupWizard.quotaPolicy.minutes")},{key:"staleAfterMinutes",label:r("setupWizard.quotaPolicy.staleAfter"),hint:r("setupWizard.quotaPolicy.staleAfterHint"),placeholder:On.staleAfterMinutes,unit:r("setupWizard.quotaPolicy.minutes")},{key:"spreadBonusMax",label:r("setupWizard.quotaPolicy.spreadBonus"),hint:r("setupWizard.quotaPolicy.spreadBonusHint"),placeholder:On.spreadBonusMax,unit:""},{key:"sessionAxisWeeklyHeadroomPercent",label:r("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroom"),hint:r("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroomHint"),placeholder:On.sessionAxisWeeklyHeadroomPercent,unit:"%"}];return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:r("setupWizard.quotaPolicy.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:r("setupWizard.quotaPolicy.description")})]}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 sm:grid-cols-2",children:g.map(k=>{const h=d[k.key];return s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:"text-[11px] text-text-muted",children:[k.label,k.unit?` (${k.unit})`:""]}),s.jsx("input",{type:"number",inputMode:"decimal",className:h?T2:A2,value:o[k.key],placeholder:String(k.placeholder),onChange:b=>c(k.key,b.target.value)}),s.jsx("span",{className:`text-[10px] leading-snug ${h?"text-red-400":"text-text-muted"}`,children:h?r(`setupWizard.quotaPolicy.errors.${h}`):k.hint})]},k.key)})}),s.jsx("p",{className:"text-[10px] leading-relaxed text-text-muted",children:r("setupWizard.quotaPolicy.blankMeansDefault")}),n?s.jsx("p",{className:"text-[11px] text-red-400",children:n}):null,s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:f,children:r("setupWizard.quotaPolicy.useDefaults")}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:m,disabled:!!t||p||!u,children:r(t?"setupWizard.quotaPolicy.saving":"setupWizard.quotaPolicy.save")})]})]})}function P2(e){return Tl(Al(e))}function dg(e,t,n,a){const{t:r}=ke(),[o,i]=l.useState(!1),[c,d]=l.useState(null),[p,u]=l.useState(null),[m,f]=l.useState(null),g=l.useCallback(async()=>{if(!e||!t){d(r("repoMesh.promptPreview.connectPrompt"));return}i(!0),d(null);try{const k=await a(e,"coordinator_prompt_preview",{meshId:t,cliType:n}),h=k!=null&&k.result&&typeof k.result=="object"?k.result:k;if(!(h!=null&&h.success))return d((h==null?void 0:h.error)||r("repoMesh.promptPreview.errorRender")),null;const b=typeof h.prompt=="string"?h.prompt:"";return u(b),f(typeof h.bytes=="number"?h.bytes:null),b}catch(k){return d((k==null?void 0:k.message)||String(k)),null}finally{i(!1)}},[e,t,n,a,r]);return{loading:o,error:c,prompt:p,bytes:m,load:g}}function D2({daemonId:e,meshId:t,cliType:n,sendCommand:a,defaultOpen:r=!1}){const{t:o}=ke(),[i,c]=l.useState(r),{loading:d,error:p,prompt:u,bytes:m,load:f}=dg(e,t,n,a),g=l.useRef(!1);l.useEffect(()=>{i&&!g.current&&(g.current=!0,f())},[i,f]);const k=l.useCallback(()=>{c(h=>!h)},[]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:k,className:"inline-flex items-center gap-1 text-[12px] text-accent-primary bg-transparent border-none cursor-pointer p-0",children:[s.jsx("span",{className:`transition-transform ${i?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),o(i?"repoMesh.promptPreview.hide":"repoMesh.promptPreview.view"),s.jsxs("span",{className:"text-text-muted",children:["(",n,")"]})]}),i&&s.jsxs("div",{className:"mt-2",children:[d&&s.jsx("div",{className:"text-[12px] text-text-muted",children:o("repoMesh.promptPreview.rendering")}),p&&s.jsxs("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:[p,s.jsx("button",{type:"button",onClick:()=>void f(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:o("repoMesh.promptPreview.retry")})]}),!d&&!p&&u!==null&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between text-[11px] text-text-muted",children:[s.jsx("span",{children:o("repoMesh.promptPreview.info")}),m!==null&&s.jsxs("span",{children:[(m/1024).toFixed(1)," KB"]})]}),s.jsx("textarea",{readOnly:!0,value:u,rows:14,className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-secondary font-mono",onFocus:h=>h.currentTarget.select()})]})]})]})}function I2({daemonId:e,meshId:t,cliType:n,sendCommand:a,disabled:r,hasContent:o,onApply:i}){const{t:c}=ke(),{loading:d,load:p}=dg(e,t,n,a),u=l.useCallback(async()=>{if(o&&!window.confirm(c("repoMesh.detail.startFromDefaultConfirm")))return;const m=await p();typeof m=="string"&&i(m)},[o,p,i,c]);return s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm mt-2",onClick:()=>void u(),disabled:r||d||!e||!t,title:c("repoMesh.detail.startFromDefaultTitle"),children:c(d?"repoMesh.promptPreview.rendering":"repoMesh.detail.startFromDefault")})}const L2=[{token:"meshName",description:"This mesh's display name.",example:"my-app"},{token:"repo",description:"Repo identity (owner/repo or workspace path).",example:"vilmire/adhdev"},{token:"defaultBranch",description:"The mesh's default branch.",example:"main"},{token:"cliType",description:"The coordinator CLI type this prompt is being rendered for.",example:"claude-cli"},{token:"nodes",description:"Live node status table, or the configured node list if no live status is available.",example:"(rendered node table)"},{token:"mission",description:"Current mission section, when a mission is active. Empty otherwise.",example:"(mission summary or empty)"},{token:"recentActivity",description:"Recent mesh activity summary. Empty when none.",example:"(recent activity or empty)"},{token:"operatingNotes",description:"Accumulated operating notes for this mesh. Empty when none.",example:"(operating notes or empty)"},{token:"policy",description:"The mesh's effective policy section (safety, scheduling, etc.).",example:"(rendered policy section)"},{token:"tools",description:"The canonical MCP tools reference table.",example:"(tools table)"},{token:"workflow",description:"The standard coordinator workflow guidance section.",example:"(workflow section)"},{token:"onboarding",description:"Onboarding/reinit guidance section.",example:"(onboarding section)"},{token:"rules",description:"CLI-type-specific and policy-derived rules section.",example:"(rules section)"},{token:"toolExposurePreflight",description:"Preflight guidance for verifying tool exposure before relying on it.",example:"(preflight section)"}],R2=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function E2(e){const t=R2(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function _2(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function H2(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const $2=["active","paused","completed","abandoned"];function ap(e){return(e.status||"active").toLowerCase()}const F2=8;function B2({status:e,daemonId:t,meshId:n,sendCommand:a}){const{t:r}=ke("common"),o=l.useMemo(()=>_2(e),[e]),[i,c]=l.useState({}),[d,p]=l.useState({}),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState("active"),[b,S]=l.useState(!1),x=l.useMemo(()=>{const A={};for(const T of o){const I=ap(T);A[I]=(A[I]||0)+1}return A},[o]),y=l.useMemo(()=>k==="all"?o:o.filter(A=>ap(A)===k),[o,k]),C=b?y:y.slice(0,F2),v=y.length-C.length,w=!!t&&o.length>0,j=l.useCallback(async()=>{if(t){m(!0),g(null);try{const A=await a(t,"mesh_status",{meshId:n,verbose:!0}),T=E2(A),I=Array.isArray(T==null?void 0:T.missions)?T.missions:[],P={};for(const M of I)M.id&&typeof M.goal=="string"&&M.goal&&(P[M.id]=M.goal);c(M=>({...M,...P}))}catch(A){g(A instanceof Error?A.message:r("repoMesh.missions.errorFetch"))}finally{m(!1)}}},[t,n,a,r]),N=l.useCallback(A=>{p(T=>({...T,[A]:!T[A]})),!d[A]&&!i[A]&&j()},[d,i,j]);return o.length===0?null:s.jsxs(xt,{title:r("repoMesh.missions.title"),description:r("repoMesh.missions.description"),children:[f&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400",children:f}),s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[$2.filter(A=>(x[A]||0)>0).map(A=>s.jsxs("button",{type:"button",onClick:()=>{h(A),S(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] capitalize transition-colors ${k===A?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:[A," ",x[A]]},A)),s.jsxs("button",{type:"button",onClick:()=>{h("all"),S(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] transition-colors ${k==="all"?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:["All ",o.length]})]}),y.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:r("repoMesh.missions.empty",{status:k})}),s.jsx("div",{className:"flex flex-col gap-2",children:C.map(A=>{var W;const T=d[A.id]===!0,I=i[A.id],P=H2(A),M=T&&I?I:P.text,E=T&&!I&&P.truncated,D=((W=A.tasks)==null?void 0:W.total)??0;return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 px-3 py-2.5",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-text-primary",title:A.title,children:A.title||A.id}),A.status&&s.jsx("span",{className:"shrink-0 rounded-full border border-border-subtle px-2 py-0.5 text-[10px] uppercase tracking-wide text-text-muted",children:A.status}),D>0&&s.jsx("span",{className:"shrink-0 text-[11px] text-text-muted",children:r("repoMesh.missions.taskCount",{count:D})})]}),M&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${T?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[M,E&&s.jsx("span",{className:"text-text-muted",children:r("repoMesh.missions.goalUnavailable")})]}),(P.truncated||I)&&w&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>N(A.id),disabled:u,children:r(T?"repoMesh.missions.showLess":u&&!I?"repoMesh.missions.loading":"repoMesh.missions.showFullGoal")})]},A.id)})}),v>0&&s.jsx("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>S(!0),children:r("repoMesh.missions.showMore",{count:v})})]})}function rp(e,t){if(t)return e.modes.find(n=>n.id===t)}function W2(e){return e.modes.find(t=>t.strategy==="pty-parse-default"&&qs(t)!=="dangerous")}function O2({config:e,requestedModeId:t,machineAutoApproveEnabled:n,machineDangerousAllowed:a}){const r=rp(e,e.default),o=r==null?void 0:r.id,i=(t==null?void 0:t.trim())||void 0;if(!n)return{status:"disabled",requestedModeId:i,providerDefaultModeId:o,requestedModeUnknown:!1,downgraded:!1};const c=rp(e,i),d=!!i&&!c,p=c??r;if(!p||p.strategy==="post-boot-command")return{status:"none",requestedModeId:i,providerDefaultModeId:o,requestedModeUnknown:d,downgraded:!1};if(qs(p)==="dangerous"&&!a){const u=W2(e);return{status:u?"downgraded":"none",requestedModeId:i,providerDefaultModeId:o,effectiveMode:u,requestedModeUnknown:d,downgraded:!0}}return{status:d?"invalid_fallback":"requested",requestedModeId:i,providerDefaultModeId:o,effectiveMode:p,requestedModeUnknown:d,downgraded:!1}}function U2(e){const t=[];for(const n of e||[]){if(!n||n.category!=="cli")continue;const a=n.autoApproveModes;if(!a||!Array.isArray(a.modes)||a.modes.length===0)continue;const r=String(n.type||n.id||"").trim();r&&t.push({type:r,label:String(n.displayName||n.name||r),autoApproveModes:a})}return t}function G2({hostDaemonId:e,hostOnline:t,hostWorkspace:n,meshProviders:a,unreportedNodeCount:r=0,machineAutoApproveEnabled:o,machineDangerousAllowed:i,onUpdatePolicy:c,savingPolicy:d,sendCommand:p}){const{t:u}=ke("common"),m=l.useMemo(()=>U2(a),[a]),[f,g]=l.useState({}),[k,h]=l.useState(!1),[b,S]=l.useState(null),[x,y]=l.useState(!1),[C,v]=l.useState(null),[w,j]=l.useState(!1),[N,A]=l.useState(null),[T,I]=l.useState(!1),P=!!e&&t&&!!n,M=!!c&&!d,E=l.useCallback(async()=>{var _,H,L;if(P){h(!0),S(null);try{const F=await p(e,"read_mesh_json_config",{workspace:n}),$=(F==null?void 0:F.result)??F,K=((_=$==null?void 0:$.providerDefaults)==null?void 0:_.autoApproveModes)||((L=(H=$==null?void 0:$.config)==null?void 0:H.providerDefaults)==null?void 0:L.autoApproveModes),z={};if(K&&typeof K=="object")for(const[ne,ie]of Object.entries(K))typeof ie=="string"&&ie.trim()&&(z[ne]=ie.trim());g(z)}catch(F){S((F==null?void 0:F.message)||u("repoMesh.providerAutoApprove.loadError"))}finally{h(!1)}}},[P,e,n,p,u]);l.useEffect(()=>{E()},[E]);const D=l.useCallback((_,H)=>{j(!1),g(L=>{const F={...L};return H&&H.trim()?F[_]=H.trim():delete F[_],F})},[]),W=l.useCallback((_,H)=>{if(qs(H)==="dangerous"){A({type:_,mode:H});return}D(_,H.id)},[D]),R=l.useCallback(()=>{N&&D(N.type,N.mode.id),A(null)},[D,N]),B=l.useCallback(async()=>{if(P){y(!0),v(null),j(!1);try{const _=await p(e,"set_mesh_provider_defaults",{workspace:n,autoApproveModes:f,merge:!1,write:!0}),H=(_==null?void 0:_.result)??_;if((H==null?void 0:H.success)===!1)throw new Error((H==null?void 0:H.error)||u("repoMesh.providerAutoApprove.saveError"));j(!0),await E()}catch(_){v((_==null?void 0:_.message)||u("repoMesh.providerAutoApprove.saveError"))}finally{y(!1)}}},[P,e,n,E,f,p,u]);return s.jsxs(xt,{title:u("repoMesh.providerAutoApprove.title"),description:u("repoMesh.providerAutoApprove.subtitle"),collapsible:!0,defaultOpen:!1,children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-3.5",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u("repoMesh.providerAutoApprove.machineSection.title")}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.machineSection.hint")}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-[11px]",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-semibold ${o?"border-status-online/25 bg-status-online/10 text-status-online":"border-border-subtle bg-surface-secondary/40 text-text-muted"}`,children:u(o?"repoMesh.providerAutoApprove.machineSection.autoApproveOn":"repoMesh.providerAutoApprove.machineSection.autoApproveOff")}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-semibold ${i?"border-status-error/30 bg-status-error/10 text-status-error":"border-border-subtle bg-surface-secondary/40 text-text-muted"}`,children:u(i?"repoMesh.providerAutoApprove.machineSection.dangerousOn":"repoMesh.providerAutoApprove.machineSection.dangerousOff")})]}),s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsx(op,{label:u("repoMesh.providerAutoApprove.machineSection.autoApproveToggleLabel"),hint:u("repoMesh.providerAutoApprove.machineSection.autoApproveToggleHint"),checked:o,disabled:!M,onChange:_=>c==null?void 0:c({delegatedWorkerAutoApprove:_})}),s.jsx(op,{label:u("repoMesh.providerAutoApprove.machineSection.dangerousToggleLabel"),hint:u(o?"repoMesh.providerAutoApprove.machineSection.dangerousToggleHint":"repoMesh.providerAutoApprove.machineSection.dangerousDisabledHint"),checked:i,disabled:!M||!o,onChange:_=>{_?I(!0):c==null||c({delegatedWorkerDangerousModeAllow:!1})}})]})]}),P?k?s.jsx("div",{className:"text-[13px] text-text-muted",children:u("repoMesh.providerAutoApprove.loading")}):m.length===0?s.jsx("div",{className:"text-[13px] text-text-muted",children:r>0?u("repoMesh.providerAutoApprove.awaitingNodes",{count:r}):u("repoMesh.providerAutoApprove.noProviders")}):s.jsxs("div",{className:"space-y-6",children:[b&&s.jsx(Mt,{variant:"error",onDismiss:()=>S(null),children:b}),r>0&&s.jsx("div",{className:"text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.partialInventory",{count:r})}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u("repoMesh.providerAutoApprove.repoSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.repoSection.hint")})]}),s.jsx("div",{className:"space-y-5",children:m.map(_=>{const H=f[_.type],L=O2({config:_.autoApproveModes,requestedModeId:H,machineAutoApproveEnabled:o,machineDangerousAllowed:i});return s.jsxs("div",{className:"rounded-xl border border-border-subtle p-3.5",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary",children:_.label}),s.jsx("button",{type:"button",className:"text-[11px] text-text-muted underline decoration-dotted hover:text-text-primary disabled:opacity-40",onClick:()=>D(_.type,void 0),disabled:!H||x,children:u("repoMesh.providerAutoApprove.repoSection.clear")})]}),s.jsx(hf,{config:_.autoApproveModes,selectedModeId:H||"",disabled:x,onSelectMode:F=>W(_.type,F)}),!H&&s.jsx("div",{className:"mt-1.5 text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.repoSection.usesProviderDefault")}),s.jsx(q2,{effective:L,config:_.autoApproveModes})]},_.type)})}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u("repoMesh.providerAutoApprove.effectiveSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.effectiveSection.hint")})]}),C&&s.jsx(Mt,{variant:"error",onDismiss:()=>v(null),children:C}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("button",{type:"button",className:"rounded-lg bg-accent-primary px-4 py-2 text-sm font-semibold text-white disabled:opacity-50",onClick:()=>void B(),disabled:x,children:u(x?"repoMesh.providerAutoApprove.saving":"repoMesh.providerAutoApprove.save")}),w&&s.jsx("span",{className:"text-[12px] text-status-online",children:u("repoMesh.providerAutoApprove.saved")})]})]}):s.jsx("div",{className:"text-[13px] text-text-muted",children:u("repoMesh.providerAutoApprove.noHostDaemon")}),T&&s.jsx(Ao,{title:u("repoMesh.providerAutoApprove.machineSection.confirmTitle"),description:u("repoMesh.providerAutoApprove.machineSection.confirmDescription"),details:[{label:u("repoMesh.providerAutoApprove.machineSection.confirmScopeLabel"),value:u("repoMesh.providerAutoApprove.machineSection.confirmScopeValue")},{label:u("repoMesh.providerAutoApprove.machineSection.confirmEffectLabel"),value:u("repoMesh.providerAutoApprove.machineSection.confirmEffectValue")}],confirmLabel:u("repoMesh.providerAutoApprove.machineSection.confirmConfirm"),onConfirm:()=>{I(!1),c==null||c({delegatedWorkerDangerousModeAllow:!0})},onCancel:()=>I(!1)}),N&&s.jsx(ff,{mode:N.mode,onConfirm:R,onCancel:()=>A(null)}),N&&s.jsx("div",{className:"fixed inset-x-0 bottom-6 z-[60] mx-auto max-w-lg px-4",children:s.jsxs("div",{className:"rounded-xl border border-status-error/40 bg-bg-primary p-3.5 shadow-lg",children:[s.jsx("div",{className:"text-sm font-semibold text-status-error",children:u("repoMesh.providerAutoApprove.dangerous.sharedWarningTitle")}),s.jsx("div",{className:"mt-1 text-[12px] text-text-muted",children:u("repoMesh.providerAutoApprove.dangerous.sharedWarning")})]})})]})}function q2({effective:e,config:t}){var c,d,p;const{t:n}=ke("common"),a=u=>{var m;return(u?(m=t.modes.find(f=>f.id===u))==null?void 0:m.label:void 0)||u||""};let r,o="ok";switch(e.status){case"requested":r=n("repoMesh.providerAutoApprove.effectiveSection.statusRequested",{mode:((c=e.effectiveMode)==null?void 0:c.label)||""});break;case"invalid_fallback":r=n("repoMesh.providerAutoApprove.effectiveSection.statusInvalidFallback",{mode:((d=e.effectiveMode)==null?void 0:d.label)||""}),o="warn";break;case"downgraded":r=n("repoMesh.providerAutoApprove.effectiveSection.statusDowngraded",{requested:a(e.requestedModeId)||a(e.providerDefaultModeId),mode:((p=e.effectiveMode)==null?void 0:p.label)||""}),o="warn";break;case"disabled":r=n("repoMesh.providerAutoApprove.effectiveSection.statusDisabled"),o="muted";break;default:r=n("repoMesh.providerAutoApprove.effectiveSection.statusNone"),o="muted"}const i=o==="ok"?"border-status-online/25 bg-status-online/5 text-text-secondary":o==="warn"?"border-status-warning/30 bg-status-warning/5 text-status-warning":"border-border-subtle bg-surface-secondary/30 text-text-muted";return s.jsxs("div",{className:`mt-3 flex items-center gap-2 rounded-lg border px-3 py-2 text-[12px] ${i}`,children:[e.effectiveMode&&s.jsx(mf,{risk:qs(e.effectiveMode)}),s.jsx("span",{className:"min-w-0",children:r})]})}function op({label:e,hint:t,checked:n,disabled:a=!1,onChange:r}){return s.jsxs("button",{type:"button",role:"switch","aria-checked":n,className:"flex w-full items-center justify-between gap-3 rounded-xl border border-border-subtle bg-bg-primary/60 px-3.5 py-2.5 text-left disabled:opacity-50",onClick:()=>r(!n),disabled:a,children:[s.jsxs("span",{children:[s.jsx("span",{className:"block text-[13px] font-semibold text-text-primary",children:e}),s.jsx("span",{className:"mt-0.5 block text-[11px] text-text-muted",children:t})]}),s.jsx("span",{className:`relative h-6 w-11 shrink-0 rounded-full transition-colors ${n?"bg-accent-primary":"bg-surface-secondary"}`,children:s.jsx("span",{className:`absolute top-0.5 h-5 w-5 rounded-full bg-white shadow transition-transform ${n?"translate-x-5":"translate-x-0.5"}`})})]})}function Sr(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function z2({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:n,isHostNodeAttached:a,selectedHostNode:r,hostPinned:o,hostLabel:i,hostOnline:c,hostRebindDaemonId:d,onHostRebindDaemonIdChange:p,settingMeshHost:u,onSetMeshHost:m}){const{t:f}=ke("common");if(o)return s.jsxs(xt,{title:f("repoMesh.host.title"),description:f("repoMesh.host.descriptionSet"),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-[13px] text-text-primary ${c?"border-accent-primary/40 bg-accent-primary/10":"border-amber-500/40 bg-amber-500/10"}`,children:[s.jsx("span",{className:"text-text-muted",children:f("repoMesh.host.hostLabel")}),s.jsx("span",{className:"font-medium",children:i||f("repoMesh.host.unknown")}),s.jsxs("span",{className:c?"text-text-muted":"text-amber-400",children:["· ",f(c?"repoMesh.host.online":"repoMesh.host.offline")]})]}),(r==null?void 0:r.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:[f("repoMesh.host.hostNode")," ",s.jsx("span",{className:"font-mono text-text-secondary",children:r.workspace})]})]}),!c&&s.jsxs("div",{className:"mt-4",children:[s.jsxs(Mt,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:f("repoMesh.host.hostOffline")})," ",f("repoMesh.host.hostOfflineText")]}),e.length>0?s.jsx(Tt,{label:f("repoMesh.host.reconnectToCommand"),hint:f("repoMesh.host.reconnectToCommandHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:d,onChange:h=>p(h.target.value),children:[s.jsx("option",{value:"",children:f("repoMesh.host.waitForHost")}),e.map(h=>s.jsx("option",{value:h.id,children:Sr(h)},h.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:f("repoMesh.host.noDaemonsToRoute")})]})]});const g=e.find(h=>h.id===t),k=m&&t?s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>m(t),disabled:!!u,children:f(u?"repoMesh.host.settingHost":"repoMesh.host.setHostAction")}):null;return s.jsxs(xt,{title:f("repoMesh.host.title"),description:f("repoMesh.host.descriptionUnset"),children:[s.jsxs(Mt,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:f("repoMesh.host.setHostBanner")})," ",f("repoMesh.host.setHostBannerText")]}),e.length>0?s.jsxs(s.Fragment,{children:[t?s.jsx("div",{className:"mb-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:a?s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:Sr(g)}),r!=null&&r.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:r.workspace})]}):null,". ",f("repoMesh.host.confirmSetsHost")]}):s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:Sr(g)}),". ",f("repoMesh.host.attachNodeThenSetHost")]})}):s.jsx(Tt,{label:f("repoMesh.host.hostDaemon"),hint:f("repoMesh.host.hostDaemonHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:"",onChange:h=>n(h.target.value),children:[s.jsx("option",{value:"",children:f("repoMesh.host.resolvingHost")}),e.map(h=>s.jsx("option",{value:h.id,children:Sr(h)},h.id))]})}),k&&s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[k,s.jsx("span",{className:"text-[12px] text-text-muted",children:f("repoMesh.host.setHostActionHint")})]})]}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:f("repoMesh.host.noDaemonsToHost")})]})}function K2({meshId:e,availableCliAgents:t}){const{t:n}=ke(),a=t.find(o=>{const i=o.id.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||o.name.toLowerCase().includes("hermes")}),r=Wh(a==null?void 0:a.meshCoordinator,{meshId:e});return r?s.jsx(xt,{title:n("repoMesh.hermesMcp.title"),description:n("repoMesh.hermesMcp.description"),children:s.jsx(pf,{setup:r,providerName:(a==null?void 0:a.name)||n("repoMesh.hermesMcp.fallbackProvider")})}):null}const $i=[{value:"preserve",label:"Preserve history and runtimes",description:"Keep completed chat history and leave live runtimes alone."},{value:"stop",label:"Stop live runtimes only",description:"Release running session processes, but keep chat records/transcripts."},{value:"delete_stopped",label:"Delete stopped sessions only",description:"Clean completed/stopped chat clutter without killing live runtimes."},{value:"stop_and_delete",label:"Stop and delete sessions",description:"Stop matching runtimes, then remove their session records/transcripts."}],V2=[{value:"smart",labelKey:"repoMesh.detail.distributionSmart",descriptionKey:"repoMesh.detail.distributionSmartDescription"},{value:"in_order",labelKey:"repoMesh.detail.distributionInOrder",descriptionKey:"repoMesh.detail.distributionInOrderDescription"}];function Y2(e){return e==="smart"?"fitness":"first_eligible"}function Q2(e,t){const n=e||"first_eligible";return n==="fitness"||n==="least_loaded"||n==="round_robin"||n==="priority_only"&&t!=null&&t.priorityConfigured?"smart":"in_order"}const J2={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function Ml(e){return{...J2,...(e==null?void 0:e.policy)||{}}}function X2(e){return{routeId:`mesh-settings:${e.meshId}`,daemonId:e.daemonId,agentName:e.meshName,agentType:"mesh",status:"idle",title:e.meshName,messages:[],workspaceName:e.meshName,displayPrimary:e.meshName,displaySecondary:"Mesh observability",streamSource:"native",tabKey:`mesh-settings:${e.meshId}`,coordinator:{meshId:e.meshId,role:"coordinator"},settings:{meshCoordinatorFor:e.meshId}}}function Z2({selectedMesh:e,error:t,onDismissError:n,onBack:a,onDelete:r,displayedMeshStatus:o,graphLoading:i,graphError:c,onRefreshGraph:d,savingPolicy:p,onUpdatePolicy:u,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:f,savingCoordinatorPrompt:g,onSaveCoordinatorPrompt:k,daemons:h,coordinatorDaemonId:b,onCoordinatorDaemonIdChange:S,coordinatorCliType:x,isHostNodeAttached:y,selectedHostNode:C,hostPinned:v,hostLabel:w,hostOnline:j,hostRebindDaemonId:N,onHostRebindDaemonIdChange:A,settingMeshHost:T,onSetMeshHost:I,activeDaemon:P,activeDaemonId:M,meshQueue:E,userName:D,availableCliProviders:W,savingNodeSlotsId:R,onUpdateNodeSlots:B,savingNodeCapabilitiesId:_,onUpdateNodeCapabilities:H,nodeSystemPromptDrafts:L,onNodeSystemPromptDraftChange:F,savingNodeSystemPromptId:$,onSaveNodeSystemPrompt:K,selectedNodeId:z,onSelectNode:ne,showAddNode:ie,onShowAddNode:Ce,onCancelAddNode:me,nodeWorkspace:O,onNodeWorkspaceChange:Y,nodeProviderPriority:X,onNodeProviderPriorityChange:Q,nodeDaemonId:ve,onNodeDaemonIdChange:he,nodeCustomPath:Z,onNodeCustomPathChange:fe,nodePickerWorkspaces:V,nodePickerProviders:q,nodeOnboardingPlan:ee,nodePlanLoading:pe,attachableDaemons:le,onAddNode:se,onRemoveNode:te,availableCliAgents:ue,features:ye,sendCommand:Me}){const{t:re}=ke("common"),ce=Ml(e),Ae=e.nodes||[],be=l.useMemo(()=>e2(Ae,h),[Ae,h]),we=Ae.some(et=>{var Le;const J=Number((Le=et.policy)==null?void 0:Le.schedulingPriority);return Number.isFinite(J)&&J!==0}),_e=!ce.schedulingStrategy,U=l.useMemo(()=>Ae.some(et=>{var J;return Array.isArray((J=et.policy)==null?void 0:J.slots)&&et.policy.slots.length>0}),[Ae]),Ne=_e&&(U||Ae.length>=2)?"smart":null,[Ie,We]=l.useState(!1),Xe=!!M&&!!e.id;return s.jsxs(Ja,{icon:s.jsx(cs,{}),title:e.name,subtitle:e.repoIdentity||e.repo_identity||"Repo Mesh",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:a,children:re("repoMesh.detail.back")}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>d(!0),disabled:i,children:[s.jsx(qL,{size:13}),re(i?"repoMesh.detail.probing":"repoMesh.detail.refresh")]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>r(e.id),children:re("repoMesh.detail.delete")})]}),children:[t&&s.jsx(Mt,{variant:"error",onDismiss:n,className:"mb-4",children:t}),(()=>{var rt;const et=s.jsxs(s.Fragment,{children:[ye.meshHostDaemonSection&&s.jsx(z2,{daemons:h,coordinatorDaemonId:b,onCoordinatorDaemonIdChange:S,isHostNodeAttached:y,selectedHostNode:C,hostPinned:v,hostLabel:w,hostOnline:j,hostRebindDaemonId:N,onHostRebindDaemonIdChange:G=>{A(G),d()},settingMeshHost:T,onSetMeshHost:I}),s.jsxs(xt,{title:re("repoMesh.detail.observabilityTitle"),description:re("repoMesh.detail.observabilityDescription"),children:[c&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:c}),s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("button",{type:"button",className:"btn btn-primary btn-sm inline-flex items-center gap-1.5",onClick:()=>We(!0),disabled:!Xe,title:re(Xe?"repoMesh.detail.observabilityOpenTitle":"repoMesh.detail.observabilityDisabledTitle"),children:[s.jsx(cs,{size:14}),re("repoMesh.detail.observabilityOpen")]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:re("repoMesh.detail.observabilityHint")})]})]}),s.jsx(v2,{nodes:Ae,meshQueue:E,activeDaemon:P,daemons:h,selectedMeshId:e.id,userName:D,features:{addNodeDaemonPicker:ye.addNodeDaemonPicker,nodeInstruction:ye.nodeInstruction},coordinatorDaemonId:b,availableCliProviders:W,savingNodeSlotsId:R,onUpdateNodeSlots:B,savingNodeCapabilitiesId:_,onUpdateNodeCapabilities:H,nodeSystemPromptDrafts:L,onNodeSystemPromptDraftChange:F,savingNodeSystemPromptId:$,onSaveNodeSystemPrompt:K,selectedNodeId:z,onSelectNode:ne,showAddNode:ie,onShowAddNode:Ce,onCancelAddNode:me,nodeWorkspace:O,onNodeWorkspaceChange:Y,nodeProviderPriority:X,onNodeProviderPriorityChange:Q,nodeDaemonId:ve,onNodeDaemonIdChange:he,nodeCustomPath:Z,onNodeCustomPathChange:fe,nodePickerWorkspaces:V,nodePickerProviders:q,nodeOnboardingPlan:ee,nodePlanLoading:pe,attachableDaemons:le,onAddNode:se,onRemoveNode:te})]}),J=s.jsxs(s.Fragment,{children:[s.jsxs(xt,{title:re("repoMesh.detail.schedulingTitle"),description:re("repoMesh.detail.schedulingDescription"),children:[s.jsxs("fieldset",{className:"border-none p-0 m-0",children:[s.jsx("legend",{className:"text-[13px] font-medium text-text-secondary mb-2",children:re("repoMesh.detail.distribution")}),s.jsx("div",{className:"flex flex-col gap-2",children:V2.map(G=>{const de=Q2(ce.schedulingStrategy,{priorityConfigured:we})===G.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${de?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:[s.jsx("input",{type:"radio",name:"mesh-distribution",className:"mt-0.5 accent-[var(--accent-primary)]",value:G.value,checked:de,disabled:p,onChange:()=>u({schedulingStrategy:Y2(G.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[re(G.labelKey),Ne===G.value&&s.jsx("span",{className:"rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-accent-primary",children:re("repoMesh.detail.recommended")})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:re(G.descriptionKey)})]})]},G.value)})})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:re("repoMesh.detail.saving")})]}),s.jsx(xt,{title:re("repoMesh.detail.visibilityTitle"),description:re("repoMesh.detail.visibilityDescription"),children:s.jsx(Tt,{label:re("repoMesh.detail.visibilityLabel"),hint:re("repoMesh.detail.visibilityHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:G=>u({spawnedSessionVisibility:G.target.value==="visible"?"visible":"hidden"}),disabled:p,children:[s.jsx("option",{value:"hidden",children:re("repoMesh.detail.visibilityHidden")}),s.jsx("option",{value:"visible",children:re("repoMesh.detail.visibilityVisible")})]})})}),o&&s.jsx(xt,{title:re("repoMesh.detail.magiTitle"),description:re("repoMesh.detail.magiDescription"),children:s.jsx(j2,{status:o,daemonId:M,sendDaemonCommand:Me,availableProviders:W})}),s.jsx(xt,{children:s.jsx(M2,{quotaRouting:ce.quotaRouting??null,saving:p,error:t,onSave:G=>u({quotaRouting:G})})}),s.jsx(G2,{hostDaemonId:b,hostOnline:j,hostWorkspace:(C==null?void 0:C.workspace)||"",meshProviders:be.providers,unreportedNodeCount:be.unreportedNodeCount,machineAutoApproveEnabled:ce.delegatedWorkerAutoApprove!==!1,machineDangerousAllowed:ce.delegatedWorkerDangerousModeAllow===!0,onUpdatePolicy:u,savingPolicy:p,sendCommand:Me})]}),Le=s.jsx(s.Fragment,{children:ye.coordinatorPrompt&&s.jsx(xt,{title:re("repoMesh.detail.coordinatorPromptTitle"),collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:re("repoMesh.detail.advanced")}),description:re("repoMesh.detail.coordinatorPromptDescription"),children:s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-1",children:re("repoMesh.detail.thisMesh")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:re("repoMesh.detail.thisMeshHint",{name:e.name})}),s.jsx(D2,{daemonId:M,meshId:e.id,cliType:x,sendCommand:Me,defaultOpen:!0}),s.jsxs(Tt,{label:re("repoMesh.detail.overrideLabel"),hint:re("repoMesh.detail.overrideHint"),className:"mt-3",children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:m.override,onChange:G=>f({...m,override:G.target.value}),disabled:g,placeholder:re("repoMesh.detail.overridePlaceholder")}),s.jsx(I2,{daemonId:M,meshId:e.id,cliType:x,sendCommand:Me,disabled:g,hasContent:!!m.override.trim(),onApply:G=>f({...m,override:G})})]}),s.jsx(Tt,{label:re("repoMesh.detail.appendLabel"),hint:re("repoMesh.detail.appendHint"),children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:4,value:m.append,onChange:G=>f({...m,append:G.target.value}),disabled:g,placeholder:re("repoMesh.detail.appendPlaceholder")})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:re("repoMesh.detail.availablePlaceholders")}),s.jsx("p",{className:"mt-1",children:re("repoMesh.detail.placeholdersIntro")}),s.jsx("div",{className:"mt-2 overflow-x-auto",children:s.jsx("table",{className:"w-full text-left border-collapse",children:s.jsx("tbody",{children:L2.map(G=>s.jsxs("tr",{className:"border-t border-border-subtle/60 align-top",children:[s.jsx("td",{className:"py-1 pr-3 font-mono whitespace-nowrap text-text-secondary",children:`{{${G.token}}}`}),s.jsx("td",{className:"py-1 pr-3",children:G.description}),s.jsx("td",{className:"py-1 font-mono text-text-muted/80",children:G.example})]},G.token))})})})]}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:k,disabled:g,children:re(g?"repoMesh.detail.saving":"repoMesh.detail.saveCoordinatorPrompt")}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>f({override:"",append:""}),disabled:g,title:re("repoMesh.detail.clearTitle"),children:re("repoMesh.detail.clear")})]})]})})}),$e=s.jsxs(s.Fragment,{children:[s.jsx(B2,{status:o,daemonId:M,meshId:e.id,sendCommand:Me}),s.jsxs(xt,{title:re("repoMesh.detail.safetyTitle"),collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:re("repoMesh.detail.advanced")}),description:re("repoMesh.detail.safetyDescription"),children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:re("repoMesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:G=>G?"yes":"no",parse:G=>G==="yes"},{label:re("repoMesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:G=>G?"yes":"no",parse:G=>G==="yes"},{label:re("repoMesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",re("repoMesh.detail.requireApprovalBeforePush")],["not_required",re("repoMesh.detail.doNotRequireApproval")]],val:G=>G?"required":"not_required",parse:G=>G==="required"},{label:re("repoMesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",re("repoMesh.detail.warnAndContinue")],["block",re("repoMesh.detail.blockTask")],["checkpoint_then_continue",re("repoMesh.detail.checkpointThenContinue")]],val:G=>G||"warn",parse:G=>G},{label:re("repoMesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",re("repoMesh.detail.requireExplicitApproval")],["enabled",re("repoMesh.detail.allowRefineryPublish")]],val:G=>G?"enabled":"disabled",parse:G=>G==="enabled"}].map(({label:G,key:oe,opts:de,val:xe,parse:Se})=>s.jsx(Tt,{label:G,children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:xe(ce[oe]),onChange:Pe=>u({[oe]:Se(Pe.target.value)}),disabled:p,children:de.map(([Pe,He])=>s.jsx("option",{value:Pe,children:He},Pe))})},oe))}),(()=>{const G=ce.autoFastForward&&typeof ce.autoFastForward=="object"?ce.autoFastForward:{},oe=G.enabled!==!1,de=G.remoteNodes===!0,xe=G.mode==="continuous"?"continuous":"idle",Se=Pe=>u({autoFastForward:{...G,...Pe}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(Tt,{label:re("repoMesh.detail.autoFastForward"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:oe?"enabled":"disabled",onChange:Pe=>Se({enabled:Pe.target.value==="enabled"}),disabled:p,children:[s.jsx("option",{value:"enabled",children:re("repoMesh.detail.ffEnabled")}),s.jsx("option",{value:"disabled",children:re("repoMesh.detail.ffDisabled")})]})}),s.jsx(Tt,{label:re("repoMesh.detail.includeRemoteNodes"),hint:re("repoMesh.detail.includeRemoteNodesHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:de?"yes":"no",onChange:Pe=>Se({remoteNodes:Pe.target.value==="yes"}),disabled:p||!oe,children:[s.jsx("option",{value:"no",children:re("repoMesh.detail.remoteNo")}),s.jsx("option",{value:"yes",children:re("repoMesh.detail.remoteYes")})]})}),s.jsx(Tt,{label:re("repoMesh.detail.detectionMode"),hint:re("repoMesh.detail.detectionModeHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:xe,onChange:Pe=>Se({mode:Pe.target.value==="continuous"?"continuous":"idle"}),disabled:p||!oe||!de,children:[s.jsx("option",{value:"idle",children:re("repoMesh.detail.idleEdgeOnly")}),s.jsx("option",{value:"continuous",children:re("repoMesh.detail.continuousScan")})]})})]})})(),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(Tt,{label:re("repoMesh.detail.sessionCleanupLabel"),hint:re("repoMesh.detail.sessionCleanupHint"),children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce.sessionCleanupOnNodeRemove||"preserve",onChange:G=>u({sessionCleanupOnNodeRemove:G.target.value}),disabled:p,children:$i.map(G=>s.jsx("option",{value:G.value,children:G.label},G.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((rt=$i.find(G=>G.value===ce.sessionCleanupOnNodeRemove))==null?void 0:rt.description)||$i[0].description})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:re("repoMesh.detail.saving")})]})]}),at=[{key:"nodes",label:re("repoMesh.detail.tabNodes"),content:et},{key:"scheduling",label:re("repoMesh.detail.tabScheduling"),content:J},{key:"prompts",label:re("repoMesh.detail.tabPrompts"),content:s.jsxs(s.Fragment,{children:[Le,ye.hermesMcpConfig&&s.jsx(K2,{meshId:e.id,availableCliAgents:ue}),ye.meshHostDaemonSection&&s.jsxs(Mt,{variant:"info",className:"mt-4",children:[s.jsx("strong",{children:re("repoMesh.detail.mcpMode")})," ",s.jsxs("code",{className:"bg-bg-secondary px-1 rounded text-xs",children:["adhdev mcp --repo-mesh ",e.id]})," ",re("repoMesh.detail.mcpDescription")]})]})},{key:"advanced",label:re("repoMesh.detail.tabAdvanced"),content:$e}];return s.jsxs(s.Fragment,{children:[s.jsx(w1,{tabs:at,ariaLabel:re("repoMesh.detail.tabsAriaLabel"),className:"flex flex-col gap-4"}),Ie&&Xe&&s.jsx(Zf,{activeConv:X2({meshId:e.id,daemonId:M,meshName:e.name}),sendDaemonCommand:Me,onClose:()=>We(!1)})]})})()]})}const ya=new Map;async function ug(e){var r,o,i,c,d,p,u,m,f,g,k;const{sendCommand:t,unwrapResult:n}=e,a={meshCreated:!1,meshId:"",error:null,warning:null,plan:null};try{const h=e.reusablePlan??n(await t(e.targetDaemonId,"plan_mesh_onboarding",{workspace:e.workspace||void 0,operation:"auto",meshInventory:e.meshInventory}));if(a.plan=h,(h==null?void 0:h.success)===!1)return{...a,error:`${h.code||"onboarding_blocked"}: ${h.error}${h.action?` ${h.action}`:""}`};if(((r=h==null?void 0:h.plan)==null?void 0:r.kind)!=="create_mesh_and_onboard")return{...a,error:((o=h==null?void 0:h.plan)==null?void 0:o.summary)||"A compatible mesh already exists; add this workspace to it instead of creating a duplicate mesh."};const b={name:e.name.trim()};(e.repoRemoteUrl||(d=(c=(i=h==null?void 0:h.discovery)==null?void 0:i.origin)==null?void 0:c.urls)!=null&&d[0])&&(b.repoRemoteUrl=e.repoRemoteUrl||h.discovery.origin.urls[0]),(e.repoIdentity||(p=h==null?void 0:h.discovery)!=null&&p.repoIdentity)&&(b.repoIdentity=e.repoIdentity||h.discovery.repoIdentity),(u=h==null?void 0:h.discovery)!=null&&u.defaultBranch&&(b.defaultBranch=h.discovery.defaultBranch);const S=await t(e.targetDaemonId,"create_mesh",b),x=n(S);if((x==null?void 0:x.success)===!1)return{...a,error:x.error||"Create failed"};const y=typeof((m=x==null?void 0:x.mesh)==null?void 0:m.id)=="string"?x.mesh.id:"",C={...a,meshCreated:!0,meshId:y};if(!y||!e.attachWorkspace||!e.workspace)return C;try{const v=await t(e.targetDaemonId,"add_mesh_node",{meshId:y,daemonId:e.targetDaemonId,machineId:e.machineId,workspace:((f=h==null?void 0:h.discovery)==null?void 0:f.repoRoot)||e.workspace,repoRoot:(g=h==null?void 0:h.discovery)==null?void 0:g.repoRoot,isLocalWorktree:((k=h==null?void 0:h.discovery)==null?void 0:k.isLinkedWorktree)===!0,role:"host",providerPriority:e.providerPriority}),w=n(v);return(w==null?void 0:w.success)===!1?{...C,warning:ip(w.error||"add_mesh_node failed")}:C}catch(v){return{...C,warning:ip((v==null?void 0:v.message)||"add_mesh_node failed")}}}catch(h){return{...a,error:(h==null?void 0:h.message)||"Create failed"}}}function ip(e){return`Mesh created, but attaching the workspace failed: ${e}. Add the workspace from the mesh's node list.`}function lp(e,t){return e===t?!0:e.length!==t.length?!1:JSON.stringify(e)===JSON.stringify(t)}function pg({daemons:e,primaryDaemonId:t,sendCommand:n,unwrapResult:a,normalizeMesh:r,features:o,loadDaemonMetadata:i}){const c=e.map(me=>me.id).filter(Boolean).sort().join(","),[d,p]=l.useState(()=>ya.get(c)??[]),[u,m]=l.useState(null),[f,g]=l.useState(()=>!ya.has(c)),[k,h]=l.useState(null),[b,S]=l.useState(!1),[x,y]=l.useState(!1),[C,v]=l.useState(null),[w,j]=l.useState(""),[N,A]=l.useState(""),[T,I]=l.useState(""),[P,M]=l.useState(""),[E,D]=l.useState(""),[W,R]=l.useState(null),[B,_]=l.useState(!1),H=o.createDaemonPicker?P:t,L=l.useMemo(()=>e.find(me=>me.id===H),[e,H]),F=(L==null?void 0:L.workspaces)||[],$=l.useMemo(()=>cn((L==null?void 0:L.availableProviders)||[]),[L]);l.useEffect(()=>{!i||!H||!L||!(!L.workspaces||!L.availableProviders)||Promise.resolve(i(H,{minFreshMs:3e4})).catch(()=>{})},[i,H,L]),l.useEffect(()=>{if(!b||!H||!E){R(null);return}let me=!1;return _(!0),n(H,"plan_mesh_onboarding",{workspace:E,operation:"auto",meshInventory:d}).then(O=>{if(me)return;const Y=a(O);R(Y),Y!=null&&Y.success&&(A(X=>{var Q;return X||((Q=Y.discovery)==null?void 0:Q.repoIdentity)||""}),I(X=>{var Q,ve,he,Z,fe,V;return X||((he=(ve=(Q=Y.discovery)==null?void 0:Q.origin)==null?void 0:ve.urls)==null?void 0:he[0])||((V=(fe=(Z=Y.discovery)==null?void 0:Z.upstream)==null?void 0:fe.urls)==null?void 0:V[0])||""}),j(X=>{var Q,ve;return X||`${String(((Q=Y.discovery)==null?void 0:Q.repoIdentity)||((ve=Y.discovery)==null?void 0:ve.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}))}).catch(O=>{me||R({success:!1,error:(O==null?void 0:O.message)||"Git discovery failed"})}).finally(()=>{me||_(!1)}),()=>{me=!0}},[b,H,E,d,n,a]);const K=l.useMemo(()=>e.map(me=>me.id).filter(Boolean).sort().join(","),[e]),z=l.useCallback(async(me=!1)=>{const O=me||ya.has(K);g(Y=>O?Y:!0);try{if(o.createDaemonPicker){const Y=await Promise.allSettled(e.map(async ve=>{if(!ve.id)return[];const he=await n(ve.id,"list_meshes",{}),Z=a(he);if((Z==null?void 0:Z.success)===!1)throw new Error(Z.error||"Failed to load meshes");return(Array.isArray(Z==null?void 0:Z.meshes)?Z.meshes:[]).map(fe=>r(fe,ve.id)).filter(fe=>fe.id)})),X=new Map;for(const ve of Y)if(ve.status==="fulfilled")for(const he of ve.value)X.has(he.id)||X.set(he.id,he);const Q=Array.from(X.values());p(ve=>lp(ve,Q)?ve:Q),ya.set(K,Q),h(null)}else{if(!t)return;const Y=await n(t,"list_meshes");if(Y!=null&&Y.success){const X=(Y.meshes||[]).map(Q=>r(Q,t));p(Q=>lp(Q,X)?Q:X),ya.set(K,X),h(null)}else h((Y==null?void 0:Y.error)||"Failed to load meshes")}}catch(Y){h((Y==null?void 0:Y.message)||"Failed to load meshes")}finally{g(!1)}},[K,t,n,a,r,o.createDaemonPicker]);async function ne(){const me=o.createDaemonPicker?P:t;if(!me||!w.trim())return;const O=T.trim(),Y=N.trim(),X=E.trim();if(!(!X&&!O&&!Y)&&!x){y(!0),v(null);try{const Q=await ug({targetDaemonId:me,name:w,repoRemoteUrl:O,repoIdentity:Y,workspace:X,attachWorkspace:!!X,machineId:L==null?void 0:L.machineId,providerPriority:Dn($),meshInventory:d,sendCommand:n,unwrapResult:a,reusablePlan:!B&&W?W:void 0});if(Q.plan!==null&&R(Q.plan),Q.warning&&v(Q.warning),!Q.meshCreated){h(Q.error||"Create failed");return}S(!1),j(""),A(""),I(""),D(""),await z(),Q.meshId&&m(Q.meshId)}finally{y(!1)}}}async function ie(me){var Y;if(!confirm("Delete this mesh? This cannot be undone."))return;const O=((Y=d.find(X=>X.id===me))==null?void 0:Y.__sourceDaemonId)||t;try{const X=await n(O,"delete_mesh",{meshId:me}),Q=a(X);if((Q==null?void 0:Q.success)===!1)throw new Error(Q.error||"Failed to delete");u===me&&m(null),await z()}catch(X){h((X==null?void 0:X.message)||"Delete failed")}}function Ce(){S(!1),j(""),A(""),I(""),D(""),R(null),v(null)}return{meshes:d,setMeshes:p,selectedMeshId:u,setSelectedMeshId:m,loading:f,error:k,setError:h,showCreate:b,setShowCreate:S,creating:x,createWarning:C,setCreateWarning:v,createName:w,setCreateName:j,createRepoIdentity:N,setCreateRepoIdentity:A,createRepoRemoteUrl:T,setCreateRepoRemoteUrl:I,newMeshDaemonId:P,setNewMeshDaemonId:M,newMeshWorkspace:E,setNewMeshWorkspace:D,createPickerWorkspaces:F,createPickerProviders:$,createOnboardingPlan:W,createPlanLoading:B,loadMeshes:z,handleCreate:ne,handleDelete:ie,cancelCreate:Ce}}function eR({selectedMesh:e,selectedMeshId:t,primaryDaemonId:n,activeDaemonId:a,daemons:r,sendCommand:o,unwrapResult:i,loadLiveMesh:c,resolveCommandTarget:d,launchCoordinator:p,features:u,loadMeshes:m,loadQueue:f,queueSection:g,setError:k}){const[h,b]=l.useState(null),[S,x]=l.useState(!1),[y,C]=l.useState(""),[v,w]=l.useState([]),[j,N]=l.useState(""),[A,T]=l.useState(!1),[I,P]=l.useState(null),[M,E]=l.useState(!1),[D,W]=l.useState(""),[R,B]=l.useState(!1),[_,H]=l.useState(!1),[L,F]=l.useState(null),[$,K]=l.useState(!1),[z,ne]=l.useState({override:"",append:""}),[ie,Ce]=l.useState(!1),[me,O]=l.useState({}),[Y,X]=l.useState(null),Q=l.useMemo(()=>r.find(ce=>ce.id===j),[r,j]),ve=(Q==null?void 0:Q.workspaces)||[],he=l.useMemo(()=>cn((Q==null?void 0:Q.availableProviders)||[]),[Q]);l.useEffect(()=>{if(!S||!t||!y.trim()){P(null);return}const ce=u.addNodeDaemonPicker?j:(e==null?void 0:e.__sourceDaemonId)||n;if(!ce)return;let Ae=!1;return E(!0),o(ce,"plan_mesh_onboarding",{workspace:y.trim(),meshId:t,inlineMesh:e,operation:"add_existing"}).then(be=>{Ae||P(i(be))}).catch(be=>{Ae||P({success:!1,error:(be==null?void 0:be.message)||"Git discovery failed"})}).finally(()=>{Ae||E(!1)}),()=>{Ae=!0}},[S,t,e,y,j,n,u.addNodeDaemonPicker,o,i]);async function Z(){var be,we,_e;const ce=(e==null?void 0:e.__sourceDaemonId)||n;if(!t||!ce)return;const Ae=y.trim();if(Ae)try{const U=u.addNodeDaemonPicker?j:ce,Ne=await o(U,"plan_mesh_onboarding",{workspace:Ae,meshId:t,inlineMesh:e,operation:"add_existing"}),Ie=i(Ne);if(P(Ie),(Ie==null?void 0:Ie.success)===!1)throw new Error(`${Ie.code||"onboarding_blocked"}: ${Ie.error}${Ie.action?` ${Ie.action}`:""}`);const We={meshId:t,workspace:((be=Ie==null?void 0:Ie.discovery)==null?void 0:be.repoRoot)||Ae,repoRoot:(we=Ie==null?void 0:Ie.discovery)==null?void 0:we.repoRoot,isLocalWorktree:((_e=Ie==null?void 0:Ie.discovery)==null?void 0:_e.isLinkedWorktree)===!0};u.addNodeDaemonPicker&&j&&(We.daemonId=j,We.machineId=Q==null?void 0:Q.machineId),We.providerPriority=Ya(v);const Xe=await o(ce,"add_mesh_node",We),et=i(Xe);if((et==null?void 0:et.success)===!1)throw new Error(et.error||"Add node failed");x(!1),C(""),w([]),N(""),T(!1),await m(),g||await f(t)}catch(U){k((U==null?void 0:U.message)||"Add node failed")}}async function fe(ce){var _e;if(!e)return;const Ae=Ml(e),be=((_e=[{value:"preserve",label:"Preserve history and runtimes"},{value:"stop",label:"Stop live runtimes only"},{value:"delete_stopped",label:"Delete stopped sessions only"},{value:"stop_and_delete",label:"Stop and delete sessions"}].find(U=>U.value===Ae.sessionCleanupOnNodeRemove))==null?void 0:_e.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
119
+ `})]})}function OL({daemonIds:e,meshId:t,sendData:n,onRevisionAdvance:a}){const r=l.useRef(new Map),o=l.useRef(a);o.current=a;const i=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{r.current=new Map},[i,t]),l.useEffect(()=>{if(!t||!n)return;const c=[...new Set(e.filter(Boolean))];if(c.length===0)return;const d=c.map(p=>ys.subscribe({sendData:n},p,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${p}`,params:{includeSessions:!0}},u=>{if(u.topic!=="daemon.metadata")return;const m=u.meshStateRevisions;if(!m)return;const f=m[t]??m["*"];if(typeof f!="number")return;const g=r.current.get(p);r.current.set(p,f),g!==void 0&&f>g&&o.current()}));return()=>{for(const p of d)p()}},[i,t,n])}const rg={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},og=l.createContext(null);function UL(){const e=l.useContext(og);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}const ro="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function Cl({workspaces:e,value:t,onChange:n,autoFocus:a}){const{t:r}=ke("common"),[o,i]=l.useState(!1),c=new Set(e.map(p=>p.path)),d=o?"__custom":c.has(t)?t:"";return e.length===0||o?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("input",{type:"text",className:ro,value:t,autoFocus:a,placeholder:r("setupWizard.machines.workspacePlaceholder"),onChange:p=>n(p.target.value)}),e.length>0&&s.jsx("button",{type:"button",className:"self-start text-[10px] text-accent-primary hover:underline",onClick:()=>i(!1),children:r("setupWizard.machines.pickFromKnown")})]}):s.jsxs("select",{className:ro,value:d,onChange:p=>{p.target.value==="__custom"?(i(!0),n("")):n(p.target.value)},children:[s.jsx("option",{value:"",children:r("setupWizard.machines.workspaceSelectPlaceholder")}),e.map(p=>s.jsx("option",{value:p.path,children:p.label||p.path},p.path)),s.jsx("option",{value:"__custom",children:r("setupWizard.machines.workspaceCustom")})]})}function oo(e){var t;return!!(e!=null&&e.success)&&((t=e==null?void 0:e.plan)==null?void 0:t.kind)!==void 0&&e.plan.kind!=="create_mesh_and_onboard"}function ig(e,t){const[n,a]=l.useState(!1),r=l.useRef(null);return l.useEffect(()=>(e?r.current=setTimeout(()=>a(!0),t):a(!1),()=>{r.current&&clearTimeout(r.current)}),[e,t]),e&&n}function lg({plan:e,loading:t}){var i,c,d;const{t:n}=ke("common"),a=ig(t,250);let r=null,o="text-[11px] text-text-muted";return a?r=n("setupWizard.machines.planChecking"):(e==null?void 0:e.success)===!1?(o="text-[11px] text-red-400",r=s.jsxs(s.Fragment,{children:[e.error,e.action?` ${e.action}`:""]})):oo(e)?(o="text-[11px] text-amber-400",r=((i=e.plan)==null?void 0:i.summary)||n("setupWizard.machines.planExists")):e&&(o="text-[11px] text-emerald-400",r=n("setupWizard.machines.planOk",{identity:((c=e.discovery)==null?void 0:c.repoIdentity)||((d=e.discovery)==null?void 0:d.repoRoot)||""})),s.jsx("p",{className:`${o} min-h-[1.4em]`,children:r})}function GL(e){var t;return e.creating||e.planLoading||!e.name.trim()||e.showDaemonPicker&&!e.daemonId||((t=e.plan)==null?void 0:t.success)===!1||oo(e.plan)?!0:e.workspace.trim()?!1:!e.repoRemoteUrl.trim()&&!e.repoIdentity.trim()}function cg(e){var E,D;const{variant:t="page",showDaemonPicker:n,daemons:a,daemonLabel:r,name:o,onNameChange:i,daemonId:c,onDaemonIdChange:d,workspace:p,onWorkspaceChange:u,workspaces:m,plan:f,planLoading:g,repoRemoteUrl:k,onRepoRemoteUrlChange:h,repoIdentity:b,onRepoIdentityChange:S,manualOpen:x,onManualOpenChange:y,creating:C,warning:v,onCreate:w,onCancel:j}=e,{t:N}=ke("common"),A=GL({creating:C,planLoading:g,plan:f,name:o,workspace:p,showDaemonPicker:n,daemonId:c,repoRemoteUrl:k,repoIdentity:b}),T=ig(g,250),I=x||!!k.trim()||!!b.trim(),P=n&&a.length>0&&s.jsxs("select",{className:t==="wizard"?ro:"input w-full",value:c,onChange:W=>d(W.target.value),children:[s.jsx("option",{value:"",children:N("setupWizard.machines.machineSelectPlaceholder")}),a.map(W=>s.jsx("option",{value:W.id,children:r(W)},W.id))]}),M=I?s.jsxs(s.Fragment,{children:[s.jsx(Tt,{label:N("repoMesh.list.remoteUrl"),hint:N("repoMesh.list.remoteUrlHint"),children:s.jsx(xs,{value:k,onChange:W=>h(W.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(Tt,{label:N("repoMesh.list.repoIdentity"),hint:N("repoMesh.list.repoIdentityHint"),children:s.jsx(xs,{value:b,onChange:W=>S(W.target.value),placeholder:"github.com/user/repo"})})]}):s.jsx("button",{type:"button",className:"self-start text-xs text-text-muted hover:text-text-primary underline underline-offset-2 mb-3 bg-transparent border-none cursor-pointer p-0",onClick:()=>y(!0),children:N("repoMesh.list.advancedIdentityToggle")});return t==="wizard"?s.jsxs("div",{className:"flex flex-col gap-2.5 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:N("setupWizard.machines.meshName")}),s.jsx("input",{type:"text",className:ro,value:o,onChange:W=>i(W.target.value)})]}),n&&a.length>1&&s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:N("setupWizard.machines.machine")}),P]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:N("setupWizard.machines.workspace")}),s.jsx(Cl,{workspaces:m,value:p,onChange:u})]}),s.jsx(lg,{plan:f,loading:g}),v&&s.jsx("p",{className:"text-[11px] text-amber-400",children:v}),s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:w,disabled:A,children:N(C?"setupWizard.machines.creating":"setupWizard.machines.create")})})]}):s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:N("repoMesh.list.createTitle")}),n&&s.jsx(Tt,{label:N("repoMesh.list.createOnMachine"),hint:N("repoMesh.list.createOnMachineHint"),children:a.length===0?s.jsx("select",{className:"input w-full",disabled:!0,children:s.jsx("option",{value:"",children:N("repoMesh.list.noConnectedDaemon")})}):P}),s.jsx(Tt,{label:N("repoMesh.list.workspace"),hint:N("repoMesh.list.workspaceHint"),children:s.jsx(Cl,{workspaces:m,value:p,onChange:u})}),(T||f)&&s.jsx(Mt,{variant:(f==null?void 0:f.success)===!1?"error":oo(f)?"warning":"info",className:"mb-4",children:T?N("setupWizard.machines.planChecking"):(f==null?void 0:f.success)===!1?`${(f==null?void 0:f.code)||"onboarding_blocked"}: ${(f==null?void 0:f.error)||"Git discovery failed"} ${(f==null?void 0:f.action)||""}`:oo(f)?((E=f.plan)==null?void 0:E.summary)||N("setupWizard.machines.planExists"):`${((D=f.plan)==null?void 0:D.summary)||"Git repository detected."} No changes will be made until you click Create.`}),s.jsx(Tt,{label:N("repoMesh.list.name"),children:s.jsx(xs,{value:o,onChange:W=>i(W.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx("div",{className:"flex flex-col",children:M}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:w,disabled:A,children:N(C?"repoMesh.list.creating":"repoMesh.list.create")}),j&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:j,disabled:C,children:N("repoMesh.list.cancel")})]})]})}function qL({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("polyline",{points:"1 20 1 14 7 14"}),s.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function zL({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"6",cy:"18",r:"3"}),s.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function KL({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"3 6 5 6 21 6"}),s.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})}function VL({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function YL({status:e}){const n={online:{color:"#22c55e",label:"Online"},dirty:{color:"#f59e0b",label:"Dirty",title:"Workspace has uncommitted changes"},offline:{color:"#6b7280",label:"Offline"},degraded:{color:"#ef4444",label:"Degraded",title:"P2P connection to this node is down or timed out — often transient. Wait and retry, or re-establish the node's connection."},enabled:{color:"#22c55e",label:"Enabled"},pending:{color:"#a855f7",label:"Pending"},assigned:{color:"#3b82f6",label:"Assigned"},completed:{color:"#22c55e",label:"Completed"},failed:{color:"#ef4444",label:"Failed"},unknown:{color:"#6b7280",label:"Unknown"}}[e]||{color:"#6b7280",label:e};return s.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-md",style:{background:n.color+"15",color:n.color,border:`1px solid ${n.color}25`},title:n.title,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:n.color}}),n.label]})}function QL(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function JL({meshes:e,loading:t,error:n,onDismissError:a,daemons:r,features:o,showCreate:i,onToggleCreate:c,createName:d,onCreateNameChange:p,createRepoIdentity:u,onCreateRepoIdentityChange:m,createRepoRemoteUrl:f,onCreateRepoRemoteUrlChange:g,newMeshDaemonId:k,onNewMeshDaemonIdChange:h,newMeshWorkspace:b,onNewMeshWorkspaceChange:S,createPickerWorkspaces:x,createOnboardingPlan:y,createPlanLoading:C,creating:v,createWarning:w,onDismissCreateWarning:j,onSelectMesh:N,onCreate:A,onCancelCreate:T}){const{t:I}=ke("common"),P=o.maxMeshes!=null&&e.length>=o.maxMeshes,[M,E]=l.useState(!1);return s.jsxs(Ja,{icon:s.jsx(cs,{}),title:I("repoMesh.list.title"),subtitle:I("repoMesh.list.count",{count:e.length}),widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,disabled:P,title:P?I("repoMesh.list.meshLimitReached",{max:o.maxMeshes}):void 0,children:I("repoMesh.list.createMesh")}),children:[P&&s.jsx(Mt,{variant:"info",className:"mb-4",children:I("repoMesh.list.meshLimitBanner",{max:o.maxMeshes})}),n&&s.jsx(Mt,{variant:"error",onDismiss:a,className:"mb-4",children:n}),w&&s.jsx(Mt,{variant:"warning",onDismiss:j,className:"mb-4",children:w}),i&&s.jsx(xt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:s.jsx(cg,{variant:"page",showDaemonPicker:o.createDaemonPicker,daemons:r,daemonLabel:QL,name:d,onNameChange:p,daemonId:k,onDaemonIdChange:h,workspace:b,onWorkspaceChange:S,workspaces:x,plan:y,planLoading:C,repoRemoteUrl:f,onRepoRemoteUrlChange:g,repoIdentity:u,onRepoIdentityChange:m,manualOpen:M,onManualOpenChange:E,creating:v,onCreate:A,onCancel:T})}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:I("repoMesh.list.loading")}):e.length===0?s.jsx(Xa,{icon:s.jsx(cs,{}),title:I("repoMesh.list.emptyTitle"),description:r.length>0?I("repoMesh.list.emptyWithDaemons"):I("repoMesh.list.emptyNoDaemons"),action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!r.length,onClick:c,children:I("repoMesh.list.createFirst")})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(D=>{var W;return s.jsx("button",{type:"button",onClick:()=>N(D.id),className:"w-full text-left bg-bg-glass border border-border-subtle rounded-xl px-5 py-4 transition-colors hover:border-border-default hover:bg-bg-secondary/70",children:s.jsxs("div",{className:"flex justify-between items-start",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(cs,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:D.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:D.repoIdentity||D.repo_identity||I("repoMesh.list.noRepoIdentity")}),(D.defaultBranch||D.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(zL,{size:11}),D.defaultBranch||D.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(D.createdAt||D.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((W=D.nodes)==null?void 0:W.length)??D.nodeCount??0," ",I("repoMesh.list.nodesSuffix")]})]})]})},D.id)})})]})}function XL(e){const t=new Map;for(const n of e)n!=null&&n.id&&t.set(n.id,cn(n.availableProviders||[]));return t}function ZL(e,t){const n=String(e.daemon_id||e.daemonId||"");return n&&t.has(n)?t.get(n):!n&&t.size===1?[...t.values()][0]:[]}function e2(e,t){const n=new Map;for(const c of t)c!=null&&c.id&&n.set(c.id,Array.isArray(c.availableProviders)?c.availableProviders:[]);const a=new Set,r=[];let o=0,i=0;for(const c of Array.isArray(e)?e:[]){const d=String((c==null?void 0:c.daemon_id)||(c==null?void 0:c.daemonId)||""),p=d?n.get(d):n.size===1?[...n.values()][0]:void 0;if(!p||p.length===0){i++;continue}o++;for(const u of p){const m=String((u==null?void 0:u.type)||(u==null?void 0:u.id)||"").trim();!m||a.has(m)||(a.add(m),r.push(u))}}return r.sort((c,d)=>String((c==null?void 0:c.type)||(c==null?void 0:c.id)||"").localeCompare(String((d==null?void 0:d.type)||(d==null?void 0:d.id)||""))),{providers:r,reportedNodeCount:o,unreportedNodeCount:i}}function t2(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},n=new Set,a=[],r=o=>{const i=typeof o=="string"?o.trim():"";!i||n.has(i)||(n.add(i),a.push(i))};for(const o of im(t.slots))r(o.provider);if(Array.isArray(t.providerPriority))for(const o of t.providerPriority)r(o);return a}function s2(e){var d,p;const t=e,n=[],a=Array.isArray(t.capabilities)?t.capabilities:[];for(const u of a){const m=typeof u=="string"?u.trim():"";m&&n.push({tag:m,custom:!0})}const r=(((d=t.userOverrides)==null?void 0:d.platform)||t.reportedPlatform||"").toString().trim(),o=(((p=t.userOverrides)==null?void 0:p.arch)||t.reportedArch||"").toString().trim();r&&n.push({tag:`os=${r}`,custom:!1}),o&&n.push({tag:`arch=${o}`,custom:!1});for(const u of t2(t.policy))n.push({tag:`provider=${u}`,custom:!1});const i=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";t.isLocalWorktree===!0&&i&&n.push({tag:`worktree=${i}`,custom:!1});const c=new Set;return n.filter(u=>c.has(u.tag)?!1:(c.add(u.tag),!0))}const n2=["","low","medium","high"],a2={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function Zu(e){return{provider:e.provider||"",model:e.model||"",thinkingLevel:e.thinkingLevel||"",difficulty:Array.isArray(e.difficulty)?e.difficulty:[],capability:Array.isArray(e.capability)?e.capability:[],maxParallel:e.maxParallel!=null?String(e.maxParallel):""}}function ep(e){const t=e.provider.trim();if(!t)return null;const n=e.model.trim(),a=e.thinkingLevel.trim()||void 0,r=Number(e.maxParallel),o=Number.isFinite(r)&&r>0?Math.floor(r):void 0;return{provider:t,...n?{model:n}:{},...a?{thinkingLevel:a}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...o!==void 0?{maxParallel:o}:{}}}function r2(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const gn="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function o2({slots:e,availableProviders:t,saving:n,onSave:a}){const{t:r}=ke("common"),[o,i]=l.useState(()=>e.map(Zu)),c=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{i(e.map(Zu))},[c]);const d=l.useMemo(()=>[...new Set(t.map(x=>x.type).filter(Boolean))],[t]),p=l.useMemo(()=>bh(t),[t]),u=l.useMemo(()=>{const x=o.map(ep).filter(Boolean);return JSON.stringify(x)!==JSON.stringify(e)},[o,e]),m=(x,y)=>i(C=>C.map((v,w)=>w===x?{...v,...y}:v)),f=(x,y)=>i(C=>C.map((v,w)=>{var A;if(w!==x)return v;const j=((A=p.get(y))==null?void 0:A.models)??[],N=!v.model||j.length===0||j.includes(v.model);return{...v,provider:y,...N?{}:{model:""}}})),g=x=>i(y=>y.filter((C,v)=>v!==x)),k=()=>i(x=>[...x,r2()]),h=(x,y)=>i(C=>{const v=x+y;if(v<0||v>=C.length)return C;const w=[...C];return[w[x],w[v]]=[w[v],w[x]],w}),b=(x,y)=>i(C=>C.map((v,w)=>{if(w!==x)return v;const j=v.difficulty.includes(y);return{...v,difficulty:j?v.difficulty.filter(N=>N!==y):[...v.difficulty,y]}})),S=()=>a(o.map(ep).filter(Boolean));return s.jsxs("div",{className:"flex flex-col gap-2",onClick:x=>x.stopPropagation(),children:[o.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:r("repoMesh.slotEditor.empty")}),o.map((x,y)=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-2.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[s.jsxs("span",{className:"text-[11px] font-semibold text-text-muted",children:["#",y+1]}),s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:y===0,onClick:()=>h(y,-1),title:r("repoMesh.slotEditor.moveUp"),children:"↑"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:y===o.length-1,onClick:()=>h(y,1),title:r("repoMesh.slotEditor.moveDown"),children:"↓"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-status-error/30 text-status-error hover:bg-status-error/10",onClick:()=>g(y),"aria-label":r("repoMesh.slotEditor.removeSlot"),children:s.jsx(Dt,{size:12})})]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.provider")}),d.length>0?s.jsxs("select",{className:gn,value:x.provider,onChange:C=>f(y,C.target.value),children:[s.jsx("option",{value:"",children:r("repoMesh.slotEditor.select")}),d.map(C=>s.jsx("option",{value:C,children:C},C)),x.provider&&!d.includes(x.provider)&&s.jsx("option",{value:x.provider,children:x.provider})]}):s.jsx("input",{className:gn,value:x.provider,placeholder:"claude-cli",onChange:C=>m(y,{provider:C.target.value})})]}),(()=>{var N;const C=p.get(x.provider),v=(C==null?void 0:C.models)??[],w=(N=C==null?void 0:C.thinking)!=null&&N.length?["",...C.thinking]:n2,j=!!x.model&&v.length>0&&!v.includes(x.model);return s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.model")}),v.length>0&&!j?s.jsxs("select",{className:gn,value:v.includes(x.model)?x.model:"",onChange:A=>m(y,{model:A.target.value==="__custom__"?" ":A.target.value}),children:[s.jsx("option",{value:"",children:r("repoMesh.slotEditor.providerDefault")}),v.map(A=>s.jsx("option",{value:A,children:A},A)),s.jsx("option",{value:"__custom__",children:r("repoMesh.slotEditor.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:gn,value:x.model.trim(),placeholder:x.provider?`${x.provider} model`:r("repoMesh.slotEditor.modelPlaceholder"),onChange:A=>m(y,{model:A.target.value})}),v.length>0&&s.jsx("button",{type:"button",className:"self-start bg-transparent border-none cursor-pointer p-0 text-[10px] text-text-muted hover:underline",onClick:()=>m(y,{model:""}),children:r("repoMesh.slotEditor.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.thinking")}),s.jsx("select",{className:gn,value:x.thinkingLevel,onChange:A=>m(y,{thinkingLevel:A.target.value}),children:w.map(A=>s.jsx("option",{value:A,children:A||r("repoMesh.slotEditor.thinkingDefault")},A||"_default"))})]})]})})()]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.difficulty")}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:om.map(C=>{const v=x.difficulty.includes(C);return s.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${v?"border-accent-primary/60 bg-accent-primary/15 text-accent-primary":"border-border-subtle bg-bg-primary/60 text-text-muted hover:text-text-primary"}`,onClick:()=>b(y,C),children:a2[C]},C)})})]}),s.jsxs("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.capabilityTags")}),s.jsx("input",{className:gn,value:x.capability.join(", "),placeholder:"worktree, os=darwin",onChange:C=>m(y,{capability:C.target.value.split(",").map(v=>v.trim()).filter(Boolean)})})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.maxParallel")}),s.jsx("input",{type:"number",inputMode:"numeric",min:1,className:gn,value:x.maxParallel,placeholder:r("repoMesh.slotEditor.maxParallelPlaceholder"),onChange:C=>m(y,{maxParallel:C.target.value})})]})]})]},y)),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1",onClick:k,children:[s.jsx(Wl,{size:13})," ",r("repoMesh.slotEditor.addSlot")]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:S,disabled:!!n||!u,children:r(n?"repoMesh.slotEditor.saving":"repoMesh.slotEditor.saveSlots")})]})]})}function i2(e){const t=e.capabilities;return Array.isArray(t)?t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean):[]}const l2=["os=","arch=","provider=","worktree=","converge="];function c2({node:e,saving:t,onSave:n}){const{t:a}=ke("common"),r=l.useMemo(()=>s2(e).filter(h=>!h.custom),[e]),o=l.useMemo(()=>i2(e),[e]),[i,c]=l.useState(o),[d,p]=l.useState(""),u=JSON.stringify(i)!==JSON.stringify(o),f=(h=>{const b=h.trim();return b?/\s/.test(b)?a("repoMesh.tagEditor.noSpaces"):l2.some(S=>b.toLowerCase().startsWith(S))?a("repoMesh.tagEditor.reservedPrefix"):i.includes(b)?a("repoMesh.tagEditor.alreadyAdded"):null:null})(d);function g(){const h=d.trim();!h||f||(c(b=>[...b,h]),p(""))}function k(h){c(b=>b.filter(S=>S!==h))}return s.jsxs("div",{className:"mt-2",onClick:h=>h.stopPropagation(),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wide text-text-muted mr-1",children:a("repoMesh.tagEditor.routingTags")}),r.map(h=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 font-mono text-[10px] text-text-muted",title:a("repoMesh.tagEditor.autoDerivedTitle"),children:h.tag},h.tag)),i.map(h=>s.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 font-mono text-[10px] text-accent-primary",title:a("repoMesh.tagEditor.customTagTitle"),children:[h,s.jsx("button",{type:"button",className:"text-accent-primary/70 hover:text-accent-primary bg-transparent border-none cursor-pointer p-0 leading-none",onClick:()=>k(h),disabled:t,"aria-label":a("repoMesh.tagEditor.remove",{tag:h}),children:"×"})]},h))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:h=>p(h.target.value),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),g())},placeholder:a("repoMesh.tagEditor.addPlaceholder"),disabled:t,className:"min-w-[12rem] flex-1 px-2 py-1 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:g,disabled:t||!d.trim()||!!f,children:a("repoMesh.tagEditor.add")}),u&&s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>n(i),disabled:t,children:a(t?"repoMesh.tagEditor.saving":"repoMesh.tagEditor.saveTags")})]}),f&&s.jsx("div",{className:"mt-1 text-[11px] text-amber-400",children:f}),i.length===0&&r.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:a("repoMesh.tagEditor.empty")})]})}function d2(e,t){const n=t;return[...Array.isArray(n==null?void 0:n.cliSessions)?n.cliSessions:[],...Array.isArray(n==null?void 0:n.acpSessions)?n.acpSessions:[],...Array.isArray(n==null?void 0:n.sessions)?n.sessions:[]].filter(r=>{var o;return((o=r==null?void 0:r.settings)==null?void 0:o.meshNodeId)===e.id||(r==null?void 0:r.workspace)===e.workspace}).map(r=>{var o;return{id:r.sessionId||r.id||r.instanceId||"unknown",provider:r.providerType||r.cliType||r.acpType||r.type||"unknown",status:r.status||((o=r.activeChat)==null?void 0:o.status)||"unknown"}})}function u2(e,t){var n;return(e==null?void 0:e.ownerName)||(e==null?void 0:e.userName)||((n=e==null?void 0:e.user)==null?void 0:n.name)||t||"You"}function tp({nodes:e,meshQueue:t,activeDaemon:n,daemons:a,userName:r,features:o,providersByDaemonId:i,savingNodeSlotsId:c,onUpdateNodeSlots:d,savingNodeCapabilitiesId:p,onUpdateNodeCapabilities:u,nodeSystemPromptDrafts:m,onNodeSystemPromptDraftChange:f,savingNodeSystemPromptId:g,onSaveNodeSystemPrompt:k,selectedNodeId:h,onSelectNode:b,onRemoveNode:S}){const{t:x}=ke("common");return e.length===0?s.jsx(Xa,{icon:s.jsx(Tn,{}),title:x("repoMesh.nodeList.emptyTitle"),description:x("repoMesh.nodeList.emptyDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:e.map(y=>{var A;const C=f2(y),v=p2(y,t),w=d2(y,n),j=h===y.id,N=y.status||y.machine_status||(v.length>0||w.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${o.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${j?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:o.addNodeDaemonPicker?void 0:"button",tabIndex:o.addNodeDaemonPicker?void 0:0,onClick:o.addNodeDaemonPicker?void 0:()=>b(j?null:y.id),onKeyDown:o.addNodeDaemonPicker?void 0:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),b(j?null:y.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[o.addNodeDaemonPicker?s.jsx("span",{className:"font-semibold text-sm text-text-primary truncate",children:y.machine_label||y.machine_nickname||y.hostname||y.workspace}):s.jsx("span",{className:"text-sm font-medium",children:y.workspace.split("/").pop()}),o.addNodeDaemonPicker&&s.jsx(YL,{status:N}),o.addNodeDaemonPicker&&s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:x("repoMesh.nodeList.setupInventory")})]}),o.addNodeDaemonPicker&&s.jsx("div",{className:"text-[11px] text-text-muted",children:x("repoMesh.nodeList.ownerMachine",{owner:u2(a.find(T=>T.id===String(y.daemon_id||"")),r),machine:y.machine_label||y.daemon_id||y.workspace})}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:y.workspace}),s.jsx(c2,{node:y,saving:p===y.id,onSave:T=>u(y,T)}),o.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:x("repoMesh.nodeList.liveDetailGraphOwned")}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:T=>T.stopPropagation(),children:[s.jsx(Tt,{label:x("repoMesh.nodeList.slotsLabel"),hint:x("repoMesh.nodeList.slotsHint"),children:s.jsx(o2,{slots:Array.isArray((A=y.policy)==null?void 0:A.slots)?y.policy.slots:[],availableProviders:ZL(y,i),saving:c===y.id,onSave:T=>d(y,T)})}),o.nodeInstruction&&s.jsxs(Tt,{label:x("repoMesh.nodeList.nodeInstruction"),hint:x("repoMesh.nodeList.nodeInstructionHint"),children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:m[y.id]??"",onChange:T=>{const I=T.target.value;f(y.id,I)},onClick:T=>T.stopPropagation(),disabled:g===y.id,placeholder:x("repoMesh.nodeList.nodeInstructionPlaceholder")}),s.jsx("div",{className:"mt-2 flex items-center gap-2",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:T=>{T.stopPropagation(),k(y)},disabled:g===y.id,children:g===y.id?x("repoMesh.nodeList.saving"):x("repoMesh.nodeList.saveInstruction")})})]})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${o.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:T=>{T.stopPropagation(),S(y.id)},title:x("repoMesh.nodeList.removeNode"),children:s.jsx(KL,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:T=>T.stopPropagation(),children:[s.jsxs("summary",{className:"cursor-pointer select-none text-[12px] text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[s.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," ",x("repoMesh.nodeList.details")]}),s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:x("repoMesh.nodeList.nodeId")})," ",s.jsx("span",{className:"font-mono break-all",children:y.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:x("repoMesh.nodeList.launchReady")})," ",s.jsx("span",{className:C.configured?"text-green-400":"text-amber-400",children:C.configured?x("repoMesh.nodeList.launchReadyYes"):x("repoMesh.nodeList.launchReadyNo")})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:x("repoMesh.nodeList.repoRoot")})," ",s.jsx("span",{className:"font-mono break-all",children:y.repoRoot||y.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:x("repoMesh.nodeList.activeSessionsLabel")})," ",w.length]}),o.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:x("repoMesh.nodeList.added")})," ",new Date(y.created_at||y.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:x("repoMesh.nodeList.activeQueueAssignments")}),v.length===0?s.jsx("div",{children:x("repoMesh.nodeList.noActiveAssignment")}):s.jsx("ul",{className:"m-0 pl-4",children:v.map(T=>s.jsx("li",{className:"font-mono",children:m2(T)},T.id))})]}),w.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:x("repoMesh.nodeList.activeSessions")}),s.jsx("ul",{className:"m-0 pl-4",children:w.map(T=>s.jsxs("li",{className:"font-mono",children:[T.provider," / ",T.status," / ",T.id]},T.id))})]})]})]})]},y.id)})})}function p2(e,t){return t.filter(n=>n.status!=="assigned"?!1:(n.assignedNodeId||n.nodeId)===e.id)}function m2(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",n=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${n}`}function h2(e){var r,o;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set,a=t.map(i=>typeof i=="string"?i.trim():"").filter(Boolean).filter(i=>n.has(i)?!1:(n.add(i),!0));return a.length?a:G0((o=e.policy)==null?void 0:o.slots)}function f2(e){const t=h2(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"No provider configured on this node — task launch is blocked until a capability slot or provider priority is set."}}function jl(e){return e.isLocalWorktree===!0}function io(e){return e&&(e.machineNickname||e.nickname||e.hostname||(e.id?Rf(e.id):void 0))||"Unknown"}function g2(e){return String(e.daemon_id||e.daemonId||"")}function b2(e,t){const n=new Map(t.map(o=>[o.id,o])),a=[],r=new Map;for(const o of e){const i=g2(o);r.has(i)||(r.set(i,[]),a.push(i)),r.get(i).push(o)}return a.map(o=>{const i=r.get(o),c=o?n.get(o):void 0,d=i[0],p=o?c?io(c):(d==null?void 0:d.machine_label)||(d==null?void 0:d.machine_nickname)||(d==null?void 0:d.hostname)||o:io(c),u=(c==null?void 0:c.status)==="online",m=i.reduce((f,g)=>{var k;return f+(Array.isArray((k=g.policy)==null?void 0:k.slots)?g.policy.slots.length:0)},0);return{key:o,label:p,online:u,nodes:i,slotCount:m}})}function x2({groups:e,activeKey:t,onChange:n}){const{t:a}=ke("common");return s.jsx("div",{className:"flex items-center gap-1 px-1 border-b border-border-subtle mb-4 overflow-x-auto",role:"tablist","aria-label":a("repoMesh.nodeList.machineTabsLabel"),children:e.map(r=>{const o=r.key===t;return s.jsxs("button",{type:"button",role:"tab","aria-selected":o,onClick:()=>n(r.key),className:`flex items-center gap-2 px-3 py-2.5 text-[13px] font-medium border-b-2 -mb-px transition-colors cursor-pointer whitespace-nowrap ${o?"border-accent text-accent":"border-transparent text-text-muted hover:text-text-secondary"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${r.online?"bg-green-400":"bg-neutral-500"}`}),s.jsx("span",{className:"truncate max-w-[160px]",children:r.label}),s.jsx("span",{className:"text-[11px] text-text-muted font-normal",children:a("repoMesh.nodeList.machineTabCounts",{nodes:r.nodes.length,slots:r.slotCount})})]},r.key)})})}function v2({nodes:e,meshQueue:t,activeDaemon:n,daemons:a,selectedMeshId:r,userName:o,features:i,coordinatorDaemonId:c,availableCliProviders:d,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:b,selectedNodeId:S,onSelectNode:x,showAddNode:y,onShowAddNode:C,onCancelAddNode:v,nodeWorkspace:w,onNodeWorkspaceChange:j,nodeProviderPriority:N,onNodeProviderPriorityChange:A,nodeDaemonId:T,onNodeDaemonIdChange:I,nodeCustomPath:P,onNodeCustomPathChange:M,nodePickerWorkspaces:E,nodePickerProviders:D,nodeOnboardingPlan:W,nodePlanLoading:R,attachableDaemons:B,onAddNode:_,onRemoveNode:H}){var Ce,me,O;const{t:L}=ke("common"),F=l.useMemo(()=>XL(a),[a]),$=l.useMemo(()=>e.filter(Y=>!jl(Y)),[e]),K=l.useMemo(()=>i.addNodeDaemonPicker?b2($,a):[],[i.addNodeDaemonPicker,$,a]),[z,ne]=l.useState(null),ie=K.some(Y=>Y.key===z)?z:((Ce=K[0])==null?void 0:Ce.key)??"";return s.jsxs(xt,{title:i.addNodeDaemonPicker?L("repoMesh.nodeList.title",{count:$.length}):L("repoMesh.nodeList.titleNoCount"),description:i.addNodeDaemonPicker?L("repoMesh.nodeList.descriptionCloud"):L("repoMesh.nodeList.descriptionStandalone"),children:[i.addNodeDaemonPicker&&s.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:L("repoMesh.nodeList.daemonCandidates")}),s.jsx("div",{className:"text-xs text-text-muted",children:L("repoMesh.nodeList.daemonCandidatesHint")})]}),s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:L("repoMesh.nodeList.available",{count:B.length})})]}),a.length===0?s.jsx("div",{className:"text-xs text-text-muted",children:L("repoMesh.nodeList.noDaemonsAvailable")}):B.length===0?s.jsx("div",{className:"text-xs text-text-muted",children:L("repoMesh.nodeList.allDaemonsAttached")}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:B.map(Y=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors min-w-0 ${Y.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{I(Y.id),j(""),M(!1),A(Dn(cn(Y.availableProviders||[]))),C()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate min-w-0",children:io(Y)}),Y.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary shrink-0",children:L("repoMesh.nodeList.selectedHost")})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:Y.id}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:L("repoMesh.nodeList.workspacesDetected",{count:(Y.workspaces||[]).length})})]},Y.id))})]}),!y&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:C,children:[s.jsx(VL,{size:13})," ",i.addNodeDaemonPicker?L("repoMesh.nodeList.attachMachine"):L("repoMesh.nodeList.addNode")]}),y&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:i.addNodeDaemonPicker?L("repoMesh.nodeList.attachMachineTitle"):L("repoMesh.nodeList.addNodeTitle")}),s.jsx("button",{onClick:()=>{v(),I(""),M(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(Dt,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(Tt,{label:L("repoMesh.nodeList.machine"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:T,onChange:Y=>{var X;I(Y.target.value),j(""),M(!1),A(Dn(cn(((X=a.find(Q=>Q.id===Y.target.value))==null?void 0:X.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:L("repoMesh.nodeList.selectMachine")}),a.map(Y=>s.jsx("option",{value:Y.id,children:io(Y)},Y.id))]})}),(i.addNodeDaemonPicker?T:!0)&&s.jsx(Tt,{label:L("repoMesh.nodeList.workspacePath"),children:i.addNodeDaemonPicker&&!P&&E.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:E.map(Y=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${w===Y.path?"border-accent-primary bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-primary hover:bg-violet-500/10 text-text-primary"}`,onClick:()=>j(Y.path),children:[s.jsx("span",{className:"font-medium block truncate",children:Y.label||Y.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:Y.path})]},Y.id||Y.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{M(!0),j("")},children:L("repoMesh.nodeList.enterCustomPath")})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(xs,{value:w,onChange:Y=>j(Y.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:Y=>{Y.key==="Enter"&&_()}}),E.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{M(!1),j("")},children:L("repoMesh.nodeList.pickFromSaved")})]}):(()=>{var Q;const Y=Array.isArray(n==null?void 0:n.workspaces)?n.workspaces:[],X=`mesh-add-node-workspaces-${r||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(xs,{value:w,onChange:ve=>j(ve.target.value),placeholder:((Q=Y[0])==null?void 0:Q.path)||"/Users/dev/projects/myapp",list:Y.length>0?X:void 0,autoFocus:!0}),Y.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:X,children:Y.map(ve=>s.jsx("option",{value:ve.path,children:ve.label||ve.path},ve.id||ve.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:Y.slice(0,6).map(ve=>s.jsx("button",{type:"button",onClick:()=>j(ve.path),className:"text-[11px] px-2 py-0.5 rounded-full border border-border-subtle hover:border-accent-primary/50 text-text-muted hover:text-text-primary transition-colors bg-transparent cursor-pointer",title:ve.path,children:ve.label||ve.path.split("/").filter(Boolean).pop()||ve.path},ve.id||ve.path))})]})]})})()})}),(R||W)&&s.jsx(Mt,{variant:(W==null?void 0:W.success)===!1?"error":"info",className:"mb-4",children:R?"Inspecting Git repository (read-only)…":W!=null&&W.success?`${((me=W.plan)==null?void 0:me.summary)||"Compatible Git workspace detected."} Adding remains an explicit action.`:`${(W==null?void 0:W.code)||"onboarding_blocked"}: ${(W==null?void 0:W.error)||"Git discovery failed"} ${(W==null?void 0:W.action)||""}`}),s.jsx(Tt,{label:L("repoMesh.nodeList.preferredTools"),hint:L("repoMesh.nodeList.preferredToolsHint"),children:s.jsx(Yj,{value:N,availableProviders:i.addNodeDaemonPicker?D:d,onChange:A})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:_,disabled:R||(W==null?void 0:W.success)===!1||!w.trim()||i.addNodeDaemonPicker&&!T,className:"btn btn-primary btn-sm",children:L("repoMesh.nodeList.add")}),s.jsx("button",{onClick:()=>{v(),I(""),M(!1)},className:"btn btn-secondary btn-sm",children:L("repoMesh.nodeList.cancel")})]})]}),$.length===0?s.jsx(Xa,{icon:s.jsx(Tn,{}),title:L("repoMesh.nodeList.emptyTitle"),description:L("repoMesh.nodeList.emptyDescription")}):i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[K.length>1&&s.jsx(x2,{groups:K,activeKey:ie,onChange:ne}),s.jsx(tp,{nodes:((O=K.find(Y=>Y.key===ie))==null?void 0:O.nodes)||$,meshQueue:t,activeDaemon:n,daemons:a,userName:o,features:i,providersByDaemonId:F,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:b,selectedNodeId:S,onSelectNode:x,onRemoveNode:H})]}):s.jsx(tp,{nodes:$,meshQueue:t,activeDaemon:n,daemons:a,userName:o,features:i,providersByDaemonId:F,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:b,selectedNodeId:S,onSelectNode:x,onRemoveNode:H})]})}const y2=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],w2=[{kind:"rca",labelKey:"meshGraph.magiKind.kindRca",hint:"rca"},{kind:"design",labelKey:"meshGraph.magiKind.kindDesign",hint:"design"},{kind:"claim_audit",labelKey:"meshGraph.magiKind.kindClaimAudit",hint:"claim_audit"},{kind:"freeform",labelKey:"meshGraph.magiKind.kindFreeform",hint:"freeform"}];function k2(){return{nodeId:"",provider:"",model:"",n:""}}function sp(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function S2(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function C2(e){const t=[];for(let n=0;n<e.length;n++){const a=e[n],r=a.provider.trim();if(!r)return{error:{code:"provider_required",slot:n+1}};const o=a.nodeId.trim(),i=a.model.trim(),c=a.n.trim();let d;if(c){const p=Number(c);if(!Number.isFinite(p)||p<1)return{error:{code:"replica_min",slot:n+1}};d=Math.floor(p)}t.push({provider:r,...o?{nodeId:o}:{},...i?{model:i}:{},...d!==void 0?{n:d}:{}})}return t.length===0?{error:{code:"no_slot"}}:{slots:t}}function j2({status:e,daemonId:t,sendDaemonCommand:n,availableProviders:a}){const{t:r}=ke(),{theme:o}=Rs(),i=l.useMemo(()=>Es(o),[o]),c=l.useMemo(()=>bh(a),[a]),[d,p]=l.useState({}),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState({}),[b,S]=l.useState(null),x=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map($=>({nodeId:$.nodeId,machineLabel:$.machineLabel,providers:$.providers,providerPriority:$.providerPriority,isLocalWorktree:$.isLocalWorktree,worktreeBranch:$.worktreeBranch})),[e==null?void 0:e.nodes]),y=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map($=>$.nodeId),[e==null?void 0:e.nodes]),C=l.useMemo(()=>new Set(x.filter(jl).map($=>$.nodeId)),[x]),v=l.useMemo(()=>Object.fromEntries(x.filter(jl).map($=>[$.nodeId,$.worktreeBranch])),[x]),w=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map($=>[$.nodeId,$.machineLabel||$.nodeId])),[e==null?void 0:e.nodes]),j=l.useMemo(()=>{const $={};for(const K of x)$[K.nodeId]=sp(K);return $},[x]),N=l.useMemo(()=>{const $=[...new Set(x.flatMap(sp).filter(Boolean))];return[...new Set([...$,...y2])].sort()},[x]),A=!!t&&!!n,T=$=>$&&typeof $=="object"&&"result"in $?$.result:$,I=e==null?void 0:e.meshId,P=l.useCallback(async()=>{if(!(!t||!n)){m(!0),g(null);try{const $=await n(t,"magi_kind_panel_list",{...I?{meshId:I}:{}}),K=T($);if((K==null?void 0:K.success)===!1)throw new Error(K.error||r("meshGraph.magiKind.errorLoad"));p(K!=null&&K.kindPanels&&typeof K.kindPanels=="object"?K.kindPanels:{}),h({})}catch($){g(($==null?void 0:$.message)||r("meshGraph.magiKind.errorLoad"))}finally{m(!1)}}},[t,n,I,r]);l.useEffect(()=>{P()},[P]);const M=l.useCallback($=>{if(k[$])return k[$];const K=d[$];return K?K.map(S2):[]},[k,d]),E=($,K)=>{h(z=>({...z,[$]:K}))},D=($,K,z)=>{const ne=M($);E($,ne.map((ie,Ce)=>Ce===K?{...ie,...z}:ie))},W=$=>{E($,[...M($),k2()])},R=($,K)=>{E($,M($).filter((z,ne)=>ne!==K))},B=l.useCallback(async $=>{if(!t||!n)return;const K=C2(M($));if("error"in K){const z=K.error,ne=z.code==="provider_required"?r("meshGraph.magiKind.errorSlotProvider",{slot:z.slot}):z.code==="replica_min"?r("meshGraph.magiKind.errorSlotReplica",{slot:z.slot}):r("meshGraph.magiKind.errorNoSlot");g(`${$}: ${ne}`);return}S($),g(null);try{const z=await n(t,"magi_kind_panel_set",{kind:$,slots:K.slots,...I?{meshId:I}:{}}),ne=T(z);if((ne==null?void 0:ne.success)===!1)throw new Error(ne.error||r("meshGraph.magiKind.errorSave"));await P()}catch(z){g((z==null?void 0:z.message)||r("meshGraph.magiKind.errorSave"))}finally{S(null)}},[t,n,M,P,I,r]),_=l.useCallback(async $=>{if(!(!t||!n)&&confirm(r("meshGraph.magiKind.removeConfirm",{kind:$}))){S($),g(null);try{const K=await n(t,"magi_kind_panel_remove",{kind:$,...I?{meshId:I}:{}}),z=T(K);if((z==null?void 0:z.success)===!1)throw new Error(z.error||r("meshGraph.magiKind.errorRemove"));await P()}catch(K){g((K==null?void 0:K.message)||r("meshGraph.magiKind.errorRemove"))}finally{S(null)}}},[t,n,P,I,r]),H=`w-full rounded-lg border px-2.5 py-1.5 text-xs ${i.isDark?"border-white/10 bg-slate-950/40 text-slate-100 placeholder:text-slate-500":"border-slate-300 bg-white text-slate-900 placeholder:text-slate-400"}`,L="btn btn-primary btn-sm",F="btn btn-secondary btn-sm";return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("p",{className:`text-[12px] ${i.textSecondary}`,children:r("meshGraph.magiKind.intro")}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:F,onClick:()=>void P(),disabled:u||!A,children:r(u?"meshGraph.magiKind.loading":"meshGraph.magiKind.refresh")})})]}),!A&&s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${i.textSecondary} ${i.isDark?"border-white/10":"border-slate-200"}`,children:r("meshGraph.magiKind.connectPrompt")}),f&&s.jsx("div",{className:"rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-[12px] text-rose-300",children:f}),s.jsx("div",{className:"flex flex-col gap-3",children:w2.map(({kind:$,labelKey:K,hint:z})=>{const ne=M($),ie=!!d[$],Ce=b===$;return s.jsxs("div",{className:`${i.cardClass} rounded-2xl p-4 flex flex-col gap-3`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[13px] font-semibold ${i.textPrimary}`,children:r(K)}),s.jsx("span",{className:`font-mono text-[10px] ${i.textMuted}`,children:z}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${ie?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:ie?r("meshGraph.magiKind.agentCount",{count:d[$].length}):r("meshGraph.magiKind.off")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[ne.length===0&&s.jsx("div",{className:`rounded-xl border p-2.5 text-[11px] ${i.textSecondary} ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:r("meshGraph.magiKind.noAgents")}),ne.map((me,O)=>{const Y=me.nodeId?j[me.nodeId]??[]:[],X=me.nodeId&&Y.length?Y:N;return s.jsxs("div",{className:`rounded-xl border p-2.5 grid grid-cols-1 sm:grid-cols-[1fr_1fr_1fr_auto_auto] gap-x-2 gap-y-1 items-start ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:r("meshGraph.magiKind.machine")}),s.jsxs("select",{className:H,value:me.nodeId,onChange:Q=>D($,O,{nodeId:Q.target.value}),title:r("meshGraph.magiKind.machineTitle"),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.anyMachine")}),y.map(Q=>{const ve=C.has(Q),he=ve?r("meshGraph.magiKind.worktreeSuffix",{label:w[Q]??Q,branch:v[Q]||r("meshGraph.magiKind.worktreeUnknownBranch")}):w[Q]??Q;return s.jsx("option",{value:Q,disabled:ve,title:ve?r("meshGraph.magiKind.worktreeDisabledTitle"):void 0,children:he},Q)}),me.nodeId&&!y.includes(me.nodeId)&&s.jsx("option",{value:me.nodeId,children:r("meshGraph.magiKind.offlineSuffix",{label:w[me.nodeId]??me.nodeId})})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:[r("meshGraph.magiKind.provider")," *"]}),s.jsxs("select",{className:H,value:me.provider,onChange:Q=>D($,O,{provider:Q.target.value}),title:r("meshGraph.magiKind.providerTitle"),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.selectProvider")}),X.map(Q=>s.jsx("option",{value:Q,children:Q},Q)),me.provider&&!X.includes(me.provider)&&s.jsx("option",{value:me.provider,children:me.provider})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:r("meshGraph.magiKind.model")}),(()=>{var he;const Q=(me.provider?(he=c.get(me.provider))==null?void 0:he.models:void 0)??[],ve=!!me.model&&Q.length>0&&!Q.includes(me.model);return Q.length>0&&!ve?s.jsxs("select",{className:H,value:Q.includes(me.model)?me.model:"",title:r("meshGraph.magiKind.modelTitle"),onChange:Z=>D($,O,{model:Z.target.value==="__custom__"?" ":Z.target.value}),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.modelDefault")}),Q.map(Z=>s.jsx("option",{value:Z,children:Z},Z)),s.jsx("option",{value:"__custom__",children:r("meshGraph.magiKind.modelCustom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:H,value:me.model.trim(),placeholder:r("meshGraph.magiKind.modelDefault"),title:r("meshGraph.magiKind.modelTitle"),onChange:Z=>D($,O,{model:Z.target.value})}),Q.length>0&&s.jsx("button",{type:"button",className:`self-start bg-transparent border-none cursor-pointer p-0 text-[10px] ${i.textSecondary} hover:underline`,onClick:()=>D($,O,{model:""}),children:r("meshGraph.magiKind.backToModelList")})]})})()]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:r("meshGraph.magiKind.copies")}),s.jsx("input",{className:`${H} sm:w-16`,value:me.n,placeholder:"1",inputMode:"numeric",title:r("meshGraph.magiKind.copiesTitle"),onChange:Q=>D($,O,{n:Q.target.value})})]}),s.jsx("button",{type:"button",className:`${F} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>R($,O),"aria-label":r("meshGraph.magiKind.removeAgent"),title:r("meshGraph.magiKind.removeAgent"),children:"✕"})]},O)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:F,onClick:()=>W($),disabled:!A,children:r("meshGraph.magiKind.addAgent")})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:L,onClick:()=>void B($),disabled:Ce||!A,children:r(Ce?"meshGraph.magiKind.saving":"meshGraph.magiKind.save")}),s.jsx("button",{type:"button",className:F,onClick:()=>void _($),disabled:Ce||!A||!ie,title:r(ie?"meshGraph.magiKind.removeBindingTitle":"meshGraph.magiKind.removeBindingDisabledTitle"),children:r("meshGraph.magiKind.removeBinding")})]})]},$)})})]})}const On={sessionMinRemainingPercent:10,weeklyMinRemainingPercent:15,sessionResetImminentMinutes:5,staleAfterMinutes:30,spreadBonusMax:30,sessionAxisWeeklyHeadroomPercent:40},Nl=60*1e3;function np(e){return e===void 0||!Number.isFinite(e)?"":String(e/Nl)}function Al(e){const t=e??{};return{sessionMinRemainingPercent:t.sessionMinRemainingPercent!==void 0?String(t.sessionMinRemainingPercent):"",weeklyMinRemainingPercent:t.weeklyMinRemainingPercent!==void 0?String(t.weeklyMinRemainingPercent):"",sessionResetImminentMinutes:np(t.sessionResetImminentMs),staleAfterMinutes:np(t.staleAfterMs),spreadBonusMax:t.spreadBonusMax!==void 0?String(t.spreadBonusMax):"",sessionAxisWeeklyHeadroomPercent:t.sessionAxisWeeklyHeadroomPercent!==void 0?String(t.sessionAxisWeeklyHeadroomPercent):""}}function N2(e,t){const n=t.trim();if(!n)return null;const a=Number(n);if(!Number.isFinite(a))return"notANumber";const r=e==="sessionMinRemainingPercent"||e==="weeklyMinRemainingPercent"||e==="sessionAxisWeeklyHeadroomPercent";return r&&(a<0||a>100)?"percentRange":!r&&a<0?"negative":null}function Tl(e){const t={},n=p=>{const u=p.trim();if(!u)return;const m=Number(u);return Number.isFinite(m)?m:void 0},a=n(e.sessionMinRemainingPercent);a!==void 0&&(t.sessionMinRemainingPercent=a);const r=n(e.weeklyMinRemainingPercent);r!==void 0&&(t.weeklyMinRemainingPercent=r);const o=n(e.sessionResetImminentMinutes);o!==void 0&&(t.sessionResetImminentMs=o*Nl);const i=n(e.staleAfterMinutes);i!==void 0&&(t.staleAfterMs=i*Nl);const c=n(e.spreadBonusMax);c!==void 0&&(t.spreadBonusMax=c);const d=n(e.sessionAxisWeeklyHeadroomPercent);return d!==void 0&&(t.sessionAxisWeeklyHeadroomPercent=d),t}const A2="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs",T2="w-full rounded-lg border border-red-500/60 bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function M2({quotaRouting:e,saving:t,error:n,onSave:a}){const{t:r}=ke("common"),[o,i]=l.useState(()=>Al(e)),c=l.useCallback((k,h)=>{i(b=>({...b,[k]:h}))},[]),d=l.useMemo(()=>{const k={};for(const h of Object.keys(o)){const b=N2(h,o[h]);b&&(k[h]=b)}return k},[o]),p=Object.keys(d).length>0,u=l.useMemo(()=>JSON.stringify(Tl(o))!==JSON.stringify(P2(e)),[o,e]),m=l.useCallback(()=>{p||a(Tl(o))},[o,p,a]),f=l.useCallback(()=>{i(Al(null))},[]),g=[{key:"sessionMinRemainingPercent",label:r("setupWizard.quotaPolicy.sessionMin"),hint:r("setupWizard.quotaPolicy.sessionMinHint"),placeholder:On.sessionMinRemainingPercent,unit:"%"},{key:"weeklyMinRemainingPercent",label:r("setupWizard.quotaPolicy.weeklyMin"),hint:r("setupWizard.quotaPolicy.weeklyMinHint"),placeholder:On.weeklyMinRemainingPercent,unit:"%"},{key:"sessionResetImminentMinutes",label:r("setupWizard.quotaPolicy.resetImminent"),hint:r("setupWizard.quotaPolicy.resetImminentHint"),placeholder:On.sessionResetImminentMinutes,unit:r("setupWizard.quotaPolicy.minutes")},{key:"staleAfterMinutes",label:r("setupWizard.quotaPolicy.staleAfter"),hint:r("setupWizard.quotaPolicy.staleAfterHint"),placeholder:On.staleAfterMinutes,unit:r("setupWizard.quotaPolicy.minutes")},{key:"spreadBonusMax",label:r("setupWizard.quotaPolicy.spreadBonus"),hint:r("setupWizard.quotaPolicy.spreadBonusHint"),placeholder:On.spreadBonusMax,unit:""},{key:"sessionAxisWeeklyHeadroomPercent",label:r("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroom"),hint:r("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroomHint"),placeholder:On.sessionAxisWeeklyHeadroomPercent,unit:"%"}];return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:r("setupWizard.quotaPolicy.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:r("setupWizard.quotaPolicy.description")})]}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 sm:grid-cols-2",children:g.map(k=>{const h=d[k.key];return s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:"text-[11px] text-text-muted",children:[k.label,k.unit?` (${k.unit})`:""]}),s.jsx("input",{type:"number",inputMode:"decimal",className:h?T2:A2,value:o[k.key],placeholder:String(k.placeholder),onChange:b=>c(k.key,b.target.value)}),s.jsx("span",{className:`text-[10px] leading-snug ${h?"text-red-400":"text-text-muted"}`,children:h?r(`setupWizard.quotaPolicy.errors.${h}`):k.hint})]},k.key)})}),s.jsx("p",{className:"text-[10px] leading-relaxed text-text-muted",children:r("setupWizard.quotaPolicy.blankMeansDefault")}),n?s.jsx("p",{className:"text-[11px] text-red-400",children:n}):null,s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:f,children:r("setupWizard.quotaPolicy.useDefaults")}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:m,disabled:!!t||p||!u,children:r(t?"setupWizard.quotaPolicy.saving":"setupWizard.quotaPolicy.save")})]})]})}function P2(e){return Tl(Al(e))}function dg(e,t,n,a){const{t:r}=ke(),[o,i]=l.useState(!1),[c,d]=l.useState(null),[p,u]=l.useState(null),[m,f]=l.useState(null),g=l.useCallback(async()=>{if(!e||!t){d(r("repoMesh.promptPreview.connectPrompt"));return}i(!0),d(null);try{const k=await a(e,"coordinator_prompt_preview",{meshId:t,cliType:n}),h=k!=null&&k.result&&typeof k.result=="object"?k.result:k;if(!(h!=null&&h.success))return d((h==null?void 0:h.error)||r("repoMesh.promptPreview.errorRender")),null;const b=typeof h.prompt=="string"?h.prompt:"";return u(b),f(typeof h.bytes=="number"?h.bytes:null),b}catch(k){return d((k==null?void 0:k.message)||String(k)),null}finally{i(!1)}},[e,t,n,a,r]);return{loading:o,error:c,prompt:p,bytes:m,load:g}}function D2({daemonId:e,meshId:t,cliType:n,sendCommand:a,defaultOpen:r=!1}){const{t:o}=ke(),[i,c]=l.useState(r),{loading:d,error:p,prompt:u,bytes:m,load:f}=dg(e,t,n,a),g=l.useRef(!1);l.useEffect(()=>{i&&!g.current&&(g.current=!0,f())},[i,f]);const k=l.useCallback(()=>{c(h=>!h)},[]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:k,className:"inline-flex items-center gap-1 text-xs text-accent-primary bg-transparent border-none cursor-pointer p-0",children:[s.jsx("span",{className:`transition-transform ${i?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),o(i?"repoMesh.promptPreview.hide":"repoMesh.promptPreview.view"),s.jsxs("span",{className:"text-text-muted",children:["(",n,")"]})]}),i&&s.jsxs("div",{className:"mt-2",children:[d&&s.jsx("div",{className:"text-xs text-text-muted",children:o("repoMesh.promptPreview.rendering")}),p&&s.jsxs("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-300",children:[p,s.jsx("button",{type:"button",onClick:()=>void f(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:o("repoMesh.promptPreview.retry")})]}),!d&&!p&&u!==null&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between text-[11px] text-text-muted",children:[s.jsx("span",{children:o("repoMesh.promptPreview.info")}),m!==null&&s.jsxs("span",{children:[(m/1024).toFixed(1)," KB"]})]}),s.jsx("textarea",{readOnly:!0,value:u,rows:14,className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-xs text-text-secondary font-mono",onFocus:h=>h.currentTarget.select()})]})]})]})}function I2({daemonId:e,meshId:t,cliType:n,sendCommand:a,disabled:r,hasContent:o,onApply:i}){const{t:c}=ke(),{loading:d,load:p}=dg(e,t,n,a),u=l.useCallback(async()=>{if(o&&!window.confirm(c("repoMesh.detail.startFromDefaultConfirm")))return;const m=await p();typeof m=="string"&&i(m)},[o,p,i,c]);return s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm mt-2",onClick:()=>void u(),disabled:r||d||!e||!t,title:c("repoMesh.detail.startFromDefaultTitle"),children:c(d?"repoMesh.promptPreview.rendering":"repoMesh.detail.startFromDefault")})}const L2=[{token:"meshName",description:"This mesh's display name.",example:"my-app"},{token:"repo",description:"Repo identity (owner/repo or workspace path).",example:"vilmire/adhdev"},{token:"defaultBranch",description:"The mesh's default branch.",example:"main"},{token:"cliType",description:"The coordinator CLI type this prompt is being rendered for.",example:"claude-cli"},{token:"nodes",description:"Live node status table, or the configured node list if no live status is available.",example:"(rendered node table)"},{token:"mission",description:"Current mission section, when a mission is active. Empty otherwise.",example:"(mission summary or empty)"},{token:"recentActivity",description:"Recent mesh activity summary. Empty when none.",example:"(recent activity or empty)"},{token:"operatingNotes",description:"Accumulated operating notes for this mesh. Empty when none.",example:"(operating notes or empty)"},{token:"policy",description:"The mesh's effective policy section (safety, scheduling, etc.).",example:"(rendered policy section)"},{token:"tools",description:"The canonical MCP tools reference table.",example:"(tools table)"},{token:"workflow",description:"The standard coordinator workflow guidance section.",example:"(workflow section)"},{token:"onboarding",description:"Onboarding/reinit guidance section.",example:"(onboarding section)"},{token:"rules",description:"CLI-type-specific and policy-derived rules section.",example:"(rules section)"},{token:"toolExposurePreflight",description:"Preflight guidance for verifying tool exposure before relying on it.",example:"(preflight section)"}],R2=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function E2(e){const t=R2(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function _2(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function H2(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const $2=["active","paused","completed","abandoned"];function ap(e){return(e.status||"active").toLowerCase()}const F2=8;function B2({status:e,daemonId:t,meshId:n,sendCommand:a}){const{t:r}=ke("common"),o=l.useMemo(()=>_2(e),[e]),[i,c]=l.useState({}),[d,p]=l.useState({}),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState("active"),[b,S]=l.useState(!1),x=l.useMemo(()=>{const A={};for(const T of o){const I=ap(T);A[I]=(A[I]||0)+1}return A},[o]),y=l.useMemo(()=>k==="all"?o:o.filter(A=>ap(A)===k),[o,k]),C=b?y:y.slice(0,F2),v=y.length-C.length,w=!!t&&o.length>0,j=l.useCallback(async()=>{if(t){m(!0),g(null);try{const A=await a(t,"mesh_status",{meshId:n,verbose:!0}),T=E2(A),I=Array.isArray(T==null?void 0:T.missions)?T.missions:[],P={};for(const M of I)M.id&&typeof M.goal=="string"&&M.goal&&(P[M.id]=M.goal);c(M=>({...M,...P}))}catch(A){g(A instanceof Error?A.message:r("repoMesh.missions.errorFetch"))}finally{m(!1)}}},[t,n,a,r]),N=l.useCallback(A=>{p(T=>({...T,[A]:!T[A]})),!d[A]&&!i[A]&&j()},[d,i,j]);return o.length===0?null:s.jsxs(xt,{title:r("repoMesh.missions.title"),description:r("repoMesh.missions.description"),children:[f&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400",children:f}),s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[$2.filter(A=>(x[A]||0)>0).map(A=>s.jsxs("button",{type:"button",onClick:()=>{h(A),S(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] capitalize transition-colors ${k===A?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:[A," ",x[A]]},A)),s.jsxs("button",{type:"button",onClick:()=>{h("all"),S(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] transition-colors ${k==="all"?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:["All ",o.length]})]}),y.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:r("repoMesh.missions.empty",{status:k})}),s.jsx("div",{className:"flex flex-col gap-2",children:C.map(A=>{var W;const T=d[A.id]===!0,I=i[A.id],P=H2(A),M=T&&I?I:P.text,E=T&&!I&&P.truncated,D=((W=A.tasks)==null?void 0:W.total)??0;return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 px-3 py-2.5",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-text-primary",title:A.title,children:A.title||A.id}),A.status&&s.jsx("span",{className:"shrink-0 rounded-full border border-border-subtle px-2 py-0.5 text-[10px] uppercase tracking-wide text-text-muted",children:A.status}),D>0&&s.jsx("span",{className:"shrink-0 text-[11px] text-text-muted",children:r("repoMesh.missions.taskCount",{count:D})})]}),M&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${T?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[M,E&&s.jsx("span",{className:"text-text-muted",children:r("repoMesh.missions.goalUnavailable")})]}),(P.truncated||I)&&w&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>N(A.id),disabled:u,children:r(T?"repoMesh.missions.showLess":u&&!I?"repoMesh.missions.loading":"repoMesh.missions.showFullGoal")})]},A.id)})}),v>0&&s.jsx("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>S(!0),children:r("repoMesh.missions.showMore",{count:v})})]})}function rp(e,t){if(t)return e.modes.find(n=>n.id===t)}function W2(e){return e.modes.find(t=>t.strategy==="pty-parse-default"&&qs(t)!=="dangerous")}function O2({config:e,requestedModeId:t,machineAutoApproveEnabled:n,machineDangerousAllowed:a}){const r=rp(e,e.default),o=r==null?void 0:r.id,i=(t==null?void 0:t.trim())||void 0;if(!n)return{status:"disabled",requestedModeId:i,providerDefaultModeId:o,requestedModeUnknown:!1,downgraded:!1};const c=rp(e,i),d=!!i&&!c,p=c??r;if(!p||p.strategy==="post-boot-command")return{status:"none",requestedModeId:i,providerDefaultModeId:o,requestedModeUnknown:d,downgraded:!1};if(qs(p)==="dangerous"&&!a){const u=W2(e);return{status:u?"downgraded":"none",requestedModeId:i,providerDefaultModeId:o,effectiveMode:u,requestedModeUnknown:d,downgraded:!0}}return{status:d?"invalid_fallback":"requested",requestedModeId:i,providerDefaultModeId:o,effectiveMode:p,requestedModeUnknown:d,downgraded:!1}}function U2(e){const t=[];for(const n of e||[]){if(!n||n.category!=="cli")continue;const a=n.autoApproveModes;if(!a||!Array.isArray(a.modes)||a.modes.length===0)continue;const r=String(n.type||n.id||"").trim();r&&t.push({type:r,label:String(n.displayName||n.name||r),autoApproveModes:a})}return t}function G2({hostDaemonId:e,hostOnline:t,hostWorkspace:n,meshProviders:a,unreportedNodeCount:r=0,machineAutoApproveEnabled:o,machineDangerousAllowed:i,onUpdatePolicy:c,savingPolicy:d,sendCommand:p}){const{t:u}=ke("common"),m=l.useMemo(()=>U2(a),[a]),[f,g]=l.useState({}),[k,h]=l.useState(!1),[b,S]=l.useState(null),[x,y]=l.useState(!1),[C,v]=l.useState(null),[w,j]=l.useState(!1),[N,A]=l.useState(null),[T,I]=l.useState(!1),P=!!e&&t&&!!n,M=!!c&&!d,E=l.useCallback(async()=>{var _,H,L;if(P){h(!0),S(null);try{const F=await p(e,"read_mesh_json_config",{workspace:n}),$=(F==null?void 0:F.result)??F,K=((_=$==null?void 0:$.providerDefaults)==null?void 0:_.autoApproveModes)||((L=(H=$==null?void 0:$.config)==null?void 0:H.providerDefaults)==null?void 0:L.autoApproveModes),z={};if(K&&typeof K=="object")for(const[ne,ie]of Object.entries(K))typeof ie=="string"&&ie.trim()&&(z[ne]=ie.trim());g(z)}catch(F){S((F==null?void 0:F.message)||u("repoMesh.providerAutoApprove.loadError"))}finally{h(!1)}}},[P,e,n,p,u]);l.useEffect(()=>{E()},[E]);const D=l.useCallback((_,H)=>{j(!1),g(L=>{const F={...L};return H&&H.trim()?F[_]=H.trim():delete F[_],F})},[]),W=l.useCallback((_,H)=>{if(qs(H)==="dangerous"){A({type:_,mode:H});return}D(_,H.id)},[D]),R=l.useCallback(()=>{N&&D(N.type,N.mode.id),A(null)},[D,N]),B=l.useCallback(async()=>{if(P){y(!0),v(null),j(!1);try{const _=await p(e,"set_mesh_provider_defaults",{workspace:n,autoApproveModes:f,merge:!1,write:!0}),H=(_==null?void 0:_.result)??_;if((H==null?void 0:H.success)===!1)throw new Error((H==null?void 0:H.error)||u("repoMesh.providerAutoApprove.saveError"));j(!0),await E()}catch(_){v((_==null?void 0:_.message)||u("repoMesh.providerAutoApprove.saveError"))}finally{y(!1)}}},[P,e,n,E,f,p,u]);return s.jsxs(xt,{title:u("repoMesh.providerAutoApprove.title"),description:u("repoMesh.providerAutoApprove.subtitle"),collapsible:!0,defaultOpen:!1,children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-3.5",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u("repoMesh.providerAutoApprove.machineSection.title")}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.machineSection.hint")}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-[11px]",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-semibold ${o?"border-status-online/25 bg-status-online/10 text-status-online":"border-border-subtle bg-surface-secondary/40 text-text-muted"}`,children:u(o?"repoMesh.providerAutoApprove.machineSection.autoApproveOn":"repoMesh.providerAutoApprove.machineSection.autoApproveOff")}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-semibold ${i?"border-status-error/30 bg-status-error/10 text-status-error":"border-border-subtle bg-surface-secondary/40 text-text-muted"}`,children:u(i?"repoMesh.providerAutoApprove.machineSection.dangerousOn":"repoMesh.providerAutoApprove.machineSection.dangerousOff")})]}),s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsx(op,{label:u("repoMesh.providerAutoApprove.machineSection.autoApproveToggleLabel"),hint:u("repoMesh.providerAutoApprove.machineSection.autoApproveToggleHint"),checked:o,disabled:!M,onChange:_=>c==null?void 0:c({delegatedWorkerAutoApprove:_})}),s.jsx(op,{label:u("repoMesh.providerAutoApprove.machineSection.dangerousToggleLabel"),hint:u(o?"repoMesh.providerAutoApprove.machineSection.dangerousToggleHint":"repoMesh.providerAutoApprove.machineSection.dangerousDisabledHint"),checked:i,disabled:!M||!o,onChange:_=>{_?I(!0):c==null||c({delegatedWorkerDangerousModeAllow:!1})}})]})]}),P?k?s.jsx("div",{className:"text-[13px] text-text-muted",children:u("repoMesh.providerAutoApprove.loading")}):m.length===0?s.jsx("div",{className:"text-[13px] text-text-muted",children:r>0?u("repoMesh.providerAutoApprove.awaitingNodes",{count:r}):u("repoMesh.providerAutoApprove.noProviders")}):s.jsxs("div",{className:"space-y-6",children:[b&&s.jsx(Mt,{variant:"error",onDismiss:()=>S(null),children:b}),r>0&&s.jsx("div",{className:"text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.partialInventory",{count:r})}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u("repoMesh.providerAutoApprove.repoSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.repoSection.hint")})]}),s.jsx("div",{className:"space-y-5",children:m.map(_=>{const H=f[_.type],L=O2({config:_.autoApproveModes,requestedModeId:H,machineAutoApproveEnabled:o,machineDangerousAllowed:i});return s.jsxs("div",{className:"rounded-xl border border-border-subtle p-3.5",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary",children:_.label}),s.jsx("button",{type:"button",className:"text-[11px] text-text-muted underline decoration-dotted hover:text-text-primary disabled:opacity-40",onClick:()=>D(_.type,void 0),disabled:!H||x,children:u("repoMesh.providerAutoApprove.repoSection.clear")})]}),s.jsx(hf,{config:_.autoApproveModes,selectedModeId:H||"",disabled:x,onSelectMode:F=>W(_.type,F)}),!H&&s.jsx("div",{className:"mt-1.5 text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.repoSection.usesProviderDefault")}),s.jsx(q2,{effective:L,config:_.autoApproveModes})]},_.type)})}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u("repoMesh.providerAutoApprove.effectiveSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.effectiveSection.hint")})]}),C&&s.jsx(Mt,{variant:"error",onDismiss:()=>v(null),children:C}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("button",{type:"button",className:"rounded-lg bg-accent-primary px-4 py-2 text-sm font-semibold text-white disabled:opacity-50",onClick:()=>void B(),disabled:x,children:u(x?"repoMesh.providerAutoApprove.saving":"repoMesh.providerAutoApprove.save")}),w&&s.jsx("span",{className:"text-[12px] text-status-online",children:u("repoMesh.providerAutoApprove.saved")})]})]}):s.jsx("div",{className:"text-[13px] text-text-muted",children:u("repoMesh.providerAutoApprove.noHostDaemon")}),T&&s.jsx(Ao,{title:u("repoMesh.providerAutoApprove.machineSection.confirmTitle"),description:u("repoMesh.providerAutoApprove.machineSection.confirmDescription"),details:[{label:u("repoMesh.providerAutoApprove.machineSection.confirmScopeLabel"),value:u("repoMesh.providerAutoApprove.machineSection.confirmScopeValue")},{label:u("repoMesh.providerAutoApprove.machineSection.confirmEffectLabel"),value:u("repoMesh.providerAutoApprove.machineSection.confirmEffectValue")}],confirmLabel:u("repoMesh.providerAutoApprove.machineSection.confirmConfirm"),onConfirm:()=>{I(!1),c==null||c({delegatedWorkerDangerousModeAllow:!0})},onCancel:()=>I(!1)}),N&&s.jsx(ff,{mode:N.mode,onConfirm:R,onCancel:()=>A(null)}),N&&s.jsx("div",{className:"fixed inset-x-0 bottom-6 z-[60] mx-auto max-w-lg px-4",children:s.jsxs("div",{className:"rounded-xl border border-status-error/40 bg-bg-primary p-3.5 shadow-lg",children:[s.jsx("div",{className:"text-sm font-semibold text-status-error",children:u("repoMesh.providerAutoApprove.dangerous.sharedWarningTitle")}),s.jsx("div",{className:"mt-1 text-[12px] text-text-muted",children:u("repoMesh.providerAutoApprove.dangerous.sharedWarning")})]})})]})}function q2({effective:e,config:t}){var c,d,p;const{t:n}=ke("common"),a=u=>{var m;return(u?(m=t.modes.find(f=>f.id===u))==null?void 0:m.label:void 0)||u||""};let r,o="ok";switch(e.status){case"requested":r=n("repoMesh.providerAutoApprove.effectiveSection.statusRequested",{mode:((c=e.effectiveMode)==null?void 0:c.label)||""});break;case"invalid_fallback":r=n("repoMesh.providerAutoApprove.effectiveSection.statusInvalidFallback",{mode:((d=e.effectiveMode)==null?void 0:d.label)||""}),o="warn";break;case"downgraded":r=n("repoMesh.providerAutoApprove.effectiveSection.statusDowngraded",{requested:a(e.requestedModeId)||a(e.providerDefaultModeId),mode:((p=e.effectiveMode)==null?void 0:p.label)||""}),o="warn";break;case"disabled":r=n("repoMesh.providerAutoApprove.effectiveSection.statusDisabled"),o="muted";break;default:r=n("repoMesh.providerAutoApprove.effectiveSection.statusNone"),o="muted"}const i=o==="ok"?"border-status-online/25 bg-status-online/5 text-text-secondary":o==="warn"?"border-status-warning/30 bg-status-warning/5 text-status-warning":"border-border-subtle bg-surface-secondary/30 text-text-muted";return s.jsxs("div",{className:`mt-3 flex items-center gap-2 rounded-lg border px-3 py-2 text-[12px] ${i}`,children:[e.effectiveMode&&s.jsx(mf,{risk:qs(e.effectiveMode)}),s.jsx("span",{className:"min-w-0",children:r})]})}function op({label:e,hint:t,checked:n,disabled:a=!1,onChange:r}){return s.jsxs("button",{type:"button",role:"switch","aria-checked":n,className:"flex w-full items-center justify-between gap-3 rounded-xl border border-border-subtle bg-bg-primary/60 px-3.5 py-2.5 text-left disabled:opacity-50",onClick:()=>r(!n),disabled:a,children:[s.jsxs("span",{children:[s.jsx("span",{className:"block text-[13px] font-semibold text-text-primary",children:e}),s.jsx("span",{className:"mt-0.5 block text-[11px] text-text-muted",children:t})]}),s.jsx("span",{className:`relative h-6 w-11 shrink-0 rounded-full transition-colors ${n?"bg-accent-primary":"bg-surface-secondary"}`,children:s.jsx("span",{className:`absolute top-0.5 h-5 w-5 rounded-full bg-white shadow transition-transform ${n?"translate-x-5":"translate-x-0.5"}`})})]})}function Sr(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function z2({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:n,isHostNodeAttached:a,selectedHostNode:r,hostPinned:o,hostLabel:i,hostOnline:c,hostRebindDaemonId:d,onHostRebindDaemonIdChange:p,settingMeshHost:u,onSetMeshHost:m}){const{t:f}=ke("common");if(o)return s.jsxs(xt,{title:f("repoMesh.host.title"),description:f("repoMesh.host.descriptionSet"),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-[13px] text-text-primary ${c?"border-accent-primary/40 bg-accent-primary/10":"border-amber-500/40 bg-amber-500/10"}`,children:[s.jsx("span",{className:"text-text-muted",children:f("repoMesh.host.hostLabel")}),s.jsx("span",{className:"font-medium",children:i||f("repoMesh.host.unknown")}),s.jsxs("span",{className:c?"text-text-muted":"text-amber-400",children:["· ",f(c?"repoMesh.host.online":"repoMesh.host.offline")]})]}),(r==null?void 0:r.workspace)&&s.jsxs("span",{className:"text-xs text-text-muted",children:[f("repoMesh.host.hostNode")," ",s.jsx("span",{className:"font-mono text-text-secondary",children:r.workspace})]})]}),!c&&s.jsxs("div",{className:"mt-4",children:[s.jsxs(Mt,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:f("repoMesh.host.hostOffline")})," ",f("repoMesh.host.hostOfflineText")]}),e.length>0?s.jsx(Tt,{label:f("repoMesh.host.reconnectToCommand"),hint:f("repoMesh.host.reconnectToCommandHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:d,onChange:h=>p(h.target.value),children:[s.jsx("option",{value:"",children:f("repoMesh.host.waitForHost")}),e.map(h=>s.jsx("option",{value:h.id,children:Sr(h)},h.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-xs text-text-muted",children:f("repoMesh.host.noDaemonsToRoute")})]})]});const g=e.find(h=>h.id===t),k=m&&t?s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>m(t),disabled:!!u,children:f(u?"repoMesh.host.settingHost":"repoMesh.host.setHostAction")}):null;return s.jsxs(xt,{title:f("repoMesh.host.title"),description:f("repoMesh.host.descriptionUnset"),children:[s.jsxs(Mt,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:f("repoMesh.host.setHostBanner")})," ",f("repoMesh.host.setHostBannerText")]}),e.length>0?s.jsxs(s.Fragment,{children:[t?s.jsx("div",{className:"mb-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-xs text-text-muted",children:a?s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:Sr(g)}),r!=null&&r.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:r.workspace})]}):null,". ",f("repoMesh.host.confirmSetsHost")]}):s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:Sr(g)}),". ",f("repoMesh.host.attachNodeThenSetHost")]})}):s.jsx(Tt,{label:f("repoMesh.host.hostDaemon"),hint:f("repoMesh.host.hostDaemonHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:"",onChange:h=>n(h.target.value),children:[s.jsx("option",{value:"",children:f("repoMesh.host.resolvingHost")}),e.map(h=>s.jsx("option",{value:h.id,children:Sr(h)},h.id))]})}),k&&s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[k,s.jsx("span",{className:"text-xs text-text-muted",children:f("repoMesh.host.setHostActionHint")})]})]}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-xs text-text-muted",children:f("repoMesh.host.noDaemonsToHost")})]})}function K2({meshId:e,availableCliAgents:t}){const{t:n}=ke(),a=t.find(o=>{const i=o.id.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||o.name.toLowerCase().includes("hermes")}),r=Wh(a==null?void 0:a.meshCoordinator,{meshId:e});return r?s.jsx(xt,{title:n("repoMesh.hermesMcp.title"),description:n("repoMesh.hermesMcp.description"),children:s.jsx(pf,{setup:r,providerName:(a==null?void 0:a.name)||n("repoMesh.hermesMcp.fallbackProvider")})}):null}const $i=[{value:"preserve",label:"Preserve history and runtimes",description:"Keep completed chat history and leave live runtimes alone."},{value:"stop",label:"Stop live runtimes only",description:"Release running session processes, but keep chat records/transcripts."},{value:"delete_stopped",label:"Delete stopped sessions only",description:"Clean completed/stopped chat clutter without killing live runtimes."},{value:"stop_and_delete",label:"Stop and delete sessions",description:"Stop matching runtimes, then remove their session records/transcripts."}],V2=[{value:"smart",labelKey:"repoMesh.detail.distributionSmart",descriptionKey:"repoMesh.detail.distributionSmartDescription"},{value:"in_order",labelKey:"repoMesh.detail.distributionInOrder",descriptionKey:"repoMesh.detail.distributionInOrderDescription"}];function Y2(e){return e==="smart"?"fitness":"first_eligible"}function Q2(e,t){const n=e||"first_eligible";return n==="fitness"||n==="least_loaded"||n==="round_robin"||n==="priority_only"&&t!=null&&t.priorityConfigured?"smart":"in_order"}const J2={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function Ml(e){return{...J2,...(e==null?void 0:e.policy)||{}}}function X2(e){return{routeId:`mesh-settings:${e.meshId}`,daemonId:e.daemonId,agentName:e.meshName,agentType:"mesh",status:"idle",title:e.meshName,messages:[],workspaceName:e.meshName,displayPrimary:e.meshName,displaySecondary:"Mesh observability",streamSource:"native",tabKey:`mesh-settings:${e.meshId}`,coordinator:{meshId:e.meshId,role:"coordinator"},settings:{meshCoordinatorFor:e.meshId}}}function Z2({selectedMesh:e,error:t,onDismissError:n,onBack:a,onDelete:r,displayedMeshStatus:o,graphLoading:i,graphError:c,onRefreshGraph:d,savingPolicy:p,onUpdatePolicy:u,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:f,savingCoordinatorPrompt:g,onSaveCoordinatorPrompt:k,daemons:h,coordinatorDaemonId:b,onCoordinatorDaemonIdChange:S,coordinatorCliType:x,isHostNodeAttached:y,selectedHostNode:C,hostPinned:v,hostLabel:w,hostOnline:j,hostRebindDaemonId:N,onHostRebindDaemonIdChange:A,settingMeshHost:T,onSetMeshHost:I,activeDaemon:P,activeDaemonId:M,meshQueue:E,userName:D,availableCliProviders:W,savingNodeSlotsId:R,onUpdateNodeSlots:B,savingNodeCapabilitiesId:_,onUpdateNodeCapabilities:H,nodeSystemPromptDrafts:L,onNodeSystemPromptDraftChange:F,savingNodeSystemPromptId:$,onSaveNodeSystemPrompt:K,selectedNodeId:z,onSelectNode:ne,showAddNode:ie,onShowAddNode:Ce,onCancelAddNode:me,nodeWorkspace:O,onNodeWorkspaceChange:Y,nodeProviderPriority:X,onNodeProviderPriorityChange:Q,nodeDaemonId:ve,onNodeDaemonIdChange:he,nodeCustomPath:Z,onNodeCustomPathChange:fe,nodePickerWorkspaces:V,nodePickerProviders:q,nodeOnboardingPlan:ee,nodePlanLoading:pe,attachableDaemons:le,onAddNode:se,onRemoveNode:te,availableCliAgents:ue,features:ye,sendCommand:Me}){const{t:re}=ke("common"),ce=Ml(e),Ae=e.nodes||[],be=l.useMemo(()=>e2(Ae,h),[Ae,h]),we=Ae.some(et=>{var Le;const J=Number((Le=et.policy)==null?void 0:Le.schedulingPriority);return Number.isFinite(J)&&J!==0}),_e=!ce.schedulingStrategy,U=l.useMemo(()=>Ae.some(et=>{var J;return Array.isArray((J=et.policy)==null?void 0:J.slots)&&et.policy.slots.length>0}),[Ae]),Ne=_e&&(U||Ae.length>=2)?"smart":null,[Ie,We]=l.useState(!1),Xe=!!M&&!!e.id;return s.jsxs(Ja,{icon:s.jsx(cs,{}),title:e.name,subtitle:e.repoIdentity||e.repo_identity||"Repo Mesh",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:a,children:re("repoMesh.detail.back")}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>d(!0),disabled:i,children:[s.jsx(qL,{size:13}),re(i?"repoMesh.detail.probing":"repoMesh.detail.refresh")]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>r(e.id),children:re("repoMesh.detail.delete")})]}),children:[t&&s.jsx(Mt,{variant:"error",onDismiss:n,className:"mb-4",children:t}),(()=>{var rt;const et=s.jsxs(s.Fragment,{children:[ye.meshHostDaemonSection&&s.jsx(z2,{daemons:h,coordinatorDaemonId:b,onCoordinatorDaemonIdChange:S,isHostNodeAttached:y,selectedHostNode:C,hostPinned:v,hostLabel:w,hostOnline:j,hostRebindDaemonId:N,onHostRebindDaemonIdChange:G=>{A(G),d()},settingMeshHost:T,onSetMeshHost:I}),s.jsxs(xt,{title:re("repoMesh.detail.observabilityTitle"),description:re("repoMesh.detail.observabilityDescription"),children:[c&&s.jsx("div",{className:"mb-3 text-xs text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:c}),s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("button",{type:"button",className:"btn btn-primary btn-sm inline-flex items-center gap-1.5",onClick:()=>We(!0),disabled:!Xe,title:re(Xe?"repoMesh.detail.observabilityOpenTitle":"repoMesh.detail.observabilityDisabledTitle"),children:[s.jsx(cs,{size:14}),re("repoMesh.detail.observabilityOpen")]}),s.jsx("span",{className:"text-xs text-text-muted",children:re("repoMesh.detail.observabilityHint")})]})]}),s.jsx(v2,{nodes:Ae,meshQueue:E,activeDaemon:P,daemons:h,selectedMeshId:e.id,userName:D,features:{addNodeDaemonPicker:ye.addNodeDaemonPicker,nodeInstruction:ye.nodeInstruction},coordinatorDaemonId:b,availableCliProviders:W,savingNodeSlotsId:R,onUpdateNodeSlots:B,savingNodeCapabilitiesId:_,onUpdateNodeCapabilities:H,nodeSystemPromptDrafts:L,onNodeSystemPromptDraftChange:F,savingNodeSystemPromptId:$,onSaveNodeSystemPrompt:K,selectedNodeId:z,onSelectNode:ne,showAddNode:ie,onShowAddNode:Ce,onCancelAddNode:me,nodeWorkspace:O,onNodeWorkspaceChange:Y,nodeProviderPriority:X,onNodeProviderPriorityChange:Q,nodeDaemonId:ve,onNodeDaemonIdChange:he,nodeCustomPath:Z,onNodeCustomPathChange:fe,nodePickerWorkspaces:V,nodePickerProviders:q,nodeOnboardingPlan:ee,nodePlanLoading:pe,attachableDaemons:le,onAddNode:se,onRemoveNode:te})]}),J=s.jsxs(s.Fragment,{children:[s.jsxs(xt,{title:re("repoMesh.detail.schedulingTitle"),description:re("repoMesh.detail.schedulingDescription"),children:[s.jsxs("fieldset",{className:"border-none p-0 m-0",children:[s.jsx("legend",{className:"text-[13px] font-medium text-text-secondary mb-2",children:re("repoMesh.detail.distribution")}),s.jsx("div",{className:"flex flex-col gap-2",children:V2.map(G=>{const de=Q2(ce.schedulingStrategy,{priorityConfigured:we})===G.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${de?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:[s.jsx("input",{type:"radio",name:"mesh-distribution",className:"mt-0.5 accent-[var(--accent-primary)]",value:G.value,checked:de,disabled:p,onChange:()=>u({schedulingStrategy:Y2(G.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[re(G.labelKey),Ne===G.value&&s.jsx("span",{className:"rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-accent-primary",children:re("repoMesh.detail.recommended")})]}),s.jsx("span",{className:"block text-xs text-text-muted",children:re(G.descriptionKey)})]})]},G.value)})})]}),p&&s.jsx("div",{className:"mt-3 text-xs text-text-muted",children:re("repoMesh.detail.saving")})]}),s.jsx(xt,{title:re("repoMesh.detail.visibilityTitle"),description:re("repoMesh.detail.visibilityDescription"),children:s.jsx(Tt,{label:re("repoMesh.detail.visibilityLabel"),hint:re("repoMesh.detail.visibilityHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:G=>u({spawnedSessionVisibility:G.target.value==="visible"?"visible":"hidden"}),disabled:p,children:[s.jsx("option",{value:"hidden",children:re("repoMesh.detail.visibilityHidden")}),s.jsx("option",{value:"visible",children:re("repoMesh.detail.visibilityVisible")})]})})}),o&&s.jsx(xt,{title:re("repoMesh.detail.magiTitle"),description:re("repoMesh.detail.magiDescription"),children:s.jsx(j2,{status:o,daemonId:M,sendDaemonCommand:Me,availableProviders:W})}),s.jsx(xt,{children:s.jsx(M2,{quotaRouting:ce.quotaRouting??null,saving:p,error:t,onSave:G=>u({quotaRouting:G})})}),s.jsx(G2,{hostDaemonId:b,hostOnline:j,hostWorkspace:(C==null?void 0:C.workspace)||"",meshProviders:be.providers,unreportedNodeCount:be.unreportedNodeCount,machineAutoApproveEnabled:ce.delegatedWorkerAutoApprove!==!1,machineDangerousAllowed:ce.delegatedWorkerDangerousModeAllow===!0,onUpdatePolicy:u,savingPolicy:p,sendCommand:Me})]}),Le=s.jsx(s.Fragment,{children:ye.coordinatorPrompt&&s.jsx(xt,{title:re("repoMesh.detail.coordinatorPromptTitle"),collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:re("repoMesh.detail.advanced")}),description:re("repoMesh.detail.coordinatorPromptDescription"),children:s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-1",children:re("repoMesh.detail.thisMesh")}),s.jsx("p",{className:"text-xs text-text-muted mb-3",children:re("repoMesh.detail.thisMeshHint",{name:e.name})}),s.jsx(D2,{daemonId:M,meshId:e.id,cliType:x,sendCommand:Me,defaultOpen:!0}),s.jsxs(Tt,{label:re("repoMesh.detail.overrideLabel"),hint:re("repoMesh.detail.overrideHint"),className:"mt-3",children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:m.override,onChange:G=>f({...m,override:G.target.value}),disabled:g,placeholder:re("repoMesh.detail.overridePlaceholder")}),s.jsx(I2,{daemonId:M,meshId:e.id,cliType:x,sendCommand:Me,disabled:g,hasContent:!!m.override.trim(),onApply:G=>f({...m,override:G})})]}),s.jsx(Tt,{label:re("repoMesh.detail.appendLabel"),hint:re("repoMesh.detail.appendHint"),children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:4,value:m.append,onChange:G=>f({...m,append:G.target.value}),disabled:g,placeholder:re("repoMesh.detail.appendPlaceholder")})}),s.jsxs("details",{className:"mt-2 text-xs text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:re("repoMesh.detail.availablePlaceholders")}),s.jsx("p",{className:"mt-1",children:re("repoMesh.detail.placeholdersIntro")}),s.jsx("div",{className:"mt-2 overflow-x-auto",children:s.jsx("table",{className:"w-full text-left border-collapse",children:s.jsx("tbody",{children:L2.map(G=>s.jsxs("tr",{className:"border-t border-border-subtle/60 align-top",children:[s.jsx("td",{className:"py-1 pr-3 font-mono whitespace-nowrap text-text-secondary",children:`{{${G.token}}}`}),s.jsx("td",{className:"py-1 pr-3",children:G.description}),s.jsx("td",{className:"py-1 font-mono text-text-muted/80",children:G.example})]},G.token))})})})]}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:k,disabled:g,children:re(g?"repoMesh.detail.saving":"repoMesh.detail.saveCoordinatorPrompt")}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>f({override:"",append:""}),disabled:g,title:re("repoMesh.detail.clearTitle"),children:re("repoMesh.detail.clear")})]})]})})}),$e=s.jsxs(s.Fragment,{children:[s.jsx(B2,{status:o,daemonId:M,meshId:e.id,sendCommand:Me}),s.jsxs(xt,{title:re("repoMesh.detail.safetyTitle"),collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:re("repoMesh.detail.advanced")}),description:re("repoMesh.detail.safetyDescription"),children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:re("repoMesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:G=>G?"yes":"no",parse:G=>G==="yes"},{label:re("repoMesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:G=>G?"yes":"no",parse:G=>G==="yes"},{label:re("repoMesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",re("repoMesh.detail.requireApprovalBeforePush")],["not_required",re("repoMesh.detail.doNotRequireApproval")]],val:G=>G?"required":"not_required",parse:G=>G==="required"},{label:re("repoMesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",re("repoMesh.detail.warnAndContinue")],["block",re("repoMesh.detail.blockTask")],["checkpoint_then_continue",re("repoMesh.detail.checkpointThenContinue")]],val:G=>G||"warn",parse:G=>G},{label:re("repoMesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",re("repoMesh.detail.requireExplicitApproval")],["enabled",re("repoMesh.detail.allowRefineryPublish")]],val:G=>G?"enabled":"disabled",parse:G=>G==="enabled"}].map(({label:G,key:oe,opts:de,val:xe,parse:Se})=>s.jsx(Tt,{label:G,children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:xe(ce[oe]),onChange:Pe=>u({[oe]:Se(Pe.target.value)}),disabled:p,children:de.map(([Pe,He])=>s.jsx("option",{value:Pe,children:He},Pe))})},oe))}),(()=>{const G=ce.autoFastForward&&typeof ce.autoFastForward=="object"?ce.autoFastForward:{},oe=G.enabled!==!1,de=G.remoteNodes===!0,xe=G.mode==="continuous"?"continuous":"idle",Se=Pe=>u({autoFastForward:{...G,...Pe}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(Tt,{label:re("repoMesh.detail.autoFastForward"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:oe?"enabled":"disabled",onChange:Pe=>Se({enabled:Pe.target.value==="enabled"}),disabled:p,children:[s.jsx("option",{value:"enabled",children:re("repoMesh.detail.ffEnabled")}),s.jsx("option",{value:"disabled",children:re("repoMesh.detail.ffDisabled")})]})}),s.jsx(Tt,{label:re("repoMesh.detail.includeRemoteNodes"),hint:re("repoMesh.detail.includeRemoteNodesHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:de?"yes":"no",onChange:Pe=>Se({remoteNodes:Pe.target.value==="yes"}),disabled:p||!oe,children:[s.jsx("option",{value:"no",children:re("repoMesh.detail.remoteNo")}),s.jsx("option",{value:"yes",children:re("repoMesh.detail.remoteYes")})]})}),s.jsx(Tt,{label:re("repoMesh.detail.detectionMode"),hint:re("repoMesh.detail.detectionModeHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:xe,onChange:Pe=>Se({mode:Pe.target.value==="continuous"?"continuous":"idle"}),disabled:p||!oe||!de,children:[s.jsx("option",{value:"idle",children:re("repoMesh.detail.idleEdgeOnly")}),s.jsx("option",{value:"continuous",children:re("repoMesh.detail.continuousScan")})]})})]})})(),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(Tt,{label:re("repoMesh.detail.sessionCleanupLabel"),hint:re("repoMesh.detail.sessionCleanupHint"),children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce.sessionCleanupOnNodeRemove||"preserve",onChange:G=>u({sessionCleanupOnNodeRemove:G.target.value}),disabled:p,children:$i.map(G=>s.jsx("option",{value:G.value,children:G.label},G.value))})}),s.jsx("div",{className:"mt-2 text-xs text-text-muted",children:((rt=$i.find(G=>G.value===ce.sessionCleanupOnNodeRemove))==null?void 0:rt.description)||$i[0].description})]}),p&&s.jsx("div",{className:"mt-3 text-xs text-text-muted",children:re("repoMesh.detail.saving")})]})]}),at=[{key:"nodes",label:re("repoMesh.detail.tabNodes"),content:et},{key:"scheduling",label:re("repoMesh.detail.tabScheduling"),content:J},{key:"prompts",label:re("repoMesh.detail.tabPrompts"),content:s.jsxs(s.Fragment,{children:[Le,ye.hermesMcpConfig&&s.jsx(K2,{meshId:e.id,availableCliAgents:ue}),ye.meshHostDaemonSection&&s.jsxs(Mt,{variant:"info",className:"mt-4",children:[s.jsx("strong",{children:re("repoMesh.detail.mcpMode")})," ",s.jsxs("code",{className:"bg-bg-secondary px-1 rounded text-xs",children:["adhdev mcp --repo-mesh ",e.id]})," ",re("repoMesh.detail.mcpDescription")]})]})},{key:"advanced",label:re("repoMesh.detail.tabAdvanced"),content:$e}];return s.jsxs(s.Fragment,{children:[s.jsx(w1,{tabs:at,ariaLabel:re("repoMesh.detail.tabsAriaLabel"),className:"flex flex-col gap-4"}),Ie&&Xe&&s.jsx(Zf,{activeConv:X2({meshId:e.id,daemonId:M,meshName:e.name}),sendDaemonCommand:Me,onClose:()=>We(!1)})]})})()]})}const ya=new Map;async function ug(e){var r,o,i,c,d,p,u,m,f,g,k;const{sendCommand:t,unwrapResult:n}=e,a={meshCreated:!1,meshId:"",error:null,warning:null,plan:null};try{const h=e.reusablePlan??n(await t(e.targetDaemonId,"plan_mesh_onboarding",{workspace:e.workspace||void 0,operation:"auto",meshInventory:e.meshInventory}));if(a.plan=h,(h==null?void 0:h.success)===!1)return{...a,error:`${h.code||"onboarding_blocked"}: ${h.error}${h.action?` ${h.action}`:""}`};if(((r=h==null?void 0:h.plan)==null?void 0:r.kind)!=="create_mesh_and_onboard")return{...a,error:((o=h==null?void 0:h.plan)==null?void 0:o.summary)||"A compatible mesh already exists; add this workspace to it instead of creating a duplicate mesh."};const b={name:e.name.trim()};(e.repoRemoteUrl||(d=(c=(i=h==null?void 0:h.discovery)==null?void 0:i.origin)==null?void 0:c.urls)!=null&&d[0])&&(b.repoRemoteUrl=e.repoRemoteUrl||h.discovery.origin.urls[0]),(e.repoIdentity||(p=h==null?void 0:h.discovery)!=null&&p.repoIdentity)&&(b.repoIdentity=e.repoIdentity||h.discovery.repoIdentity),(u=h==null?void 0:h.discovery)!=null&&u.defaultBranch&&(b.defaultBranch=h.discovery.defaultBranch);const S=await t(e.targetDaemonId,"create_mesh",b),x=n(S);if((x==null?void 0:x.success)===!1)return{...a,error:x.error||"Create failed"};const y=typeof((m=x==null?void 0:x.mesh)==null?void 0:m.id)=="string"?x.mesh.id:"",C={...a,meshCreated:!0,meshId:y};if(!y||!e.attachWorkspace||!e.workspace)return C;try{const v=await t(e.targetDaemonId,"add_mesh_node",{meshId:y,daemonId:e.targetDaemonId,machineId:e.machineId,workspace:((f=h==null?void 0:h.discovery)==null?void 0:f.repoRoot)||e.workspace,repoRoot:(g=h==null?void 0:h.discovery)==null?void 0:g.repoRoot,isLocalWorktree:((k=h==null?void 0:h.discovery)==null?void 0:k.isLinkedWorktree)===!0,role:"host",providerPriority:e.providerPriority}),w=n(v);return(w==null?void 0:w.success)===!1?{...C,warning:ip(w.error||"add_mesh_node failed")}:C}catch(v){return{...C,warning:ip((v==null?void 0:v.message)||"add_mesh_node failed")}}}catch(h){return{...a,error:(h==null?void 0:h.message)||"Create failed"}}}function ip(e){return`Mesh created, but attaching the workspace failed: ${e}. Add the workspace from the mesh's node list.`}function lp(e,t){return e===t?!0:e.length!==t.length?!1:JSON.stringify(e)===JSON.stringify(t)}function pg({daemons:e,primaryDaemonId:t,sendCommand:n,unwrapResult:a,normalizeMesh:r,features:o,loadDaemonMetadata:i}){const c=e.map(me=>me.id).filter(Boolean).sort().join(","),[d,p]=l.useState(()=>ya.get(c)??[]),[u,m]=l.useState(null),[f,g]=l.useState(()=>!ya.has(c)),[k,h]=l.useState(null),[b,S]=l.useState(!1),[x,y]=l.useState(!1),[C,v]=l.useState(null),[w,j]=l.useState(""),[N,A]=l.useState(""),[T,I]=l.useState(""),[P,M]=l.useState(""),[E,D]=l.useState(""),[W,R]=l.useState(null),[B,_]=l.useState(!1),H=o.createDaemonPicker?P:t,L=l.useMemo(()=>e.find(me=>me.id===H),[e,H]),F=(L==null?void 0:L.workspaces)||[],$=l.useMemo(()=>cn((L==null?void 0:L.availableProviders)||[]),[L]);l.useEffect(()=>{!i||!H||!L||!(!L.workspaces||!L.availableProviders)||Promise.resolve(i(H,{minFreshMs:3e4})).catch(()=>{})},[i,H,L]),l.useEffect(()=>{if(!b||!H||!E){R(null);return}let me=!1;return _(!0),n(H,"plan_mesh_onboarding",{workspace:E,operation:"auto",meshInventory:d}).then(O=>{if(me)return;const Y=a(O);R(Y),Y!=null&&Y.success&&(A(X=>{var Q;return X||((Q=Y.discovery)==null?void 0:Q.repoIdentity)||""}),I(X=>{var Q,ve,he,Z,fe,V;return X||((he=(ve=(Q=Y.discovery)==null?void 0:Q.origin)==null?void 0:ve.urls)==null?void 0:he[0])||((V=(fe=(Z=Y.discovery)==null?void 0:Z.upstream)==null?void 0:fe.urls)==null?void 0:V[0])||""}),j(X=>{var Q,ve;return X||`${String(((Q=Y.discovery)==null?void 0:Q.repoIdentity)||((ve=Y.discovery)==null?void 0:ve.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}))}).catch(O=>{me||R({success:!1,error:(O==null?void 0:O.message)||"Git discovery failed"})}).finally(()=>{me||_(!1)}),()=>{me=!0}},[b,H,E,d,n,a]);const K=l.useMemo(()=>e.map(me=>me.id).filter(Boolean).sort().join(","),[e]),z=l.useCallback(async(me=!1)=>{const O=me||ya.has(K);g(Y=>O?Y:!0);try{if(o.createDaemonPicker){const Y=await Promise.allSettled(e.map(async ve=>{if(!ve.id)return[];const he=await n(ve.id,"list_meshes",{}),Z=a(he);if((Z==null?void 0:Z.success)===!1)throw new Error(Z.error||"Failed to load meshes");return(Array.isArray(Z==null?void 0:Z.meshes)?Z.meshes:[]).map(fe=>r(fe,ve.id)).filter(fe=>fe.id)})),X=new Map;for(const ve of Y)if(ve.status==="fulfilled")for(const he of ve.value)X.has(he.id)||X.set(he.id,he);const Q=Array.from(X.values());p(ve=>lp(ve,Q)?ve:Q),ya.set(K,Q),h(null)}else{if(!t)return;const Y=await n(t,"list_meshes");if(Y!=null&&Y.success){const X=(Y.meshes||[]).map(Q=>r(Q,t));p(Q=>lp(Q,X)?Q:X),ya.set(K,X),h(null)}else h((Y==null?void 0:Y.error)||"Failed to load meshes")}}catch(Y){h((Y==null?void 0:Y.message)||"Failed to load meshes")}finally{g(!1)}},[K,t,n,a,r,o.createDaemonPicker]);async function ne(){const me=o.createDaemonPicker?P:t;if(!me||!w.trim())return;const O=T.trim(),Y=N.trim(),X=E.trim();if(!(!X&&!O&&!Y)&&!x){y(!0),v(null);try{const Q=await ug({targetDaemonId:me,name:w,repoRemoteUrl:O,repoIdentity:Y,workspace:X,attachWorkspace:!!X,machineId:L==null?void 0:L.machineId,providerPriority:Dn($),meshInventory:d,sendCommand:n,unwrapResult:a,reusablePlan:!B&&W?W:void 0});if(Q.plan!==null&&R(Q.plan),Q.warning&&v(Q.warning),!Q.meshCreated){h(Q.error||"Create failed");return}S(!1),j(""),A(""),I(""),D(""),await z(),Q.meshId&&m(Q.meshId)}finally{y(!1)}}}async function ie(me){var Y;if(!confirm("Delete this mesh? This cannot be undone."))return;const O=((Y=d.find(X=>X.id===me))==null?void 0:Y.__sourceDaemonId)||t;try{const X=await n(O,"delete_mesh",{meshId:me}),Q=a(X);if((Q==null?void 0:Q.success)===!1)throw new Error(Q.error||"Failed to delete");u===me&&m(null),await z()}catch(X){h((X==null?void 0:X.message)||"Delete failed")}}function Ce(){S(!1),j(""),A(""),I(""),D(""),R(null),v(null)}return{meshes:d,setMeshes:p,selectedMeshId:u,setSelectedMeshId:m,loading:f,error:k,setError:h,showCreate:b,setShowCreate:S,creating:x,createWarning:C,setCreateWarning:v,createName:w,setCreateName:j,createRepoIdentity:N,setCreateRepoIdentity:A,createRepoRemoteUrl:T,setCreateRepoRemoteUrl:I,newMeshDaemonId:P,setNewMeshDaemonId:M,newMeshWorkspace:E,setNewMeshWorkspace:D,createPickerWorkspaces:F,createPickerProviders:$,createOnboardingPlan:W,createPlanLoading:B,loadMeshes:z,handleCreate:ne,handleDelete:ie,cancelCreate:Ce}}function eR({selectedMesh:e,selectedMeshId:t,primaryDaemonId:n,activeDaemonId:a,daemons:r,sendCommand:o,unwrapResult:i,loadLiveMesh:c,resolveCommandTarget:d,launchCoordinator:p,features:u,loadMeshes:m,loadQueue:f,queueSection:g,setError:k}){const[h,b]=l.useState(null),[S,x]=l.useState(!1),[y,C]=l.useState(""),[v,w]=l.useState([]),[j,N]=l.useState(""),[A,T]=l.useState(!1),[I,P]=l.useState(null),[M,E]=l.useState(!1),[D,W]=l.useState(""),[R,B]=l.useState(!1),[_,H]=l.useState(!1),[L,F]=l.useState(null),[$,K]=l.useState(!1),[z,ne]=l.useState({override:"",append:""}),[ie,Ce]=l.useState(!1),[me,O]=l.useState({}),[Y,X]=l.useState(null),Q=l.useMemo(()=>r.find(ce=>ce.id===j),[r,j]),ve=(Q==null?void 0:Q.workspaces)||[],he=l.useMemo(()=>cn((Q==null?void 0:Q.availableProviders)||[]),[Q]);l.useEffect(()=>{if(!S||!t||!y.trim()){P(null);return}const ce=u.addNodeDaemonPicker?j:(e==null?void 0:e.__sourceDaemonId)||n;if(!ce)return;let Ae=!1;return E(!0),o(ce,"plan_mesh_onboarding",{workspace:y.trim(),meshId:t,inlineMesh:e,operation:"add_existing"}).then(be=>{Ae||P(i(be))}).catch(be=>{Ae||P({success:!1,error:(be==null?void 0:be.message)||"Git discovery failed"})}).finally(()=>{Ae||E(!1)}),()=>{Ae=!0}},[S,t,e,y,j,n,u.addNodeDaemonPicker,o,i]);async function Z(){var be,we,_e;const ce=(e==null?void 0:e.__sourceDaemonId)||n;if(!t||!ce)return;const Ae=y.trim();if(Ae)try{const U=u.addNodeDaemonPicker?j:ce,Ne=await o(U,"plan_mesh_onboarding",{workspace:Ae,meshId:t,inlineMesh:e,operation:"add_existing"}),Ie=i(Ne);if(P(Ie),(Ie==null?void 0:Ie.success)===!1)throw new Error(`${Ie.code||"onboarding_blocked"}: ${Ie.error}${Ie.action?` ${Ie.action}`:""}`);const We={meshId:t,workspace:((be=Ie==null?void 0:Ie.discovery)==null?void 0:be.repoRoot)||Ae,repoRoot:(we=Ie==null?void 0:Ie.discovery)==null?void 0:we.repoRoot,isLocalWorktree:((_e=Ie==null?void 0:Ie.discovery)==null?void 0:_e.isLinkedWorktree)===!0};u.addNodeDaemonPicker&&j&&(We.daemonId=j,We.machineId=Q==null?void 0:Q.machineId),We.providerPriority=Ya(v);const Xe=await o(ce,"add_mesh_node",We),et=i(Xe);if((et==null?void 0:et.success)===!1)throw new Error(et.error||"Add node failed");x(!1),C(""),w([]),N(""),T(!1),await m(),g||await f(t)}catch(U){k((U==null?void 0:U.message)||"Add node failed")}}async function fe(ce){var _e;if(!e)return;const Ae=Ml(e),be=((_e=[{value:"preserve",label:"Preserve history and runtimes"},{value:"stop",label:"Stop live runtimes only"},{value:"delete_stopped",label:"Delete stopped sessions only"},{value:"stop_and_delete",label:"Stop and delete sessions"}].find(U=>U.value===Ae.sessionCleanupOnNodeRemove))==null?void 0:_e.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
120
120
 
121
121
  Node removal cleanup policy: ${be}`))return;const we=e.__sourceDaemonId||n;try{const U=await o(we,"remove_mesh_node",{meshId:e.id,nodeId:ce}),Ne=i(U);if((Ne==null?void 0:Ne.success)===!1)throw new Error(Ne.error||"Remove failed");h===ce&&b(null),await m(),g||await f(t)}catch(U){k((U==null?void 0:U.message)||"Remove node failed")}}async function V(ce){if(!e)return;const Ae={...Ml(e),...ce},be=e.__sourceDaemonId||n;try{K(!0),k(null);const we=await o(be,"update_mesh",{meshId:e.id,policy:Ae}),_e=i(we);if((_e==null?void 0:_e.success)===!1)throw new Error(_e.error||"Policy update failed");await m()}catch(we){k((we==null?void 0:we.message)||"Policy update failed")}finally{K(!1)}}const[q,ee]=l.useState(null);async function pe(ce,Ae){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n;try{ee(ce.id),k(null);const we=await o(be,"update_mesh_node",{meshId:t,nodeId:ce.id,policy:{slots:Ae}}),_e=i(we);if((_e==null?void 0:_e.success)===!1){k(_e.error||"Node slots update failed");return}await m()}catch(we){k((we==null?void 0:we.message)||"Node slots update failed")}finally{ee(null)}}const[le,se]=l.useState(null);async function te(ce,Ae){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n,we=Ae.map(_e=>_e.trim()).filter(Boolean);try{se(ce.id),k(null);const _e=await o(be,"update_mesh_node",{meshId:t,nodeId:ce.id,capabilities:we}),U=i(_e);if((U==null?void 0:U.success)===!1){k(U.error||"Node tag update failed");return}await m()}catch(_e){k((_e==null?void 0:_e.message)||"Node tag update failed")}finally{se(null)}}async function ue(){if(!n||!t)return;const Ae={...(e==null?void 0:e.coordinator)||{}};z.override.trim()?Ae.systemPromptOverride=z.override:delete Ae.systemPromptOverride,z.append.trim()?Ae.systemPromptAppend=z.append:delete Ae.systemPromptAppend,delete Ae.systemPromptSuffix;try{Ce(!0),k(null);const be=await o(n,"update_mesh",{meshId:t,coordinator:Ae}),we=i(be);if((we==null?void 0:we.success)===!1){k(we.error||"Coordinator prompt save failed");return}await m()}catch(be){k((be==null?void 0:be.message)||"Coordinator prompt save failed")}finally{Ce(!1)}}async function ye(ce){if(!n||!t)return;const Ae=(me[ce.id]||"").trim();try{X(ce.id),k(null);const be=await o(n,"update_mesh_node",{meshId:t,nodeId:ce.id,systemPrompt:Ae}),we=i(be);if((we==null?void 0:we.success)===!1){k(we.error||"Node instruction save failed");return}await m()}catch(be){k((be==null?void 0:be.message)||"Node instruction save failed")}finally{X(null)}}async function Me(ce){if(!(!e||!ce)){k(null),F(null);try{H(!0);const Ae=(e.nodes||[]).find(_e=>en(String(_e.daemon_id||_e.daemonId||""),ce)),be=await o(ce,"set_mesh_host",{meshId:e.id,hostDaemonId:ce,...Ae!=null&&Ae.id?{hostNodeId:Ae.id}:{}}),we=i(be);if((we==null?void 0:we.success)===!1){k(we.error||"Setting the mesh host failed");return}await m()}catch(Ae){k((Ae==null?void 0:Ae.message)||"Setting the mesh host failed")}finally{H(!1)}}}async function re(){if(e){k(null),F(null);try{B(!0);const ce=c?await c(a,e.id,e):null,Ae=d(a,e.id,e,e.nodes||[],ce);if("error"in Ae)throw new Error(Ae.error);const be=await p(Ae.targetDaemonId,{meshId:e.id,inlineMesh:Ae.inlineMesh,coordinatorNodeId:Ae.coordinatorNodeId,cliType:D.trim()||void 0});F(be.message)}catch(ce){k((ce==null?void 0:ce.message)||"Coordinator launch failed")}finally{B(!1)}}}return{selectedNodeId:h,setSelectedNodeId:b,showAddNode:S,setShowAddNode:x,nodeWorkspace:y,setNodeWorkspace:C,nodeProviderPriority:v,setNodeProviderPriority:w,nodeDaemonId:j,setNodeDaemonId:N,nodeCustomPath:A,setNodeCustomPath:T,nodePickerWorkspaces:ve,nodePickerProviders:he,nodeOnboardingPlan:I,nodePlanLoading:M,coordinatorCliType:D,setCoordinatorCliType:W,launchingCoordinator:R,launchResult:L,settingMeshHost:_,savingPolicy:$,coordinatorPromptDraft:z,setCoordinatorPromptDraft:ne,savingCoordinatorPrompt:ie,nodeSystemPromptDrafts:me,setNodeSystemPromptDrafts:O,savingNodeSystemPromptId:Y,savingNodeSlotsId:q,savingNodeCapabilitiesId:le,handleAddNode:Z,handleRemoveNode:fe,handleUpdatePolicy:V,handleUpdateNodeSlots:pe,handleUpdateNodeCapabilities:te,handleSaveCoordinatorPrompt:ue,handleSaveNodeSystemPrompt:ye,handleLaunchCoordinator:re,handleSetMeshHost:Me}}function tR(e){const t=e.filter(a=>a.status==="pending"||a.status==="assigned"),n=e.filter(a=>a.status==="completed"||a.status==="failed"||a.status==="cancelled");return{active:t.length,historical:n.length,activeCounts:{pending:t.filter(a=>a.status==="pending").length,assigned:t.filter(a=>a.status==="assigned").length},historicalCounts:{completed:n.filter(a=>a.status==="completed").length,failed:n.filter(a=>a.status==="failed").length},counts:{pending:e.filter(a=>a.status==="pending").length,assigned:e.filter(a=>a.status==="assigned").length,completed:e.filter(a=>a.status==="completed").length,failed:e.filter(a=>a.status==="failed").length},staleAssignedCount:e.filter(a=>a.staleAssigned).length,recent:e.slice(0,20)}}function sR({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:a,loadLiveMesh:r,resolveCommandTarget:o}){const[i,c]=l.useState([]),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),k=l.useCallback(async b=>{if(!e||!b){c([]);return}try{const S=await n(e,"get_mesh_queue",{meshId:b});c(S!=null&&S.success?Array.isArray(S.queue)?S.queue:[]:[])}catch{c([])}},[e,n]);async function h(b){var S,x;if(b){m(!0),g(null);try{const y=r?await r(t,b.id,b):null,C=o(t,b.id,b,b.nodes||[],y);if("error"in C)throw new Error(C.error);const v=await n(C.targetDaemonId,"get_mesh_queue",{meshId:b.id}),w=a(v);if((w==null?void 0:w.success)===!1)throw new Error(w.error||"Queue load failed");const j=Array.isArray(((S=w==null?void 0:w.result)==null?void 0:S.rows)??(w==null?void 0:w.rows)??(w==null?void 0:w.queue))?((x=w==null?void 0:w.result)==null?void 0:x.rows)??(w==null?void 0:w.rows)??(w==null?void 0:w.queue):[];p(tR(j))}catch(y){g((y==null?void 0:y.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:d,queueLoading:u,queueError:f,loadQueue:k,handleLoadQueue:h}}function nR(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const mg=new Map;function hg(e){return e?mg.get(e)??null:null}function aR(e,t){!e||!t||mg.set(e,t)}function rR({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:a,gateIncompleteGraph:r}){const[o,i]=l.useState(()=>hg(e)),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,f]=l.useState("idle"),[g,k]=l.useState(!1),h=l.useRef(!1);async function b(S,x=e,y=!1){if(!(!S||!x))try{d(!y&&o===null),f(y?"settling":"first_paint"),u(null);const C=await t(S,x,{refresh:y,retryProfile:y?"settled":"interactive"});k(nR(C));const v=n(C),w=a&&v?{...v,nodes:(v.nodes??[]).map(j=>a(j,v.meshId??x,""))}:v;if(w){if(r&&!y&&o!==null&&!yM(Pf(w))){f("settling"),h.current||(h.current=!0,Promise.resolve().then(()=>b(S,x,!0)).finally(()=>{h.current=!1}));return}i(w),aR(x,w),f("settled")}else i(null),u("mesh_status returned an unexpected payload."),f("idle")}catch(C){o||i(null),u((C==null?void 0:C.message)||"Failed to load mesh graph"),f("idle")}finally{d(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:p,setGraphError:u,graphProvenance:m,graphBootstrapFallback:g,loadGraph:b}}function cp(e){return!e||e.hostSynthesized?{hostDaemonId:"",hostNodeId:""}:{hostDaemonId:String(e.hostDaemonId||""),hostNodeId:String(e.hostNodeId||"")}}function oR(e,t,n,a,r){if(!e.length)return"";const o=String(r||"");if(o){const d=e.find(p=>en(p.id,o));return d?d.id:o}const i=t.find(d=>d.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const d=e.find(p=>en(p.id,c));if(d)return d.id}return""}function iR(e){var r;if(!e)return"null";const t=[...e.nodes??[]].map(o=>{var i,c,d,p,u,m;return[o.nodeId,o.health,((i=o.git)==null?void 0:i.branch)??"",((c=o.git)==null?void 0:c.headCommit)??"",(d=o.git)!=null&&d.dirty?"1":"0",((p=o.git)==null?void 0:p.ahead)??0,((u=o.git)==null?void 0:u.behind)??0,(m=o.git)!=null&&m.hasConflicts?"1":"0",[...o.activeSessions??[]].sort().join(",")].join("|")}).sort().join(";"),n=(r=e.queue)==null?void 0:r.summary,a=n?[n.pending,n.assigned,n.completed,n.failed,n.cancelled].join(","):"";return`${t}::${a}`}const lR=4,cR=3e4;function dR(){return{lastFingerprint:null,stableTicks:0,backedOff:!1}}function Pl(e){e.stableTicks=0,e.backedOff=!1}function uR(e,t){const n=iR(t);return e.lastFingerprint===null?(e.lastFingerprint=n,e.backedOff):n!==e.lastFingerprint?(e.lastFingerprint=n,Pl(e),!1):(e.stableTicks+=1,e.stableTicks>=lR&&(e.backedOff=!0),e.backedOff)}function pR(e,t){return e.backedOff?Math.max(t,cR):t}const mR=7e3,hR=45e3;function fR(){const e=UL(),{sendCommand:t,sendData:n,daemons:a,userName:r,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:d,unwrapResult:p,normalizeMesh:u,normalizeNode:m,resolveCommandTarget:f,features:g,gateIncompleteGraph:k}=e,h=da(),b=a[0],S=(b==null?void 0:b.id)||"",x=l.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(lt=>lt.category==="cli").map(lt=>({id:lt.type||lt.id,name:lt.displayName||lt.name||lt.type,meshCoordinator:lt.meshCoordinator})),[b]),y=l.useMemo(()=>cn((b==null?void 0:b.availableProviders)||[]),[b]),{meshes:C,selectedMeshId:v,setSelectedMeshId:w,loading:j,error:N,setError:A,showCreate:T,setShowCreate:I,createName:P,setCreateName:M,createRepoIdentity:E,setCreateRepoIdentity:D,createRepoRemoteUrl:W,setCreateRepoRemoteUrl:R,newMeshDaemonId:B,setNewMeshDaemonId:_,newMeshWorkspace:H,setNewMeshWorkspace:L,createPickerWorkspaces:F,createOnboardingPlan:$,createPlanLoading:K,creating:z,createWarning:ne,setCreateWarning:ie,loadMeshes:Ce,handleCreate:me,handleDelete:O,cancelCreate:Y}=pg({daemons:a,primaryDaemonId:S,sendCommand:t,unwrapResult:p,normalizeMesh:u,features:g,loadDaemonMetadata:h}),X=C.find(Oe=>Oe.id===v)||null,{meshGraphStatus:Q,setMeshGraphStatus:ve,graphLoading:he,graphError:Z,setGraphError:fe,loadGraph:V}=rR({selectedMeshId:v,loadMeshStatus:o,extractStatus:d,normalizeNode:m,gateIncompleteGraph:k}),[q,ee]=l.useState(""),[pe,le]=l.useState(""),se=g.meshHostDaemonSection?q:S,{meshQueue:te,loadQueue:ue}=sR({primaryDaemonId:S,activeDaemonId:se,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f}),{selectedNodeId:ye,setSelectedNodeId:Me,showAddNode:re,setShowAddNode:ce,nodeWorkspace:Ae,setNodeWorkspace:be,nodeProviderPriority:we,setNodeProviderPriority:_e,nodeDaemonId:U,setNodeDaemonId:Ne,nodeCustomPath:Ie,setNodeCustomPath:We,nodePickerWorkspaces:Xe,nodePickerProviders:et,nodeOnboardingPlan:J,nodePlanLoading:Le,coordinatorCliType:$e,savingPolicy:at,coordinatorPromptDraft:rt,setCoordinatorPromptDraft:G,savingCoordinatorPrompt:oe,nodeSystemPromptDrafts:de,setNodeSystemPromptDrafts:xe,savingNodeSystemPromptId:Se,savingNodeSlotsId:Pe,savingNodeCapabilitiesId:He,handleAddNode:Ee,handleRemoveNode:Je,handleUpdatePolicy:st,handleUpdateNodeSlots:Ze,handleUpdateNodeCapabilities:Ue,handleSaveCoordinatorPrompt:Qe,handleSaveNodeSystemPrompt:nt,settingMeshHost:Be,handleSetMeshHost:ge}=eR({selectedMesh:X,selectedMeshId:v,primaryDaemonId:S,activeDaemonId:se,daemons:a,availableCliProviders:y,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:Ce,loadQueue:ue,queueSection:g.queueSection,setError:A}),je=l.useMemo(()=>a.find(Oe=>Oe.id===se)||b,[a,se,b]),Te=l.useMemo(()=>new Set(((X==null?void 0:X.nodes)||[]).map(Oe=>String(Oe.daemon_id||Oe.daemonId||""))),[X]),Fe=l.useMemo(()=>a.filter(Oe=>Oe.id&&!Te.has(Oe.id)&&!am(Oe)),[a,Te]),Ge=(X==null?void 0:X.nodes)||[],dt=l.useMemo(()=>Ge.find(Oe=>en(String(Oe.daemon_id||Oe.daemonId||""),q)),[Ge,q]),Ve=g.meshHostDaemonSection?!!dt:!0,ut=l.useMemo(()=>{if(!g.meshHostDaemonSection||!X)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Oe=X.meshHost,lt=Q!=null&&Q.meshId&&String(Q.meshId)===String(X.id??"")?Q.meshHost:void 0,es=lt!=null&&lt.hostDaemonId?lt:Oe??lt,ns=cp(es),js=ns.hostDaemonId,Qs=Ge.find(Bs=>Bs.role==="host"),dn=ns.hostNodeId||String((Qs==null?void 0:Qs.id)||""),ae=dn?Ge.find(Bs=>String(Bs.id)===dn):void 0,Ke=String((ae==null?void 0:ae.daemon_id)||(ae==null?void 0:ae.daemonId)||""),qe=js||Ke;if(!qe)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Nt=a.find(Bs=>js&&en(Bs.id,js))||(Ke?a.find(Bs=>en(Bs.id,Ke)):void 0);if(Nt)return{pinned:!0,daemonId:Nt.id,label:gR(Nt),online:!0,hostNode:ae};const un=String((ae==null?void 0:ae.machineLabel)||"")||String((ae==null?void 0:ae.workspace)||"")||qe;return{pinned:!0,daemonId:qe,label:un,online:!1,hostNode:ae}},[X,Ge,a,Q,g.meshHostDaemonSection]),Kt=ut.daemonId,Et=ut.online,ps=ut.pinned?ut.hostNode:dt,Zt=l.useMemo(()=>!g.meshHostDaemonSection||!ut.pinned?"":!Et&&pe&&a.some(Oe=>Oe.id===pe)?pe:Kt,[g.meshHostDaemonSection,ut.pinned,Et,pe,a,Kt]),Hs=l.useMemo(()=>Q?[...new Set((Q.nodes??[]).map(Oe=>String(Oe.daemonId||Oe.daemon_id||"")).filter(Boolean))]:[],[Q]),Re=Xf({status:Q,daemonId:se||null,extraDaemonIds:Hs,meshId:v,sendData:n});l.useEffect(()=>{const Oe=(X==null?void 0:X.coordinator)||{};G({override:typeof Oe.systemPromptOverride=="string"?Oe.systemPromptOverride:"",append:typeof Oe.systemPromptAppend=="string"?Oe.systemPromptAppend:typeof Oe.systemPromptSuffix=="string"?Oe.systemPromptSuffix:""}),xe(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(lt=>[lt.id,typeof lt.systemPrompt=="string"?lt.systemPrompt:""])))},[X]),l.useEffect(()=>{const Oe=g.addNodeDaemonPicker?Dn(et):Dn(y);re&&we.length===0&&Oe.length>0&&_e(Oe)},[re,y,et,we.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const Oe=new Set(((X==null?void 0:X.nodes)||[]).map(lt=>lt.id));ye&&!Oe.has(ye)&&Me(null)},[X,ye]);const tt=l.useMemo(()=>{if(!(!(Q!=null&&Q.meshId)||String(Q.meshId)!==String((X==null?void 0:X.id)??"")))return cp(Q.meshHost).hostDaemonId||void 0},[Q,X]),It=l.useMemo(()=>oR(a,Ge,se,S,tt),[a,Ge,se,S,tt]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!a.length&&!ut.pinned){ee("");return}const Oe=ut.pinned?Zt:It;Oe&&!en(Oe,q)&&ee(Oe)},[a,q,ut.pinned,Zt,It,g.meshHostDaemonSection]),l.useEffect(()=>{pe&&(Et||!a.some(Oe=>Oe.id===pe))&&le("")},[Et,pe,a]),l.useEffect(()=>{if(g.createDaemonPicker){if(!a.length){_("");return}(!B||!a.some(Oe=>Oe.id===B))&&_(a[0].id)}},[a,B,g.createDaemonPicker]),l.useEffect(()=>{var Oe;if(!g.createDaemonPicker||!B){L("");return}if(!F.length){L("");return}F.some(lt=>lt.path===H)||L(((Oe=F[0])==null?void 0:Oe.path)||"")},[B,H,F,g.createDaemonPicker]);const pt=l.useRef(null),Yt=l.useRef(dR()),_t=g.meshStatePushRefresh?hR:mR,[Qt,Cs]=l.useState(_t);l.useEffect(()=>{if(!v)return;const Oe=pt.current!==v;if(pt.current=v,Oe){Pl(Yt.current),Cs(_t);const lt=hg(v);ve(lt),fe(null),V(se,v,lt!==null)}else fe(null),V(se,v,!0)},[v,se]);const $s=l.useRef(V);$s.current=V;const ms=l.useRef(!1),ss=l.useRef(()=>{});ss.current=()=>{ms.current||!v||!se||(ms.current=!0,Promise.resolve($s.current(se,v,!0)).finally(()=>{ms.current=!1}))},l.useEffect(()=>{uR(Yt.current,Q),Cs(pR(Yt.current,_t))},[Q,_t]),OL({daemonIds:l.useMemo(()=>[se,...Hs].filter(Boolean),[se,Hs]),meshId:v,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||ss.current()}}),l.useEffect(()=>{if(!v||!se||typeof document>"u")return;let Oe=null;const lt=()=>{document.visibilityState==="visible"&&ss.current()},es=()=>{Oe===null&&(Oe=setInterval(lt,Qt))},ns=()=>{Oe!==null&&(clearInterval(Oe),Oe=null)},js=()=>{document.visibilityState==="visible"?es():ns()};return document.visibilityState==="visible"&&es(),document.addEventListener("visibilitychange",js),()=>{ns(),document.removeEventListener("visibilitychange",js)}},[v,se,Qt]),l.useEffect(()=>{g.queueSection||ue(v)},[v,g.queueSection]);const Ys=l.useMemo(()=>a.map(Oe=>Oe.id).filter(Boolean).sort().join(","),[a]),Fs=l.useRef(!1);return l.useEffect(()=>{Ce(Fs.current),Fs.current=!0},[Ys]),S?X?s.jsx(Z2,{selectedMesh:X,error:N,onDismissError:()=>A(null),onBack:()=>{w(null),ve(null)},onDelete:O,displayedMeshStatus:Re,graphLoading:he,graphError:Z,onRefreshGraph:()=>{Pl(Yt.current),V(se,v,!0)},savingPolicy:at,onUpdatePolicy:st,coordinatorPromptDraft:rt,onCoordinatorPromptDraftChange:G,savingCoordinatorPrompt:oe,onSaveCoordinatorPrompt:Qe,daemons:a,coordinatorDaemonId:q,onCoordinatorDaemonIdChange:ee,coordinatorCliType:$e,isHostNodeAttached:Ve,selectedHostNode:ps,hostPinned:ut.pinned,hostLabel:ut.label,hostOnline:Et,hostRebindDaemonId:pe,onHostRebindDaemonIdChange:Oe=>le(Oe),settingMeshHost:Be,onSetMeshHost:ge,activeDaemon:je,activeDaemonId:se,meshQueue:te,userName:r,availableCliProviders:y,savingNodeSlotsId:Pe,onUpdateNodeSlots:Ze,savingNodeCapabilitiesId:He,onUpdateNodeCapabilities:Ue,nodeSystemPromptDrafts:de,onNodeSystemPromptDraftChange:(Oe,lt)=>xe(es=>({...es,[Oe]:lt})),savingNodeSystemPromptId:Se,onSaveNodeSystemPrompt:nt,selectedNodeId:ye,onSelectNode:Me,showAddNode:re,onShowAddNode:()=>ce(!0),onCancelAddNode:()=>ce(!1),nodeWorkspace:Ae,onNodeWorkspaceChange:be,nodeProviderPriority:we,onNodeProviderPriorityChange:_e,nodeDaemonId:U,onNodeDaemonIdChange:Ne,nodeCustomPath:Ie,onNodeCustomPathChange:We,nodePickerWorkspaces:Xe,nodePickerProviders:et,nodeOnboardingPlan:J,nodePlanLoading:Le,attachableDaemons:Fe,onAddNode:Ee,onRemoveNode:Je,availableCliAgents:x,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(JL,{meshes:C,loading:j,error:N,onDismissError:()=>A(null),daemons:a,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:T,onToggleCreate:()=>I(!T),createName:P,onCreateNameChange:M,createRepoIdentity:E,onCreateRepoIdentityChange:D,createRepoRemoteUrl:W,onCreateRepoRemoteUrlChange:R,newMeshDaemonId:B,onNewMeshDaemonIdChange:_,newMeshWorkspace:H,onNewMeshWorkspaceChange:L,createPickerWorkspaces:F,createOnboardingPlan:$,createPlanLoading:K,creating:z,createWarning:ne,onDismissCreateWarning:()=>ie(null),onSelectMesh:w,onCreate:me,onCancelCreate:Y}):s.jsx(Ja,{icon:s.jsx(cs,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})})}function gR(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function bR({children:e}){const{sendCommand:t,sendData:n}=St(),{ides:a}=Ss(),r=l.useMemo(()=>a.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[a]),o=l.useMemo(()=>({sendCommand:t,sendData:n,daemons:r,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var f;const d={meshId:c.meshId};c.cliType&&(d.cliType=c.cliType);const p=await t(i,"launch_mesh_coordinator",d),u=(p==null?void 0:p.result)??p;if((u==null?void 0:u.success)===!1)throw new Error(u.error||"Coordinator launch failed");const m=(u==null?void 0:u.sessionId)||((f=u==null?void 0:u.session)==null?void 0:f.id)||(u==null?void 0:u.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Xl,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:rg}),[t,n,r]);return s.jsx(og.Provider,{value:o,children:e})}function xR(e){const{daemons:t,features:n,meshes:a,meshesLoading:r,selectedMeshId:o,onSelectMesh:i,createMode:c,onCreateModeChange:d,createName:p,onCreateNameChange:u,createDaemonId:m,onCreateDaemonIdChange:f,createWorkspace:g,onCreateWorkspaceChange:k,createPickerWorkspaces:h,createPlan:b,createPlanLoading:S,creating:x,createWarning:y,onCreate:C,createRepoRemoteUrl:v,onCreateRepoRemoteUrlChange:w,createRepoIdentity:j,onCreateRepoIdentityChange:N,createManualOpen:A,onCreateManualOpenChange:T,nodes:I,attachableDaemons:P,attachDaemonId:M,onAttachDaemonIdChange:E,attachWorkspace:D,onAttachWorkspaceChange:W,attachPickerWorkspaces:R,attachPlan:B,attachPlanLoading:_,attaching:H,onAttach:L,renderInstallOnboarding:F,nodeLabel:$,daemonLabel:K}=e,{t:z}=ke("common");if(t.length===0)return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:z("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:z("setupWizard.machines.noMachinesDescription")})]}),F?F():s.jsx("p",{className:"text-[11px] text-text-muted",children:z("setupWizard.machines.noMachinesFallback")})]});const ne=H||_||(B==null?void 0:B.success)===!1||!D.trim()||n.addNodeDaemonPicker&&!M;return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:z("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:z("setupWizard.machines.description")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[a.map(ie=>{const Ce=!c&&o===ie.id;return s.jsx("button",{type:"button",onClick:()=>{d(!1),i(ie.id)},className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${Ce?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block truncate text-sm text-text-primary",children:ie.name}),s.jsxs("span",{className:"block truncate text-[11px] text-text-muted",children:[ie.repoIdentity||ie.repoRemoteUrl||""," · ",z("setupWizard.machines.nodeCount",{count:(ie.nodes||[]).length})]})]})},ie.id)}),s.jsx("button",{type:"button",onClick:()=>d(!0),className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${c?"border-accent-primary/60 bg-accent-primary/10":"border-dashed border-border-subtle bg-bg-secondary/40 hover:border-border-default"}`,children:s.jsxs("span",{className:"text-sm text-text-primary",children:["+ ",z("setupWizard.machines.createNew")]})}),r&&a.length===0&&s.jsx("p",{className:"text-[11px] text-text-muted",children:z("setupWizard.machines.loadingMeshes")})]}),c&&s.jsx(cg,{variant:"wizard",showDaemonPicker:n.createDaemonPicker,daemons:t,daemonLabel:K,name:p,onNameChange:u,daemonId:m,onDaemonIdChange:f,workspace:g,onWorkspaceChange:k,workspaces:h,plan:b,planLoading:S,repoRemoteUrl:v,onRepoRemoteUrlChange:w,repoIdentity:j,onRepoIdentityChange:N,manualOpen:A,onManualOpenChange:T,creating:x,warning:y,onCreate:C}),!c&&o&&s.jsxs("div",{className:"flex flex-col gap-2.5 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[I.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5",children:I.map(ie=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] text-text-secondary",children:$(ie)},ie.id))}),s.jsx("span",{className:"text-[11px] font-medium text-text-secondary",children:z("setupWizard.machines.attachTitle")}),n.addNodeDaemonPicker&&(P.length>0?s.jsx("div",{className:"flex flex-wrap gap-1.5",children:P.map(ie=>{const Ce=M===ie.id;return s.jsx("button",{type:"button",onClick:()=>E(ie.id),className:`rounded-full border px-2.5 py-1 text-[11px] transition-colors ${Ce?"border-accent-primary/60 bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-secondary text-text-secondary hover:border-border-default"}`,children:K(ie)},ie.id)})}):s.jsx("p",{className:"text-[11px] text-text-muted",children:z("setupWizard.machines.allMachinesAttached")})),(!n.addNodeDaemonPicker||M)&&s.jsxs(s.Fragment,{children:[s.jsx(Cl,{workspaces:R,value:D,onChange:W}),s.jsx(lg,{plan:B,loading:_}),s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:L,disabled:ne,children:z(H?"setupWizard.machines.attaching":"setupWizard.machines.addMachine")})})]})]})]})}function vR(e){var t;return e.machineNickname||e.nickname||e.hostname||((t=e.user)==null?void 0:t.name)||e.id}function yR(e){const t=e;return t.machine_label||t.machineLabel||t.hostname||String(e.workspace||"").split(/[\\/]/).filter(Boolean).pop()||e.id}function wR({daemons:e,features:t,sendCommand:n,unwrapResult:a,normalizeMesh:r,loadDaemonMetadata:o,initialMeshId:i,onClose:c,renderInstallOnboarding:d}){var Ae,be;const{t:p}=ke("common"),u=((Ae=e[0])==null?void 0:Ae.id)||"",{meshes:m,loading:f,error:g,setError:k,loadMeshes:h,selectedMeshId:b,setSelectedMeshId:S}=pg({daemons:e,primaryDaemonId:u,sendCommand:n,unwrapResult:a,normalizeMesh:r,features:{createDaemonPicker:t.createDaemonPicker,addNodeDaemonPicker:t.addNodeDaemonPicker},loadDaemonMetadata:o});l.useEffect(()=>{h()},[h]);const x=l.useRef(m);x.current=m;const y=l.useMemo(()=>m.map(we=>we.id).sort().join(","),[m]),C=l.useRef(n);C.current=n;const v=l.useRef(a);v.current=a,l.useEffect(()=>{b||m.length===0||(i&&m.some(we=>we.id===i)?S(i):m.length===1&&S(m[0].id))},[m,b,i,S]);const w=l.useMemo(()=>m.find(we=>we.id===b)??null,[m,b]),j=l.useMemo(()=>(w==null?void 0:w.nodes)||[],[w]),N=l.useCallback(we=>(we==null?void 0:we.__sourceDaemonId)||u,[u]),[A,T]=l.useState(!1),[I,P]=l.useState(""),[M,E]=l.useState(""),[D,W]=l.useState(""),[R,B]=l.useState(null),[_,H]=l.useState(!1),[L,F]=l.useState(!1),[$,K]=l.useState(null),[z,ne]=l.useState(""),[ie,Ce]=l.useState(""),[me,O]=l.useState(!1),Y=t.createDaemonPicker&&M||u,X=l.useMemo(()=>e.find(we=>we.id===Y),[e,Y]),Q=(X==null?void 0:X.workspaces)||[];l.useEffect(()=>{if(!A||!Y||!D.trim()){B(null),H(!1);return}let we=!1;const _e=setTimeout(()=>{we||(H(!0),C.current(Y,"plan_mesh_onboarding",{workspace:D.trim(),operation:"auto",meshInventory:x.current}).then(U=>{if(we)return;const Ne=v.current(U);B(Ne),Ne!=null&&Ne.success&&(P(Ie=>{var We,Xe;return Ie||`${String(((We=Ne.discovery)==null?void 0:We.repoIdentity)||((Xe=Ne.discovery)==null?void 0:Xe.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}),Ce(Ie=>{var We;return Ie||((We=Ne.discovery)==null?void 0:We.repoIdentity)||""}),ne(Ie=>{var We,Xe,et,J,Le,$e;return Ie||((et=(Xe=(We=Ne.discovery)==null?void 0:We.origin)==null?void 0:Xe.urls)==null?void 0:et[0])||(($e=(Le=(J=Ne.discovery)==null?void 0:J.upstream)==null?void 0:Le.urls)==null?void 0:$e[0])||""}))}).catch(U=>{we||B({success:!1,error:(U==null?void 0:U.message)||"Git discovery failed"})}).finally(()=>{we||H(!1)}))},300);return()=>{we=!0,clearTimeout(_e)}},[A,Y,D,y]);const ve=l.useCallback(async()=>{const we=Y,_e=D.trim(),U=z.trim(),Ne=ie.trim();if(!(!we||!I.trim()||L)&&!(!_e&&!U&&!Ne)){F(!0),K(null),k(null);try{const Ie=await ug({targetDaemonId:we,name:I,repoRemoteUrl:U,repoIdentity:Ne,workspace:_e,attachWorkspace:!!_e,machineId:X==null?void 0:X.machineId,providerPriority:Dn(cn((X==null?void 0:X.availableProviders)||[])),meshInventory:m,sendCommand:n,unwrapResult:a});if(Ie.warning&&K(Ie.warning),!Ie.meshCreated){k(Ie.error||p("setupWizard.machines.createFailed"));return}await h(!0),Ie.meshId&&S(Ie.meshId),T(!1)}finally{F(!1)}}},[Y,I,D,z,ie,L,X,m,n,a,h,S,k,p]),[he,Z]=l.useState(""),[fe,V]=l.useState(""),[q,ee]=l.useState(null),[pe,le]=l.useState(!1),[se,te]=l.useState(!1),ue=l.useMemo(()=>{if(!t.addNodeDaemonPicker)return[];const we=new Set(j.map(_e=>String(_e.daemon_id||_e.daemonId||"")));return e.filter(_e=>_e.id&&!we.has(_e.id)&&!am(_e))},[t.addNodeDaemonPicker,j,e]),ye=l.useMemo(()=>e.find(we=>we.id===he),[e,he]),Me=t.addNodeDaemonPicker?(ye==null?void 0:ye.workspaces)||[]:((be=e.find(we=>we.id===u))==null?void 0:be.workspaces)||[];l.useEffect(()=>{if(A||!b||!fe.trim()){ee(null);return}const we=t.addNodeDaemonPicker?he:N(w);if(!we)return;let _e=!1;return le(!0),n(we,"plan_mesh_onboarding",{workspace:fe.trim(),meshId:b,inlineMesh:w,operation:"add_existing"}).then(U=>{_e||ee(a(U))}).catch(U=>{_e||ee({success:!1,error:(U==null?void 0:U.message)||"Git discovery failed"})}).finally(()=>{_e||le(!1)}),()=>{_e=!0}},[A,b,w,fe,he,t.addNodeDaemonPicker,N,n,a]);const re=l.useCallback(async()=>{var U,Ne,Ie,We;const we=N(w);if(!b||!we||se)return;const _e=fe.trim();if(_e){te(!0),k(null);try{const Xe=t.addNodeDaemonPicker?he:we,et=await n(Xe,"plan_mesh_onboarding",{workspace:_e,meshId:b,inlineMesh:w,operation:"add_existing"}),J=a(et);if(ee(J),(J==null?void 0:J.success)===!1)throw new Error(`${J.code||"onboarding_blocked"}: ${J.error}${J.action?` ${J.action}`:""}`);const Le={meshId:b,workspace:((U=J==null?void 0:J.discovery)==null?void 0:U.repoRoot)||_e,repoRoot:(Ne=J==null?void 0:J.discovery)==null?void 0:Ne.repoRoot,isLocalWorktree:((Ie=J==null?void 0:J.discovery)==null?void 0:Ie.isLinkedWorktree)===!0};t.addNodeDaemonPicker&&he&&(Le.daemonId=he,Le.machineId=ye==null?void 0:ye.machineId),Le.providerPriority=Dn(cn(((We=t.addNodeDaemonPicker?ye:e[0])==null?void 0:We.availableProviders)||[]));const $e=await n(we,"add_mesh_node",Le),at=a($e);if((at==null?void 0:at.success)===!1)throw new Error(at.error||"Add node failed");V(""),ee(null),await h(!0)}catch(Xe){k((Xe==null?void 0:Xe.message)||"Add node failed")}finally{te(!1)}}},[w,b,fe,he,ye,se,t.addNodeDaemonPicker,N,e,n,a,h,k]),ce=!A&&!!w&&j.length>0;return s.jsxs("div",{className:"mx-auto flex w-full max-w-2xl flex-col gap-4 p-4",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-base font-semibold text-text-primary",children:p("setupWizard.title")}),s.jsx("p",{className:"mt-1.5 text-[11px] text-text-muted",children:p("setupWizard.machines.description")})]}),g&&s.jsx("p",{className:"text-[11px] text-red-400",children:g}),s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary p-4",children:s.jsx(xR,{daemons:e,features:t,meshes:m,meshesLoading:f,selectedMeshId:b,onSelectMesh:we=>{S(we),V(""),Z("")},createMode:A,onCreateModeChange:T,createName:I,onCreateNameChange:P,createDaemonId:M,onCreateDaemonIdChange:E,createWorkspace:D,onCreateWorkspaceChange:W,createPickerWorkspaces:Q,createPlan:R,createPlanLoading:_,creating:L,createWarning:$,onCreate:ve,createRepoRemoteUrl:z,onCreateRepoRemoteUrlChange:ne,createRepoIdentity:ie,onCreateRepoIdentityChange:Ce,createManualOpen:me,onCreateManualOpenChange:O,nodes:j,attachableDaemons:ue,attachDaemonId:he,onAttachDaemonIdChange:we=>{Z(we),V("")},attachWorkspace:fe,onAttachWorkspaceChange:V,attachPickerWorkspaces:Me,attachPlan:q,attachPlanLoading:pe,attaching:se,onAttach:re,renderInstallOnboarding:d,nodeLabel:yR,daemonLabel:vR})}),s.jsx("div",{className:"flex items-center gap-2",children:s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:ce?"btn btn-primary btn-sm":"btn btn-secondary btn-sm",onClick:c,children:p(ce?"setupWizard.continueToMesh":"setupWizard.close")})})})]})}function Ic(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function kR(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),n=Ic();return n&&!t.searchParams.has("token")&&t.searchParams.set("token",n),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Ms(e,t){return await fetch(kR(e),{credentials:"same-origin",...t})}function fg(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class SR{constructor(){it(this,"adapters",new Map);it(this,"states",new Map);it(this,"runtimeListeners",new Map);it(this,"screenshotCallbacks",new Map);it(this,"statusCallbacks",new Set);it(this,"stateChangeCallbacks",new Set);it(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const n of this.adapters.keys())if(n.startsWith("standalone"))return n}return null}register(t,n){this.adapters.set(t,n),this.states.set(t,n.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,n){this.states.set(t,n);const a=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(r=>r(a,n))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const n=this.resolveDaemonId(t);return n?this.adapters.get(n):void 0}getState(t){const n=this.resolveDaemonId(t);return n&&this.states.get(n)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,n){return!1}sendPtyInput(t,n,a){return this.ptyInputSender?this.ptyInputSender(t,n,a):!1}onScreenshot(t,n){return this.screenshotCallbacks.set(t,n),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,n){this.screenshotCallbacks.forEach(a=>a(t,n))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,n){this.statusCallbacks.forEach(a=>a(t,n))}emitRuntimeSnapshot(t,n,a=0,r=!1,o,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:a,text:n,truncated:r,cols:o,rows:i})}emitSessionOutput(t,n,a){!t||typeof n!="string"||!n||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof a=="number"?{seq:a}:{},data:n})}onRuntimeEvent(t,n){const a=this.runtimeListeners.get(t)||new Set;return a.add(n),this.runtimeListeners.set(t,a),()=>{const r=this.runtimeListeners.get(t);r&&(r.delete(n),r.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,n,a){if(!n)return{success:!1,error:"sessionId is required"};const r=new URL(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`,window.location.origin);typeof(a==null?void 0:a.sinceSeq)=="number"&&r.searchParams.set("sinceSeq",String(a.sinceSeq));const o=await Ms(`${r.pathname}${r.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const i=await o.json();return this.emitRuntimeEvent(n,{type:"runtime_snapshot",sessionId:n,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(a!=null&&a.force)}),{success:!0}}emitRuntimeEvent(t,n){var a;(a=this.runtimeListeners.get(t))==null||a.forEach(r=>r(n))}}const Ts=new SR;function CR(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=Ic();return n?`${t}?token=${encodeURIComponent(n)}`:t}const Cr=CR(),dp=3e3,jR=3e4;let gs=null,NR=0;const lo=new Map;let bn=null,La=null;function up(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function wa(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function AR(e){return e==="connected"?"connected":e}async function Ra(e,t,n){const a=xh(e,n||{}),r=gs;if(r&&r.readyState===WebSocket.OPEN){const o=`req_${++NR}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{lo.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);lo.set(o,{resolve:p=>{clearTimeout(d),i(p)},reject:p=>{clearTimeout(d),c(p)}}),r.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:a.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Dl(e,t){const n=gs;if(!n||n.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return n.send(JSON.stringify(t)),!0}catch{return!1}}function gg(e,t,n){const a=gs;if(!a||a.readyState!==WebSocket.OPEN)return!1;const r=xh(e,{sessionId:t,targetSessionId:t,data:n});try{return a.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:r.payload}})),!0}catch{return!1}}Ts.registerPtyInputSender(gg);class TR{constructor(t){it(this,"daemonId");it(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(gs==null?void 0:gs.readyState)===WebSocket.OPEN}get connectionState(){return(gs==null?void 0:gs.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return Ra(this.daemonId,t,n)}async sendInput(t,n){return Ra(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,bn&&(clearInterval(bn),bn=null);const n=async()=>{if(this.hasCommandChannel)try{const a=await Ra(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(a!=null&&a.success&&(a!=null&&a.base64)){const r=await fetch(`data:image/jpeg;base64,${a.base64}`).then(o=>o.blob());Ts.emitScreenshot(this.daemonId,r)}}catch{}};n(),bn=setInterval(n,2e3)}stopScreenshots(t){bn&&(clearInterval(bn),bn=null)}}let rs=null;function MR(e){return(!rs||rs.daemonId!==e)&&(rs=new TR(e)),rs}function PR({children:e}){const t=l.useRef(Ea()),n=Ea();t.current=n;const{setUserName:a}=Ss(),r=l.useRef(a);r.current=a;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((h,b)=>{c(h),La==null||La(h,b)},[]),p=l.useRef(null),u=l.useRef(),m=l.useRef(dp),f=l.useRef(!0),g=l.useRef(!1),k=l.useRef("initial_connect");return l.useEffect(()=>{f.current=!0,g.current=!1;function h(){var x,y;if(!f.current||((x=p.current)==null?void 0:x.readyState)===WebSocket.OPEN||((y=p.current)==null?void 0:y.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Cr}...`),wa("connect_attempt",{url:Cr,reason:k.current,delayMs:m.current});let S;try{S=new WebSocket(Cr)}catch(C){console.error("[Standalone WS] Failed to create WebSocket:",C),b();return}p.current=S,S.onopen=()=>{if(!f.current){S.close();return}d("connected"),m.current=dp,wa("open",{url:Cr,reason:k.current}),ys.resubscribeAll({sendData:Dl}),console.log("[Standalone WS] Connected")},gs=S,S.onmessage=C=>{var v,w;try{const j=JSON.parse(C.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const N=lo.get(j.requestId);N&&(lo.delete(j.requestId),j.type==="error"?N.reject(new Error(((v=j.data)==null?void 0:v.message)||"Command failed")):N.resolve(j.data));return}if(j.type==="session_output"){const N=j.sessionId||j.cliId||j.cliType;N&&Ts.emitSessionOutput(N,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){Ts.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated,typeof j.cols=="number"?j.cols:void 0,typeof j.rows=="number"?j.rows:void 0);return}if(j.type==="topic_update"){const N=j.update;N&&ys.publish(N);return}if(j.type==="status"||j.type==="initial_state"){const N=j.data;if(!N)return;const{injectEntries:A,markLoaded:T,getIdes:I}=t.current,P=N.instanceId||"standalone",M=I().find(W=>W.id===P),E=MR(P);Ts.register(P,E),Ts.setState(P,"connected"),d("connected",P),Ts.emitStatus(P,N);const D=Or(N,{daemonId:P,existingDaemon:M,existingEntries:I()});up("ws_status",{type:j.type,daemonId:P,sessions:(N.sessions||[]).map(W=>({id:W.id,parentId:W.parentId,providerType:W.providerType,kind:W.kind,transport:W.transport,unread:W.unread,inboxBucket:W.inboxBucket,lastSeenAt:W.lastSeenAt,lastUpdated:W.lastUpdated,title:W.title})),recentLaunches:(N.recentLaunches||[]).map(W=>({id:W.id,providerType:W.providerType,kind:W.kind,workspace:W.workspace,lastLaunchedAt:W.lastLaunchedAt}))}),up("entries",{daemonId:P,entries:D.filter(W=>W.type!=="adhdev-daemon").map(W=>({id:W.id,type:W.type,unread:W.unread,inboxBucket:W.inboxBucket,lastSeenAt:W.lastSeenAt,lastUpdated:W.lastUpdated,sessionId:W.sessionId}))}),D.length>0&&A(D,{authoritativeDaemonIds:[P]}),T(),i.current!==P&&((w=o.current)==null||w.call(o),i.current=P,o.current=ys.subscribe({sendData:Dl},P,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${P}`,params:{includeSessions:!0}},W=>{if(W.topic!=="daemon.metadata")return;const R=t.current.getIdes(),B=R.find(H=>H.id===P),_=Or(W.status,{daemonId:P,existingDaemon:B,existingEntries:R,timestamp:W.timestamp});_.length>0&&t.current.injectEntries(_,{authoritativeDaemonIds:[P]}),W.userName&&r.current&&r.current(W.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},S.onclose=C=>{f.current&&(rs==null||rs.stopScreenshots(),rs&&Ts.setState(rs.daemonId,"disconnected"),d("disconnected"),p.current=null,k.current=`close:${C.code}${C.wasClean?":clean":":unclean"}`,wa("close",{code:C.code,reason:C.reason||"",wasClean:C.wasClean}),b())},S.onerror=C=>{g.current||!f.current||(k.current="error",wa("error",{message:C instanceof Event?"event":String(C),readyState:S.readyState}),console.warn("[Standalone WS] Error, will reconnect:",C))}}function b(){if(!f.current)return;clearTimeout(u.current);const S=m.current;console.log(`[Standalone WS] Reconnecting in ${S}ms...`),wa("schedule_reconnect",{reason:k.current,delayMs:S}),u.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,jR),h()},S)}return h(),()=>{var S;f.current=!1,g.current=!0,(S=o.current)==null||S.call(o),o.current=null,i.current=null,clearTimeout(u.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,gs=null),rs&&(rs.stopScreenshots(),Ts.unregister(rs.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function DR({children:e}){const[t,n]=l.useState("disconnected"),[a,r]=l.useState(null);l.useEffect(()=>(La=(i,c)=>{n(i),c&&r(c)},()=>{La=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=AR(t),d={};return a&&(d[a]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d,usesP2P:!1}},[t,a]);return s.jsx(rb,{connectionOverrides:o,children:s.jsx(PR,{children:e})})}const bg="adhdev_standalone_font_preferences",An={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Eo=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],Oa=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],IR=new Set(Eo.map(e=>e.id)),LR=new Set(Oa.map(e=>e.id));function Ps(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Er("chat",t.chat),code:Er("code",t.code),terminal:Er("terminal",t.terminal)}}function Er(e,t){const n=An[e],a=t&&typeof t=="object"&&!Array.isArray(t)?t:{},r=typeof a.preset=="string"?a.preset.trim():"",o=typeof a.customFamily=="string"?a.customFamily.trim():"";return(e==="chat"?IR:LR).has(r)?r==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:r}:n}function _r(e,t){var r;const n=Er(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const a=e==="chat"?Eo:Oa;return((r=a.find(o=>o.id===n.preset))==null?void 0:r.family)||a[0].family}function RR(e){const t=Ps(e),n=_r("chat",t.chat),a=_r("code",t.code),r=_r("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":a,"--chat-terminal-font-family":r,"--chat-tool-font-family":r}}function vn(e,t=document.documentElement){const n=Ps(e),a=RR(n);t.setAttribute("data-standalone-fonts","custom");for(const[r,o]of Object.entries(a))t.style.setProperty(r,o);return n}function Il(e){const t=Ps(e);try{localStorage.setItem(bg,JSON.stringify(t))}catch{}return t}function ER(){try{const e=localStorage.getItem(bg);if(e)return Ps(JSON.parse(e))}catch{}return An}function _R(){return vn(ER())}function ka(e,t){var a;const n=e==="chat"?Eo:Oa;return((a=n.find(r=>r.id===t))==null?void 0:a.label)||n[0].label}function HR({children:e}){const t=ia(),n=Rl(),{t:a}=ke("common"),r=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(Tp,{}),label:a("nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(nn,{}),label:a("nav.machines"),active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(cs,{}),label:a("nav.mesh"),active:n.pathname.startsWith("/mesh")||n.pathname.startsWith("/setup"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(Ua,{}),label:a("nav.settings"),active:n.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[n.pathname,t,a]),o=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:a("nav.docs")}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(Mp,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:a("nav.docs")},{id:"about",label:a("nav.about"),icon:s.jsx(uo,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:a("nav.about")}],[n.pathname,t,a]);return s.jsx(m1,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:r,footerItems:o,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","1.0.57"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:a(i?"standalone.layout.expandSidebar":"standalone.layout.collapseSidebar"),children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:a("standalone.layout.collapse")})]}),children:e})}function $R(){const e=ia(),{sendCommand:t}=St(),{ides:n}=Ss(),a=l.useMemo(()=>n.filter(r=>r.daemonMode||r.type==="adhdev-daemon").map(r=>r),[n]);return s.jsx(wR,{daemons:a,features:rg,sendCommand:t,unwrapResult:r=>r,normalizeMesh:r=>r,onClose:()=>e("/mesh")})}const FR=[{icon:s.jsx(nn,{size:16}),key:"localFirst"},{icon:s.jsx(Is,{size:16}),key:"chatRelay"},{icon:s.jsx(Fl,{size:16}),key:"screenshots"},{icon:s.jsx(us,{size:16}),key:"remoteControl"},{icon:s.jsx(_a,{size:16}),key:"multiIde"},{icon:s.jsx(Mp,{size:16}),key:"cliAcp"}],BR=[{icon:s.jsx(ho,{size:16}),key:"anywhere"},{icon:s.jsx(Tp,{size:16}),key:"p2pStream"},{icon:s.jsx(la,{size:16}),key:"mobileNotifications"},{icon:s.jsx(fb,{size:16}),key:"restApi"},{icon:s.jsx(bb,{size:16}),key:"enterpriseControls"}],WR=[{key:"chatRelay",selfhost:!0,cloud:!0},{key:"screenshots",selfhost:!0,cloud:!0},{key:"remoteControl",selfhost:!0,cloud:!0},{key:"multiIde",selfhost:!0,cloud:!0},{key:"extensionCli",selfhost:!0,cloud:!0},{key:"anyNetwork",selfhost:!1,cloud:!0},{key:"webrtc",selfhost:!1,cloud:!0},{key:"mobilePush",selfhost:!1,cloud:!0},{key:"restApi",selfhost:!1,cloud:!0},{key:"multiMachineDashboards",selfhost:!1,cloud:!0},{key:"ssoRbacAuditLogs",selfhost:!1,cloud:!0}];function OR(){const{t:e}=ke("common");return s.jsxs(Ja,{icon:s.jsx(uo,{className:"text-text-primary"}),title:e("standalone.about.title"),subtitle:e("standalone.about.subtitle"),widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","1.0.57"]}),children:[s.jsx(xt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:e("standalone.about.selfHostedEdition")}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:e("standalone.about.headline")}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:e("standalone.about.description")})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.docs")}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.github")}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.tryCloud")})]})]})}),s.jsx(xt,{title:e("standalone.about.includedSection"),description:e("standalone.about.includedDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:FR.map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:t.icon}),e("standalone.about.features."+t.key+".title")]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e("standalone.about.features."+t.key+".desc")})]},t.key))})}),s.jsx(xt,{title:e("standalone.about.inventorySection"),description:e("standalone.about.inventoryDescription"),children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:vh.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:wh.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:yh.map(t=>`${t.icon} ${t.name}`)}].map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:t.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:t.items.map(n=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:n},n))})]},t.label))})}),s.jsx(xt,{title:e("standalone.about.cloudExtrasSection"),description:e("standalone.about.cloudExtrasDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:BR.map(t=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:t.icon}),e("standalone.about.extras."+t.key+".title")]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e("standalone.about.extras."+t.key+".desc")})]},t.key))})}),s.jsx(xt,{title:e("standalone.about.comparisonSection"),description:e("standalone.about.comparisonDescription"),children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:e("standalone.about.featureHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.selfhostHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.cloudHeader")})]})}),s.jsx("tbody",{children:WR.map((t,n)=>s.jsxs("tr",{className:n%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e("standalone.about.comparison."+t.key)}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:t.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},t.key))})]})})}),s.jsx(Xa,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:e("standalone.about.cloudOptional"),description:e("standalone.about.cloudOptionalDescription"),action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:e("standalone.about.compareCloud")}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(Nb,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function Fi(e,t,n){return{...e,[t]:n}}function Bi({surface:e,title:t,description:n,value:a,options:r,onChange:o}){const{t:i}=ke("common");return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:n})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(b1,{value:a.preset,onChange:c=>{const d=c.target.value;o(d==="custom"?{preset:"custom",customFamily:a.customFamily||""}:{preset:d})},children:r.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),a.preset==="custom"&&s.jsx(xs,{type:"text",className:"font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:a.customFamily||"",onChange:c=>o({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:i("standalone.fonts.resolvedStack")})," ",s.jsx("span",{className:"font-mono break-all",children:_r(e,a)})]})]})]})}function UR({value:e,savedValue:t,saving:n=!1,error:a,notice:r,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:d}){const{t:p}=ke("common"),u=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:p("standalone.fonts.fontOverridesNotice")}),a&&s.jsx(Mt,{variant:"error",children:a}),r&&s.jsx(Mt,{variant:"success",children:r}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Bi,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:Eo,onChange:m=>o(Fi(e,"chat",m))}),s.jsx(Bi,{surface:"code",title:p("standalone.fonts.code"),description:p("standalone.fonts.codeDescription"),value:e.code,options:Oa,onChange:m=>o(Fi(e,"code",m))}),s.jsx(Bi,{surface:"terminal",title:p("standalone.fonts.terminal"),description:p("standalone.fonts.terminalDescription"),value:e.terminal,options:Oa,onChange:m=>o(Fi(e,"terminal",m))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:p("standalone.fonts.livePreview")}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",ka("chat",e.chat.preset)," · Code: ",ka("code",e.code.preset)," · Terminal: ",ka("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",ka("chat",An.chat.preset)," / ",ka("code",An.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Gs,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!u,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(Gs,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!u,children:p("standalone.fonts.revertToSaved")}),s.jsx(Gs,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function GR(){const{t:e}=ke("common"),{ides:t}=Ss(),n=t.find(O=>O.type==="adhdev-daemon"),a=(n==null?void 0:n.detectedIdes)||[],{sendCommand:r}=St(),{userName:o}=Ss(),[i,c]=l.useState(o||""),[d,p]=l.useState(null),[u,m]=l.useState(null),[f,g]=l.useState(An),[k,h]=l.useState(!1),[b,S]=l.useState(""),[x,y]=l.useState(""),[C,v]=l.useState("127.0.0.1"),[w,j]=l.useState(""),[N,A]=l.useState(""),[T,I]=l.useState(""),[P,M]=l.useState(""),[E,D]=l.useState(""),[W,R]=l.useState(!1),B=async()=>{const Y=await(await Ms("/auth/session")).json();p(Y)},_=async()=>{const Y=await(await Ms("/api/v1/standalone/preferences")).json();m(Y),v(Y.standaloneBindHost);const X=Ps(Y.standaloneFontPreferences);g(X),vn(X),Il(X)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([B(),_()]).catch(O=>{M(O instanceof Error?O.message:String(O))})},[]),l.useEffect(()=>{vn(f)},[f]);const H=O=>{const Y=O.target.value.trim();n!=null&&n.id&&Y!==o&&r(n.id,"set_user_name",{userName:Y}).catch(console.error)},[L,F]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),$=O=>{F(O);try{localStorage.setItem("adhdev_sound",O?"1":"0")}catch{}},K=async()=>{S(""),y(""),h(!0);try{const O=Ps(f),Y=await Ms("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:O})}),X=await Y.json();if(!Y.ok)throw new Error((X==null?void 0:X.error)||"Failed to save standalone font preferences");const Q=Ps(X.standaloneFontPreferences);m(X),g(Q),vn(Q),Il(Q),y(e("standalone.settings.fontsSaved"))}catch(O){S(O instanceof Error?O.message:String(O))}finally{h(!1)}},z=()=>{const O=Ps(u==null?void 0:u.standaloneFontPreferences);S(""),y(""),g(O),vn(O)},ne=()=>{S(""),y(""),g(An),vn(An)},ie=async()=>{M(""),D(""),R(!0);try{const O=await Ms("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),Y=await O.json();if(!O.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to save standalone network preference");m(Y),v(Y.standaloneBindHost),D(Y.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(O){M(O instanceof Error?O.message:String(O))}finally{R(!1)}},Ce=async()=>{if(M(""),D(""),N.trim().length<4){M(e("standalone.settings.passwordTooShort"));return}if(N!==T){M(e("standalone.settings.passwordMismatch"));return}R(!0);try{const O=await Ms("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,newPassword:N})}),Y=await O.json();if(!O.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to save password");p(Y),await _(),j(""),A(""),I(""),D(d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),fg()}catch(O){M(O instanceof Error?O.message:String(O))}finally{R(!1)}},me=async()=>{M(""),D(""),R(!0);try{const O=await Ms("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,clear:!0})}),Y=await O.json();if(!O.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to clear password");p(Y),await _(),j(""),A(""),I(""),D(e("standalone.settings.passwordDisabled"))}catch(O){M(O instanceof Error?O.message:String(O))}finally{R(!1)}};return s.jsxs(Ja,{icon:s.jsx(Ua,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Mt,{variant:"info",children:e("standalone.settings.infoNotice")}),(d==null?void 0:d.publicHostWarning)&&s.jsx(Mt,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(xt,{title:e("standalone.settings.daemonSection"),description:e("standalone.settings.daemonDescription"),children:s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.versionLabel")}),s.jsxs("span",{className:"font-mono text-xs text-text-primary",children:["v","1.0.57"]})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.statusLabel")}),s.jsx("span",{className:`text-xs font-medium ${n?"text-green-400":"text-yellow-400"}`,children:e(n?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.currentBindLabel")}),s.jsx("span",{className:"font-mono text-xs text-text-primary",children:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.boundHost)||"127.0.0.1"})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.defaultBindLabel")}),s.jsx("span",{className:"font-mono text-xs text-text-primary",children:(u==null?void 0:u.standaloneBindHost)||"127.0.0.1"})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs text-text-primary",children:d!=null&&d.hasPasswordAuth?e("standalone.settings.authPassword"):d!=null&&d.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]})]})}),s.jsx(xt,{title:e("standalone.settings.networkSection"),description:e("standalone.settings.networkDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:e("standalone.settings.networkHint")}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="127.0.0.1",onChange:()=>v("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.localhostLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.localhostHint")})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="0.0.0.0",onChange:()=>v("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.allInterfacesLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.allInterfacesHint")})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Gs,{type:"button",variant:"primary",size:"sm",onClick:()=>{ie()},disabled:W,children:e(W?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.boundHost)||"127.0.0.1"})})]})]})}),s.jsx(xt,{title:e("standalone.settings.securitySection"),description:e("standalone.settings.securityDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),P&&s.jsx(Mt,{variant:"error",children:P}),E&&s.jsx(Mt,{variant:"success",children:E}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(xs,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:w,onChange:O=>j(O.target.value)}),s.jsx(xs,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:N,onChange:O=>A(O.target.value)}),s.jsx(xs,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:T,onChange:O=>I(O.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Gs,{type:"button",variant:"primary",size:"sm",onClick:()=>{Ce()},disabled:W,children:W?e("standalone.settings.saving"):d!=null&&d.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(d==null?void 0:d.hasPasswordAuth)&&s.jsx(Gs,{type:"button",variant:"danger",size:"sm",onClick:()=>{me()},disabled:W,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(xt,{title:e("standalone.settings.detectedIdesSection"),description:e("standalone.settings.detectedIdesDescription"),children:a.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:e("standalone.settings.noIdesDetected")}):s.jsx("div",{className:"flex flex-col gap-2",children:a.map(O=>s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${O.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium text-text-primary",children:O.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:O.type})]},O.type))})}),s.jsx(xt,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(A1,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(xt,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(q1,{themeDescription:e("standalone.settings.themeDescription"),mobileDescription:e("standalone.settings.mobileDescription"),fontsSlot:s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:e("standalone.settings.fontsLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e("standalone.settings.fontsDescription")}),s.jsx(UR,{value:f,savedValue:Ps(u==null?void 0:u.standaloneFontPreferences),saving:k,error:b,notice:x,onChange:g,onSave:()=>{K()},onResetToSaved:z,onResetToDefaults:ne})]})})}),s.jsx(xt,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(k1,{}),s.jsx(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(jb,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:L,onChange:$})]})}),s.jsx(xt,{title:e("standalone.settings.profileSection"),description:e("standalone.settings.profileDescription"),children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(hb,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel")]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:e("standalone.settings.displayNameHint")})]}),s.jsx(xs,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:O=>c(O.target.value),onBlur:H,onKeyDown:O=>{O.key==="Enter"&&O.currentTarget.blur()}})]})})})]})}const qR=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],Na="adhdev_onboarding_done",zR=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],KR={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function VR({onDone:e}){const{t}=ke("common"),[n,a]=l.useState([]),[r,o]=l.useState(new Set(qR)),[i,c]=l.useState(!0),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState("all");l.useEffect(()=>{let w=!1;return fetch("https://api.adhf.dev/api/v1/registry/providers?sort=popular&limit=100").then(async N=>{if(!N.ok)throw new Error(`HTTP ${N.status}`);const A=await N.text();try{return JSON.parse(A)}catch{throw new Error(`unexpected non-JSON response (${N.headers.get("content-type")??"unknown content type"})`)}}).then(N=>{w||a(N.providers??[])}).catch(N=>{w||p(N instanceof Error?N.message:String(N))}).finally(()=>{w||c(!1)}),()=>{w=!0}},[]);const b=n.filter(w=>k==="all"||w.category===k),S=["cli","ide","extension","acp"].map(w=>({category:w,items:b.filter(j=>j.category===w)})).filter(w=>w.items.length>0),x=l.useCallback(w=>{o(j=>{const N=new Set(j);return N.has(w)?N.delete(w):N.add(w),N})},[]),y=l.useCallback(async()=>{if(r.size===0){localStorage.setItem(Na,"1"),e();return}m(!0);const w=[];for(const j of r)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:j})})).json().catch(()=>({}));w.push({type:j,ok:!!A.success,error:A.error})}catch(N){w.push({type:j,ok:!1,error:N instanceof Error?N.message:String(N)})}g(w),m(!1),w.every(j=>j.ok)&&localStorage.setItem(Na,"1")},[r,e]),C=l.useCallback(()=>{localStorage.setItem(Na,"1"),e()},[e]),v=l.useCallback(()=>{f&&f.every(w=>w.ok)?e():u||C()},[f,u,e,C]);return s.jsx(Cm,{open:!0,onClose:v,size:"lg",contentClassName:"max-w-2xl",title:t("standalone.onboarding.title"),footer:s.jsxs("div",{className:"flex w-full items-center gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t(r.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:r.size})}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(Gs,{variant:"secondary",size:"sm",onClick:C,disabled:u,children:t("standalone.onboarding.skip")}),s.jsx(Gs,{variant:"primary",size:"sm",onClick:()=>{f?(localStorage.setItem(Na,"1"),e()):y()},disabled:u||!f&&r.size===0,children:u?t("standalone.onboarding.installing"):f?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:r.size})})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsx("div",{className:"text-[12px] text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!d&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:zR.map(w=>{const j=w.key==="all"?n.length:n.filter(N=>N.category===w.key).length;return j===0&&w.key!=="all"?null:s.jsxs("button",{onClick:()=>h(w.key),className:`machine-btn text-[10px] px-2 py-0.5 ${k===w.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[w.label," ",s.jsxs("span",{className:"opacity-60",children:["(",j,")"]})]},w.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&d&&s.jsx(Mt,{variant:"error",children:t("standalone.onboarding.loadError",{error:d})}),!i&&!d&&b.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!d&&b.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:S.map(w=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:KR[w.category]??w.category}),s.jsx("div",{className:"grid gap-1.5",children:w.items.map(j=>{var I;const N=r.has(j.type),A=f==null?void 0:f.find(P=>P.type===j.type),T=((I=j.manifest)==null?void 0:I.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${N?"bg-accent-primary/[0.06] border-accent-primary/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:N,onChange:()=>x(j.type),disabled:u,className:"shrink-0"}),s.jsx(Qa,{type:j.type,label:j.displayName??j.type,size:18,className:"shrink-0"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:j.displayName}),T&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:T})]}),A&&s.jsx("span",{className:`text-[10px] font-semibold ${A.ok?"text-status-online":"text-status-error"}`,children:A.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:A.error??"failed"})})]},j.type)})})]},w.category))})]})})}function YR(){try{return localStorage.getItem(Na)==="1"}catch{return!1}}s1();H1();T0();_R();const QR=jp({baseUrl:"",getToken:Ic});function JR({children:e}){const{t}=ke("common"),[n,a]=l.useState(null),[r,o]=l.useState(!0),[i,c]=l.useState(""),[d,p]=l.useState(""),[u,m]=l.useState(!1),f=async()=>{o(!0),p("");try{const h=await(await Ms("/auth/session")).json();a(h)}catch(k){p(k instanceof Error?k.message:String(k))}finally{o(!1)}};l.useEffect(()=>{f()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let k=!1;return(async()=>{try{const h=await Ms("/api/v1/standalone/preferences");if(!h.ok)return;const b=await h.json();if(k)return;const S=Ps(b.standaloneFontPreferences);vn(S),Il(S)}catch{}})(),()=>{k=!0}},[n==null?void 0:n.authenticated,n==null?void 0:n.required]);const g=async k=>{k.preventDefault(),m(!0),p("");try{const h=await Ms("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),b=await h.json();if(!h.ok)throw new Error((b==null?void 0:b.error)||"Login failed");a(b),c(""),fg()}catch(h){p(h instanceof Error?h.message:String(h))}finally{m(!1)}};return r?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):n?!n.required||n.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t("standalone.auth.signInTitle")}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:n.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),n.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[s.jsx(xs,{type:"password",value:i,onChange:k=>c(k.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(Gs,{type:"submit",variant:"primary",disabled:u||!i,className:"justify-center",children:t(u?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Mt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),d&&s.jsx(Mt,{variant:"error",children:d})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:d||"unknown error"})})}function pp(){const{t:e}=ke("common"),{ides:t,initialLoaded:n}=Ss();if(!n)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:e("standalone.machine.loading")});const a=t.find(r=>r.daemonMode||r.type==="adhdev-daemon");return a?s.jsx(Ui,{to:`/machines/${a.id}`,replace:!0}):s.jsx(Ui,{to:"/dashboard",replace:!0})}function XR(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!YR())return fetch("/api/v1/providers/installed").then(a=>a.ok?a.json():{providers:[]}).then(a=>{n||(a.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{n=!0}},[]),e?s.jsx(VR,{onDone:()=>t(!1)}):null}function ZR(){const{t:e}=ke("common"),{ides:t}=Ss(),n=l.useMemo(()=>{for(const u of t)if(u.activeInteractivePrompt)return u.instanceId??u.id;return null},[t]),{promptSession:a,hasActivePrompt:r,responseError:o,isSubmitting:i,submit:c,cancel:d,reopen:p}=Dh(n);return r?s.jsxs("div",{className:"relative",children:[!a&&s.jsx("button",{type:"button",onClick:p,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:e("standalone.machine.awaitingInput")}),s.jsx(Xp,{promptSession:a,isSubmitting:i,error:o,onSubmit:c,onCancel:d})]}):null}function eE(){const e=l.useMemo(()=>({sendCommand:Ra,sendData:Dl,sendPtyInput:gg}),[]);return s.jsx(Og,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(lb,{client:QR,children:s.jsx(JR,{children:s.jsx(DR,{children:s.jsx(db,{value:e,children:s.jsxs(Hb,{sendDaemonCommand:Ra,children:[s.jsx(ZR,{}),s.jsxs(HR,{children:[s.jsx(XR,{}),s.jsxs(Ug,{children:[s.jsx(Ws,{path:"/dashboard",element:s.jsx(TI,{})}),s.jsx(Ws,{path:"/machine",element:s.jsx(pp,{})}),s.jsx(Ws,{path:"/machines/:id",element:s.jsx(WL,{})}),s.jsx(Ws,{path:"/machines",element:s.jsx(pp,{})}),s.jsx(Ws,{path:"/about",element:s.jsx(OR,{})}),s.jsx(Ws,{path:"/settings",element:s.jsx(GR,{})}),s.jsx(Ws,{path:"/mesh",element:s.jsx(bR,{children:s.jsx(fR,{})})}),s.jsx(Ws,{path:"/setup",element:s.jsx($R,{})}),s.jsx(Ws,{path:"*",element:s.jsx(Ui,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}UC({connectionManager:Ts});Gg(document.getElementById("root")).render(s.jsx(eE,{}));