@adhdev/daemon-standalone 0.9.82-rc.192 → 0.9.82-rc.193
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.
|
@@ -62,14 +62,14 @@ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Mach
|
|
|
62
62
|
<button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
|
|
63
63
|
<button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
|
|
64
64
|
</div>
|
|
65
|
-
`,V.style.top="52px",V.style.height="calc(100% - 52px)";const fe=ne.querySelector("[data-adhdev-popout-focus]");fe&&(fe.onclick=()=>{window.focus()});const ke=ne.querySelector("[data-adhdev-popout-dock]");ke&&(ke.disabled=!te,ke.style.opacity=te?"1":"0.5",ke.style.cursor=te?"pointer":"default",ke.onclick=()=>{var Ce;te&&Me(te),(Ce=H.defaultView)==null||Ce.focus()})}},[D,Me]),ue=l.useCallback(z=>{var re;const G=M.current,Y=G==null?void 0:G.getPanel(z);if(!(!G||!Y)){Y.group.model.openPanel(Y),Y.api.setActive(),Q(z,"dockview-shortcut");try{const H=Y.group.model.location;H.type==="popout"?H.getWindow().focus():Wa((re=Y.group.element)==null?void 0:re.ownerDocument)}catch{}}},[Q]),U=l.useCallback(z=>{const G=M.current,Y=G==null?void 0:G.activePanel,re=(G==null?void 0:G.activeGroup)||(Y==null?void 0:Y.group);if(!G||!Y||!re)return;const H=re.panels||[];if(H.length<=1)return;const V=H.findIndex(Se=>Se.id===Y.id);if(V<0)return;const te=(V+z+H.length)%H.length,le=H[te];le&&(le.group.model.openPanel(le),le.api.setActive(),Dt(le.id)||Q(le.id,"dockview-shortcut"))},[Q]),ce=l.useCallback(z=>{var fe;const G=M.current,Y=(G==null?void 0:G.activeGroup)||((fe=G==null?void 0:G.activePanel)==null?void 0:fe.group);if(!G||!Y)return;const re=G.groups||[],H=re.find(ke=>ke.id===Y.id);if(!H)return;const V=H.element.getBoundingClientRect(),te=V.left+V.width/2,le=V.top+V.height/2,Se=(ke,Ce,Ke,Ge)=>Math.max(0,Math.min(Ce,Ge)-Math.max(ke,Ke)),Le=ke=>{const Ce=ke.element.getBoundingClientRect(),Ke=Ce.left+Ce.width/2,Ge=Ce.top+Ce.height/2;let Be=0,ht=0,ct=0,ft=!1;if(z==="left"?(ft=Ke<te,Be=Math.max(0,V.left-Ce.right),ht=Math.abs(Ge-le),ct=Se(V.top,V.bottom,Ce.top,Ce.bottom)):z==="right"?(ft=Ke>te,Be=Math.max(0,Ce.left-V.right),ht=Math.abs(Ge-le),ct=Se(V.top,V.bottom,Ce.top,Ce.bottom)):z==="above"?(ft=Ge<le,Be=Math.max(0,V.top-Ce.bottom),ht=Math.abs(Ke-te),ct=Se(V.left,V.right,Ce.left,Ce.right)):(ft=Ge>le,Be=Math.max(0,Ce.top-V.bottom),ht=Math.abs(Ke-te),ct=Se(V.left,V.right,Ce.left,Ce.right)),!ft)return Number.POSITIVE_INFINITY;const He=ct>0?0:120;return Be*3+ht+He};let O=null,ne=Number.POSITIVE_INFINITY;for(const ke of re){if(ke.id===H.id)continue;const Ce=Le(ke);Number.isFinite(Ce)&&(Ce>=ne||(ne=Ce,O=ke))}return O||void 0},[]),ie=l.useCallback(z=>{var re;const G=ce(z);if(!G)return;const Y=G.activePanel||G.panels[0];Y&&(G.model.openPanel(Y),Y.api.setActive(),Dt(Y.id)||Q(Y.id,"dockview-focus"),Wa((re=G.element)==null?void 0:re.ownerDocument))},[ce,Q]),de=l.useCallback((z,G)=>{const Y=M.current,re=Y==null?void 0:Y.activePanel,H=(Y==null?void 0:Y.activeGroup)||(re==null?void 0:re.group);if(!Y||!re||!H)return;let V=ce(z);!V&&(G!=null&&G.createGroupIfMissing)&&(V=Y.addGroup({referenceGroup:H,direction:z})),V&&(re.api.moveTo({group:V,position:"center"}),re.group.model.openPanel(re),re.api.setActive(),Dt(re.id)||Q(re.id,G!=null&&G.createGroupIfMissing?"dockview-split":"dockview-move"))},[ce,Q]),{isMac:me,tabShortcuts:oe,shortcutListening:P,setShortcutListening:xe,saveShortcuts:Ne}=Pu({sortedTabKeys:e.map(z=>z.tabKey),onFocus:J,onSelectTab:ue}),_e=l.useCallback(()=>{var Y;const z=M.current;if(!z)return;const G=z.activePanel;if(G){if(Dt(G.id)){const re=((Y=G.params)==null?void 0:Y.routeId)||G.id.slice(7),H=Bt(e,re);H!=null&&H.tabKey&&xe(H.tabKey);return}D.has(G.id)&&xe(G.id)}},[D,ue,xe,e]),se=l.useCallback(z=>{const G=[];return z.metaKey&&G.push(me?"⌘":"Meta"),z.ctrlKey&&G.push("Ctrl"),z.altKey&&G.push(me?"⌥":"Alt"),z.shiftKey&&z.key.length!==1&&G.push(me?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(z.key)?null:(G.push(Bu(z.key)),G.join("+"))},[me]),De=l.useCallback(z=>{var G,Y;switch(z){case"splitActiveTabRight":de("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":de("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const re=pe();re&&ge(re);return}case"popoutActiveTab":{const re=pe();re&&we(re);return}case"dockActiveTab":{const re=pe();if(!re)return;q(re)?Me(re):ve(re)&&Ie(re);return}case"focusLeftPane":ie("left");return;case"focusRightPane":ie("right");return;case"focusUpPane":ie("above");return;case"focusDownPane":ie("below");return;case"moveActiveTabToLeftPane":de("left");return;case"moveActiveTabToRightPane":de("right");return;case"moveActiveTabToUpPane":de("above");return;case"moveActiveTabToDownPane":de("below");return;case"selectPreviousGroupTab":U(-1);return;case"selectNextGroupTab":U(1);return;case"setActiveTabShortcut":_e();return;case"hideCurrentTab":{const re=(Y=(G=M.current)==null?void 0:G.activePanel)==null?void 0:Y.id;re&&!Dt(re)&&ye(re);return}default:return}},[U,Ie,ie,ge,pe,ye,ve,q,Me,de,we,_e]);l.useEffect(()=>{if(!_)return;const z=_.sourceDocument,G=z.defaultView??window,Y=re=>{const H=z.querySelector("[data-dockview-tab-context-menu]");H&&H.contains(re.target)||L(null)};return G.addEventListener("mousedown",Y,!0),G!==window&&window.addEventListener("mousedown",()=>L(null),!0),()=>{G.removeEventListener("mousedown",Y,!0),G!==window&&window.removeEventListener("mousedown",()=>L(null),!0)}},[_]);const Te=l.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:D,hasDetachedConversationPanels:K,ides:r,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:b,liveSessionInboxState:S,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:ye,userName:m,scrollToBottomRequest:w,tabShortcuts:oe,openTabContextMenu:({x:z,y:G,tabKey:Y,sourceDocument:re})=>L({x:z,y:G,tabKey:Y,sourceDocument:re??document}),popoutTab:we,moveTabBackToMain:Me,isTabInPopout:q,floatTab:ge,isTabFloating:ve}),[n,t,D,K,r,i,c,b,S,a,o,ye,m,w,oe,we,Me,q,ge,ve]),$e=_?J0({isTabInPopout:q(_.tabKey),isTabFloating:ve(_.tabKey),tabShortcut:oe[_.tabKey],actionShortcuts:h}):[],Oe=l.useCallback(z=>{var re;const G=M.current;if((((re=G==null?void 0:G.activePanel)==null?void 0:re.id)??null)===z.id){z.group.model.openPanel(z);return}z.group.model.openPanel(z),z.api.setActive()},[]),Je=l.useCallback((z,G="requested-tab")=>{if(!z)return!1;const Y=M.current;if(!Y)return!1;const re=Y.getPanel(z);return re?(Oe(re),Q(z,G),f==null||f(),!0):!1},[Oe,f,Q]),qe=l.useCallback(()=>{if(I.current)return!1;const z=Je(A.current,"stored-layout-restore");return z&&(I.current=!0),z},[Je]),Ze=l.useCallback(()=>{var G;const z=M.current;z&&My(v,{activeTabId:((G=z.activePanel)==null?void 0:G.id)??null,layout:z.toJSON()})},[v]),et=l.useCallback(()=>{Ay(v,E.current)},[v]),ut=l.useCallback(z=>{var re,H,V,te;const G=M.current;if(!G)return{kind:"grid"};const Y=G.toJSON();for(const le of Y.floatingGroups||[])if((H=(re=le.data)==null?void 0:re.views)!=null&&H.includes(z)&&le.position)return{kind:"floating",position:le.position};for(const le of Y.popoutGroups||[])if((te=(V=le.data)==null?void 0:V.views)!=null&&te.includes(z))return{kind:"popout",position:le.position,popoutUrl:le.url};return{kind:"grid"}},[]),mt=l.useCallback(z=>{const G=M.current;if(!G)return;const Y=G.getPanel(z),re=E.current[z];if(!Y||!re||re.kind==="grid")return;if(Y.group.model.location.type===re.kind){delete E.current[z],et();return}if(re.kind==="floating"){G.addFloatingGroup(Y,{x:re.position.left??24,y:re.position.top??24,width:re.position.width,height:re.position.height}),delete E.current[z],et();return}delete E.current[z],et()},[et]);l.useEffect(()=>(p==null||p({setShortcutForActiveTab:_e,restoreHiddenTabToSavedLocation:mt,activateConversationTab:ue,resetAllPanelsToMain:X,activatePreviousTabInGroup:()=>U(-1),activateNextTabInGroup:()=>U(1),floatActiveTab:()=>{const z=pe();z&&ge(z)},popoutActiveTab:()=>{const z=pe();z&&we(z)},dockActiveTab:()=>{const z=pe();z&&(q(z)?Me(z):ve(z)&&Ie(z))},splitActiveTabRight:()=>de("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>de("below",{createGroupIfMissing:!0}),focusLeftPane:()=>ie("left"),focusRightPane:()=>ie("right"),focusUpPane:()=>ie("above"),focusDownPane:()=>ie("below"),moveActiveTabToLeftPane:()=>de("left"),moveActiveTabToRightPane:()=>de("right"),moveActiveTabToUpPane:()=>de("above"),moveActiveTabToDownPane:()=>de("below")}),()=>p==null?void 0:p(null)),[U,Ie,ge,ie,pe,ve,q,de,Me,we,p,X,mt,ue,_e]),l.useEffect(()=>()=>{var z;(z=$.current)==null||z.call($),$.current=null},[]);const bt=l.useCallback(z=>{var Y,re;M.current=z.api,(Y=$.current)==null||Y.call($),$.current=null;const G=Cy(v);if(A.current=(G==null?void 0:G.activeTabId)??null,G!=null&&G.layout&&z.api.fromJSON(G.layout,{reuseExistingPanels:!1}),T.current=zl({hasStoredLayout:!!(G!=null&&G.layout),initialDataLoaded:u,visibleConversationCount:e.length,ides:r}),T.current||(Jl(z.api,e),Ql(z.api,e,j)),z.api.totalPanels===0&&e.length>0){const H=av(z.api,e,k);if(H){const V=z.api.getPanel(H);V&&Oe(V)}}else!T.current&&!Je(k)&&qe();if(R.current=!0,z.api.onDidActivePanelChange(H=>{var te;if(A.current=(H==null?void 0:H.id)??null,I.current=!0,be(),H&&Dt(H.id)){const le=((te=H.params)==null?void 0:te.routeId)||H.id.slice(7),Se=Bt(e,le);y((Se==null?void 0:Se.tabKey)??null),Ze();return}if(y((H==null?void 0:H.id)??null),Ze(),!H)return;const V=D.get(H.id);(V==null?void 0:V.streamSource)==="agent-stream"&&V.agentType&&N(V.routeId,jd(),{agentType:V.agentType,...V.sessionId&&{targetSessionId:V.sessionId}}).catch(()=>{})}),z.api.onDidLayoutChange(()=>{Ze(),be(),F(H=>H+1)}),tv()){const H=ne=>({clientX:ne.clientX,clientY:ne.clientY}),V=ne=>{const fe=ne==null?void 0:ne.getBoundingClientRect();return fe?{left:fe.left,right:fe.right,top:fe.top,bottom:fe.bottom}:null},te=ne=>{var ke;const fe=(ke=C.current)==null?void 0:ke.getBoundingClientRect();return fe?ne.clientX<fe.left||ne.clientX>fe.right||ne.clientY<fe.top||ne.clientY>fe.bottom:!1},le=ev({detachDelayMs:Fu,onDetach:({panelId:ne,clientX:fe,clientY:ke})=>{var ct,ft;const Ce=z.api.getPanel(ne);if(!Ce)return;try{if(Ce.group.model.location.type!=="grid")return}catch{return}const Ke=(ct=C.current)==null?void 0:ct.getBoundingClientRect(),Ge=(ft=Ce.group.element)==null?void 0:ft.getBoundingClientRect(),Be=Math.round(Math.min(Math.max((Ge==null?void 0:Ge.width)??600,360),720)),ht=Math.round(Math.min(Math.max((Ge==null?void 0:Ge.height)??500,260),640));z.api.addFloatingGroup(Ce,{x:Ke?Math.max(0,fe-Ke.left-32):void 0,y:Ke?Math.max(0,ke-Ke.top-18):void 0,width:Be,height:ht}),Ce.api.setActive(),Ze(),be(),F(He=>He+1)}}),Se=[z.api.onWillDragPanel(ne=>{if(!(ne.nativeEvent.defaultPrevented||ne.nativeEvent.shiftKey)){try{if(ne.panel.group.model.location.type!=="grid")return}catch{return}le.startDrag({panelId:ne.panel.id,selfPanelBounds:V(ne.panel.group.element),...H(ne.nativeEvent)})}}),z.api.onWillShowOverlay(ne=>{if(le.hasDetached()){ne.preventDefault();return}le.markDockTarget(H(ne.nativeEvent))}),z.api.onWillDrop(ne=>{if(le.hasDetached()){ne.preventDefault(),le.endDrag();return}le.markDockTarget(H(ne.nativeEvent))}),z.api.onDidDrop(()=>le.endDrag()),z.api.onUnhandledDragOverEvent(ne=>{le.isDragging()&&le.markSelfPanel(H(ne.nativeEvent))})],Le=ne=>{if(!le.isDragging())return;const fe=H(ne);te(fe)&&le.markNonSelfPanel(fe)},O=()=>le.endDrag();window.addEventListener("dragover",Le,!0),window.addEventListener("drop",O,!0),window.addEventListener("dragend",O,!0),$.current=()=>{le.dispose();for(const ne of Se)ne.dispose();window.removeEventListener("dragover",Le,!0),window.removeEventListener("drop",O,!0),window.removeEventListener("dragend",O,!0)}}z.api.onDidAddGroup(H=>{requestAnimationFrame(()=>{var V,te;try{const le=(V=H.element)==null?void 0:V.ownerDocument;if(!le||le===document)return;(te=le.getElementById("dv-popout-window"))==null||te.classList.add("adhdev-dockview");const Se=document.documentElement.getAttribute("data-theme");Se&&le.documentElement.setAttribute("data-theme",Se),le.body.className=document.body.className;const Le=document.documentElement.getAttribute("style");Le&&le.documentElement.setAttribute("style",Le)}catch{}be(),F(le=>le+1)})}),y(((re=z.api.activePanel)==null?void 0:re.id)??null)},[Oe,Je,D,r,u,v,y,Ze,k,j,N,be,e]);l.useLayoutEffect(()=>{const z=M.current;if(!z||!R.current||T.current&&zl({hasStoredLayout:!0,initialDataLoaded:u,visibleConversationCount:e.length,ides:r}))return;T.current&&(T.current=!1);const G=W.current,Y=new Set(G),re=e.map(O=>O.tabKey),H=new Set(re),V=Q0({previousVisibleConversationCount:G.length,visibleConversationCount:e.length,ides:r});let te=!1;for(const O of G)H.has(O)||V||(E.current[O]=ut(O),te=!0);te&&et(),V||(Jl(z,e),Ql(z,e,j));const le=re.filter(O=>!Y.has(O));let Se=!1;for(const O of le){const ne=z.getPanel(O),fe=E.current[O];if(!ne||!fe||fe.kind==="grid")continue;if(ne.group.model.location.type===fe.kind){delete E.current[O],Se=!0;continue}if(fe.kind==="floating"){z.addFloatingGroup(ne,{x:fe.position.left??24,y:fe.position.top??24,width:fe.position.width,height:fe.position.height}),delete E.current[O],Se=!0;continue}}if(Se&&et(),W.current=re,k&&Je(k))return;!z.activePanel&&z.panels[0]&&Oe(z.panels[0]),!!(z.activePanel&&z.getPanel(z.activePanel.id))||qe()},[Oe,Je,qe,r,u,et,ut,k,j,e]),l.useEffect(()=>{R.current&&Je(k)},[Je,k]),l.useEffect(()=>{const z=Y=>{const re=Y.target;if(!re)return;const H=re.querySelector("[data-tab-key]")||re.closest("[data-tab-key]");if(H){const V=H.getAttribute("data-tab-key");if(V&&Y.dataTransfer){const te=re.closest(".dv-tab")||H.closest(".dv-tab")||H;Y.dataTransfer.effectAllowed="move",Y.dataTransfer.setData("text/tab-key",V),te instanceof HTMLElement&&Y.dataTransfer.setDragImage(te,Math.max(12,Math.round(te.clientWidth/2)),Math.max(10,Math.round(te.clientHeight/2)))}}};window.addEventListener("dragstart",z);const G=Xl(M.current);for(const Y of G)Y.addEventListener("dragstart",z);return()=>{window.removeEventListener("dragstart",z);for(const Y of G)Y.removeEventListener("dragstart",z)}},[B]),l.useEffect(()=>{var G;const z=(G=C.current)==null?void 0:G.querySelector(".adhdev-dockview");z instanceof HTMLElement&&Ka(z,g),he(),be()},[be,he,g]),l.useEffect(()=>{be()},[be]),l.useEffect(()=>{const z=G=>{if(G.defaultPrevented||P)return;const Y=se(G);if(!Y)return;const re=G.metaKey||G.ctrlKey||G.altKey;Lo(G.target)&&!re||Zn(me).setActiveTabShortcut!==Y||(G.preventDefault(),G.stopPropagation(),_e())};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[se,me,P,_e]),l.useEffect(()=>{const z=C.current;if(!z)return;const G=Y=>{var le,Se;if(!Y.isTrusted)return;const re=(Se=(le=Y.target)==null?void 0:le.closest)==null?void 0:Se.call(le,".dv-scrollable");if(!re)return;Y.preventDefault(),Y.stopPropagation();const H=Math.abs(Y.deltaX),V=Math.abs(Y.deltaY),te=H>V?Y.deltaX:Y.deltaY;re.dispatchEvent(new WheelEvent("wheel",{deltaY:te,deltaMode:Y.deltaMode,bubbles:!1,cancelable:!0}))};return z.addEventListener("wheel",G,{passive:!1,capture:!0}),()=>z.removeEventListener("wheel",G,{capture:!0})},[]),l.useEffect(()=>{const z=Xl(M.current);if(z.length===0)return;const G=z.map(Y=>{let re=[],H=null;const V=()=>{H!=null&&Y.clearTimeout(H),H=null,re=[]},te=()=>{H!=null&&Y.clearTimeout(H),H=Y.setTimeout(()=>{H=null,re=[]},1200)},le=Le=>{if(!Le.ctrlKey&&!Le.metaKey&&!Le.altKey)return;const O=se(Le);if(!O)return;const ne=Ru();for(const[fe,ke]of Object.entries(ne))if(e.some(Ce=>Ce.tabKey===fe)&&ke===O){Le.preventDefault(),ue(fe);return}},Se=Le=>{if(Le.defaultPrevented||P)return;const O=se(Le);if(!O)return;const ne=Le.metaKey||Le.ctrlKey||Le.altKey;if(Lo(Le.target))return;const fe=Zn(me),ke=Object.entries(fe).filter(([He,Qt])=>!!Qt&&(He==="splitActiveTabRight"||He==="splitActiveTabDown"||He==="floatActiveTab"||He==="popoutActiveTab"||He==="dockActiveTab"||He==="focusLeftPane"||He==="focusRightPane"||He==="focusUpPane"||He==="focusDownPane"||He==="moveActiveTabToLeftPane"||He==="moveActiveTabToRightPane"||He==="moveActiveTabToUpPane"||He==="moveActiveTabToDownPane"||He==="selectPreviousGroupTab"||He==="selectNextGroupTab"||He==="setActiveTabShortcut"||He==="hideCurrentTab")),Ce=ne?[O]:[...re.slice(-1),O].slice(-2),Ke=Ce.join(" "),Ge=Ce[Ce.length-1],Be=ke.find(([,He])=>He===Ke);if(Be){Le.preventDefault(),V(),De(Be[0]);return}if(ke.some(([,He])=>He.startsWith(`${Ke} `))){Le.preventDefault(),re=Ce,te();return}const ct=ke.find(([,He])=>He===Ge);if(ct){Le.preventDefault(),V(),De(ct[0]);return}if(ke.some(([,He])=>He.startsWith(`${Ge} `))){Le.preventDefault(),re=[Ge],te();return}V()};return Y.addEventListener("keydown",le),Y.addEventListener("keydown",Se),()=>{V(),Y.removeEventListener("keydown",le),Y.removeEventListener("keydown",Se)}});return()=>{for(const Y of G)Y()}},[se,me,B,ue,P,De,e]);const Ae=g==="light"?lo:co,We=((tt=(Ye=(rt=M.current)==null?void 0:rt.activePanel)==null?void 0:Ye.group.element)==null?void 0:tt.ownerDocument)??document;return s.jsxs(Hu.Provider,{value:Te,children:[s.jsx("div",{ref:C,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(Qm,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:ov,remote:iv},defaultTabComponent:cv,watermarkComponent:lv,onReady:bt,singleTabMode:"default",tabAnimation:"smooth",theme:Ae,popoutUrl:"/popout.html"})}),_&&Nr.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:_.x,top:_.y},children:$e.map(z=>{if(z.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},z.id);let G=s.jsx(cp,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{};switch(z.id){case"dockInWindow":case"dockBackToGrid":G=s.jsx(up,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{Ie(_.tabKey),L(null)};break;case"moveBackToMain":G=s.jsx(lp,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{Me(_.tabKey),L(null)};break;case"floatAsPanel":G=s.jsx(dp,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{ge(_.tabKey),L(null)};break;case"openInNewWindow":G=s.jsx(ip,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{we(_.tabKey),L(null)};break;case"setShortcut":Y=re=>{re.stopPropagation(),xe(_.tabKey),L(null)};break;case"removeShortcut":G=s.jsx(yt,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{const re={...oe};delete re[_.tabKey],Ne(re),L(null)};break;case"hideTab":G=s.jsx(Wo,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{ye(_.tabKey),L(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${z.tone==="muted"?"text-text-muted":""}`,onMouseDown:rv,onClick:Y,children:[G,s.jsx("span",{className:"flex-1 min-w-0",children:z.label}),z.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:z.shortcut}):null]},z.id)})}),_.sourceDocument.body),P&&Nr.createPortal(s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>xe(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:z=>z.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. ",me?"⌘+1":"Ctrl+1",", ",me?"⌥+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:"Press Esc to cancel"})]})}),We.body)]})}const Wu="adhdev-recent-launch-args-v1",uv=8;function mv(e){return String(e||"").trim().replace(/\s+/g," ")}function Ku(e,t){return`${e.trim()}::${t.trim()}`}function Uu(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Wu)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function hv(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Wu,JSON.stringify(e))}catch{}}function pv(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=Uu().byKey[Ku(r,n)])==null?void 0:o.items)||[]}function fv(e,t,r){var d;const n=String(e||"").trim(),a=String(t||"").trim(),o=mv(r);if(!n||!a||!o)return;const i=Uu(),c=Ku(n,a),u=((d=i.byKey[c])==null?void 0:d.items)||[],m=[o,...u.filter(h=>h!==o)].slice(0,uv);i.byKey[c]={items:m},hv(i)}function xv(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Tn({title:e,description:t,action:r,children:n,className:a="",contentClassName:o=""}){return s.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),t&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:t})]}),r?s.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?s.jsx("div",{className:t||r?`mt-3 ${o}`.trim():o,children:n}):null]})}function bv({savedSessionsLoading:e,savedSessionsLoaded:t,savedSessionsCount:r=0}){return e?"Refreshing saved history…":t?r>0?`${r} saved ${r===1?"history":"histories"} loaded. Open saved history to choose one.`:"No saved history found yet. New Hermes CLI conversations will appear here after ADHDev captures provider history.":"Start fresh, or open saved history when you want continuity."}function gv({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:i,onOpenHistory:c,onClearSelection:u}){const m=o?Iu(o):null,d=bv({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Tn,{title:"Saved history",description:ri(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:i,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:c,children:Kb()})]}),children:[m?s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),s.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:m.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:m.providerSessionId}),s.jsx("div",{className:"mt-1",children:m.metaLine}),m.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:m.updatedLabel}),m.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:m.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:u,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:d}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function zu({setup:e,providerName:t,className:r=""}){return e?s.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${r}`,children:[s.jsxs("div",{className:"font-semibold",children:["Manual MCP setup required",t?` for ${t}`:""]}),e.instructions&&s.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-text-muted",children:[e.serverName&&s.jsxs("span",{children:["Server: ",s.jsx("code",{children:e.serverName})]}),e.configFormat&&s.jsxs("span",{children:["Format: ",s.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&s.jsxs("span",{children:["Config path: ",s.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&s.jsx("span",{children:"Start a fresh CLI session after editing config."})]}),e.template&&s.jsx("pre",{className:"mt-3 max-h-72 overflow-auto rounded-lg border border-border-subtle bg-bg-primary p-3 text-xs font-mono leading-relaxed text-text-primary select-all whitespace-pre-wrap",children:e.template})]}):null}function yv({workspaceMode:e,activeKind:t,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:o,onSelect:i}){return e==="mesh"?null:s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:r},{id:"ide",label:"Workspace",enabled:n},{id:"acp",label:"ACP",enabled:a}].map(c=>s.jsx("button",{type:"button",className:`btn btn-sm ${t===c.id?"btn-primary":"btn-secondary"}`,onClick:()=>i(c.id),disabled:!c.enabled||o,children:c.label},c.id))})]})}function Ua(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>Ks(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>Ks(a,"acp"))?"acp":null}function pn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function vv({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:u,onListSavedSessions:m}){var He,Qt;const d=$r(),h=l.useMemo(()=>[...e].sort(qo),[e]),[p,y]=l.useState(((He=h[0])==null?void 0:He.id)||""),b=l.useMemo(()=>h.find(ee=>ee.id===p)||h[0],[p,h]),x=l.useMemo(()=>((b==null?void 0:b.workspaces)||[]).map(ee=>({id:ee.id,path:ee.path,label:ee.label})),[b]),k=(b==null?void 0:b.defaultWorkspaceId)||null,[j,f]=l.useState("workspace"),[w,S]=l.useState(""),[v,g]=l.useState(""),[N,M]=l.useState([]),[C,$]=l.useState(""),[R,T]=l.useState(!1),[I,A]=l.useState(null),[W,_]=l.useState(""),[L,B]=l.useState(Ua(h[0])),[F,E]=l.useState(""),[D,K]=l.useState(""),[J,Q]=l.useState([]),[Z,he]=l.useState(""),[we,Me]=l.useState([]),[q,ye]=l.useState(!1),[ge,ve]=l.useState(!1),[pe,Ie]=l.useState(""),[X,be]=l.useState(!1),[ue,U]=l.useState(()=>kt()),[ce,ie]=l.useState(null),[de,me]=l.useState(!1),[oe,P]=l.useState(""),[xe,Ne]=l.useState(null),[_e,se]=l.useState(!1),[De,Te]=l.useState(""),[$e,Oe]=l.useState([]),[Je,qe]=l.useState(!1),[Ze,et]=l.useState(""),[ut,mt]=l.useState(!1),bt=l.useRef(null),Ae=l.useRef(0);l.useEffect(()=>{var ee;!p&&((ee=h[0])!=null&&ee.id)&&y(h[0].id)},[p,h]),l.useEffect(()=>{!b||!(!b.workspaces||!b.availableProviders||!b.detectedIdes||!b.recentLaunches)||d(b.id,{minFreshMs:3e4}).catch(()=>{})},[d,b]);const We=l.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(ee=>Ks(ee,"cli")),[b]),rt=l.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(ee=>Ks(ee,"acp")),[b]),Ye=l.useMemo(()=>((b==null?void 0:b.detectedIdes)||[]).map(ee=>({id:ee.type,label:ee.name||ee.type,meta:ee.running?"Detected locally":"Available to open"})),[b]),tt=l.useMemo(()=>L==="cli"?We.map(ee=>({id:ee.type,label:ee.displayName||ee.type,meta:"CLI provider"})):L==="acp"?rt.map(ee=>({id:ee.type,label:ee.displayName||ee.type,meta:"ACP provider"})):Ye,[rt,L,We,Ye]),z=l.useMemo(()=>N.find(ee=>ee.id===C)||null,[N,C]),G=l.useMemo(()=>We.find(ee=>ee.type===F)||null,[We,F]),Y=l.useMemo(()=>ju(G==null?void 0:G.meshCoordinator,{meshId:(z==null?void 0:z.id)||"",workspace:(z==null?void 0:z.workspace)||""}),[G,z]),re=xe||Y,H=l.useCallback(async ee=>{T(!0),_("");try{const Re=await c(ee);M(Re),$(ae=>{var Pe;return Re.some(Nt=>Nt.id===ae)?ae:((Pe=Re[0])==null?void 0:Pe.id)||""}),A(ee)}catch(Re){M([]),$(""),A(ee),_(Re instanceof Error?Re.message:"Could not load meshes")}finally{T(!1)}},[c]);l.useEffect(()=>{var Re;if(!b)return;if(bt.current!==b.id){bt.current=b.id,f("workspace"),S(k||((Re=x[0])==null?void 0:Re.id)||"__home__"),g(""),M([]),$(""),A(null),_(""),B(Ua(b)),E(""),K(""),he(""),Me([]),ve(!1),Ie(""),U(kt()),P(""),Ne(null);return}S(ae=>{var Pe;return ae==="__custom__"||ae==="__home__"||x.some(Nt=>Nt.id===ae)?ae:k||((Pe=x[0])==null?void 0:Pe.id)||"__home__"}),B(ae=>ae==="ide"&&Ye.length>0||ae==="cli"&&We.length>0||ae==="acp"&&rt.length>0?ae:Ua(b))},[rt.length,We.length,k,Ye.length,b,x]),l.useEffect(()=>{!b||j!=="mesh"||I===b.id||R||H(b.id)},[H,I,R,b,j]),l.useEffect(()=>{j==="mesh"&&L!=="cli"&&We.length>0&&B("cli")},[L,We.length,j]),l.useEffect(()=>{var ee;L&&(tt.some(Re=>Re.id===F)||E(((ee=tt[0])==null?void 0:ee.id)||""))},[L,tt,F]),l.useEffect(()=>{Ne(null)},[b==null?void 0:b.id,C,F,j]);const V=l.useCallback(async(ee,Re)=>{const ae=Ae.current+1;return Ae.current=ae,ye(!0),Ie(""),m(ee,Re).then(Pe=>{Ae.current===ae&&Me(Pe)}).catch(Pe=>{Ae.current===ae&&(Me([]),Ie(Pe instanceof Error?Pe.message:"Could not load saved sessions"))}).finally(()=>{Ae.current===ae&&(ye(!1),ve(!0))})},[m]),te=l.useCallback((ee,Re)=>{Q(pv(ee,Re))},[]);l.useEffect(()=>{Ae.current+=1,he(""),U(kt()),!b||!F||L==="ide"?Q([]):te(b.id,F),ve(!1),Me([]),Ie(""),ye(!1)},[L,te,V,b,F]),l.useEffect(()=>{if(!Z)return;const ee=we.find(Re=>Re.providerSessionId===Z);ee!=null&&ee.canResume||he("")},[we,Z]);const le=w==="__custom__"?v.trim():w==="__home__"?"":((Qt=x.find(ee=>ee.id===w))==null?void 0:Qt.path)||"",Se=l.useMemo(()=>b?t.filter(ee=>ee.id!==b.id&&ee.daemonId===b.id).map(ee=>ee.workspace):[],[t,b]),Le=l.useMemo(()=>((b==null?void 0:b.recentLaunches)||[]).map(ee=>ee.workspace),[b]),O=l.useCallback(ee=>{const Re=String(ee.workspace||"").trim();if(!Re)return;const ae=x.find(Pe=>pn(Pe.path)===pn(Re));if(ae){S(ae.id),g("");return}S("__custom__"),g(Re)},[x]),ne=l.useCallback(ee=>{const Re=String(ee.workspace||"").trim();if(!Re)return{workspaceId:null,workspacePath:null};const ae=x.find(Pe=>pn(Pe.path)===pn(Re));return ae?{workspaceId:ae.id,workspacePath:null}:{workspaceId:null,workspacePath:Re}},[x]),fe=l.useMemo(()=>we.find(ee=>ee.providerSessionId===Z)||null,[we,Z]),ke=l.useMemo(()=>{var Re;if(L!=="cli"||!b||!F)return null;const ee=((Re=We.find(ae=>ae.type===F))==null?void 0:Re.displayName)||F;return{routeId:b.id,daemonId:b.id,providerSessionId:Z||void 0,transport:"pty",mode:"chat",agentName:ee,agentType:F,status:"idle",title:ee,messages:[],ideType:F,workspaceName:le,workspacePath:le,displayPrimary:ee,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${b.id}:${F}`,machineName:It(b,{fallbackId:b.id})}},[L,We,le,b,Z,F]),Ce=l.useCallback(()=>{var Re;if(!b)return;S("__custom__"),se(!0),et("");const ee=mi(b.platform,ui(v.trim(),le,Se,Le,b.defaultWorkspacePath,(Re=x.find(ae=>ae.id===k))==null?void 0:Re.path,x.map(ae=>ae.path)));qe(!0),n(b.id,ee).then(ae=>{Te(ae.path),g(ae.path),Oe(ae.directories)}).catch(ae=>{et(ae instanceof Error?ae.message:"Could not load folder")}).finally(()=>qe(!1))},[v,k,Le,Se,n,le,b,x]),Ke=l.useCallback(ee=>{b&&(qe(!0),et(""),n(b.id,ee).then(Re=>{Te(Re.path),g(Re.path),Oe(Re.directories)}).catch(Re=>{et(Re instanceof Error?Re.message:"Could not load folder")}).finally(()=>qe(!1)))},[n,b]),Ge=l.useCallback(async()=>{if(!b||!le)return;mt(!0),P("");const ee=await a(b.id,le);if(mt(!1),!ee.ok){P(ee.error||"Could not save workspace");return}P("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,le,b]),Be=l.useCallback(async()=>{if(!b)return;if(j==="mesh"){if(!C||!F)return;me(!0),P(""),Ne(null);const ae=await u(b.id,C,F);if(me(!1),!ae.ok){if(ae.code==="mesh_coordinator_manual_mcp_setup_required"&&ae.manualSetup){Ne(ae.manualSetup),P("Manual MCP setup required before this provider can act as mesh coordinator.");return}P(ae.error||"Could not start mesh coordinator");return}r();return}if(!L||!F)return;me(!0),P("");const ee=D.trim()?D.trim().split(/\s+/).filter(Boolean):[],Re=L==="ide"?await o(b.id,F,{workspacePath:le||null}):await i(b.id,L,F,{workspaceId:w!=="__home__"&&w!=="__custom__"?w:null,workspacePath:w==="__custom__"&&le||null,resumeSessionId:L==="cli"&&Z?Z:null,cliArgs:ee});if(me(!1),!Re.ok){P(Re.error||"Could not start session");return}L!=="ide"&&D.trim()&&(fv(b.id,F,D),te(b.id,F)),r()},[L,D,te,r,o,u,i,le,b,C,Z,F,w,j]),ht=j==="mesh"?"Start mesh coordinator":L?Fb(L,L==="cli"&&!!Z):"Start",ct=j==="mesh"?"Starting coordinator…":L?Hb(L,L==="cli"&&!!Z):"Starting…",ft=h.length>5;return b?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] 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":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] 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-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),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:r,"aria-label":"Close new session dialog",children:s.jsx(yt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[h.length>1&&s.jsx(Tn,{title:"Machine",children:ft?s.jsx("select",{"aria-label":"Machine",value:b.id,onChange:ee=>y(ee.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:de,children:h.map(ee=>s.jsx("option",{value:ee.id,children:It(ee,{fallbackId:ee.id})},ee.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:h.map(ee=>{const Re=It(ee,{fallbackId:ee.id}),ae=b.id===ee.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${Re}`,"aria-pressed":ae,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${ae?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/60 text-text-secondary hover:bg-bg-secondary hover:text-text-primary"}`,onClick:()=>y(ee.id),disabled:de,title:Re,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${ee.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:Re})]},ee.id)})})}),s.jsxs(Tn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:j==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ce,disabled:de,children:"Browse…"}):void 0,children:[s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":"Launch target type",children:[{id:"workspace",label:"Workspace",desc:"Normal session"},{id:"mesh",label:"Mesh",desc:"Coordinator session"}].map(ee=>s.jsxs("button",{type:"button",role:"radio","aria-checked":j===ee.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${j===ee.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{f(ee.id),P(""),ee.id==="mesh"&&b&&I!==b.id&&!R&&H(b.id)},disabled:de,children:[s.jsx("div",{className:"text-sm font-semibold",children:ee.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:ee.desc})]},ee.id))}),j==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:w,onChange:ee=>{const Re=ee.target.value;S(Re),Re==="__custom__"?Ce():P("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:de,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),x.map(ee=>s.jsxs("option",{value:ee.id,children:[ee.id===k?"⭐ ":"",id(ee.path,ee.label)||ee.path]},ee.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:w==="__home__"?"Launch without a workspace.":le||"Select a workspace folder."}),w==="__custom__"&&le&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ce,disabled:de,children:[s.jsx(Os,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ge,disabled:de||ut,children:ut?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[R&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!R&&W&&s.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:W}),!R&&!W&&N.length===0&&s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker."}),N.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:N.map(ee=>s.jsxs("button",{type:"button",role:"radio","aria-checked":C===ee.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${C===ee.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(ee.id),disabled:de,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:ee.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[ee.repoIdentity||"Repo mesh",typeof ee.nodesCount=="number"?` · ${ee.nodesCount} node${ee.nodesCount===1?"":"s"}`:""]}),ee.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",ee.workspace]})]},ee.id))}),z&&s.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),s.jsx(yv,{workspaceMode:j,activeKind:L,cliEnabled:We.length>0,ideEnabled:Ye.length>0,acpEnabled:rt.length>0,busy:de,onSelect:B}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:L==="ide"?"Choose IDE":L==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[tt.map(ee=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${F===ee.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>E(ee.id),disabled:de,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:ee.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ee.meta})]},ee.id)),tt.length===0&&s.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),j==="mesh"&&re&&s.jsx(zu,{setup:re,providerName:(G==null?void 0:G.displayName)||(G==null?void 0:G.name)||F}),j!=="mesh"&&L!=="ide"&&s.jsxs(Tn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:D,onChange:ee=>K(ee.target.value),placeholder:"Optional flags...",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:de}),J.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:J.map(ee=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>K(ee),disabled:de,title:ee,children:ee},ee))})]}),j!=="mesh"&&L==="cli"&&s.jsx(gv,{busy:de,savedSessionsLoading:q,savedSessionsError:pe,selectedSession:fe,onRefresh:()=>{!b||!F||V(b.id,F)},onOpenHistory:()=>{!b||!F||(be(!0),xv({hasLoadedInitialResults:ge,isLoading:q})&&V(b.id,F))},onClearSelection:()=>he("")}),oe&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${oe.includes("saved")||oe.includes("requested")||oe.includes("Manual MCP setup")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:oe})]}),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:r,disabled:de,children:"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:Be,disabled:de||(j==="mesh"?!C||!F||L!=="cli"||R:!L||!F||w==="__custom__"&&!le),children:[s.jsx(Gc,{size:14}),de?ct:ht]})]})]})}),_e&&s.jsx(fi,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:De,directories:$e,busy:Je,error:Ze,onClose:()=>se(!1),onNavigate:Ke,onConfirm:ee=>{g(ee),Te(ee),S("__custom__"),se(!1)}}),X&&ke&&s.jsx(zd,{activeConv:ke,ides:[],isCreatingChat:!1,isRefreshingHistory:q,savedSessions:we,isSavedSessionsLoading:q,isResumingSavedSessionId:ce,savedHistoryFilters:ue,missingWorkspaceResumePath:le||null,onSavedHistoryFiltersChange:U,onClose:()=>be(!1),onNewChat:()=>{he(""),be(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!b||!F||V(b.id,F)},onResumeSavedSession:ee=>{if(!b||!F||ce||!ee.canResume)return;const Re=ne(ee);he(ee.providerSessionId),O(ee),ie(ee.providerSessionId),be(!1),me(!0),P(""),i(b.id,"cli",F,{workspaceId:Re.workspaceId,workspacePath:Re.workspacePath,resumeSessionId:ee.providerSessionId}).then(ae=>{if(!ae.ok){P(ae.error||"Could not resume session");return}r()}).finally(()=>{me(!1),ie(ae=>ae===ee.providerSessionId?null:ae)})}})]}):null}function Gu(e){return e.ahead<=0&&e.behind<=0?null:e.ahead>0&&e.behind>0?`ahead ${e.ahead} / behind ${e.behind}`:e.behind>0?`behind ${e.behind}`:`ahead ${e.ahead}`}function bi(e){if(e.type==="submoduleNode")return e.outOfSync||e.error?{label:"submodule drift",tone:"danger"}:e.dirty?{label:"submodule dirty",tone:"warn"}:null;const t=e.branchConvergence;if((t==null?void 0:t.status)==="not_mergeable")return{label:e.hasConflicts?"conflicts present":"dirty workspace",tone:"danger"};if((t==null?void 0:t.status)==="blocked_review"){if(t.reason==="upstream_unverified")return{label:"upstream unverified",tone:"warn"};const r=Gu(e);return r?{label:r,tone:"danger"}:!e.upstream&&e.branch&&e.branch!==t.defaultBranch?{label:"push branch",tone:"warn"}:{label:"blocked review",tone:"danger"}}return(t==null?void 0:t.status)==="pushed_feature_branch_needs_merge"?{label:"needs merge",tone:"warn"}:(t==null?void 0:t.status)==="cleanup_candidate"?{label:"refine worktree",tone:"info"}:e.isOrphan?{label:"needs follow-up",tone:"warn"}:e.health==="offline"?{label:"offline",tone:"danger"}:null}function gi(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function Vu(e){var t;return!gi(e)||e.type==="defaultBranchNode"?!1:!!((t=e.branchConvergence)!=null&&t.needsConvergence||e.isOrphan||e.hasConflicts||e.outOfSync||e.error||e.health==="offline"||e.health==="degraded"||e.health==="wrong_branch"||e.dirty)}function fn(e){return[...new Set(e.filter(t=>!!t))]}function wv(e){const t=e.nodes.find(i=>i.type==="defaultBranchNode")??null,r=(t==null?void 0:t.branch)??null,n=e.nodes.filter(i=>i.type!=="defaultBranchNode"&&i.type!=="submoduleNode"&&!i.isOrphan&&!!r&&i.branch===r),a=e.nodes.filter(i=>i.type!=="submoduleNode"&&!i.isOrphan),o=e.nodes.filter(i=>i.type!=="submoduleNode");return t||n.length>0?fn([t==null?void 0:t.id,...n.map(i=>i.id)]):a.length>0?fn(a.map(i=>i.id)):o.length>0?fn(o.map(i=>i.id)):fn(e.nodes.map(i=>i.id))}function qu(e){const t=[...e.nodes].sort((n,a)=>n.id.localeCompare(a.id)).map(n=>[n.id,n.type,n.branch??"",n.parentNodeId??"",n.submodulePath??""].join(":")).join("|"),r=[...e.edges].sort((n,a)=>n.id.localeCompare(a.id)).map(n=>[n.id,n.source,n.target,n.type].join(":")).join("|");return`${e.meshId}::${t}::${r}`}function jv(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${qu(e)}::${n}x${a}`}const kv={default:"border-white/10 bg-white/[0.04] text-slate-200",good:"border-emerald-400/20 bg-emerald-500/10 text-emerald-200",warn:"border-amber-400/20 bg-amber-500/10 text-amber-100",danger:"border-rose-400/20 bg-rose-500/10 text-rose-100",info:"border-sky-400/20 bg-sky-500/10 text-sky-100"},Sv={default:"border-slate-300 bg-white/95 text-slate-700",good:"border-emerald-300 bg-emerald-50 text-emerald-700",warn:"border-amber-300 bg-amber-50 text-amber-700",danger:"border-rose-300 bg-rose-50 text-rose-700",info:"border-sky-300 bg-sky-50 text-sky-700"},Nv={default:"border-white/10 bg-white/[0.04] text-slate-200 hover:bg-white/[0.08]",info:"border-sky-400/25 bg-sky-500/10 text-sky-100 hover:bg-sky-500/16",success:"border-emerald-400/25 bg-emerald-500/10 text-emerald-100 hover:bg-emerald-500/16"},Cv={default:"border-slate-300 bg-white text-slate-700 hover:bg-slate-50",info:"border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100",success:"border-emerald-300 bg-emerald-50 text-emerald-700 hover:bg-emerald-100"};function Ys(e){return e==="light"?{theme:e,isDark:!1,flowColorMode:"light",textPrimary:"text-slate-900",textSecondary:"text-slate-700",textMuted:"text-slate-500",graphShellClass:"relative w-full min-w-0 overflow-hidden rounded-2xl border border-slate-200 bg-[radial-gradient(circle_at_top,_rgba(14,165,233,0.16),_rgba(248,250,252,0.98)_42%,_rgba(255,255,255,1))]",graphStatChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-slate-700 shadow-sm",graphHintChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-[10px] text-slate-500 shadow-sm",graphControlsClass:"!bottom-4 !left-4 !shadow-md",graphBackgroundDotColor:"rgba(148, 163, 184, 0.34)",edgeLabelTextColor:"#334155",edgeLabelBackgroundColor:"rgba(255, 255, 255, 0.96)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.45)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[rgba(148,163,184,0.22)] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"flex h-[100dvh] w-full flex-col overflow-hidden bg-white md:h-[min(90vh,960px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-slate-200 md:bg-white/98 md:shadow-[0_28px_120px_rgba(148,163,184,0.28)]",dialogHeaderClass:"flex shrink-0 flex-col gap-3 border-b border-slate-200 bg-white/96 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-slate-900 md:text-xl",dialogKickerClass:"rounded-full border border-slate-300 bg-slate-50 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-600",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-500",dialogRefreshedChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1.5 text-xs text-slate-600",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-300 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",dialogBodyClass:"min-h-0 flex-1 overflow-y-auto bg-[linear-gradient(180deg,rgba(248,250,252,0.98),rgba(241,245,249,0.96))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-slate-300 bg-white/90 px-6 text-center text-sm text-slate-500",cardClass:"rounded-2xl border border-slate-200 bg-white/95 shadow-sm",cardHeaderClass:"border-b border-slate-200 px-4 py-3",cardTitleClass:"text-sm font-semibold text-slate-900",cardSubtitleClass:"mt-1 text-xs text-slate-500",rowClass:"flex items-start justify-between gap-3 border-b border-slate-200/80 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"text-slate-500",rowValueClass:"max-w-[65%] break-all text-right text-slate-800",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-slate-200 bg-white/95 p-4 shadow-md md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-slate-200 bg-white/95 p-4 text-xs text-slate-500 shadow-sm md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-900",panelCloseButtonClass:"text-xs text-slate-500 hover:text-slate-900",panelFieldRowClass:"flex justify-between gap-3 border-b border-slate-200/80 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-500",panelFieldValueClass:"break-all text-right font-medium text-slate-700",infoCalloutClass:"mt-1 rounded border border-sky-300 bg-sky-50 px-2 py-1.5 text-[10px] text-sky-700",badge:t=>Sv[t],actionButton:t=>Cv[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative w-full min-w-0 overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",graphStatChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-slate-200",graphHintChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-[10px] text-slate-300",graphControlsClass:"!bottom-4 !left-4 !shadow-lg",graphBackgroundDotColor:"rgba(148, 163, 184, 0.22)",edgeLabelTextColor:"#cbd5e1",edgeLabelBackgroundColor:"rgba(2, 6, 23, 0.86)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.2)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[#030617]/[0.58] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"flex h-[100dvh] w-full flex-col overflow-hidden bg-slate-950 md:h-[min(90vh,960px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-white/10 md:bg-slate-950/96 md:shadow-[0_28px_120px_rgba(2,6,23,0.46)]",dialogHeaderClass:"flex shrink-0 flex-col gap-3 border-b border-white/10 bg-slate-950/92 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-white md:text-xl",dialogKickerClass:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-300",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-400",dialogRefreshedChipClass:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 bg-white/6 text-slate-300 transition hover:bg-white/10 hover:text-white",dialogBodyClass:"min-h-0 flex-1 overflow-y-auto bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-white/10 bg-white/[0.03] px-6 text-center text-sm text-slate-400",cardClass:"rounded-2xl border border-white/10 bg-white/[0.04]",cardHeaderClass:"border-b border-white/10 px-4 py-3",cardTitleClass:"text-sm font-semibold text-white",cardSubtitleClass:"mt-1 text-xs text-slate-400",rowClass:"flex items-start justify-between gap-3 border-b border-white/5 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"text-slate-400",rowValueClass:"max-w-[65%] break-all text-right text-slate-100",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-white/10 bg-white/[0.04] p-4 shadow-lg md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-white/10 bg-white/[0.04] p-4 text-xs text-slate-400 md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-100",panelCloseButtonClass:"text-xs text-slate-400 hover:text-slate-100",panelFieldRowClass:"flex justify-between gap-3 border-b border-white/6 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-400",panelFieldValueClass:"break-all text-right font-medium text-slate-200",infoCalloutClass:"mt-1 rounded bg-blue-500/10 border border-blue-500/20 px-2 py-1.5 text-[10px] text-blue-300",badge:t=>kv[t],actionButton:t=>Nv[t]}}const Us={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,layerGap:220,nodeGap:82,edgeLabelBuffer:180,placeholderTopOffset:0},Fr={worktreeCardWidth:188,submoduleCardWidth:188,minWorktreeCardHeight:88,minSubmoduleCardHeight:88,maxEstimatedCardHeight:178,layerGap:160,nodeGap:52,edgeLabelBuffer:120},Mv={maxWidth:180};function Iv(e){return e==="TB"?"DOWN":"RIGHT"}function yi(e,t){return{"elk.algorithm":"layered","elk.direction":Iv(t),"elk.edgeRouting":"ORTHOGONAL","elk.spacing.nodeNode":String(e.nodeGap),"elk.layered.spacing.nodeNodeBetweenLayers":String(e.layerGap),"elk.layered.spacing.edgeNodeBetweenLayers":String(e.edgeLabelBuffer),"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.layered.mergeEdges":"false","elk.randomSeed":"1"}}const Av=yi(Us,"LR");yi(Fr,"LR");function Tv(e){const t=e.nodes.length;if(t<8)return"LR";const r=new Map;for(const a of e.edges)r.set(a.source,(r.get(a.source)??0)+1);let n=0;for(const a of r.values())a>n&&(n=a);return n>=Math.max(6,Math.floor(t/2))?"TB":"LR"}const _v=new Zm;function Tr(e,t=!1){const r=t?Fr:Us;return e.type==="submoduleNode"?r.submoduleCardWidth:r.worktreeCardWidth}function _n(e){var r;if(e.type==="defaultBranchNode")return e.nextStepHint||"Default branch anchor";if(e.type==="submoduleNode"){const n=[e.machineLabel?`parent ${e.machineLabel}`:null];return e.outOfSync?n.push("out of sync"):e.dirty?n.push("local changes"):n.push("synced"),n.filter(Boolean).join(" · ")}const t=[];if(e.upstream&&t.push(e.upstream),e.upstream&&e.upstreamStatus!=="fresh")t.push("upstream unverified");else{const n=Gu(e);n&&t.push(n)}return e.activeSessionCount>0&&t.push(`${e.activeSessionCount} session${e.activeSessionCount===1?"":"s"}`),e.dirtyFiles>0&&t.push(`${e.dirtyFiles} dirty`),e.hasConflicts&&t.push("conflicts"),t.length===0?(r=e.branchConvergence)!=null&&r.needsConvergence?"Needs follow-up":"Clean and even with upstream":t.join(" · ")}function Yu(e,t=!1){const r=t?Fr:Us,n=Tr(e,t),a=t?e.type==="submoduleNode"?20:22:e.type==="submoduleNode"?24:30,o=t?(e.type==="submoduleNode",2):e.type==="submoduleNode"?2:3,i=Math.ceil(Lv(e)/o),c=xn(e.label,a,2),u=xn(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,a,2),m=xn(_n(e),a+(t?1:4),t?2:3),d=bi(e),h=Vu(e)?gi(e):null,p=t?0:xn(h,Math.max(24,Math.floor(n/8)),4),y=t?40+c*16+u*12+(d?22:0)+Math.max(0,i-1)*18+Math.max(18,m*16):52+c*18+u*14+(d?30:0)+i*24+Math.max(22,m*18)+(p>0?22+p*16:0),b=e.type==="submoduleNode"?r.minSubmoduleCardHeight:r.minWorktreeCardHeight;return Math.min(r.maxEstimatedCardHeight,Math.max(b,Math.ceil(y)))}function xn(e,t,r){const n=(e||"").trim();return n?Math.max(1,Math.min(r,Math.ceil(n.length/t))):0}function Lv(e){let t=1;return e.type==="submoduleNode"&&(t+=1),e.branch&&e.type!=="submoduleNode"&&(t+=1),e.submoduleCommit&&e.type==="submoduleNode"&&(t+=1),e.dirty&&(t+=1),e.outOfSync&&(t+=1),e.hasConflicts&&(t+=1),e.type!=="submoduleNode"&&e.upstream&&e.upstreamStatus!=="fresh"&&(t+=1),e.isOrphan&&(t+=1),t}function Rv(e,t){return e.type==="defaultBranchNode"&&t.type!=="defaultBranchNode"?-1:t.type==="defaultBranchNode"&&e.type!=="defaultBranchNode"||e.type==="submoduleNode"&&t.type!=="submoduleNode"?1:t.type==="submoduleNode"&&e.type!=="submoduleNode"?-1:e.branch&&t.branch&&e.branch!==t.branch?e.branch.localeCompare(t.branch):e.branch&&!t.branch?-1:!e.branch&&t.branch?1:e.label.localeCompare(t.label)||e.id.localeCompare(t.id)}function Pv(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function Dv(e,t,r,n=!0){return{id:e.id,type:"meshNode",position:{x:t,y:r},graphNode:e,selected:!1,draggable:!1,selectable:n}}function $v(e,t,r){return{id:e.id,x:t,y:r,width:Tr(e),height:Yu(e)}}function Ev(e,t){return{id:`${e.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:t.repoIdentity,branch:e.branch,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:null,locality:"unknown",health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],nextStepHint:"Waiting for worktree nodes to report live mesh status.",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{nodeId:`${e.id}__placeholder`,machineLabel:"",workspace:t.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}}function Xu(e){const t=[...e.nodes].sort(Rv),r=t.find(a=>a.type==="defaultBranchNode")??null,n=t.some(a=>a.id!==(r==null?void 0:r.id)&&a.type!=="submoduleNode");return!r||n?t:[...t,Ev(r,e)]}function Bv(e,t=Av,r=!1,n="LR"){const a=Xu(e),o=new Set(a.map(u=>u.id)),i=a.map(u=>({id:u.id,width:Tr(u,r),height:Yu(u,r)})),c=e.edges.filter(u=>o.has(u.source)&&o.has(u.target)).sort(Pv).map(u=>({id:u.id,sources:[u.source],targets:[u.target]}));return{id:`${e.meshId||"mesh"}__elk_root`,layoutOptions:{...t},children:i,edges:c}}function Ov(e,t=!1){const r=[...new Set(e.map(a=>Math.round(a.x)))].sort((a,o)=>a-o),n=t?Fr.layerGap:Us.layerGap;return r.length<2?n:Math.min(...r.slice(1).map((a,o)=>a-r[o]))}async function Fv(e,t=!1,r="LR"){var p,y;const a=yi(t?Fr:Us,r),o=Xu(e),i=new Map(o.map(b=>[b.id,b])),c=await _v.layout(Bv(e,a,t,r)),u=(c.children??[]).map(b=>{const x=i.get(b.id);return x?Dv(x,Math.round(b.x??0),Math.round(b.y??Us.placeholderTopOffset),!b.id.endsWith("__placeholder")):null}).filter(Boolean),m=new Map(o.map((b,x)=>[b.id,x]));u.sort((b,x)=>(m.get(b.id)??0)-(m.get(x.id)??0));const d=u.map(b=>$v(b.graphNode,b.position.x,b.position.y)),h=new Map;for(const b of c.edges??[]){const x=b.sections;if(!x||x.length===0)continue;const k=x[0],j=(p=b.sources)==null?void 0:p[0],f=(y=b.targets)==null?void 0:y[0];if(!j||!f)continue;const w=[];w.push({x:Math.round(k.startPoint.x),y:Math.round(k.startPoint.y)});for(const S of k.bendPoints??[])w.push({x:Math.round(S.x),y:Math.round(S.y)});w.push({x:Math.round(k.endPoint.x),y:Math.round(k.endPoint.y)}),h.set(b.id,{id:b.id,source:j,target:f,points:w})}return{nodes:u,bounds:d,edgeRoutes:h,columnGap:Ov(d,t),layoutOptions:{...a}}}function Hv(e){var t,r;return[e.id,e.type,e.label,e.branch??"",e.upstream??"",e.upstreamStatus??"",e.daemonId??"",e.machineId??"",e.machineLabel??"",e.locality,e.health,e.ahead,e.behind,e.dirty?1:0,e.dirtyFiles,e.hasConflicts?1:0,e.activeSessionCount,e.sessionDetails.map(n=>[n.sessionId,n.providerType??"",n.state??"",n.chatStatus??"",n.lifecycle??"",n.role??"",n.isSelfCoordinator?1:0,n.statusNote??"",n.startedAt??"",n.createdAt??""].join("/")).join(","),e.isOrphan?1:0,e.outOfSync?1:0,e.snapshotCompleteness,((t=e.branchConvergence)==null?void 0:t.status)??"",(r=e.branchConvergence)!=null&&r.needsConvergence?1:0,e.nextStepHint??"",e.error??"",e.parentNodeId??"",e.submodulePath??"",e.submoduleCommit??""].join("|")}function Ju(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function Wv(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(Hv),...e.edges.map(Ju)].join("::")}function Kv(e){return[e.meshId,e.nodes.length,e.edges.length,...e.nodes.map(t=>{var r,n;return[t.id,t.type,t.label,t.branch??"",t.machineLabel??"",t.locality,t.health,t.dirty?1:0,t.dirtyFiles,t.hasConflicts?1:0,t.activeSessionCount,t.isOrphan?1:0,t.outOfSync?1:0,t.snapshotCompleteness,((r=t.branchConvergence)==null?void 0:r.status)??"",(n=t.branchConvergence)!=null&&n.needsConvergence?1:0,t.nextStepHint??"",t.parentNodeId??"",t.submodulePath??"",t.submoduleCommit??""].join("|")}),...e.edges.map(Ju)].join("::")}const Uv=7,vi=l.createContext(Ys("dark")),Qu=l.createContext(!1),Zu=l.createContext("LR"),em={overflowWrap:"anywhere",wordBreak:"break-word"},zv={...em,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},Gv={...em,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function tm(e){return e.activeSessionCount>0}function Vv(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function Zl(e,t,r){const n=tm(e),a=Vv(e);let o;t?o="border-cyan-400/70 shadow-[0_0_0_1px_rgba(34,211,238,0.35),0_24px_60px_rgba(8,145,178,0.18)]":n?o=r?"border-emerald-400/40 shadow-[0_0_0_1px_rgba(52,211,153,0.18),0_18px_48px_rgba(3,7,18,0.22)]":"border-emerald-400/60 shadow-[0_0_0_1px_rgba(52,211,153,0.2),0_18px_48px_rgba(148,163,184,0.20)]":a?o=r?"border-white/6 shadow-[0_12px_32px_rgba(3,7,18,0.16)] opacity-60":"border-slate-200/70 shadow-[0_12px_32px_rgba(148,163,184,0.14)] opacity-60":o=r?"border-white/10 shadow-[0_18px_48px_rgba(3,7,18,0.22)]":"border-slate-300/90 shadow-[0_18px_48px_rgba(148,163,184,0.20)]";const i=bi(e);if((i==null?void 0:i.tone)==="danger")return`${o} ${r?"bg-rose-500/12":"bg-rose-50/95"}`;if((i==null?void 0:i.tone)==="warn")return`${o} ${r?"bg-amber-500/10":"bg-amber-50/95"}`;if((i==null?void 0:i.tone)==="info")return`${o} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;switch(e.health){case"online":return`${o} ${r?n?"bg-emerald-500/10":"bg-emerald-500/8":n?"bg-emerald-50":"bg-emerald-50/95"}`;case"dirty":return`${o} ${r?"bg-amber-500/8":"bg-amber-50/95"}`;case"degraded":return`${o} ${r?"bg-rose-500/10":"bg-rose-50/95"}`;case"wrong_branch":return`${o} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;case"offline":return`${o} ${r?"bg-slate-500/10":"bg-slate-100/90"}`;default:return`${o} ${r?"bg-slate-950/78":"bg-white/96"}`}}function At(e,t){switch(e){case"health":return t?"border-white/10 bg-slate-950/60 text-slate-200":"border-slate-300 bg-white/95 text-slate-700";case"dirty":return t?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700";case"conflict":return t?"border-rose-400/25 bg-rose-500/10 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700";case"orphan":return t?"border-fuchsia-400/25 bg-fuchsia-500/10 text-fuchsia-200":"border-fuchsia-300 bg-fuchsia-50 text-fuchsia-700";case"submodule":return t?"border-violet-400/25 bg-violet-500/10 text-violet-200":"border-violet-300 bg-violet-50 text-violet-700";case"meta":default:return t?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}}function ec(e,t){switch(e){case"danger":return t?"border-rose-400/35 bg-rose-500/14 text-rose-50":"border-rose-300 bg-rose-50 text-rose-700";case"warn":return t?"border-amber-400/35 bg-amber-500/14 text-amber-50":"border-amber-300 bg-amber-50 text-amber-700";case"info":return t?"border-violet-400/35 bg-violet-500/14 text-violet-50":"border-violet-300 bg-violet-50 text-violet-700";case"good":default:return t?"border-emerald-400/35 bg-emerald-500/12 text-emerald-50":"border-emerald-300 bg-emerald-50 text-emerald-700"}}function tc(e){switch(e){case"online":return"#34d399";case"dirty":return"#fbbf24";case"degraded":return"#fb7185";case"wrong_branch":return"#a78bfa";case"offline":return"#94a3b8";default:return"#64748b"}}function qv(e){return e.replace(/_/g," ")}function Gt(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const r=t.toLowerCase().replace(/[\s-]+/g,"_");return r.includes("approval")?"awaiting approval":r.includes("generating")||r.includes("running")||r.includes("busy")?"generating":r.includes("failed")||r.includes("stopped")||r.includes("interrupted")?r.replace(/_/g," "):r.includes("idle")||r.includes("ready")||r.includes("waiting_input")?"idle":r.replace(/_/g," ")}function za(e,t){const r=Gt(e);return r.includes("approval")?t?"border-amber-400/30 bg-amber-500/12 text-amber-100":"border-amber-300 bg-amber-50 text-amber-700":r==="generating"?t?"border-cyan-400/30 bg-cyan-500/12 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700":r==="idle"?t?"border-emerald-400/30 bg-emerald-500/12 text-emerald-100":"border-emerald-300 bg-emerald-50 text-emerald-700":r.includes("failed")||r.includes("stopped")||r.includes("interrupted")?t?"border-rose-400/30 bg-rose-500/12 text-rose-100":"border-rose-300 bg-rose-50 text-rose-700":At("health",t)}function Yv(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function sc(e){const t=Yv(e);if(t===null)return"runtime age not reported";const r=Math.max(0,Math.floor((Date.now()-t)/1e3));if(r<60)return`${r}s`;const n=Math.floor(r/60);if(n<60)return`${n}m`;const a=Math.floor(n/60);return a<48?`${a}h ${n%60}m`:`${Math.floor(a/24)}d ${a%24}h`}function Ga(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function cr(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function Xv(e){if(e.sessionDetails.length===0)return null;const t=e.sessionDetails.filter(o=>Gt(o)==="generating").length,r=e.sessionDetails.filter(o=>o.isSelfCoordinator).length,n=e.sessionDetails.length-r,a=[`${e.sessionDetails.length} chat${e.sessionDetails.length===1?"":"s"}`];return t>0&&a.push(`${t} generating`),r>0&&a.push(r===1?"coordinator attached":`${r} coordinators`),n>0&&a.push(`${n} worker${n===1?"":"s"}`),t===0&&r>0&&a.push("sampled status"),a.join(" · ")}function rc(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function Jv(e){return e.locality==="remote"?"meta":"health"}function Qv({data:e,selected:t}){const r=l.useContext(vi),n=l.useContext(Qu),a=l.useContext(Zu),o=e.graphNode,i=o.type==="defaultBranchNode",c=o.type==="submoduleNode",u=Vu(o),m=i?"default branch anchor":c?o.submodulePath||"submodule checkout":[o.machineLabel,rc(o.locality)].filter(Boolean).join(" · ")||o.workspace,d=o.submoduleCommit?o.submoduleCommit.slice(0,7):null,h=bi(o),p=gi(o),y=tm(o),b=o.sessionDetails,x=o.sessionDetails,k=Xv(o),j=o.sessionDetails.map(S=>{const v=Gt(S),g=S.providerType||"provider unknown",N=cr(S),M=S.startedAt||S.createdAt||null,C=S.statusNote?` · ${S.statusNote}`:"";return`Session: ${S.sessionId} · ${g} · ${v} · ${N} · ${sc(M)}${C}`});if(n)return s.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${Zl(o,t,r.isDark)}`,style:{width:Tr(o,!0)},title:[o.label,o.branch?`Branch: ${o.branch}`:null,o.machineLabel?`Machine: ${o.machineLabel}`:null,o.workspace?`Workspace: ${o.workspace}`:null,h?`Status: ${h.label}`:null,_n(o),...j].filter(Boolean).join(`
|
|
65
|
+
`,V.style.top="52px",V.style.height="calc(100% - 52px)";const fe=ne.querySelector("[data-adhdev-popout-focus]");fe&&(fe.onclick=()=>{window.focus()});const ke=ne.querySelector("[data-adhdev-popout-dock]");ke&&(ke.disabled=!te,ke.style.opacity=te?"1":"0.5",ke.style.cursor=te?"pointer":"default",ke.onclick=()=>{var Ce;te&&Me(te),(Ce=H.defaultView)==null||Ce.focus()})}},[D,Me]),ue=l.useCallback(z=>{var re;const G=M.current,Y=G==null?void 0:G.getPanel(z);if(!(!G||!Y)){Y.group.model.openPanel(Y),Y.api.setActive(),Q(z,"dockview-shortcut");try{const H=Y.group.model.location;H.type==="popout"?H.getWindow().focus():Wa((re=Y.group.element)==null?void 0:re.ownerDocument)}catch{}}},[Q]),U=l.useCallback(z=>{const G=M.current,Y=G==null?void 0:G.activePanel,re=(G==null?void 0:G.activeGroup)||(Y==null?void 0:Y.group);if(!G||!Y||!re)return;const H=re.panels||[];if(H.length<=1)return;const V=H.findIndex(Se=>Se.id===Y.id);if(V<0)return;const te=(V+z+H.length)%H.length,le=H[te];le&&(le.group.model.openPanel(le),le.api.setActive(),Dt(le.id)||Q(le.id,"dockview-shortcut"))},[Q]),ce=l.useCallback(z=>{var fe;const G=M.current,Y=(G==null?void 0:G.activeGroup)||((fe=G==null?void 0:G.activePanel)==null?void 0:fe.group);if(!G||!Y)return;const re=G.groups||[],H=re.find(ke=>ke.id===Y.id);if(!H)return;const V=H.element.getBoundingClientRect(),te=V.left+V.width/2,le=V.top+V.height/2,Se=(ke,Ce,Ke,Ge)=>Math.max(0,Math.min(Ce,Ge)-Math.max(ke,Ke)),Le=ke=>{const Ce=ke.element.getBoundingClientRect(),Ke=Ce.left+Ce.width/2,Ge=Ce.top+Ce.height/2;let Be=0,ht=0,ct=0,ft=!1;if(z==="left"?(ft=Ke<te,Be=Math.max(0,V.left-Ce.right),ht=Math.abs(Ge-le),ct=Se(V.top,V.bottom,Ce.top,Ce.bottom)):z==="right"?(ft=Ke>te,Be=Math.max(0,Ce.left-V.right),ht=Math.abs(Ge-le),ct=Se(V.top,V.bottom,Ce.top,Ce.bottom)):z==="above"?(ft=Ge<le,Be=Math.max(0,V.top-Ce.bottom),ht=Math.abs(Ke-te),ct=Se(V.left,V.right,Ce.left,Ce.right)):(ft=Ge>le,Be=Math.max(0,Ce.top-V.bottom),ht=Math.abs(Ke-te),ct=Se(V.left,V.right,Ce.left,Ce.right)),!ft)return Number.POSITIVE_INFINITY;const He=ct>0?0:120;return Be*3+ht+He};let O=null,ne=Number.POSITIVE_INFINITY;for(const ke of re){if(ke.id===H.id)continue;const Ce=Le(ke);Number.isFinite(Ce)&&(Ce>=ne||(ne=Ce,O=ke))}return O||void 0},[]),ie=l.useCallback(z=>{var re;const G=ce(z);if(!G)return;const Y=G.activePanel||G.panels[0];Y&&(G.model.openPanel(Y),Y.api.setActive(),Dt(Y.id)||Q(Y.id,"dockview-focus"),Wa((re=G.element)==null?void 0:re.ownerDocument))},[ce,Q]),de=l.useCallback((z,G)=>{const Y=M.current,re=Y==null?void 0:Y.activePanel,H=(Y==null?void 0:Y.activeGroup)||(re==null?void 0:re.group);if(!Y||!re||!H)return;let V=ce(z);!V&&(G!=null&&G.createGroupIfMissing)&&(V=Y.addGroup({referenceGroup:H,direction:z})),V&&(re.api.moveTo({group:V,position:"center"}),re.group.model.openPanel(re),re.api.setActive(),Dt(re.id)||Q(re.id,G!=null&&G.createGroupIfMissing?"dockview-split":"dockview-move"))},[ce,Q]),{isMac:me,tabShortcuts:oe,shortcutListening:P,setShortcutListening:xe,saveShortcuts:Ne}=Pu({sortedTabKeys:e.map(z=>z.tabKey),onFocus:J,onSelectTab:ue}),_e=l.useCallback(()=>{var Y;const z=M.current;if(!z)return;const G=z.activePanel;if(G){if(Dt(G.id)){const re=((Y=G.params)==null?void 0:Y.routeId)||G.id.slice(7),H=Bt(e,re);H!=null&&H.tabKey&&xe(H.tabKey);return}D.has(G.id)&&xe(G.id)}},[D,ue,xe,e]),se=l.useCallback(z=>{const G=[];return z.metaKey&&G.push(me?"⌘":"Meta"),z.ctrlKey&&G.push("Ctrl"),z.altKey&&G.push(me?"⌥":"Alt"),z.shiftKey&&z.key.length!==1&&G.push(me?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(z.key)?null:(G.push(Bu(z.key)),G.join("+"))},[me]),De=l.useCallback(z=>{var G,Y;switch(z){case"splitActiveTabRight":de("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":de("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const re=pe();re&&ge(re);return}case"popoutActiveTab":{const re=pe();re&&we(re);return}case"dockActiveTab":{const re=pe();if(!re)return;q(re)?Me(re):ve(re)&&Ie(re);return}case"focusLeftPane":ie("left");return;case"focusRightPane":ie("right");return;case"focusUpPane":ie("above");return;case"focusDownPane":ie("below");return;case"moveActiveTabToLeftPane":de("left");return;case"moveActiveTabToRightPane":de("right");return;case"moveActiveTabToUpPane":de("above");return;case"moveActiveTabToDownPane":de("below");return;case"selectPreviousGroupTab":U(-1);return;case"selectNextGroupTab":U(1);return;case"setActiveTabShortcut":_e();return;case"hideCurrentTab":{const re=(Y=(G=M.current)==null?void 0:G.activePanel)==null?void 0:Y.id;re&&!Dt(re)&&ye(re);return}default:return}},[U,Ie,ie,ge,pe,ye,ve,q,Me,de,we,_e]);l.useEffect(()=>{if(!_)return;const z=_.sourceDocument,G=z.defaultView??window,Y=re=>{const H=z.querySelector("[data-dockview-tab-context-menu]");H&&H.contains(re.target)||L(null)};return G.addEventListener("mousedown",Y,!0),G!==window&&window.addEventListener("mousedown",()=>L(null),!0),()=>{G.removeEventListener("mousedown",Y,!0),G!==window&&window.removeEventListener("mousedown",()=>L(null),!0)}},[_]);const Te=l.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:D,hasDetachedConversationPanels:K,ides:r,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:b,liveSessionInboxState:S,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:ye,userName:m,scrollToBottomRequest:w,tabShortcuts:oe,openTabContextMenu:({x:z,y:G,tabKey:Y,sourceDocument:re})=>L({x:z,y:G,tabKey:Y,sourceDocument:re??document}),popoutTab:we,moveTabBackToMain:Me,isTabInPopout:q,floatTab:ge,isTabFloating:ve}),[n,t,D,K,r,i,c,b,S,a,o,ye,m,w,oe,we,Me,q,ge,ve]),$e=_?J0({isTabInPopout:q(_.tabKey),isTabFloating:ve(_.tabKey),tabShortcut:oe[_.tabKey],actionShortcuts:h}):[],Oe=l.useCallback(z=>{var re;const G=M.current;if((((re=G==null?void 0:G.activePanel)==null?void 0:re.id)??null)===z.id){z.group.model.openPanel(z);return}z.group.model.openPanel(z),z.api.setActive()},[]),Je=l.useCallback((z,G="requested-tab")=>{if(!z)return!1;const Y=M.current;if(!Y)return!1;const re=Y.getPanel(z);return re?(Oe(re),Q(z,G),f==null||f(),!0):!1},[Oe,f,Q]),qe=l.useCallback(()=>{if(I.current)return!1;const z=Je(A.current,"stored-layout-restore");return z&&(I.current=!0),z},[Je]),Ze=l.useCallback(()=>{var G;const z=M.current;z&&My(v,{activeTabId:((G=z.activePanel)==null?void 0:G.id)??null,layout:z.toJSON()})},[v]),et=l.useCallback(()=>{Ay(v,E.current)},[v]),ut=l.useCallback(z=>{var re,H,V,te;const G=M.current;if(!G)return{kind:"grid"};const Y=G.toJSON();for(const le of Y.floatingGroups||[])if((H=(re=le.data)==null?void 0:re.views)!=null&&H.includes(z)&&le.position)return{kind:"floating",position:le.position};for(const le of Y.popoutGroups||[])if((te=(V=le.data)==null?void 0:V.views)!=null&&te.includes(z))return{kind:"popout",position:le.position,popoutUrl:le.url};return{kind:"grid"}},[]),mt=l.useCallback(z=>{const G=M.current;if(!G)return;const Y=G.getPanel(z),re=E.current[z];if(!Y||!re||re.kind==="grid")return;if(Y.group.model.location.type===re.kind){delete E.current[z],et();return}if(re.kind==="floating"){G.addFloatingGroup(Y,{x:re.position.left??24,y:re.position.top??24,width:re.position.width,height:re.position.height}),delete E.current[z],et();return}delete E.current[z],et()},[et]);l.useEffect(()=>(p==null||p({setShortcutForActiveTab:_e,restoreHiddenTabToSavedLocation:mt,activateConversationTab:ue,resetAllPanelsToMain:X,activatePreviousTabInGroup:()=>U(-1),activateNextTabInGroup:()=>U(1),floatActiveTab:()=>{const z=pe();z&&ge(z)},popoutActiveTab:()=>{const z=pe();z&&we(z)},dockActiveTab:()=>{const z=pe();z&&(q(z)?Me(z):ve(z)&&Ie(z))},splitActiveTabRight:()=>de("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>de("below",{createGroupIfMissing:!0}),focusLeftPane:()=>ie("left"),focusRightPane:()=>ie("right"),focusUpPane:()=>ie("above"),focusDownPane:()=>ie("below"),moveActiveTabToLeftPane:()=>de("left"),moveActiveTabToRightPane:()=>de("right"),moveActiveTabToUpPane:()=>de("above"),moveActiveTabToDownPane:()=>de("below")}),()=>p==null?void 0:p(null)),[U,Ie,ge,ie,pe,ve,q,de,Me,we,p,X,mt,ue,_e]),l.useEffect(()=>()=>{var z;(z=$.current)==null||z.call($),$.current=null},[]);const bt=l.useCallback(z=>{var Y,re;M.current=z.api,(Y=$.current)==null||Y.call($),$.current=null;const G=Cy(v);if(A.current=(G==null?void 0:G.activeTabId)??null,G!=null&&G.layout&&z.api.fromJSON(G.layout,{reuseExistingPanels:!1}),T.current=zl({hasStoredLayout:!!(G!=null&&G.layout),initialDataLoaded:u,visibleConversationCount:e.length,ides:r}),T.current||(Jl(z.api,e),Ql(z.api,e,j)),z.api.totalPanels===0&&e.length>0){const H=av(z.api,e,k);if(H){const V=z.api.getPanel(H);V&&Oe(V)}}else!T.current&&!Je(k)&&qe();if(R.current=!0,z.api.onDidActivePanelChange(H=>{var te;if(A.current=(H==null?void 0:H.id)??null,I.current=!0,be(),H&&Dt(H.id)){const le=((te=H.params)==null?void 0:te.routeId)||H.id.slice(7),Se=Bt(e,le);y((Se==null?void 0:Se.tabKey)??null),Ze();return}if(y((H==null?void 0:H.id)??null),Ze(),!H)return;const V=D.get(H.id);(V==null?void 0:V.streamSource)==="agent-stream"&&V.agentType&&N(V.routeId,jd(),{agentType:V.agentType,...V.sessionId&&{targetSessionId:V.sessionId}}).catch(()=>{})}),z.api.onDidLayoutChange(()=>{Ze(),be(),F(H=>H+1)}),tv()){const H=ne=>({clientX:ne.clientX,clientY:ne.clientY}),V=ne=>{const fe=ne==null?void 0:ne.getBoundingClientRect();return fe?{left:fe.left,right:fe.right,top:fe.top,bottom:fe.bottom}:null},te=ne=>{var ke;const fe=(ke=C.current)==null?void 0:ke.getBoundingClientRect();return fe?ne.clientX<fe.left||ne.clientX>fe.right||ne.clientY<fe.top||ne.clientY>fe.bottom:!1},le=ev({detachDelayMs:Fu,onDetach:({panelId:ne,clientX:fe,clientY:ke})=>{var ct,ft;const Ce=z.api.getPanel(ne);if(!Ce)return;try{if(Ce.group.model.location.type!=="grid")return}catch{return}const Ke=(ct=C.current)==null?void 0:ct.getBoundingClientRect(),Ge=(ft=Ce.group.element)==null?void 0:ft.getBoundingClientRect(),Be=Math.round(Math.min(Math.max((Ge==null?void 0:Ge.width)??600,360),720)),ht=Math.round(Math.min(Math.max((Ge==null?void 0:Ge.height)??500,260),640));z.api.addFloatingGroup(Ce,{x:Ke?Math.max(0,fe-Ke.left-32):void 0,y:Ke?Math.max(0,ke-Ke.top-18):void 0,width:Be,height:ht}),Ce.api.setActive(),Ze(),be(),F(He=>He+1)}}),Se=[z.api.onWillDragPanel(ne=>{if(!(ne.nativeEvent.defaultPrevented||ne.nativeEvent.shiftKey)){try{if(ne.panel.group.model.location.type!=="grid")return}catch{return}le.startDrag({panelId:ne.panel.id,selfPanelBounds:V(ne.panel.group.element),...H(ne.nativeEvent)})}}),z.api.onWillShowOverlay(ne=>{if(le.hasDetached()){ne.preventDefault();return}le.markDockTarget(H(ne.nativeEvent))}),z.api.onWillDrop(ne=>{if(le.hasDetached()){ne.preventDefault(),le.endDrag();return}le.markDockTarget(H(ne.nativeEvent))}),z.api.onDidDrop(()=>le.endDrag()),z.api.onUnhandledDragOverEvent(ne=>{le.isDragging()&&le.markSelfPanel(H(ne.nativeEvent))})],Le=ne=>{if(!le.isDragging())return;const fe=H(ne);te(fe)&&le.markNonSelfPanel(fe)},O=()=>le.endDrag();window.addEventListener("dragover",Le,!0),window.addEventListener("drop",O,!0),window.addEventListener("dragend",O,!0),$.current=()=>{le.dispose();for(const ne of Se)ne.dispose();window.removeEventListener("dragover",Le,!0),window.removeEventListener("drop",O,!0),window.removeEventListener("dragend",O,!0)}}z.api.onDidAddGroup(H=>{requestAnimationFrame(()=>{var V,te;try{const le=(V=H.element)==null?void 0:V.ownerDocument;if(!le||le===document)return;(te=le.getElementById("dv-popout-window"))==null||te.classList.add("adhdev-dockview");const Se=document.documentElement.getAttribute("data-theme");Se&&le.documentElement.setAttribute("data-theme",Se),le.body.className=document.body.className;const Le=document.documentElement.getAttribute("style");Le&&le.documentElement.setAttribute("style",Le)}catch{}be(),F(le=>le+1)})}),y(((re=z.api.activePanel)==null?void 0:re.id)??null)},[Oe,Je,D,r,u,v,y,Ze,k,j,N,be,e]);l.useLayoutEffect(()=>{const z=M.current;if(!z||!R.current||T.current&&zl({hasStoredLayout:!0,initialDataLoaded:u,visibleConversationCount:e.length,ides:r}))return;T.current&&(T.current=!1);const G=W.current,Y=new Set(G),re=e.map(O=>O.tabKey),H=new Set(re),V=Q0({previousVisibleConversationCount:G.length,visibleConversationCount:e.length,ides:r});let te=!1;for(const O of G)H.has(O)||V||(E.current[O]=ut(O),te=!0);te&&et(),V||(Jl(z,e),Ql(z,e,j));const le=re.filter(O=>!Y.has(O));let Se=!1;for(const O of le){const ne=z.getPanel(O),fe=E.current[O];if(!ne||!fe||fe.kind==="grid")continue;if(ne.group.model.location.type===fe.kind){delete E.current[O],Se=!0;continue}if(fe.kind==="floating"){z.addFloatingGroup(ne,{x:fe.position.left??24,y:fe.position.top??24,width:fe.position.width,height:fe.position.height}),delete E.current[O],Se=!0;continue}}if(Se&&et(),W.current=re,k&&Je(k))return;!z.activePanel&&z.panels[0]&&Oe(z.panels[0]),!!(z.activePanel&&z.getPanel(z.activePanel.id))||qe()},[Oe,Je,qe,r,u,et,ut,k,j,e]),l.useEffect(()=>{R.current&&Je(k)},[Je,k]),l.useEffect(()=>{const z=Y=>{const re=Y.target;if(!re)return;const H=re.querySelector("[data-tab-key]")||re.closest("[data-tab-key]");if(H){const V=H.getAttribute("data-tab-key");if(V&&Y.dataTransfer){const te=re.closest(".dv-tab")||H.closest(".dv-tab")||H;Y.dataTransfer.effectAllowed="move",Y.dataTransfer.setData("text/tab-key",V),te instanceof HTMLElement&&Y.dataTransfer.setDragImage(te,Math.max(12,Math.round(te.clientWidth/2)),Math.max(10,Math.round(te.clientHeight/2)))}}};window.addEventListener("dragstart",z);const G=Xl(M.current);for(const Y of G)Y.addEventListener("dragstart",z);return()=>{window.removeEventListener("dragstart",z);for(const Y of G)Y.removeEventListener("dragstart",z)}},[B]),l.useEffect(()=>{var G;const z=(G=C.current)==null?void 0:G.querySelector(".adhdev-dockview");z instanceof HTMLElement&&Ka(z,g),he(),be()},[be,he,g]),l.useEffect(()=>{be()},[be]),l.useEffect(()=>{const z=G=>{if(G.defaultPrevented||P)return;const Y=se(G);if(!Y)return;const re=G.metaKey||G.ctrlKey||G.altKey;Lo(G.target)&&!re||Zn(me).setActiveTabShortcut!==Y||(G.preventDefault(),G.stopPropagation(),_e())};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[se,me,P,_e]),l.useEffect(()=>{const z=C.current;if(!z)return;const G=Y=>{var le,Se;if(!Y.isTrusted)return;const re=(Se=(le=Y.target)==null?void 0:le.closest)==null?void 0:Se.call(le,".dv-scrollable");if(!re)return;Y.preventDefault(),Y.stopPropagation();const H=Math.abs(Y.deltaX),V=Math.abs(Y.deltaY),te=H>V?Y.deltaX:Y.deltaY;re.dispatchEvent(new WheelEvent("wheel",{deltaY:te,deltaMode:Y.deltaMode,bubbles:!1,cancelable:!0}))};return z.addEventListener("wheel",G,{passive:!1,capture:!0}),()=>z.removeEventListener("wheel",G,{capture:!0})},[]),l.useEffect(()=>{const z=Xl(M.current);if(z.length===0)return;const G=z.map(Y=>{let re=[],H=null;const V=()=>{H!=null&&Y.clearTimeout(H),H=null,re=[]},te=()=>{H!=null&&Y.clearTimeout(H),H=Y.setTimeout(()=>{H=null,re=[]},1200)},le=Le=>{if(!Le.ctrlKey&&!Le.metaKey&&!Le.altKey)return;const O=se(Le);if(!O)return;const ne=Ru();for(const[fe,ke]of Object.entries(ne))if(e.some(Ce=>Ce.tabKey===fe)&&ke===O){Le.preventDefault(),ue(fe);return}},Se=Le=>{if(Le.defaultPrevented||P)return;const O=se(Le);if(!O)return;const ne=Le.metaKey||Le.ctrlKey||Le.altKey;if(Lo(Le.target))return;const fe=Zn(me),ke=Object.entries(fe).filter(([He,Qt])=>!!Qt&&(He==="splitActiveTabRight"||He==="splitActiveTabDown"||He==="floatActiveTab"||He==="popoutActiveTab"||He==="dockActiveTab"||He==="focusLeftPane"||He==="focusRightPane"||He==="focusUpPane"||He==="focusDownPane"||He==="moveActiveTabToLeftPane"||He==="moveActiveTabToRightPane"||He==="moveActiveTabToUpPane"||He==="moveActiveTabToDownPane"||He==="selectPreviousGroupTab"||He==="selectNextGroupTab"||He==="setActiveTabShortcut"||He==="hideCurrentTab")),Ce=ne?[O]:[...re.slice(-1),O].slice(-2),Ke=Ce.join(" "),Ge=Ce[Ce.length-1],Be=ke.find(([,He])=>He===Ke);if(Be){Le.preventDefault(),V(),De(Be[0]);return}if(ke.some(([,He])=>He.startsWith(`${Ke} `))){Le.preventDefault(),re=Ce,te();return}const ct=ke.find(([,He])=>He===Ge);if(ct){Le.preventDefault(),V(),De(ct[0]);return}if(ke.some(([,He])=>He.startsWith(`${Ge} `))){Le.preventDefault(),re=[Ge],te();return}V()};return Y.addEventListener("keydown",le),Y.addEventListener("keydown",Se),()=>{V(),Y.removeEventListener("keydown",le),Y.removeEventListener("keydown",Se)}});return()=>{for(const Y of G)Y()}},[se,me,B,ue,P,De,e]);const Ae=g==="light"?lo:co,We=((tt=(Ye=(rt=M.current)==null?void 0:rt.activePanel)==null?void 0:Ye.group.element)==null?void 0:tt.ownerDocument)??document;return s.jsxs(Hu.Provider,{value:Te,children:[s.jsx("div",{ref:C,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(Qm,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:ov,remote:iv},defaultTabComponent:cv,watermarkComponent:lv,onReady:bt,singleTabMode:"default",tabAnimation:"smooth",theme:Ae,popoutUrl:"/popout.html"})}),_&&Nr.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:_.x,top:_.y},children:$e.map(z=>{if(z.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},z.id);let G=s.jsx(cp,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{};switch(z.id){case"dockInWindow":case"dockBackToGrid":G=s.jsx(up,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{Ie(_.tabKey),L(null)};break;case"moveBackToMain":G=s.jsx(lp,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{Me(_.tabKey),L(null)};break;case"floatAsPanel":G=s.jsx(dp,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{ge(_.tabKey),L(null)};break;case"openInNewWindow":G=s.jsx(ip,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{we(_.tabKey),L(null)};break;case"setShortcut":Y=re=>{re.stopPropagation(),xe(_.tabKey),L(null)};break;case"removeShortcut":G=s.jsx(yt,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{const re={...oe};delete re[_.tabKey],Ne(re),L(null)};break;case"hideTab":G=s.jsx(Wo,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{ye(_.tabKey),L(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${z.tone==="muted"?"text-text-muted":""}`,onMouseDown:rv,onClick:Y,children:[G,s.jsx("span",{className:"flex-1 min-w-0",children:z.label}),z.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:z.shortcut}):null]},z.id)})}),_.sourceDocument.body),P&&Nr.createPortal(s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>xe(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:z=>z.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. ",me?"⌘+1":"Ctrl+1",", ",me?"⌥+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:"Press Esc to cancel"})]})}),We.body)]})}const Wu="adhdev-recent-launch-args-v1",uv=8;function mv(e){return String(e||"").trim().replace(/\s+/g," ")}function Ku(e,t){return`${e.trim()}::${t.trim()}`}function Uu(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Wu)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function hv(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Wu,JSON.stringify(e))}catch{}}function pv(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=Uu().byKey[Ku(r,n)])==null?void 0:o.items)||[]}function fv(e,t,r){var d;const n=String(e||"").trim(),a=String(t||"").trim(),o=mv(r);if(!n||!a||!o)return;const i=Uu(),c=Ku(n,a),u=((d=i.byKey[c])==null?void 0:d.items)||[],m=[o,...u.filter(h=>h!==o)].slice(0,uv);i.byKey[c]={items:m},hv(i)}function xv(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Tn({title:e,description:t,action:r,children:n,className:a="",contentClassName:o=""}){return s.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),t&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:t})]}),r?s.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?s.jsx("div",{className:t||r?`mt-3 ${o}`.trim():o,children:n}):null]})}function bv({savedSessionsLoading:e,savedSessionsLoaded:t,savedSessionsCount:r=0}){return e?"Refreshing saved history…":t?r>0?`${r} saved ${r===1?"history":"histories"} loaded. Open saved history to choose one.`:"No saved history found yet. New Hermes CLI conversations will appear here after ADHDev captures provider history.":"Start fresh, or open saved history when you want continuity."}function gv({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:i,onOpenHistory:c,onClearSelection:u}){const m=o?Iu(o):null,d=bv({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Tn,{title:"Saved history",description:ri(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:i,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:c,children:Kb()})]}),children:[m?s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),s.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:m.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:m.providerSessionId}),s.jsx("div",{className:"mt-1",children:m.metaLine}),m.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:m.updatedLabel}),m.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:m.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:u,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:d}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function zu({setup:e,providerName:t,className:r=""}){return e?s.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${r}`,children:[s.jsxs("div",{className:"font-semibold",children:["Manual MCP setup required",t?` for ${t}`:""]}),e.instructions&&s.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-text-muted",children:[e.serverName&&s.jsxs("span",{children:["Server: ",s.jsx("code",{children:e.serverName})]}),e.configFormat&&s.jsxs("span",{children:["Format: ",s.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&s.jsxs("span",{children:["Config path: ",s.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&s.jsx("span",{children:"Start a fresh CLI session after editing config."})]}),e.template&&s.jsx("pre",{className:"mt-3 max-h-72 overflow-auto rounded-lg border border-border-subtle bg-bg-primary p-3 text-xs font-mono leading-relaxed text-text-primary select-all whitespace-pre-wrap",children:e.template})]}):null}function yv({workspaceMode:e,activeKind:t,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:o,onSelect:i}){return e==="mesh"?null:s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:r},{id:"ide",label:"Workspace",enabled:n},{id:"acp",label:"ACP",enabled:a}].map(c=>s.jsx("button",{type:"button",className:`btn btn-sm ${t===c.id?"btn-primary":"btn-secondary"}`,onClick:()=>i(c.id),disabled:!c.enabled||o,children:c.label},c.id))})]})}function Ua(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>Ks(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>Ks(a,"acp"))?"acp":null}function pn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function vv({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:u,onListSavedSessions:m}){var He,Qt;const d=$r(),h=l.useMemo(()=>[...e].sort(qo),[e]),[p,y]=l.useState(((He=h[0])==null?void 0:He.id)||""),b=l.useMemo(()=>h.find(ee=>ee.id===p)||h[0],[p,h]),x=l.useMemo(()=>((b==null?void 0:b.workspaces)||[]).map(ee=>({id:ee.id,path:ee.path,label:ee.label})),[b]),k=(b==null?void 0:b.defaultWorkspaceId)||null,[j,f]=l.useState("workspace"),[w,S]=l.useState(""),[v,g]=l.useState(""),[N,M]=l.useState([]),[C,$]=l.useState(""),[R,T]=l.useState(!1),[I,A]=l.useState(null),[W,_]=l.useState(""),[L,B]=l.useState(Ua(h[0])),[F,E]=l.useState(""),[D,K]=l.useState(""),[J,Q]=l.useState([]),[Z,he]=l.useState(""),[we,Me]=l.useState([]),[q,ye]=l.useState(!1),[ge,ve]=l.useState(!1),[pe,Ie]=l.useState(""),[X,be]=l.useState(!1),[ue,U]=l.useState(()=>kt()),[ce,ie]=l.useState(null),[de,me]=l.useState(!1),[oe,P]=l.useState(""),[xe,Ne]=l.useState(null),[_e,se]=l.useState(!1),[De,Te]=l.useState(""),[$e,Oe]=l.useState([]),[Je,qe]=l.useState(!1),[Ze,et]=l.useState(""),[ut,mt]=l.useState(!1),bt=l.useRef(null),Ae=l.useRef(0);l.useEffect(()=>{var ee;!p&&((ee=h[0])!=null&&ee.id)&&y(h[0].id)},[p,h]),l.useEffect(()=>{!b||!(!b.workspaces||!b.availableProviders||!b.detectedIdes||!b.recentLaunches)||d(b.id,{minFreshMs:3e4}).catch(()=>{})},[d,b]);const We=l.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(ee=>Ks(ee,"cli")),[b]),rt=l.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(ee=>Ks(ee,"acp")),[b]),Ye=l.useMemo(()=>((b==null?void 0:b.detectedIdes)||[]).map(ee=>({id:ee.type,label:ee.name||ee.type,meta:ee.running?"Detected locally":"Available to open"})),[b]),tt=l.useMemo(()=>L==="cli"?We.map(ee=>({id:ee.type,label:ee.displayName||ee.type,meta:"CLI provider"})):L==="acp"?rt.map(ee=>({id:ee.type,label:ee.displayName||ee.type,meta:"ACP provider"})):Ye,[rt,L,We,Ye]),z=l.useMemo(()=>N.find(ee=>ee.id===C)||null,[N,C]),G=l.useMemo(()=>We.find(ee=>ee.type===F)||null,[We,F]),Y=l.useMemo(()=>ju(G==null?void 0:G.meshCoordinator,{meshId:(z==null?void 0:z.id)||"",workspace:(z==null?void 0:z.workspace)||""}),[G,z]),re=xe||Y,H=l.useCallback(async ee=>{T(!0),_("");try{const Re=await c(ee);M(Re),$(ae=>{var Pe;return Re.some(Nt=>Nt.id===ae)?ae:((Pe=Re[0])==null?void 0:Pe.id)||""}),A(ee)}catch(Re){M([]),$(""),A(ee),_(Re instanceof Error?Re.message:"Could not load meshes")}finally{T(!1)}},[c]);l.useEffect(()=>{var Re;if(!b)return;if(bt.current!==b.id){bt.current=b.id,f("workspace"),S(k||((Re=x[0])==null?void 0:Re.id)||"__home__"),g(""),M([]),$(""),A(null),_(""),B(Ua(b)),E(""),K(""),he(""),Me([]),ve(!1),Ie(""),U(kt()),P(""),Ne(null);return}S(ae=>{var Pe;return ae==="__custom__"||ae==="__home__"||x.some(Nt=>Nt.id===ae)?ae:k||((Pe=x[0])==null?void 0:Pe.id)||"__home__"}),B(ae=>ae==="ide"&&Ye.length>0||ae==="cli"&&We.length>0||ae==="acp"&&rt.length>0?ae:Ua(b))},[rt.length,We.length,k,Ye.length,b,x]),l.useEffect(()=>{!b||j!=="mesh"||I===b.id||R||H(b.id)},[H,I,R,b,j]),l.useEffect(()=>{j==="mesh"&&L!=="cli"&&We.length>0&&B("cli")},[L,We.length,j]),l.useEffect(()=>{var ee;L&&(tt.some(Re=>Re.id===F)||E(((ee=tt[0])==null?void 0:ee.id)||""))},[L,tt,F]),l.useEffect(()=>{Ne(null)},[b==null?void 0:b.id,C,F,j]);const V=l.useCallback(async(ee,Re)=>{const ae=Ae.current+1;return Ae.current=ae,ye(!0),Ie(""),m(ee,Re).then(Pe=>{Ae.current===ae&&Me(Pe)}).catch(Pe=>{Ae.current===ae&&(Me([]),Ie(Pe instanceof Error?Pe.message:"Could not load saved sessions"))}).finally(()=>{Ae.current===ae&&(ye(!1),ve(!0))})},[m]),te=l.useCallback((ee,Re)=>{Q(pv(ee,Re))},[]);l.useEffect(()=>{Ae.current+=1,he(""),U(kt()),!b||!F||L==="ide"?Q([]):te(b.id,F),ve(!1),Me([]),Ie(""),ye(!1)},[L,te,V,b,F]),l.useEffect(()=>{if(!Z)return;const ee=we.find(Re=>Re.providerSessionId===Z);ee!=null&&ee.canResume||he("")},[we,Z]);const le=w==="__custom__"?v.trim():w==="__home__"?"":((Qt=x.find(ee=>ee.id===w))==null?void 0:Qt.path)||"",Se=l.useMemo(()=>b?t.filter(ee=>ee.id!==b.id&&ee.daemonId===b.id).map(ee=>ee.workspace):[],[t,b]),Le=l.useMemo(()=>((b==null?void 0:b.recentLaunches)||[]).map(ee=>ee.workspace),[b]),O=l.useCallback(ee=>{const Re=String(ee.workspace||"").trim();if(!Re)return;const ae=x.find(Pe=>pn(Pe.path)===pn(Re));if(ae){S(ae.id),g("");return}S("__custom__"),g(Re)},[x]),ne=l.useCallback(ee=>{const Re=String(ee.workspace||"").trim();if(!Re)return{workspaceId:null,workspacePath:null};const ae=x.find(Pe=>pn(Pe.path)===pn(Re));return ae?{workspaceId:ae.id,workspacePath:null}:{workspaceId:null,workspacePath:Re}},[x]),fe=l.useMemo(()=>we.find(ee=>ee.providerSessionId===Z)||null,[we,Z]),ke=l.useMemo(()=>{var Re;if(L!=="cli"||!b||!F)return null;const ee=((Re=We.find(ae=>ae.type===F))==null?void 0:Re.displayName)||F;return{routeId:b.id,daemonId:b.id,providerSessionId:Z||void 0,transport:"pty",mode:"chat",agentName:ee,agentType:F,status:"idle",title:ee,messages:[],ideType:F,workspaceName:le,workspacePath:le,displayPrimary:ee,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${b.id}:${F}`,machineName:It(b,{fallbackId:b.id})}},[L,We,le,b,Z,F]),Ce=l.useCallback(()=>{var Re;if(!b)return;S("__custom__"),se(!0),et("");const ee=mi(b.platform,ui(v.trim(),le,Se,Le,b.defaultWorkspacePath,(Re=x.find(ae=>ae.id===k))==null?void 0:Re.path,x.map(ae=>ae.path)));qe(!0),n(b.id,ee).then(ae=>{Te(ae.path),g(ae.path),Oe(ae.directories)}).catch(ae=>{et(ae instanceof Error?ae.message:"Could not load folder")}).finally(()=>qe(!1))},[v,k,Le,Se,n,le,b,x]),Ke=l.useCallback(ee=>{b&&(qe(!0),et(""),n(b.id,ee).then(Re=>{Te(Re.path),g(Re.path),Oe(Re.directories)}).catch(Re=>{et(Re instanceof Error?Re.message:"Could not load folder")}).finally(()=>qe(!1)))},[n,b]),Ge=l.useCallback(async()=>{if(!b||!le)return;mt(!0),P("");const ee=await a(b.id,le);if(mt(!1),!ee.ok){P(ee.error||"Could not save workspace");return}P("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,le,b]),Be=l.useCallback(async()=>{if(!b)return;if(j==="mesh"){if(!C||!F)return;me(!0),P(""),Ne(null);const ae=await u(b.id,C,F);if(me(!1),!ae.ok){if(ae.code==="mesh_coordinator_manual_mcp_setup_required"&&ae.manualSetup){Ne(ae.manualSetup),P("Manual MCP setup required before this provider can act as mesh coordinator.");return}P(ae.error||"Could not start mesh coordinator");return}r();return}if(!L||!F)return;me(!0),P("");const ee=D.trim()?D.trim().split(/\s+/).filter(Boolean):[],Re=L==="ide"?await o(b.id,F,{workspacePath:le||null}):await i(b.id,L,F,{workspaceId:w!=="__home__"&&w!=="__custom__"?w:null,workspacePath:w==="__custom__"&&le||null,resumeSessionId:L==="cli"&&Z?Z:null,cliArgs:ee});if(me(!1),!Re.ok){P(Re.error||"Could not start session");return}L!=="ide"&&D.trim()&&(fv(b.id,F,D),te(b.id,F)),r()},[L,D,te,r,o,u,i,le,b,C,Z,F,w,j]),ht=j==="mesh"?"Start mesh coordinator":L?Fb(L,L==="cli"&&!!Z):"Start",ct=j==="mesh"?"Starting coordinator…":L?Hb(L,L==="cli"&&!!Z):"Starting…",ft=h.length>5;return b?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] 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":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] 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-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),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:r,"aria-label":"Close new session dialog",children:s.jsx(yt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[h.length>1&&s.jsx(Tn,{title:"Machine",children:ft?s.jsx("select",{"aria-label":"Machine",value:b.id,onChange:ee=>y(ee.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:de,children:h.map(ee=>s.jsx("option",{value:ee.id,children:It(ee,{fallbackId:ee.id})},ee.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:h.map(ee=>{const Re=It(ee,{fallbackId:ee.id}),ae=b.id===ee.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${Re}`,"aria-pressed":ae,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${ae?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/60 text-text-secondary hover:bg-bg-secondary hover:text-text-primary"}`,onClick:()=>y(ee.id),disabled:de,title:Re,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${ee.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:Re})]},ee.id)})})}),s.jsxs(Tn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:j==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ce,disabled:de,children:"Browse…"}):void 0,children:[s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":"Launch target type",children:[{id:"workspace",label:"Workspace",desc:"Normal session"},{id:"mesh",label:"Mesh",desc:"Coordinator session"}].map(ee=>s.jsxs("button",{type:"button",role:"radio","aria-checked":j===ee.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${j===ee.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{f(ee.id),P(""),ee.id==="mesh"&&b&&I!==b.id&&!R&&H(b.id)},disabled:de,children:[s.jsx("div",{className:"text-sm font-semibold",children:ee.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:ee.desc})]},ee.id))}),j==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:w,onChange:ee=>{const Re=ee.target.value;S(Re),Re==="__custom__"?Ce():P("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:de,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),x.map(ee=>s.jsxs("option",{value:ee.id,children:[ee.id===k?"⭐ ":"",id(ee.path,ee.label)||ee.path]},ee.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:w==="__home__"?"Launch without a workspace.":le||"Select a workspace folder."}),w==="__custom__"&&le&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ce,disabled:de,children:[s.jsx(Os,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ge,disabled:de||ut,children:ut?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[R&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!R&&W&&s.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:W}),!R&&!W&&N.length===0&&s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker."}),N.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:N.map(ee=>s.jsxs("button",{type:"button",role:"radio","aria-checked":C===ee.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${C===ee.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(ee.id),disabled:de,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:ee.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[ee.repoIdentity||"Repo mesh",typeof ee.nodesCount=="number"?` · ${ee.nodesCount} node${ee.nodesCount===1?"":"s"}`:""]}),ee.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",ee.workspace]})]},ee.id))}),z&&s.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),s.jsx(yv,{workspaceMode:j,activeKind:L,cliEnabled:We.length>0,ideEnabled:Ye.length>0,acpEnabled:rt.length>0,busy:de,onSelect:B}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:L==="ide"?"Choose IDE":L==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[tt.map(ee=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${F===ee.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>E(ee.id),disabled:de,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:ee.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ee.meta})]},ee.id)),tt.length===0&&s.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),j==="mesh"&&re&&s.jsx(zu,{setup:re,providerName:(G==null?void 0:G.displayName)||(G==null?void 0:G.name)||F}),j!=="mesh"&&L!=="ide"&&s.jsxs(Tn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:D,onChange:ee=>K(ee.target.value),placeholder:"Optional flags...",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:de}),J.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:J.map(ee=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>K(ee),disabled:de,title:ee,children:ee},ee))})]}),j!=="mesh"&&L==="cli"&&s.jsx(gv,{busy:de,savedSessionsLoading:q,savedSessionsError:pe,selectedSession:fe,onRefresh:()=>{!b||!F||V(b.id,F)},onOpenHistory:()=>{!b||!F||(be(!0),xv({hasLoadedInitialResults:ge,isLoading:q})&&V(b.id,F))},onClearSelection:()=>he("")}),oe&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${oe.includes("saved")||oe.includes("requested")||oe.includes("Manual MCP setup")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:oe})]}),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:r,disabled:de,children:"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:Be,disabled:de||(j==="mesh"?!C||!F||L!=="cli"||R:!L||!F||w==="__custom__"&&!le),children:[s.jsx(Gc,{size:14}),de?ct:ht]})]})]})}),_e&&s.jsx(fi,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:De,directories:$e,busy:Je,error:Ze,onClose:()=>se(!1),onNavigate:Ke,onConfirm:ee=>{g(ee),Te(ee),S("__custom__"),se(!1)}}),X&&ke&&s.jsx(zd,{activeConv:ke,ides:[],isCreatingChat:!1,isRefreshingHistory:q,savedSessions:we,isSavedSessionsLoading:q,isResumingSavedSessionId:ce,savedHistoryFilters:ue,missingWorkspaceResumePath:le||null,onSavedHistoryFiltersChange:U,onClose:()=>be(!1),onNewChat:()=>{he(""),be(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!b||!F||V(b.id,F)},onResumeSavedSession:ee=>{if(!b||!F||ce||!ee.canResume)return;const Re=ne(ee);he(ee.providerSessionId),O(ee),ie(ee.providerSessionId),be(!1),me(!0),P(""),i(b.id,"cli",F,{workspaceId:Re.workspaceId,workspacePath:Re.workspacePath,resumeSessionId:ee.providerSessionId}).then(ae=>{if(!ae.ok){P(ae.error||"Could not resume session");return}r()}).finally(()=>{me(!1),ie(ae=>ae===ee.providerSessionId?null:ae)})}})]}):null}function Gu(e){return e.ahead<=0&&e.behind<=0?null:e.ahead>0&&e.behind>0?`ahead ${e.ahead} / behind ${e.behind}`:e.behind>0?`behind ${e.behind}`:`ahead ${e.ahead}`}function bi(e){if(e.type==="submoduleNode")return e.outOfSync||e.error?{label:"submodule drift",tone:"danger"}:e.dirty?{label:"submodule dirty",tone:"warn"}:null;const t=e.branchConvergence;if((t==null?void 0:t.status)==="not_mergeable")return{label:e.hasConflicts?"conflicts present":"dirty workspace",tone:"danger"};if((t==null?void 0:t.status)==="blocked_review"){if(t.reason==="upstream_unverified")return{label:"upstream unverified",tone:"warn"};const r=Gu(e);return r?{label:r,tone:"danger"}:!e.upstream&&e.branch&&e.branch!==t.defaultBranch?{label:"push branch",tone:"warn"}:{label:"blocked review",tone:"danger"}}return(t==null?void 0:t.status)==="pushed_feature_branch_needs_merge"?{label:"needs merge",tone:"warn"}:(t==null?void 0:t.status)==="cleanup_candidate"?{label:"refine worktree",tone:"info"}:e.isOrphan?{label:"needs follow-up",tone:"warn"}:e.health==="offline"?{label:"offline",tone:"danger"}:null}function gi(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function Vu(e){var t;return!gi(e)||e.type==="defaultBranchNode"?!1:!!((t=e.branchConvergence)!=null&&t.needsConvergence||e.isOrphan||e.hasConflicts||e.outOfSync||e.error||e.health==="offline"||e.health==="degraded"||e.health==="wrong_branch"||e.dirty)}function fn(e){return[...new Set(e.filter(t=>!!t))]}function wv(e){const t=e.nodes.find(i=>i.type==="defaultBranchNode")??null,r=(t==null?void 0:t.branch)??null,n=e.nodes.filter(i=>i.type!=="defaultBranchNode"&&i.type!=="submoduleNode"&&!i.isOrphan&&!!r&&i.branch===r),a=e.nodes.filter(i=>i.type!=="submoduleNode"&&!i.isOrphan),o=e.nodes.filter(i=>i.type!=="submoduleNode");return t||n.length>0?fn([t==null?void 0:t.id,...n.map(i=>i.id)]):a.length>0?fn(a.map(i=>i.id)):o.length>0?fn(o.map(i=>i.id)):fn(e.nodes.map(i=>i.id))}function qu(e){const t=[...e.nodes].sort((n,a)=>n.id.localeCompare(a.id)).map(n=>[n.id,n.type,n.branch??"",n.parentNodeId??"",n.submodulePath??""].join(":")).join("|"),r=[...e.edges].sort((n,a)=>n.id.localeCompare(a.id)).map(n=>[n.id,n.source,n.target,n.type].join(":")).join("|");return`${e.meshId}::${t}::${r}`}function jv(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${qu(e)}::${n}x${a}`}const kv={default:"border-white/10 bg-white/[0.04] text-slate-200",good:"border-emerald-400/20 bg-emerald-500/10 text-emerald-200",warn:"border-amber-400/20 bg-amber-500/10 text-amber-100",danger:"border-rose-400/20 bg-rose-500/10 text-rose-100",info:"border-sky-400/20 bg-sky-500/10 text-sky-100"},Sv={default:"border-slate-300 bg-white/95 text-slate-700",good:"border-emerald-300 bg-emerald-50 text-emerald-700",warn:"border-amber-300 bg-amber-50 text-amber-700",danger:"border-rose-300 bg-rose-50 text-rose-700",info:"border-sky-300 bg-sky-50 text-sky-700"},Nv={default:"border-white/10 bg-white/[0.04] text-slate-200 hover:bg-white/[0.08]",info:"border-sky-400/25 bg-sky-500/10 text-sky-100 hover:bg-sky-500/16",success:"border-emerald-400/25 bg-emerald-500/10 text-emerald-100 hover:bg-emerald-500/16"},Cv={default:"border-slate-300 bg-white text-slate-700 hover:bg-slate-50",info:"border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100",success:"border-emerald-300 bg-emerald-50 text-emerald-700 hover:bg-emerald-100"};function Ys(e){return e==="light"?{theme:e,isDark:!1,flowColorMode:"light",textPrimary:"text-slate-900",textSecondary:"text-slate-700",textMuted:"text-slate-500",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-slate-200 bg-[radial-gradient(circle_at_top,_rgba(14,165,233,0.16),_rgba(248,250,252,0.98)_42%,_rgba(255,255,255,1))]",graphStatChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-slate-700 shadow-sm",graphHintChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-[10px] text-slate-500 shadow-sm",graphControlsClass:"!bottom-4 !left-4 !shadow-md",graphBackgroundDotColor:"rgba(148, 163, 184, 0.34)",edgeLabelTextColor:"#334155",edgeLabelBackgroundColor:"rgba(255, 255, 255, 0.96)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.45)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[rgba(148,163,184,0.22)] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"flex h-[100dvh] w-full flex-col overflow-hidden bg-white md:h-[min(90vh,960px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-slate-200 md:bg-white/98 md:shadow-[0_28px_120px_rgba(148,163,184,0.28)]",dialogHeaderClass:"flex shrink-0 flex-col gap-3 border-b border-slate-200 bg-white/96 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-slate-900 md:text-xl",dialogKickerClass:"rounded-full border border-slate-300 bg-slate-50 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-600",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-500",dialogRefreshedChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1.5 text-xs text-slate-600",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-300 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",dialogBodyClass:"min-h-0 flex-1 overflow-y-auto bg-[linear-gradient(180deg,rgba(248,250,252,0.98),rgba(241,245,249,0.96))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-slate-300 bg-white/90 px-6 text-center text-sm text-slate-500",cardClass:"rounded-2xl border border-slate-200 bg-white/95 shadow-sm",cardHeaderClass:"border-b border-slate-200 px-4 py-3",cardTitleClass:"text-sm font-semibold text-slate-900",cardSubtitleClass:"mt-1 text-xs text-slate-500",rowClass:"flex items-start justify-between gap-3 border-b border-slate-200/80 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"text-slate-500",rowValueClass:"max-w-[65%] break-all text-right text-slate-800",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-slate-200 bg-white/95 p-4 shadow-md md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-slate-200 bg-white/95 p-4 text-xs text-slate-500 shadow-sm md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-900",panelCloseButtonClass:"text-xs text-slate-500 hover:text-slate-900",panelFieldRowClass:"flex justify-between gap-3 border-b border-slate-200/80 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-500",panelFieldValueClass:"break-all text-right font-medium text-slate-700",infoCalloutClass:"mt-1 rounded border border-sky-300 bg-sky-50 px-2 py-1.5 text-[10px] text-sky-700",badge:t=>Sv[t],actionButton:t=>Cv[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",graphStatChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-slate-200",graphHintChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-[10px] text-slate-300",graphControlsClass:"!bottom-4 !left-4 !shadow-lg",graphBackgroundDotColor:"rgba(148, 163, 184, 0.22)",edgeLabelTextColor:"#cbd5e1",edgeLabelBackgroundColor:"rgba(2, 6, 23, 0.86)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.2)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[#030617]/[0.58] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"flex h-[100dvh] w-full flex-col overflow-hidden bg-slate-950 md:h-[min(90vh,960px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-white/10 md:bg-slate-950/96 md:shadow-[0_28px_120px_rgba(2,6,23,0.46)]",dialogHeaderClass:"flex shrink-0 flex-col gap-3 border-b border-white/10 bg-slate-950/92 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-white md:text-xl",dialogKickerClass:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-300",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-400",dialogRefreshedChipClass:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 bg-white/6 text-slate-300 transition hover:bg-white/10 hover:text-white",dialogBodyClass:"min-h-0 flex-1 overflow-y-auto bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-white/10 bg-white/[0.03] px-6 text-center text-sm text-slate-400",cardClass:"rounded-2xl border border-white/10 bg-white/[0.04]",cardHeaderClass:"border-b border-white/10 px-4 py-3",cardTitleClass:"text-sm font-semibold text-white",cardSubtitleClass:"mt-1 text-xs text-slate-400",rowClass:"flex items-start justify-between gap-3 border-b border-white/5 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"text-slate-400",rowValueClass:"max-w-[65%] break-all text-right text-slate-100",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-white/10 bg-white/[0.04] p-4 shadow-lg md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-white/10 bg-white/[0.04] p-4 text-xs text-slate-400 md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-100",panelCloseButtonClass:"text-xs text-slate-400 hover:text-slate-100",panelFieldRowClass:"flex justify-between gap-3 border-b border-white/6 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-400",panelFieldValueClass:"break-all text-right font-medium text-slate-200",infoCalloutClass:"mt-1 rounded bg-blue-500/10 border border-blue-500/20 px-2 py-1.5 text-[10px] text-blue-300",badge:t=>kv[t],actionButton:t=>Nv[t]}}const Us={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,layerGap:220,nodeGap:82,edgeLabelBuffer:180,placeholderTopOffset:0},Fr={worktreeCardWidth:188,submoduleCardWidth:188,minWorktreeCardHeight:88,minSubmoduleCardHeight:88,maxEstimatedCardHeight:178,layerGap:160,nodeGap:52,edgeLabelBuffer:120},Mv={maxWidth:180};function Iv(e){return e==="TB"?"DOWN":"RIGHT"}function yi(e,t){return{"elk.algorithm":"layered","elk.direction":Iv(t),"elk.edgeRouting":"ORTHOGONAL","elk.spacing.nodeNode":String(e.nodeGap),"elk.layered.spacing.nodeNodeBetweenLayers":String(e.layerGap),"elk.layered.spacing.edgeNodeBetweenLayers":String(e.edgeLabelBuffer),"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.layered.mergeEdges":"false","elk.randomSeed":"1"}}const Av=yi(Us,"LR");yi(Fr,"LR");function Tv(e){const t=e.nodes.length;if(t<8)return"LR";const r=new Map;for(const a of e.edges)r.set(a.source,(r.get(a.source)??0)+1);let n=0;for(const a of r.values())a>n&&(n=a);return n>=Math.max(6,Math.floor(t/2))?"TB":"LR"}const _v=new Zm;function Tr(e,t=!1){const r=t?Fr:Us;return e.type==="submoduleNode"?r.submoduleCardWidth:r.worktreeCardWidth}function _n(e){var r;if(e.type==="defaultBranchNode")return e.nextStepHint||"Default branch anchor";if(e.type==="submoduleNode"){const n=[e.machineLabel?`parent ${e.machineLabel}`:null];return e.outOfSync?n.push("out of sync"):e.dirty?n.push("local changes"):n.push("synced"),n.filter(Boolean).join(" · ")}const t=[];if(e.upstream&&t.push(e.upstream),e.upstream&&e.upstreamStatus!=="fresh")t.push("upstream unverified");else{const n=Gu(e);n&&t.push(n)}return e.activeSessionCount>0&&t.push(`${e.activeSessionCount} session${e.activeSessionCount===1?"":"s"}`),e.dirtyFiles>0&&t.push(`${e.dirtyFiles} dirty`),e.hasConflicts&&t.push("conflicts"),t.length===0?(r=e.branchConvergence)!=null&&r.needsConvergence?"Needs follow-up":"Clean and even with upstream":t.join(" · ")}function Yu(e,t=!1){const r=t?Fr:Us,n=Tr(e,t),a=t?e.type==="submoduleNode"?20:22:e.type==="submoduleNode"?24:30,o=t?(e.type==="submoduleNode",2):e.type==="submoduleNode"?2:3,i=Math.ceil(Lv(e)/o),c=xn(e.label,a,2),u=xn(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,a,2),m=xn(_n(e),a+(t?1:4),t?2:3),d=bi(e),h=Vu(e)?gi(e):null,p=t?0:xn(h,Math.max(24,Math.floor(n/8)),4),y=t?40+c*16+u*12+(d?22:0)+Math.max(0,i-1)*18+Math.max(18,m*16):52+c*18+u*14+(d?30:0)+i*24+Math.max(22,m*18)+(p>0?22+p*16:0),b=e.type==="submoduleNode"?r.minSubmoduleCardHeight:r.minWorktreeCardHeight;return Math.min(r.maxEstimatedCardHeight,Math.max(b,Math.ceil(y)))}function xn(e,t,r){const n=(e||"").trim();return n?Math.max(1,Math.min(r,Math.ceil(n.length/t))):0}function Lv(e){let t=1;return e.type==="submoduleNode"&&(t+=1),e.branch&&e.type!=="submoduleNode"&&(t+=1),e.submoduleCommit&&e.type==="submoduleNode"&&(t+=1),e.dirty&&(t+=1),e.outOfSync&&(t+=1),e.hasConflicts&&(t+=1),e.type!=="submoduleNode"&&e.upstream&&e.upstreamStatus!=="fresh"&&(t+=1),e.isOrphan&&(t+=1),t}function Rv(e,t){return e.type==="defaultBranchNode"&&t.type!=="defaultBranchNode"?-1:t.type==="defaultBranchNode"&&e.type!=="defaultBranchNode"||e.type==="submoduleNode"&&t.type!=="submoduleNode"?1:t.type==="submoduleNode"&&e.type!=="submoduleNode"?-1:e.branch&&t.branch&&e.branch!==t.branch?e.branch.localeCompare(t.branch):e.branch&&!t.branch?-1:!e.branch&&t.branch?1:e.label.localeCompare(t.label)||e.id.localeCompare(t.id)}function Pv(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function Dv(e,t,r,n=!0){return{id:e.id,type:"meshNode",position:{x:t,y:r},graphNode:e,selected:!1,draggable:!1,selectable:n}}function $v(e,t,r){return{id:e.id,x:t,y:r,width:Tr(e),height:Yu(e)}}function Ev(e,t){return{id:`${e.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:t.repoIdentity,branch:e.branch,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:null,locality:"unknown",health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],nextStepHint:"Waiting for worktree nodes to report live mesh status.",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{nodeId:`${e.id}__placeholder`,machineLabel:"",workspace:t.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}}function Xu(e){const t=[...e.nodes].sort(Rv),r=t.find(a=>a.type==="defaultBranchNode")??null,n=t.some(a=>a.id!==(r==null?void 0:r.id)&&a.type!=="submoduleNode");return!r||n?t:[...t,Ev(r,e)]}function Bv(e,t=Av,r=!1,n="LR"){const a=Xu(e),o=new Set(a.map(u=>u.id)),i=a.map(u=>({id:u.id,width:Tr(u,r),height:Yu(u,r)})),c=e.edges.filter(u=>o.has(u.source)&&o.has(u.target)).sort(Pv).map(u=>({id:u.id,sources:[u.source],targets:[u.target]}));return{id:`${e.meshId||"mesh"}__elk_root`,layoutOptions:{...t},children:i,edges:c}}function Ov(e,t=!1){const r=[...new Set(e.map(a=>Math.round(a.x)))].sort((a,o)=>a-o),n=t?Fr.layerGap:Us.layerGap;return r.length<2?n:Math.min(...r.slice(1).map((a,o)=>a-r[o]))}async function Fv(e,t=!1,r="LR"){var p,y;const a=yi(t?Fr:Us,r),o=Xu(e),i=new Map(o.map(b=>[b.id,b])),c=await _v.layout(Bv(e,a,t,r)),u=(c.children??[]).map(b=>{const x=i.get(b.id);return x?Dv(x,Math.round(b.x??0),Math.round(b.y??Us.placeholderTopOffset),!b.id.endsWith("__placeholder")):null}).filter(Boolean),m=new Map(o.map((b,x)=>[b.id,x]));u.sort((b,x)=>(m.get(b.id)??0)-(m.get(x.id)??0));const d=u.map(b=>$v(b.graphNode,b.position.x,b.position.y)),h=new Map;for(const b of c.edges??[]){const x=b.sections;if(!x||x.length===0)continue;const k=x[0],j=(p=b.sources)==null?void 0:p[0],f=(y=b.targets)==null?void 0:y[0];if(!j||!f)continue;const w=[];w.push({x:Math.round(k.startPoint.x),y:Math.round(k.startPoint.y)});for(const S of k.bendPoints??[])w.push({x:Math.round(S.x),y:Math.round(S.y)});w.push({x:Math.round(k.endPoint.x),y:Math.round(k.endPoint.y)}),h.set(b.id,{id:b.id,source:j,target:f,points:w})}return{nodes:u,bounds:d,edgeRoutes:h,columnGap:Ov(d,t),layoutOptions:{...a}}}function Hv(e){var t,r;return[e.id,e.type,e.label,e.branch??"",e.upstream??"",e.upstreamStatus??"",e.daemonId??"",e.machineId??"",e.machineLabel??"",e.locality,e.health,e.ahead,e.behind,e.dirty?1:0,e.dirtyFiles,e.hasConflicts?1:0,e.activeSessionCount,e.sessionDetails.map(n=>[n.sessionId,n.providerType??"",n.state??"",n.chatStatus??"",n.lifecycle??"",n.role??"",n.isSelfCoordinator?1:0,n.statusNote??"",n.startedAt??"",n.createdAt??""].join("/")).join(","),e.isOrphan?1:0,e.outOfSync?1:0,e.snapshotCompleteness,((t=e.branchConvergence)==null?void 0:t.status)??"",(r=e.branchConvergence)!=null&&r.needsConvergence?1:0,e.nextStepHint??"",e.error??"",e.parentNodeId??"",e.submodulePath??"",e.submoduleCommit??""].join("|")}function Ju(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function Wv(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(Hv),...e.edges.map(Ju)].join("::")}function Kv(e){return[e.meshId,e.nodes.length,e.edges.length,...e.nodes.map(t=>{var r,n;return[t.id,t.type,t.label,t.branch??"",t.machineLabel??"",t.locality,t.health,t.dirty?1:0,t.dirtyFiles,t.hasConflicts?1:0,t.activeSessionCount,t.isOrphan?1:0,t.outOfSync?1:0,t.snapshotCompleteness,((r=t.branchConvergence)==null?void 0:r.status)??"",(n=t.branchConvergence)!=null&&n.needsConvergence?1:0,t.nextStepHint??"",t.parentNodeId??"",t.submodulePath??"",t.submoduleCommit??""].join("|")}),...e.edges.map(Ju)].join("::")}const Uv=7,vi=l.createContext(Ys("dark")),Qu=l.createContext(!1),Zu=l.createContext("LR"),em={overflowWrap:"anywhere",wordBreak:"break-word"},zv={...em,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},Gv={...em,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function tm(e){return e.activeSessionCount>0}function Vv(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function Zl(e,t,r){const n=tm(e),a=Vv(e);let o;t?o="border-cyan-400/70 shadow-[0_0_0_1px_rgba(34,211,238,0.35),0_24px_60px_rgba(8,145,178,0.18)]":n?o=r?"border-emerald-400/40 shadow-[0_0_0_1px_rgba(52,211,153,0.18),0_18px_48px_rgba(3,7,18,0.22)]":"border-emerald-400/60 shadow-[0_0_0_1px_rgba(52,211,153,0.2),0_18px_48px_rgba(148,163,184,0.20)]":a?o=r?"border-white/6 shadow-[0_12px_32px_rgba(3,7,18,0.16)] opacity-60":"border-slate-200/70 shadow-[0_12px_32px_rgba(148,163,184,0.14)] opacity-60":o=r?"border-white/10 shadow-[0_18px_48px_rgba(3,7,18,0.22)]":"border-slate-300/90 shadow-[0_18px_48px_rgba(148,163,184,0.20)]";const i=bi(e);if((i==null?void 0:i.tone)==="danger")return`${o} ${r?"bg-rose-500/12":"bg-rose-50/95"}`;if((i==null?void 0:i.tone)==="warn")return`${o} ${r?"bg-amber-500/10":"bg-amber-50/95"}`;if((i==null?void 0:i.tone)==="info")return`${o} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;switch(e.health){case"online":return`${o} ${r?n?"bg-emerald-500/10":"bg-emerald-500/8":n?"bg-emerald-50":"bg-emerald-50/95"}`;case"dirty":return`${o} ${r?"bg-amber-500/8":"bg-amber-50/95"}`;case"degraded":return`${o} ${r?"bg-rose-500/10":"bg-rose-50/95"}`;case"wrong_branch":return`${o} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;case"offline":return`${o} ${r?"bg-slate-500/10":"bg-slate-100/90"}`;default:return`${o} ${r?"bg-slate-950/78":"bg-white/96"}`}}function At(e,t){switch(e){case"health":return t?"border-white/10 bg-slate-950/60 text-slate-200":"border-slate-300 bg-white/95 text-slate-700";case"dirty":return t?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700";case"conflict":return t?"border-rose-400/25 bg-rose-500/10 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700";case"orphan":return t?"border-fuchsia-400/25 bg-fuchsia-500/10 text-fuchsia-200":"border-fuchsia-300 bg-fuchsia-50 text-fuchsia-700";case"submodule":return t?"border-violet-400/25 bg-violet-500/10 text-violet-200":"border-violet-300 bg-violet-50 text-violet-700";case"meta":default:return t?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}}function ec(e,t){switch(e){case"danger":return t?"border-rose-400/35 bg-rose-500/14 text-rose-50":"border-rose-300 bg-rose-50 text-rose-700";case"warn":return t?"border-amber-400/35 bg-amber-500/14 text-amber-50":"border-amber-300 bg-amber-50 text-amber-700";case"info":return t?"border-violet-400/35 bg-violet-500/14 text-violet-50":"border-violet-300 bg-violet-50 text-violet-700";case"good":default:return t?"border-emerald-400/35 bg-emerald-500/12 text-emerald-50":"border-emerald-300 bg-emerald-50 text-emerald-700"}}function tc(e){switch(e){case"online":return"#34d399";case"dirty":return"#fbbf24";case"degraded":return"#fb7185";case"wrong_branch":return"#a78bfa";case"offline":return"#94a3b8";default:return"#64748b"}}function qv(e){return e.replace(/_/g," ")}function Gt(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const r=t.toLowerCase().replace(/[\s-]+/g,"_");return r.includes("approval")?"awaiting approval":r.includes("generating")||r.includes("running")||r.includes("busy")?"generating":r.includes("failed")||r.includes("stopped")||r.includes("interrupted")?r.replace(/_/g," "):r.includes("idle")||r.includes("ready")||r.includes("waiting_input")?"idle":r.replace(/_/g," ")}function za(e,t){const r=Gt(e);return r.includes("approval")?t?"border-amber-400/30 bg-amber-500/12 text-amber-100":"border-amber-300 bg-amber-50 text-amber-700":r==="generating"?t?"border-cyan-400/30 bg-cyan-500/12 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700":r==="idle"?t?"border-emerald-400/30 bg-emerald-500/12 text-emerald-100":"border-emerald-300 bg-emerald-50 text-emerald-700":r.includes("failed")||r.includes("stopped")||r.includes("interrupted")?t?"border-rose-400/30 bg-rose-500/12 text-rose-100":"border-rose-300 bg-rose-50 text-rose-700":At("health",t)}function Yv(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function sc(e){const t=Yv(e);if(t===null)return"runtime age not reported";const r=Math.max(0,Math.floor((Date.now()-t)/1e3));if(r<60)return`${r}s`;const n=Math.floor(r/60);if(n<60)return`${n}m`;const a=Math.floor(n/60);return a<48?`${a}h ${n%60}m`:`${Math.floor(a/24)}d ${a%24}h`}function Ga(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function cr(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function Xv(e){if(e.sessionDetails.length===0)return null;const t=e.sessionDetails.filter(o=>Gt(o)==="generating").length,r=e.sessionDetails.filter(o=>o.isSelfCoordinator).length,n=e.sessionDetails.length-r,a=[`${e.sessionDetails.length} chat${e.sessionDetails.length===1?"":"s"}`];return t>0&&a.push(`${t} generating`),r>0&&a.push(r===1?"coordinator attached":`${r} coordinators`),n>0&&a.push(`${n} worker${n===1?"":"s"}`),t===0&&r>0&&a.push("sampled status"),a.join(" · ")}function rc(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function Jv(e){return e.locality==="remote"?"meta":"health"}function Qv({data:e,selected:t}){const r=l.useContext(vi),n=l.useContext(Qu),a=l.useContext(Zu),o=e.graphNode,i=o.type==="defaultBranchNode",c=o.type==="submoduleNode",u=Vu(o),m=i?"default branch anchor":c?o.submodulePath||"submodule checkout":[o.machineLabel,rc(o.locality)].filter(Boolean).join(" · ")||o.workspace,d=o.submoduleCommit?o.submoduleCommit.slice(0,7):null,h=bi(o),p=gi(o),y=tm(o),b=o.sessionDetails,x=o.sessionDetails,k=Xv(o),j=o.sessionDetails.map(S=>{const v=Gt(S),g=S.providerType||"provider unknown",N=cr(S),M=S.startedAt||S.createdAt||null,C=S.statusNote?` · ${S.statusNote}`:"";return`Session: ${S.sessionId} · ${g} · ${v} · ${N} · ${sc(M)}${C}`});if(n)return s.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${Zl(o,t,r.isDark)}`,style:{width:Tr(o,!0)},title:[o.label,o.branch?`Branch: ${o.branch}`:null,o.machineLabel?`Machine: ${o.machineLabel}`:null,o.workspace?`Workspace: ${o.workspace}`:null,h?`Status: ${h.label}`:null,_n(o),...j].filter(Boolean).join(`
|
|
66
66
|
`),children:[s.jsx(Qr,{type:"target",position:a==="TB"?Zt.Top:Zt.Left,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-xs font-semibold leading-4 ${r.textPrimary}`,children:o.label}),!i&&s.jsx("div",{className:`truncate text-[10px] leading-3.5 ${r.textMuted}`,children:m})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[y&&s.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${r.isDark?"bg-emerald-400":"bg-emerald-500"} animate-pulse`,"aria-label":"active session"}),s.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full",style:{backgroundColor:tc(o.health)},"aria-hidden":!0})]})]}),h&&s.jsx("div",{className:`mt-1.5 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[9px] font-semibold uppercase tracking-[0.14em] ${ec(h.tone,r.isDark)}`,title:h.label,children:s.jsx("span",{className:"truncate",children:h.label})}),!h&&o.branch&&!c&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[10px] ${At("meta",r.isDark)} rounded-full border px-2 py-0.5 inline-block`,title:o.branch,children:o.branch}),k&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[9px] ${r.isDark?"text-cyan-100/85":"text-sky-700"}`,title:j.join(`
|
|
67
67
|
`),children:k}),x.length>0&&s.jsx("div",{className:"mt-1.5 flex max-h-28 min-w-0 flex-col gap-1 overflow-y-auto pr-1",children:x.map(S=>s.jsxs("div",{className:`min-w-0 rounded-md border px-1.5 py-1 ${r.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/80"}`,title:[`Session ID: ${S.sessionId}`,S.providerType?`Provider: ${S.providerType}`:null,`Status: ${Gt(S)}`,`Role: ${cr(S)}`].filter(Boolean).join(`
|
|
68
68
|
`),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-1.5",children:[s.jsx("span",{className:`min-w-0 truncate text-[9px] ${r.textMuted}`,children:S.providerType||"provider unknown"}),s.jsx("span",{className:`shrink-0 rounded-full border px-1 py-0 text-[8px] font-semibold uppercase tracking-[0.1em] ${za(S,r.isDark)}`,children:Gt(S)})]}),s.jsxs("div",{className:`mt-0.5 flex min-w-0 items-center gap-1.5 text-[8px] ${r.textMuted}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",children:Ga(S.sessionId)}),s.jsx("span",{className:"shrink-0",children:cr(S)})]})]},S.sessionId))}),s.jsx(Qr,{type:"source",position:a==="TB"?Zt.Bottom:Zt.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]});const f=t,w=[o.label,m,h?`Status: ${h.label}`:null,_n(o),o.branch?`Branch: ${o.branch}`:null,o.dirty?c?"Local changes":`${o.dirtyFiles} dirty`:null,o.hasConflicts?"Has conflicts":null,o.outOfSync?"Out of sync":null,!c&&o.upstream&&o.upstreamStatus!=="fresh"?"Upstream unverified":null,o.isOrphan?"Needs follow-up":null,u&&p?`Note: ${p}`:null,...j].filter(Boolean).join(`
|
|
69
69
|
`);return s.jsxs("div",{className:`group rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all ${Zl(o,t,r.isDark)}`,style:{width:Tr(o)},title:w,children:[s.jsx(Qr,{type:"target",position:a==="TB"?Zt.Top:Zt.Left,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),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:`truncate text-sm font-semibold ${r.textPrimary}`,children:o.label}),s.jsx("div",{className:`truncate text-[11px] ${r.textMuted}`,children:m})]}),s.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 shrink-0",children:[y&&s.jsx("span",{className:`h-2 w-2 rounded-full ${r.isDark?"bg-emerald-400":"bg-emerald-500"} animate-pulse`,"aria-label":"active session"}),s.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:tc(o.health)},"aria-hidden":!0})]})]}),h?s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${ec(h.tone,r.isDark)}`,title:h.label,children:s.jsx("span",{className:"truncate",children:h.label})}):o.branch&&!c?s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[10px] ${At("meta",r.isDark)}`,title:o.branch,children:s.jsx("span",{className:"truncate",children:o.branch})}):null,k&&s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[10px] font-medium ${r.isDark?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}`,title:j.join(`
|
|
70
70
|
`),children:s.jsx("span",{className:"truncate",children:k})}),x.length>0&&s.jsx("div",{className:"mt-2 flex max-h-44 min-w-0 flex-col gap-1.5 overflow-y-auto pr-1",children:x.map(S=>{const v=cr(S);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/85"}`,title:[`Session ID: ${S.sessionId}`,S.providerType?`Provider: ${S.providerType}`:null,`Status: ${Gt(S)}`,`Role: ${v}`].filter(Boolean).join(`
|
|
71
71
|
`),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate text-[10px] ${r.textMuted}`,children:S.providerType||"provider unknown"}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${za(S,r.isDark)}`,children:Gt(S)})]}),s.jsxs("div",{className:`mt-0.5 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",children:Ga(S.sessionId)}),s.jsx("span",{children:v})]})]},S.sessionId)})}),s.jsxs("div",{className:`overflow-hidden transition-all ${f?"mt-3 max-h-[400px] opacity-100":"mt-0 max-h-0 opacity-0 group-hover:mt-3 group-hover:max-h-[400px] group-hover:opacity-100"}`,children:[s.jsxs("div",{className:"flex min-w-0 flex-wrap gap-1.5 text-[10px]",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${At("health",r.isDark)}`,children:qv(o.health)}),c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${At("submodule",r.isDark)}`,children:"submodule"}),!i&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${At(Jv(o),r.isDark)}`,children:rc(o.locality)}),d&&c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${At("meta",r.isDark)}`,children:d}),o.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${At("dirty",r.isDark)}`,children:c?"local changes":`${o.dirtyFiles} dirty`}),o.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${At("conflict",r.isDark)}`,children:"out of sync"}),o.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${At("conflict",r.isDark)}`,children:"conflicts"}),!c&&o.upstream&&o.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${At("orphan",r.isDark)}`,children:"upstream unverified"}),o.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${At("orphan",r.isDark)}`,children:"needs follow-up"})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,style:zv,children:_n(o)}),b.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[9px] font-semibold uppercase tracking-[0.16em] ${r.textMuted}`,children:"Attached Chats"}),s.jsx("div",{className:"flex max-h-56 flex-col gap-1.5 overflow-y-auto pr-1",children:b.map(S=>{const v=S.startedAt||S.createdAt||null,g=cr(S);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-white/8 bg-white/[0.035]":"border-slate-200 bg-white/80"}`,title:[`Session ID: ${S.sessionId}`,S.providerType?`Provider: ${S.providerType}`:null,`Status: ${Gt(S)}`,`Role: ${g}`,v?`Started: ${v}`:"Started: not reported",S.statusNote?`Note: ${S.statusNote}`:null].filter(Boolean).join(`
|
|
72
|
-
`),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 ${r.textPrimary}`,children:Ga(S.sessionId)}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${za(S,r.isDark)}`,children:Gt(S)})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"truncate",children:S.providerType||"provider unknown"}),s.jsx("span",{children:g}),s.jsx("span",{children:sc(v)})]}),S.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${r.textMuted}`,children:S.statusNote})]},S.sessionId)})})]}),u&&p&&s.jsx("div",{className:`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${r.isDark?"border-cyan-400/15 bg-cyan-500/8 text-cyan-50/90":"border-sky-300 bg-sky-50 text-sky-700"}`,style:Gv,children:p})]}),s.jsx(Qr,{type:"source",position:a==="TB"?Zt.Bottom:Zt.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const Zv={meshNode:Qv},ew=8;function tw(e){if(e.length<2)return null;if(e.length===2){const[m,d]=e;return{d:`M ${m.x},${m.y} L ${d.x},${d.y}`,labelX:(m.x+d.x)/2,labelY:(m.y+d.y)/2}}const t=ew,r=[`M ${e[0].x},${e[0].y}`];for(let m=1;m<e.length-1;m+=1){const d=e[m-1],h=e[m],p=e[m+1],y=Math.sign(h.x-d.x),b=Math.sign(h.y-d.y),x=Math.sign(p.x-h.x),k=Math.sign(p.y-h.y),j=Math.hypot(h.x-d.x,h.y-d.y),f=Math.hypot(p.x-h.x,p.y-h.y),w=Math.min(t,j/2,f/2);if(w<1||y===x&&b===k){r.push(`L ${h.x},${h.y}`);continue}const S=h.x-y*w,v=h.y-b*w,g=h.x+x*w,N=h.y+k*w;r.push(`L ${S},${v}`),r.push(`Q ${h.x},${h.y} ${g},${N}`)}const n=e[e.length-1];r.push(`L ${n.x},${n.y}`);let a=0;const o=[0];for(let m=1;m<e.length;m+=1)a+=Math.hypot(e[m].x-e[m-1].x,e[m].y-e[m-1].y),o.push(a);const i=a/2;let c=e[0].x,u=e[0].y;for(let m=1;m<e.length;m+=1)if(o[m]>=i){const d=o[m]-o[m-1],h=d===0?0:(i-o[m-1])/d;c=e[m-1].x+(e[m].x-e[m-1].x)*h,u=e[m-1].y+(e[m].y-e[m-1].y)*h;break}return{d:r.join(" "),labelX:c,labelY:u}}function sw(e){const t=e.data.routePoints;if(t&&t.length>=2){const o=tw(t);if(o)return[o.d,o.labelX,o.labelY]}const r={sourceX:e.sourceX,sourceY:e.sourceY,sourcePosition:e.sourcePosition,targetX:e.targetX,targetY:e.targetY,targetPosition:e.targetPosition},n=e.data.graphEdge;let a;return n.type==="parentBranch"?a=mh(r):n.type==="worktreeLink"||n.type==="submoduleLink"||n.type==="cloneLink"?a=dh(r):a=uh(r),[a[0],a[1],a[2]]}function rw(e,t){const r="nodrag nopan rounded-md border px-2 py-1 text-[10px] font-semibold shadow-sm backdrop-blur-sm";switch(e.type){case"orphanLink":return t?`${r} border-orange-400/35 bg-orange-500/14 text-orange-100`:`${r} border-orange-300 bg-orange-50 text-orange-700`;case"submoduleLink":return t?`${r} border-violet-400/30 bg-violet-500/14 text-violet-100`:`${r} border-violet-300 bg-violet-50 text-violet-700`;case"sessionLink":return t?`${r} border-emerald-400/30 bg-emerald-500/14 text-emerald-100`:`${r} border-emerald-300 bg-emerald-50 text-emerald-700`;case"cloneLink":return t?`${r} border-teal-400/30 bg-teal-500/14 text-teal-100`:`${r} border-teal-300 bg-teal-50 text-teal-700`;default:return t?`${r} border-sky-400/25 bg-slate-950/78 text-sky-100`:`${r} border-sky-300 bg-white/95 text-sky-700`}}function nw(e){const t=l.useContext(vi),r=e.data.graphEdge,[n,a,o]=sw(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(oh,{id:e.id,path:n,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(ih,{children:s.jsx("div",{className:rw(r,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${a}px, ${o}px)`,pointerEvents:"none",maxWidth:Mv.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const aw={meshEdge:nw};async function ow(e,t=Ys("dark"),r=!1,n="LR"){const a=await Fv(e,r,n),o=new Set(a.nodes.map(d=>d.id)),i=a.nodes.map(d=>({id:d.id,type:d.type,position:d.position,data:{graphNode:d.graphNode,compact:r},selected:d.selected,draggable:d.draggable,selectable:d.selectable})),c=e.edges.filter(d=>o.has(d.source)&&o.has(d.target)),u=cw(c),m=c.map(d=>{var h;return{id:d.id,source:d.source,target:d.target,label:u.has(d.id)?d.label:void 0,type:"meshEdge",data:{graphEdge:d,routePoints:(h=a.edgeRoutes.get(d.id))==null?void 0:h.points},animated:d.type==="orphanLink",markerEnd:d.direction==="directed"?{type:ah.ArrowClosed,width:d.type==="submoduleLink"?16:18,height:d.type==="submoduleLink"?16:18,color:ac(d)}:void 0,style:{stroke:ac(d),strokeWidth:d.type==="orphanLink"?2.25:d.type==="submoduleLink"?1.7:d.type==="worktreeLink"?1.8:d.type==="cloneLink"?1.6:2,strokeDasharray:d.type==="orphanLink"?"5 4":d.type==="submoduleLink"?"4 3":d.type==="cloneLink"?"6 3":void 0},labelStyle:{fill:t.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:t.edgeLabelBackgroundColor,fillOpacity:1,stroke:t.edgeLabelBorderColor},labelBgPadding:[6,4],labelBgBorderRadius:7}});return{nodes:i,edges:m}}const iw=3,lw=2;function nc(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 cw(e){const t=new Set,r=new Map;for(const n of e){if(!n.label)continue;const a=r.get(n.source);a?a.push(n):r.set(n.source,[n])}for(const n of r.values()){if(n.length<iw){for(const o of n)t.add(o.id);continue}const a=[...n].sort((o,i)=>{const c=nc(i)-nc(o);return c!==0?c:o.id.localeCompare(i.id)});for(const o of a.slice(0,lw))t.add(o.id)}return t}function ac(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 dw(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 uw(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 mw({data:e,viewportKey:t}){const r=lh(),n=ch(),a=l.useRef(null),o=l.useMemo(()=>qu(e),[e]),i=l.useMemo(()=>wv(e),[e]);return l.useEffect(()=>{if(!r||e.nodes.length===0||a.current===t)return;let c=!1;const u=requestAnimationFrame(()=>{if(c)return;const m=i.length>0&&i.length<e.nodes.length;n.fitView({nodes:m?i.map(d=>({id:d})):void 0,padding:m?.24:.2,maxZoom:m?.98:.9,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(u)}},[e.nodes.length,i,o,r,n,t]),null}function hw(e){return e>=16?"h-[720px] min-h-[720px] sm:h-[860px] xl:h-[980px]":e>=10?"h-[580px] min-h-[580px] sm:h-[700px] xl:h-[820px]":"h-[460px] min-h-[460px] sm:h-[560px] xl:h-[680px]"}const pw=12;function fw({data:e,selectedNodeId:t=null,onNodeClick:r,onNodeHoverChange:n,onEdgeHoverChange:a}){const{theme:o}=qs(),i=l.useMemo(()=>Ys(o),[o]),c=l.useMemo(()=>Wv(e),[e]),u=l.useMemo(()=>Kv(e),[e]),m=e.nodes.length>=Uv,[d,h]=l.useState("LR"),p=l.useMemo(()=>d==="auto"?Tv(e):d,[d,c,e]),y=e.nodes.length>=pw,[b,x]=l.useState({nodes:[],edges:[]}),k=l.useRef(null),[j,f]=l.useState({width:0,height:0}),w=l.useMemo(()=>`${jv(e,j.width,j.height)}::${p}`,[c,e,j.height,j.width,p]);l.useEffect(()=>{let N=!1;return ow(e,i,m,p).then(M=>{N||x(M)}),()=>{N=!0}},[e,u,i,m,p]);const S=l.useMemo(()=>b.nodes.map(N=>({...N,selected:N.id===t})),[b.nodes,t]);l.useEffect(()=>{const N=k.current;if(!N)return;const M=()=>{const $=Math.max(0,Math.round(N.clientWidth)),R=Math.max(0,Math.round(N.clientHeight));f(T=>T.width===$&&T.height===R?T:{width:$,height:R})};M();const C=typeof ResizeObserver=="function"?new ResizeObserver(()=>M()):null;return C==null||C.observe(N),window.addEventListener("resize",M),()=>{C==null||C.disconnect(),window.removeEventListener("resize",M)}},[]);const v=hw(e.nodes.length),g=N=>N?i.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":i.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(vi.Provider,{value:i,children:s.jsx(Qu.Provider,{value:m,children:s.jsx(Zu.Provider,{value:p,children:s.jsxs("div",{ref:k,className:i.graphShellClass,children:[s.jsxs("div",{className:`flex flex-wrap items-center justify-between gap-2 px-3 pt-3 pb-2 text-[11px] ${i.textSecondary}`,children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs("span",{className:i.graphStatChipClass,children:[e.stats.totalNodes," node",e.stats.totalNodes===1?"":"s"]}),e.stats.totalActiveSessions>0&&s.jsxs("span",{className:i.isDark?"rounded-full border border-emerald-400/25 bg-emerald-500/12 px-3 py-1 text-emerald-100":"rounded-full border border-emerald-300 bg-emerald-50 px-3 py-1 text-emerald-700",children:[e.stats.totalActiveSessions," active session",e.stats.totalActiveSessions===1?"":"s"]}),e.stats.orphanNodes>0&&s.jsxs("span",{className:i.isDark?"rounded-full border border-orange-400/25 bg-orange-500/12 px-3 py-1 text-orange-100":"rounded-full border border-orange-300 bg-orange-50 px-3 py-1 text-orange-700",children:[e.stats.orphanNodes," need attention"]}),m&&s.jsx("span",{className:i.isDark?"rounded-full border border-white/8 bg-white/[0.03] px-3 py-1 text-slate-400":"rounded-full border border-slate-200 bg-slate-50/80 px-3 py-1 text-slate-500",children:"dense view · hover for details"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:i.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:()=>h("auto"),className:g(d==="auto"),title:`Auto (currently ${p==="TB"?"top-bottom":"left-right"})`,children:"Auto"}),s.jsx("button",{type:"button",onClick:()=>h("LR"),className:g(d==="LR"),title:"Left to right",children:"LR"}),s.jsx("button",{type:"button",onClick:()=>h("TB"),className:g(d==="TB"),title:"Top to bottom",children:"TB"})]}),s.jsx("div",{className:i.graphHintChipClass,children:"drag or scroll to pan"})]})]}),s.jsx("div",{className:`w-full min-w-0 ${v}`,children:s.jsxs(eh,{nodes:S,edges:b.edges,nodeTypes:Zv,edgeTypes:aw,minZoom:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(N,M)=>r==null?void 0:r(M.data.graphNode),onNodeMouseEnter:(N,M)=>n==null?void 0:n(M.data.graphNode),onNodeMouseLeave:()=>n==null?void 0:n(null),onEdgeMouseEnter:(N,M)=>{var C;return a==null?void 0:a(((C=M.data)==null?void 0:C.graphEdge)??null)},onEdgeMouseLeave:()=>a==null?void 0:a(null),className:"h-full w-full",colorMode:i.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(mw,{data:e,viewportKey:w}),s.jsx(th,{className:i.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),y&&s.jsx(sh,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:dw,nodeClassName:uw,nodeStrokeWidth:3,className:i.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(rh,{variant:nh.Dots,gap:18,size:1.2,color:i.graphBackgroundDotColor})]})})]})})})})}function at(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function je(...e){for(const t of e){if(typeof t!="string")continue;const r=t.trim();if(r)return r}}function Mt(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function St(...e){for(const t of e)if(typeof t=="boolean")return t}function Va(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function wi(e){switch(e){case"fresh":return 30;case"no_upstream":return 4;case"unchecked":case void 0:return 0;case"stale":return-10;case"unavailable":return-15;default:return 0}}function xw(e,t){const r=typeof e=="string"?e.trim().replace(/[\\/]+$/,""):"",n=typeof t=="string"?t.trim():"";if(n){if(/^(?:[A-Za-z]:[\\/]|\/)/.test(n))return n;if(r)return`${r}/${n.replace(/^[\\/]+/,"")}`}}function bw(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=at(n),o=je(a.path),i=je(a.commit),c=je(a.repoPath,a.repo_root)??xw(t,o);return!o||!i||!c?null:{path:o,commit:i,repoPath:c,dirty:St(a.dirty)??!1,outOfSync:St(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:Mt(a.lastCheckedAt,a.last_checked_at)??Date.now(),...je(a.error)?{error:je(a.error)}:{}}}).filter(n=>n!==null);return r.length>0?r:void 0}function gw(e){return St(e.isGitRepo)!==void 0||!!je(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||Mt(e.ahead,e.behind,e.staged,e.modified,e.untracked,e.deleted,e.renamed,e.lastCheckedAt,e.last_checked_at)!==void 0||Array.isArray(e.submodules)&&e.submodules.length>0}function Ln(e,t,r){const n=St(e.isGitRepo);if(!Object.keys(e).length||!gw(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(w=>typeof w=="string"):[],i=Mt(e.conflicts)??o.length,c=St(e.hasConflicts)??i>0,u=je(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,m=bw(e.submodules,u),d=je(e.upstreamStatus,e.upstream_status),h=Mt(e.upstreamFetchedAt,e.upstream_fetched_at),p=je(e.upstreamFetchError,e.upstream_fetch_error),y=je(e.error),b=Mt(e.staged)??0,x=Mt(e.modified)??0,k=Mt(e.untracked)??0,j=Mt(e.deleted)??0,f=Mt(e.renamed)??0;return{workspace:je(e.workspace,t.workspace)||"",repoRoot:u??null,isGitRepo:a,branch:je(e.branch)??null,headCommit:je(e.headCommit)??null,headMessage:je(e.headMessage)??null,upstream:je(e.upstream)??null,upstreamStatus:d??"unchecked",...h!==void 0?{upstreamFetchedAt:h}:{},...p?{upstreamFetchError:p}:{},ahead:Mt(e.ahead)??0,behind:Mt(e.behind)??0,staged:b,modified:x,untracked:k,deleted:j,renamed:f,dirty:St(e.dirty,e.isDirty,e.is_dirty)??(b+x+k+j+f>0||c),hasConflicts:c,conflictFiles:o,stashCount:Mt(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??Mt(e.lastCheckedAt,e.last_checked_at)??Date.now(),...m?{submodules:m}:{},...y?{error:y}:{}}}function yw(e){if(!e)return Number.NEGATIVE_INFINITY;let t=0;return e.isGitRepo===!0&&(t+=50),e.isGitRepo===!1&&(t-=10),e.branch&&(t+=20),e.headCommit&&(t+=20),e.upstream&&(t+=10),t+=wi(e.upstreamStatus),typeof e.ahead=="number"&&(t+=2),typeof e.behind=="number"&&(t+=2),Array.isArray(e.submodules)&&e.submodules.length>0&&(t+=4+e.submodules.length),e.error&&(t-=20),t}function vw(e){const t=at(e.lastGit??e.last_git),r=at(t.result),n=at(t.status),a=at(r.status),o=at(e.lastProbe??e.last_probe),i=at(o.git),c=at(i.result),u=at(i.status),m=at(c.status);let d=null;for(const h of[n,a,u,m]){const p=Ln(h,e,{lastCheckedAt:Date.now()});if(!p)continue;const y=yw(p);(!d||y>d.score)&&(d={git:p,score:y})}return d==null?void 0:d.git}function ww(e){const t=Array.isArray(e==null?void 0:e.submodules)?e.submodules:[];let r=!1,n=!1;for(const a of t)a!=null&&a.outOfSync&&(n=!0),a!=null&&a.dirty&&(r=!0);return{dirty:r,outOfSync:n}}function jw(e){return e?(e.staged??0)>0||(e.modified??0)>0||(e.untracked??0)>0||(e.deleted??0)>0||(e.renamed??0)>0||e.hasConflicts===!0:!1}function ea(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=ww(e);return t.outOfSync?"degraded":t.dirty||jw(e)?"dirty":"online"}function kw(e,t){const r=t?ea(t):void 0;return!e||e==="unknown"?r:e}function sm(e){const t=at(e),r=je(t.sessionId,t.session_id,t.id);return r?{sessionId:r,...je(t.providerType,t.provider)?{providerType:je(t.providerType,t.provider)}:{},...je(t.state,t.status)?{state:je(t.state,t.status)}:{},...je(t.chatStatus,t.chat_status)?{chatStatus:je(t.chatStatus,t.chat_status)}:{},...je(t.lifecycle)?{lifecycle:je(t.lifecycle)}:{},...je(t.surfaceKind,t.surface_kind)?{surfaceKind:je(t.surfaceKind,t.surface_kind)}:{},...je(t.recoveryState,t.recovery_state)?{recoveryState:je(t.recoveryState,t.recovery_state)}:{},...je(t.workspace)?{workspace:je(t.workspace)}:{},...je(t.title)?{title:je(t.title)}:{},...je(t.role)?{role:je(t.role)}:{},...St(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:St(t.isSelfCoordinator,t.is_self_coordinator)}:{},...je(t.statusNote,t.status_note)?{statusNote:je(t.statusNote,t.status_note)}:{},...je(t.createdAt,t.created_at)?{createdAt:je(t.createdAt,t.created_at)}:{},...je(t.startedAt,t.started_at)?{startedAt:je(t.startedAt,t.started_at)}:{},...je(t.lastActivityAt,t.last_activity_at)?{lastActivityAt:je(t.lastActivityAt,t.last_activity_at)}:{},...St(t.isCached,t.is_cached)!==void 0?{isCached:St(t.isCached,t.is_cached)}:{}}:null}function Sw(e){const t=Array.isArray(e.activeSessionDetails)?e.activeSessionDetails:Array.isArray(e.active_session_details)?e.active_session_details:Array.isArray(e.sessions)?e.sessions:null;if(t){const a=t.map(sm).filter(o=>o!==null);if(a.length>0)return a}const r=at(e.activeSession??e.active_session),n=je(r.id,r.sessionId,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id);if(n)return[{sessionId:n,...je(r.providerType,r.provider)?{providerType:je(r.providerType,r.provider)}:{},...je(r.state,r.status)?{state:je(r.state,r.status)}:{},...je(r.chatStatus,r.chat_status)?{chatStatus:je(r.chatStatus,r.chat_status)}:{},...je(r.statusNote,r.status_note)?{statusNote:je(r.statusNote,r.status_note)}:{},...je(r.createdAt,r.created_at)?{createdAt:je(r.createdAt,r.created_at)}:{},...je(r.startedAt,r.started_at)?{startedAt:je(r.startedAt,r.started_at)}:{}}]}function Nw(e){const t=at(e.connection);return Object.keys(t).length>0?t:void 0}function Cw(e){const t=e==null?void 0:e.source,r=e==null?void 0:e.transport;return{...e,perspective:(e==null?void 0:e.perspective)??"selected_coordinator",source:t&&t!=="not_reported"?t:"mesh_peer_status",state:"connected",transport:r&&r!=="unknown"?r:"direct",reported:!0,reason:"Live peer git snapshot reported by the selected coordinator."}}function ji(e){var r;const t=e.git;return!!(t&&(t.isGitRepo===!0||t.isGitRepo===!1||t.branch||t.upstream||t.headCommit||typeof t.lastCheckedAt=="number"||(((r=t.submodules)==null?void 0:r.length)??0)>0))}function oc(e){var n,a,o,i,c,u;let t=0;const r=e.git;return ji(e)&&(t+=80,(r==null?void 0:r.isGitRepo)===!0&&(t+=20),(r==null?void 0:r.isGitRepo)===!1&&(t+=5),r!=null&&r.branch&&(t+=20),r!=null&&r.upstream&&(t+=12),r!=null&&r.headCommit&&(t+=12),t+=wi(r==null?void 0:r.upstreamStatus),typeof(r==null?void 0:r.lastCheckedAt)=="number"&&(t+=6),t+=(((n=r==null?void 0:r.submodules)==null?void 0:n.length)??0)*6),(a=e.branchConvergence)!=null&&a.status&&(t+=12),(((o=e.connection)==null?void 0:o.state)==="connected"||((i=e.connection)==null?void 0:i.state)==="self")&&(t+=8),((c=e.connection)==null?void 0:c.transport)==="direct"&&(t+=4),((u=e.connection)==null?void 0:u.source)==="mesh_peer_status"&&(t+=4),e.health==="online"&&(t+=4),e.health==="dirty"&&(t+=3),e.health==="degraded"&&(t+=2),e.launchReady&&(t+=2),e.gitProbePending&&(t-=40),e.error&&(t-=10),t}function Mw(e,t){var b,x,k,j;const r=oc(e),a=oc(t)>r?t:e,o=a===t?e:t,i=a.git??o.git,c=(((b=a.providers)==null?void 0:b.length)??0)>0?a.providers:o.providers,u=(((x=a.activeSessions)==null?void 0:x.length)??0)>0?a.activeSessions:o.activeSessions,m=(((k=a.activeSessionDetails)==null?void 0:k.length)??0)>0?a.activeSessionDetails:o.activeSessionDetails,d=(((j=a.providerPriority)==null?void 0:j.length)??0)>0?a.providerPriority:o.providerPriority,h=a.connection??o.connection,p={...o,...a,machineLabel:a.machineLabel||o.machineLabel,workspace:a.workspace||o.workspace,...a.repoRoot||o.repoRoot?{repoRoot:a.repoRoot||o.repoRoot}:{},...a.daemonId||o.daemonId?{daemonId:a.daemonId||o.daemonId}:{},...a.machineId||o.machineId?{machineId:a.machineId||o.machineId}:{},...a.machineStatus||o.machineStatus?{machineStatus:a.machineStatus||o.machineStatus}:{},health:i&&(!a.health||a.health==="unknown")?ea(i):a.health,providers:c??[],activeSessions:u??[],...m&&m.length>0?{activeSessionDetails:m}:{},...d&&d.length>0?{providerPriority:d}:{},...h?{connection:h}:{},...i?{git:i}:{}},y=at(a.branchConvergence);return Object.keys(y).length>0?Object.assign(p,{branchConvergence:y}):delete p.branchConvergence,i&&(delete p.gitProbePending,delete p.error),p}function rm(e){const t=at(e),r=je(t.nodeId,t.id);if(!r)return null;const n=at(t.cachedStatus),a=vw(t),o=a?void 0:Ln(at(t.git),t)??Ln(t,t),i=a??o,c=i?void 0:Ln(at(n.git),t),u=i??c,m=je(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),d=je(t.health),h=a?ea(u):kw(d,i)||(u?ea(u):void 0)||je(n.health)||m||je(t.status)||"unknown",y=(a?void 0:je(t.error))??(i?void 0:je(n.error)),b=Sw(t),x=Va(t.activeSessions),k=(b==null?void 0:b.map(M=>M.sessionId))??[],j=Va(t.providerPriority),f=St(t.gitProbePending,t.git_probe_pending),w=i?void 0:f,S=Nw(t),v=at(t.branchConvergence??t.branch_convergence),g=S==null?void 0:S.state,N=a&&(!(S!=null&&S.reported)||g==="unknown")?Cw(S):S;return{nodeId:r,machineLabel:je(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:je(t.workspace,u==null?void 0:u.workspace)||"",...je(t.repoRoot,t.repo_root,u==null?void 0:u.repoRoot)?{repoRoot:je(t.repoRoot,t.repo_root,u==null?void 0:u.repoRoot)}:{},...je(t.daemonId,t.daemon_id)?{daemonId:je(t.daemonId,t.daemon_id)}:{},...je(t.machineId,t.machine_id)?{machineId:je(t.machineId,t.machine_id)}:{},...m?{machineStatus:m}:{},...St(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:St(t.isLocalWorktree,t.is_local_worktree)}:{},...je(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:je(t.worktreeBranch,t.worktree_branch)}:{},...je(t.clonedFromNodeId,t.cloned_from_node_id)?{clonedFromNodeId:je(t.clonedFromNodeId,t.cloned_from_node_id)}:{},health:h,...u?{git:u}:{},...w!==void 0?{gitProbePending:w}:{},providers:Va(t.providers),activeSessions:x.length>0?x:k,...b&&b.length>0?{activeSessionDetails:b}:{},...j.length>0?{providerPriority:j}:{},...St(t.launchReady)!==void 0?{launchReady:St(t.launchReady)}:a?{launchReady:!0}:{},...je(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:je(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},...je(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:je(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...N?{connection:N}:{},...Object.keys(v).length>0?{branchConvergence:v}:{},...y?{error:y}:{}}}function ic(e){const t=new Map;for(const r of e){const n=t.get(r.sessionId);t.set(r.sessionId,n?{...n,...r}:r)}return[...t.values()]}function nm(e,t){const r=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],n=r.map(sm).filter(a=>a!==null);return n.length===0?t:t.map(a=>{const o=n.filter(c=>{const u=at(r.find(p=>{const y=at(p);return je(y.sessionId,y.session_id,y.id)===c.sessionId})),m=je(u.nodeId,u.node_id),d=je(u.daemonId,u.daemon_id),h=je(u.workspace);return m&&m===a.nodeId?!0:d&&a.daemonId&&d===a.daemonId?!h||!a.workspace||h===a.workspace:!!(h&&a.workspace&&h===a.workspace)});if(o.length===0)return a;const i=ic([...a.activeSessionDetails??[],...o]);return{...a,activeSessionDetails:i,activeSessions:ic([...a.activeSessionDetails??[],...o,...(a.activeSessions??[]).map(c=>({sessionId:c}))]).map(c=>c.sessionId)}})}function Iw(e){const t=at(e);return Array.isArray(t.sessions)||Array.isArray(t.active_session_details)||je(t.daemon_id,t.machine_id,t.repo_root,t.worktree_branch,t.cloned_from_node_id)!==void 0||St(t.is_local_worktree)!==void 0}function am(e){const t=new Map,r=[];for(const n of e){const a=Iw(n)?rm(n)??n:n;if(!(a!=null&&a.nodeId))continue;const o=t.get(a.nodeId);if(!o){t.set(a.nodeId,a),r.push(a);continue}const i=Mw(o,a);t.set(a.nodeId,i);const c=r.findIndex(u=>u.nodeId===a.nodeId);c>=0&&(r[c]=i)}return r}function om(e){const t=am(e.nodes??[]);return{...e,nodes:nm(e,t)}}function Aw(e){var r;const t=e==null?void 0:e.git;return{nodeId:(e==null?void 0:e.nodeId)??null,chosenSource:t?"live_git":e!=null&&e.gitProbePending?"pending_git":"no_git",hasLiveGit:ji(e??{git:void 0}),branch:(t==null?void 0:t.branch)??null,upstream:(t==null?void 0:t.upstream)??null,headCommit:(t==null?void 0:t.headCommit)??null,submoduleCount:((r=t==null?void 0:t.submodules)==null?void 0:r.length)??0,pendingGit:(e==null?void 0:e.gitProbePending)===!0,connection:e!=null&&e.connection?{state:e.connection.state,transport:e.connection.transport,source:e.connection.source}:null}}function Tw(e){const t=je(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(u=>rm(u)).filter(u=>u!==null):null;if(!t||!n)return null;const a=nm(e,am(n)),o=je(e.meshName,e.mesh_name,e.name),i=je(e.repoIdentity,e.repo_identity),c=je(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!o||!i||!c?null:{...e,meshId:t,meshName:o,repoIdentity:i,refreshedAt:c,nodes:a}}function _w(e){var o;let t=0;const r=at(e.sourceOfTruth),n=at(r.directPeerTruth);je(r.currentStatus)==="live_git_and_session_probes"&&(t+=100),r.coordinatorOwnsLiveTruth===!0&&(t+=25),n.satisfied===!0&&(t+=15);for(const i of e.nodes){const c=i.git;if(!c){i.gitProbePending&&(t-=8);continue}t+=10,c.isGitRepo===!0&&(t+=5),c.isGitRepo===!1&&(t+=1),c.branch&&(t+=4),c.upstream&&(t+=3),c.headCommit&&(t+=3),t+=wi(c.upstreamStatus),typeof c.ahead=="number"&&(t+=1),typeof c.behind=="number"&&(t+=1),typeof c.lastCheckedAt=="number"&&(t+=2),t+=(((o=c.submodules)==null?void 0:o.length)??0)*2}return t}function lc(e){let t=null;for(const r of e){const n=Tw(at(r));if(!n)continue;const a=_w(n);(!t||a>t.score)&&(t={status:n,score:a})}return(t==null?void 0:t.status)??null}function im(e){const r=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,n=lc([r==null?void 0:r.status,r]);return n||lc([e==null?void 0:e.status,e])}const Lw=5*60*1e3;function lm(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function cm(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function Rw(e){var t,r,n;return((t=e.connection)==null?void 0:t.state)==="self"||e.isLocalWorktree===!0?"local":((r=e.connection)==null?void 0:r.transport)==="direct"||((n=e.connection)==null?void 0:n.transport)==="relay"||lm(e)||cm(e)?"remote":"unknown"}function Pw(e){return ji(e)}function dm(e){var t;return Pw(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function Dw(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function $w(e){return e.activeSessionDetails&&e.activeSessionDetails.length>0?e.activeSessionDetails:(e.activeSessions??[]).map(t=>({sessionId:t,workspace:e.workspace,isCached:!0}))}function um(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function mm(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function ki(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function Ew(e){return ki(e)?"degraded":mm(e)?"dirty":"online"}function Bw(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function cc(e){switch(e){case"online":return 0;case"dirty":return 1;case"degraded":return 2;case"wrong_branch":return 3;case"offline":return 4;case"unknown":default:return 5}}function qa(e){return e.length===0?"unknown":e.reduce((t,r)=>cc(r)>cc(t)?r:t)}function Ow(e){var o,i,c,u,m;const t=new Map,r=new Map;for(const d of e){const h=(i=(o=d.git)==null?void 0:o.branch)==null?void 0:i.trim();h&&(r.set(h,(r.get(h)??0)+1),(c=d.git)!=null&&c.upstream&&t.set(h,(t.get(h)??0)+1))}const n=[...t.entries()].sort((d,h)=>{if(h[1]!==d[1])return h[1]-d[1];const p=["main","master","develop","dev"],y=p.indexOf(d[0]),b=p.indexOf(h[0]);return y!==-1||b!==-1?y===-1?1:b===-1?-1:y-b:d[0].localeCompare(h[0])});return(u=n[0])!=null&&u[0]?n[0][0]:((m=[...r.entries()].sort((d,h)=>h[1]-d[1])[0])==null?void 0:m[0])??null}function Fw(e,t){const r=[],n=e.git;return n?n.isGitRepo?(!n.branch&&n.headCommit&&r.push("Detached HEAD"),n.hasConflicts&&r.push("Merge conflicts need resolution"),n.branch&&t&&n.branch!==t&&!n.upstream&&r.push(`No upstream tracking for ${n.branch}`),n.upstream&&n.upstreamStatus&&n.upstreamStatus!=="fresh"&&r.push(`Upstream freshness unverified for ${n.branch??"workspace"}`),e.error&&r.push(e.error),r):(r.push("Not a git repository"),r):(r.push("No git status available"),r)}function dc(e){switch(e){case"merged_to_main":return 0;case"pushed_feature_branch_needs_merge":return 1;case"cleanup_candidate":return 2;case"blocked_review":return 3;case"not_mergeable":default:return 4}}function Hw(e){return e.reduce((t,r)=>dc(r.status)>dc(t.status)?r:t)}function Ww(e){const t=e.branchConvergenceSummary;if(Array.isArray(t==null?void 0:t.followUps))return t.followUps;const r=e.followUps;return Array.isArray(r)?r:(t==null?void 0:t.needsFollowUp)===!1||(t==null?void 0:t.unresolvedCount)===0?[]:null}function Kw(e){var a,o,i;const t=e.sourceOfTruth,r=[],n=(a=t==null?void 0:t.fallback)==null?void 0:a.warning;return typeof n=="string"&&n.trim()&&r.push(n.trim()),(t==null?void 0:t.currentStatus)==="bootstrap_inventory_fallback"&&((o=t.directPeerTruth)==null?void 0:o.required)===!0&&((i=t.directPeerTruth)==null?void 0:i.satisfied)!==!0&&!r.some(c=>c.includes("direct mesh truth"))&&r.push("Direct mesh truth is not confirmed yet; this graph is drawn from setup inventory only."),r}function Uw(e,t){return e.type!=="submoduleNode"&&e.branch===t&&e.ahead===0&&e.behind===0&&!e.dirty&&!e.hasConflicts&&(!e.upstreamStatus||e.upstreamStatus==="fresh")&&e.snapshotCompleteness==="complete"}function zw(e,t){var r,n;return{status:"merged_to_main",needsConvergence:!1,reason:"clean_default_branch_aggregate",nextStep:null,branch:e,defaultBranch:e,upstream:((r=t.find(a=>a.upstream))==null?void 0:r.upstream)??null,upstreamStatus:((n=t.find(a=>a.upstreamStatus))==null?void 0:n.upstreamStatus)??null,ahead:0,behind:0,dirty:!1,hasConflicts:!1}}function Gw(e,t){if(dm(e))return null;const r=e.branchConvergence;if(!r||typeof r!="object")return null;const n=r.status;if(!n||!["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"].includes(n))return null;const a=e.git,o=um(a)||mm(a),i=!!(a!=null&&a.hasConflicts)||ki(a),c=(a==null?void 0:a.ahead)??0,u=(a==null?void 0:a.behind)??0,m=(a==null?void 0:a.branch)??null,d=(a==null?void 0:a.upstream)??null,h=(a==null?void 0:a.upstreamStatus)??null,p=r.defaultBranch??t??null;return{status:n,needsConvergence:r.needsConvergence??n!=="merged_to_main",reason:r.reason??"provided_by_coordinator",nextStep:r.nextStep??null,branch:r.branch??m,defaultBranch:p,upstream:r.upstream??d,upstreamStatus:r.upstreamStatus??h,ahead:r.ahead??c,behind:r.behind??u,dirty:r.dirty??o,hasConflicts:r.hasConflicts??i}}function Vw(e,t){const r=Gw(e,t);return r?{...r,defaultBranch:r.defaultBranch??t}:null}function qw(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function Yw(e){var u,m,d;const{nodeStatus:t,expectedSubmodulePaths:r,refreshedAtMs:n}=e,a=[],o=t.machineLabel||t.nodeId,i=t.git;if(!i){if(dm(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const h=t.health==="online"||t.machineStatus==="online"||((u=t.connection)==null?void 0:u.state)==="connected"||((m=t.connection)==null?void 0:m.state)==="self";return a.push(h?`${o} is online but no peer git snapshot is visible yet.`:`${o} has no peer git snapshot visible yet.`),{snapshotCompleteness:"missing_git",snapshotWarnings:a}}const c=new Set((i.submodules??[]).map(h=>h.path));if(r.size>0){const h=[...r].filter(p=>!c.has(p));h.length>0&&a.push(`${o} is missing submodule visibility for ${h.join(", ")} even though another peer reported it.`)}return((d=t.connection)==null?void 0:d.state)!=="self"&&n!==null&&typeof i.lastCheckedAt=="number"&&n-i.lastCheckedAt>Lw&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(h=>h.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(h=>h.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function Xw(e){const t=om(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??Ow(t.nodes),a=Dw(t.refreshedAt),o=new Set(t.nodes.flatMap(I=>{var A;return(((A=I.git)==null?void 0:A.submodules)??[]).map(W=>W.path)})),i=[],c=[],u=Kw(t),m=new Map;for(const I of t.nodes){const A=I.git,W=(A==null?void 0:A.branch)??null,_=Ew(A),L=um(A)||_==="dirty",B=Fw(I,n),F=Vw(I,n),E=Yw({nodeStatus:I,expectedSubmodulePaths:o,refreshedAtMs:a}),D=typeof I.clonedFromNodeId=="string"?I.clonedFromNodeId:null,K=$w(I),J={id:I.nodeId,type:B.length>0?"orphanNode":"worktreeNode",label:I.machineLabel||I.nodeId.slice(0,8),workspace:I.workspace,branch:W,upstream:(A==null?void 0:A.upstream)??null,upstreamStatus:(A==null?void 0:A.upstreamStatus)??null,daemonId:lm(I),machineId:cm(I),machineLabel:I.machineLabel||null,locality:Rw(I),health:qa([I.health,_]),ahead:(A==null?void 0:A.ahead)??0,behind:(A==null?void 0:A.behind)??0,dirty:L,dirtyFiles:Bw(A),hasConflicts:(A==null?void 0:A.hasConflicts)??!1,activeSessionCount:K.length,activeSessions:K.map(Q=>Q.sessionId),sessionDetails:K,providers:I.providers??[],isOrphan:B.length>0,orphanReasons:B,error:I.error,nextStepHint:E.snapshotWarnings[0]??B[0]??(F==null?void 0:F.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:D,worktreeBranch:I.worktreeBranch??null,submodulePath:null,submoduleCommit:(A==null?void 0:A.headCommit)??null,outOfSync:ki(A),snapshotCompleteness:E.snapshotCompleteness,snapshotWarnings:E.snapshotWarnings,branchConvergence:F,source:I};if(i.push(J),W){const Q=m.get(W)??[];Q.push(J.id),m.set(W,Q)}for(const Q of(A==null?void 0:A.submodules)??[]){const Z=`${J.id}::submodule::${Q.path}`,he=Q.path.split("/").filter(Boolean).pop()||Q.path;i.push({id:Z,type:"submoduleNode",label:he,workspace:Q.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:J.daemonId,machineId:J.machineId,machineLabel:J.machineLabel,locality:J.locality,health:qw(Q),ahead:0,behind:0,dirty:Q.dirty,dirtyFiles:Q.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],error:Q.error,nextStepHint:Q.error||(Q.outOfSync?`${Q.path} is out of sync with the parent checkout`:Q.dirty?`${Q.path} has local changes`:`${Q.path} is in sync with the parent checkout`),parentNodeId:J.id,submodulePath:Q.path,submoduleCommit:Q.commit,outOfSync:Q.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:J.id,parentWorkspace:I.workspace,submodule:Q}}),c.push({id:`${J.id}--${Z}`,source:J.id,target:Z,type:"submoduleLink",label:Q.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const d=n?`__branch_${n}`:null;if(d&&n){const A=(m.get(n)??[]).map(D=>i.find(K=>K.id===D)).filter(Boolean),W=A.map(D=>D.branchConvergence).filter(Boolean),_=Ww(t),L=A.length>0&&A.every(D=>Uw(D,n)),B=(_==null?void 0:_.length)===0&&L?zw(n,A):W.length>0?Hw(W):null,F=(_==null?void 0:_.length)===0&&L?0:W.filter(D=>D.needsConvergence).length,E={id:d,type:"defaultBranchNode",label:n,workspace:t.repoIdentity,branch:n,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:"default branch",locality:"unknown",health:qa(A.map(D=>D.health)),ahead:0,behind:0,dirty:A.some(D=>D.dirty),dirtyFiles:A.reduce((D,K)=>D+K.dirtyFiles,0),hasConflicts:A.some(D=>D.hasConflicts),activeSessionCount:A.reduce((D,K)=>D+K.activeSessionCount,0),activeSessions:A.flatMap(D=>D.activeSessions),sessionDetails:A.flatMap(D=>D.sessionDetails),providers:[...new Set(A.flatMap(D=>D.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:F>0?`${F} workspace(s) on ${n} still need follow-up`:A.length>0?`${A.length} workspace(s) currently on ${n}`:"No workspaces currently checked out to the default branch",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:B,source:{nodeId:d,machineLabel:n,workspace:t.repoIdentity,health:qa(A.map(D=>D.health)),providers:[],activeSessions:[],activeSessionDetails:[]}};i.push(E);for(const D of i)if(!(D.id===d||D.type==="submoduleNode")){if(D.branch===n){c.push({id:`${d}--${D.id}`,source:d,target:D.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(D.branch){c.push({id:`${d}--${D.id}`,source:d,target:D.id,type:D.isOrphan?"orphanLink":"parentBranch",label:D.branch,direction:"undirected"});continue}D.isOrphan&&c.push({id:`${d}--${D.id}`,source:d,target:D.id,type:"orphanLink",label:"detached",direction:"undirected"})}}for(const[I,A]of m){if(A.length<2)continue;const W=A.map(_=>i.find(L=>L.id===_)).filter(Boolean);W.sort((_,L)=>_.label.localeCompare(L.label));for(let _=1;_<W.length;_+=1)c.push({id:`wt_${W[_-1].id}--${W[_].id}`,source:W[_-1].id,target:W[_].id,type:"worktreeLink",label:_===1?`${I} peers`:void 0,direction:"undirected"})}const h=new Set(i.map(I=>I.id)),p=new Set;for(const I of i){if(!I.clonedFromNodeId||I.type==="submoduleNode"||!h.has(I.clonedFromNodeId))continue;const A=`clone_${I.clonedFromNodeId}--${I.id}`;if(p.has(A))continue;p.add(A);const W=I.worktreeBranch??I.branch??void 0;c.push({id:A,source:I.clonedFromNodeId,target:I.id,type:"cloneLink",label:W?`cloned · ${W}`:"cloned",direction:"directed"})}const y=i.filter(I=>I.type!=="defaultBranchNode"),b=y.filter(I=>I.isOrphan).length,x=y.filter(I=>I.hasConflicts).length,k=y.filter(I=>I.health==="offline").length,j=y.filter(I=>I.type==="submoduleNode"&&I.outOfSync).length,f=y.filter(I=>{var A;return I.type!=="submoduleNode"&&((A=I.branchConvergence)==null?void 0:A.needsConvergence)}).length,w=y.filter(I=>{var A;return((A=I.branchConvergence)==null?void 0:A.status)==="blocked_review"}).length,S=y.filter(I=>{var A;return((A=I.branchConvergence)==null?void 0:A.status)==="pushed_feature_branch_needs_merge"}).length,v=y.filter(I=>{var A;return((A=I.branchConvergence)==null?void 0:A.status)==="cleanup_candidate"}).length,g=y.filter(I=>{var A;return((A=I.branchConvergence)==null?void 0:A.status)==="not_mergeable"}).length,N=y.filter(I=>I.snapshotWarnings.length>0).length,M=y.filter(I=>I.snapshotCompleteness==="pending_git").length,C=y.filter(I=>I.snapshotCompleteness==="missing_git").length,$=y.filter(I=>I.snapshotCompleteness==="missing_submodule_report").length,R=y.filter(I=>I.snapshotCompleteness==="stale").length,T=[M>0?`${M} node(s) are still waiting for a live peer git snapshot`:null,C>0?`${C} node(s) have no visible peer git snapshot`:null,$>0?`${$} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,R>0?`${R} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return f>0&&u.push(`${f} workspace(s) still need follow-up before the mesh is converged`),b>0&&u.push(`${b} workspace(s) need attention before safe coordination`),w>0&&u.push(`${w} workspace(s) are blocked on branch convergence or upstream sync`),S>0&&u.push(`${S} clean feature branch workspace(s) still need merge follow-up`),v>0&&u.push(`${v} worktree workspace(s) are ready for refine / cleanup`),g>0&&u.push(`${g} workspace(s) have local changes or conflicts blocking convergence`),x>0&&u.push(`${x} workspace(s) report merge conflicts`),k>0&&u.push(`${k} node(s) are currently offline`),j>0&&u.push(`${j} submodule(s) are out of sync with their parent checkout`),u.push(...T),n||u.push("Could not infer a default branch from live mesh status"),{meshId:t.meshId,meshName:t.meshName,repoIdentity:t.repoIdentity,refreshedAt:t.refreshedAt,nodes:i,edges:c,stats:{totalNodes:y.length,onlineNodes:y.filter(I=>I.health==="online").length,dirtyNodes:y.filter(I=>I.dirty).length,orphanNodes:b,errorNodes:y.filter(I=>!!I.error||I.outOfSync).length,offlineNodes:k,followUpNodes:f,blockedReviewNodes:w,mergeReadyNodes:S,cleanupCandidateNodes:v,notMergeableNodes:g,incompleteSnapshotNodes:N,missingGitSnapshotNodes:C,missingSubmoduleSnapshotNodes:$,staleGitSnapshotNodes:R,totalActiveSessions:y.reduce((I,A)=>I+A.activeSessionCount,0)},warnings:u,snapshotWarnings:T}}const Jw={recentFailures:0,taskCompleted:0,taskFailed:0,sessionLaunched:0},Si=l.createContext(Ys("dark"));function Fe({label:e,tone:t="default"}){const r=l.useContext(Si);return s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${r.badge(t)}`,children:e})}function nt({label:e,value:t}){const r=l.useContext(Si);return s.jsxs("div",{className:r.rowClass,children:[s.jsx("span",{className:r.rowLabelClass,children:e}),s.jsx("span",{className:r.rowValueClass,children:t})]})}function uc(e){switch(e){case"online":return"good";case"dirty":return"warn";case"degraded":case"offline":return"danger";case"wrong_branch":return"info";default:return"default"}}function Ya(e){switch((e||"").toLowerCase()){case"idle":return"good";case"generating":case"running":return"info";case"waiting_approval":case"starting":case"pending":return"warn";case"failed":case"stopped":case"interrupted":return"danger";default:return"default"}}function bn(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const r=t.toLowerCase().replace(/[\s-]+/g,"_");return r.includes("approval")?"awaiting approval":r.includes("generating")||r.includes("running")||r.includes("busy")?"generating":r.includes("idle")||r.includes("ready")||r.includes("waiting_input")?"idle":r.replace(/_/g," ")}function Qw(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function Zw(e){return e.startedAt||e.createdAt||null}function ej(e){const t=Zw(e);if(!t)return"runtime age not reported";const r=Date.parse(t);if(!Number.isFinite(r))return"runtime age not reported";const n=Math.max(0,Math.floor((Date.now()-r)/1e3));if(n<60)return`${n}s`;const a=Math.floor(n/60);if(a<60)return`${a}m`;const o=Math.floor(a/60);return o<48?`${o}h ${a%60}m`:`${Math.floor(o/24)}d ${o%24}h`}function tj(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function sj(e){if(!e)return"default";if(e.state==="self")return"info";if(e.transport==="direct"&&e.state==="connected")return"good";if(e.transport==="relay"&&e.state==="connected")return"info";switch(e.state){case"connected":return"good";case"connecting":return"warn";case"disconnected":case"failed":case"closed":return"danger";default:return"default"}}function rj(e){return e?e.state==="self"?"mesh self":e.transport==="direct"&&e.state==="connected"?"mesh direct":e.transport==="relay"&&e.state==="connected"?"mesh relay":!e.reported&&e.source==="not_reported"?"mesh unknown / not reported":`mesh ${e.state}`:"mesh unknown"}function nj(e){var r;const t=[];for(const n of e.nodes){const a=n.activeSessionDetails&&n.activeSessionDetails.length>0?n.activeSessionDetails:(n.activeSessions??[]).map(o=>({sessionId:o,workspace:n.workspace,isCached:!0}));for(const o of a)t.push({nodeId:n.nodeId,machineLabel:n.machineLabel,workspace:n.workspace,branch:((r=n.git)==null?void 0:r.branch)??null,nodeHealth:n.health,session:o})}return t}function aj(e){return e.assignedNodeId||e.targetNodeId||null}function mc(e){return e?e.slice(0,7):null}function oj(e,t){var o,i,c;const r=mc((o=e==null?void 0:e.git)==null?void 0:o.headCommit),n=((c=(i=e==null?void 0:e.git)==null?void 0:i.headMessage)==null?void 0:c.trim())||"";if(r||n)return[r,n].filter(Boolean).join(" · ");const a=t[0];return a?[mc(a.commit),a.message].filter(Boolean).join(" · "):null}function ij(e,t){const r=oj(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function lj(e){const t=(e==null?void 0:e.result)??e,r=(t==null?void 0:t.log)??(e==null?void 0:e.log)??t;return Array.isArray(r==null?void 0:r.entries)?r.entries:[]}function cj(e){var r,n,a,o,i,c;const t=((r=e.selectedSessionEntry)==null?void 0:r.session.workspace)||((n=e.selectedSessionEntry)==null?void 0:n.workspace)||((o=(a=e.selectedNodeStatus)==null?void 0:a.git)==null?void 0:o.workspace)||((i=e.selectedNodeStatus)==null?void 0:i.workspace)||null;if(t&&e.selectedSessionEntry){const u=((c=e.selectedNodeStatus)==null?void 0:c.daemonId)||e.coordinatorDaemonId;return u?{daemonId:u,workspace:t}:null}if(t&&e.selectedNodeStatus){const u=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return u?{daemonId:u,workspace:t}:null}return null}function dj(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":rj(e.connection)}function hc(e){var r;const t=e.source;return t!=null&&t.kind?t.kind:((r=t==null?void 0:t.connection)==null?void 0:r.source)??"mesh_status"}function pc(e){switch(e.type){case"parentBranch":return"default branch link";case"worktreeLink":return"worktree relationship";case"sessionLink":return"session relationship";case"orphanLink":return"orphan relationship";case"submoduleLink":return"submodule relationship";case"cloneLink":return"clone relationship";default:return e.type}}function uj(e){return e.direction==="directed"?"directed":"undirected"}function fc(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function mj(e){var t,r,n,a;return[e.meshId,e.refreshedAt,e.nodes.length,((r=(t=e.queue)==null?void 0:t.summary)==null?void 0:r.active)??"",((a=(n=e.ledger)==null?void 0:n.summary)==null?void 0:a.recentFailures)??"",...e.nodes.map(o=>{var i,c,u,m,d,h,p,y,b,x,k,j,f,w,S,v,g,N,M,C,$,R;return[o.nodeId,o.daemonId??"",o.machineId??"",o.machineLabel,o.machineStatus??"",((i=o.connection)==null?void 0:i.state)??"",((c=o.connection)==null?void 0:c.transport)??"",((u=o.connection)==null?void 0:u.source)??"",o.health,o.gitProbePending?1:0,((m=o.git)==null?void 0:m.branch)??"",((d=o.git)==null?void 0:d.upstream)??"",((h=o.git)==null?void 0:h.upstreamStatus)??"",((p=o.git)==null?void 0:p.ahead)??"",((y=o.git)==null?void 0:y.behind)??"",((b=o.git)==null?void 0:b.headCommit)??"",((x=o.git)==null?void 0:x.staged)??"",((k=o.git)==null?void 0:k.modified)??"",((j=o.git)==null?void 0:j.untracked)??"",((f=o.git)==null?void 0:f.deleted)??"",((w=o.git)==null?void 0:w.renamed)??"",(S=o.git)!=null&&S.hasConflicts?1:0,((v=o.git)==null?void 0:v.lastCheckedAt)??"",((g=o.activeSessions)==null?void 0:g.join(","))??"",((N=o.activeSessionDetails)==null?void 0:N.length)??"",((M=o.activeSessionDetails)==null?void 0:M.map(T=>[T.sessionId,T.providerType??"",T.state??"",T.chatStatus??"",T.lifecycle??"",T.role??"",T.isSelfCoordinator?1:0,T.statusNote??"",T.startedAt??"",T.createdAt??""].join("/")).join(","))??"",((C=o.providers)==null?void 0:C.join(","))??"",(($=o.providerPriority)==null?void 0:$.join(","))??"",o.error??"",(((R=o.git)==null?void 0:R.submodules)??[]).map(T=>[T.path,T.commit,T.dirty?1:0,T.outOfSync?1:0,T.error??""].join("/")).join(",")].join("|")})].join("::")}function hm({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null}){var pe,Ie,X,be,ue;const{theme:a}=qs(),o=l.useMemo(()=>Ys(a),[a]),i=l.useMemo(()=>om(e),[e]),c=l.useMemo(()=>mj(i),[i]),u=l.useMemo(()=>Xw(i),[c]),[m,d]=l.useState(null),[h,p]=l.useState(null),[y,b]=l.useState(null),[x,k]=l.useState(null),[j,f]=l.useState({}),[w,S]=l.useState(null),[v,g]=l.useState(null),N=l.useMemo(()=>new Map(i.nodes.map(U=>[U.nodeId,U])),[i.nodes]),M=l.useMemo(()=>new Map(u.nodes.map(U=>[U.id,U])),[u.nodes]),C=((pe=i.queue)==null?void 0:pe.summary)??null,$=((Ie=i.ledger)==null?void 0:Ie.summary)??Jw,R=l.useMemo(()=>nj(i),[i]),T=l.useMemo(()=>{const U=new Map;for(const ce of R){const ie=bn(ce.session);U.set(ie,(U.get(ie)??0)+1)}return[...U.entries()].sort((ce,ie)=>ie[1]-ce[1])},[R]);l.useEffect(()=>{m&&(M.has(m)||(d(null),k(U=>!U||"nodeId"in U&&U.nodeId===m?null:U)))},[M,m]);const I=m?N.get(m)??null:null,A=fc(u,m),W=fc(u,h),_=y?u.edges.find(U=>U.id===y)??null:null,L=_?u.nodes.find(U=>U.id===_.source)??null:null,B=_?u.nodes.find(U=>U.id===_.target)??null:null;l.useEffect(()=>{var U,ce,ie;if(m)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:i.meshId,selectedNodeId:m,canonicalNode:Aw(I),graphNode:A?{id:A.id,branch:A.branch,upstream:A.upstream,headCommit:A.submoduleCommit,submoduleCount:((ce=(U=I==null?void 0:I.git)==null?void 0:U.submodules)==null?void 0:ce.length)??0,snapshotCompleteness:A.snapshotCompleteness,snapshotWarnings:A.snapshotWarnings,branchConvergence:((ie=A.branchConvergence)==null?void 0:ie.status)??null}:null})}catch{}},[i.meshId,A,m,I]);const F=(x==null?void 0:x.kind)==="session"?R.find(U=>U.nodeId===x.nodeId&&U.session.sessionId===x.sessionId)??null:null,E=l.useMemo(()=>R.filter(U=>U.nodeId===m),[m,R]),D=cj({coordinatorDaemonId:r,selectedNodeStatus:I,selectedSessionEntry:F}),K=(D==null?void 0:D.workspace)??null,J=K?j[K]??null:null,Q=ij(I,(J==null?void 0:J.entries)??[]),Z=(A==null?void 0:A.daemonId)??(I==null?void 0:I.daemonId)??r??null,he=!!(A&&n&&Z&&A.type!=="submoduleNode"&&A.behind>0&&A.ahead===0&&A.dirtyFiles===0&&!A.dirty&&!A.hasConflicts&&A.upstreamStatus==="fresh"),we=l.useCallback(()=>{d(null),k(null),S(null)},[]);l.useEffect(()=>{S(null)},[m]);const Me=l.useCallback(async()=>{if(!(!A||!Z||!n||!he)){g(A.id),S(null);try{const U=await n(Z,"fast_forward_mesh_node",{meshId:i.meshId,nodeId:A.id,dryRun:!0,execute:!1});if(S({phase:"dry_run",code:typeof(U==null?void 0:U.code)=="string"?U.code:void 0,error:typeof(U==null?void 0:U.operationError)=="string"?U.operationError:null,executed:(U==null?void 0:U.executed)===!0}),!(U!=null&&U.success)||U.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${A.label}?`))return;const ie=await n(Z,"fast_forward_mesh_node",{meshId:i.meshId,nodeId:A.id,dryRun:!1,execute:!0});S({phase:"execute",code:typeof(ie==null?void 0:ie.code)=="string"?ie.code:void 0,error:typeof(ie==null?void 0:ie.operationError)=="string"?ie.operationError:null,executed:(ie==null?void 0:ie.executed)===!0})}catch(U){S({phase:"dry_run",error:U instanceof Error?U.message:"fast-forward failed"})}finally{g(null)}}},[he,i.meshId,A,Z,n]);l.useEffect(()=>{if(!A)return;const U=ce=>{ce.key==="Escape"&&we()};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[we,A]),l.useEffect(()=>{if(!D||!n)return;const{daemonId:U,workspace:ce}=D,ie=j[ce];if(ie!=null&&ie.loading||ie&&(ie.entries.length>0||ie.error))return;let de=!1;return f(me=>{var oe;return{...me,[ce]:{loading:!0,error:null,entries:((oe=me[ce])==null?void 0:oe.entries)??[]}}}),n(U,"git_log",{workspace:ce,limit:5}).then(me=>{de||f(oe=>({...oe,[ce]:{loading:!1,error:null,entries:lj(me)}}))}).catch(me=>{de||f(oe=>({...oe,[ce]:{loading:!1,error:me instanceof Error?me.message:"git_log failed",entries:[]}}))}),()=>{de=!0}},[j,D,n]);const q=[...u.warnings??[],...i.nodes.filter(U=>U.machineStatus&&U.machineStatus!=="online").map(U=>`${U.machineLabel}: ${U.machineStatus}`)],ye=u.stats.incompleteSnapshotNodes>0,ge=u.stats.followUpNodes>0?`${u.stats.followUpNodes} need follow-up`:ye?"mesh visibility incomplete":"mesh converged",ve=u.stats.followUpNodes>0?"danger":ye?"warn":"good";return s.jsx(Si.Provider,{value:o,children:s.jsx("div",{className:"flex min-h-0 flex-col gap-4",children:s.jsx("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-4",children:s.jsxs("div",{className:`${o.cardClass} relative min-h-0 flex-1 rounded-[28px] p-3 sm:p-4`,style:{minHeight:420},children:[s.jsxs("div",{className:`absolute inset-x-4 top-4 z-30 flex max-h-[42dvh] flex-wrap items-start justify-between gap-3 overflow-y-auto rounded-2xl px-3.5 py-3 backdrop-blur-xl sm:static sm:mb-3 sm:max-h-none sm:overflow-visible sm:backdrop-blur-none ${o.isDark?"border border-white/10 bg-slate-950/85 sm:bg-slate-950/45":"border border-slate-200 bg-white/95 shadow-lg shadow-slate-900/10 sm:bg-white/95 sm:shadow-sm"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-wrap gap-2 text-xs ${o.textSecondary}`,children:[s.jsx(Fe,{label:ge,tone:ve}),u.stats.blockedReviewNodes>0&&s.jsx(Fe,{label:`${u.stats.blockedReviewNodes} blocked review`,tone:"danger"}),u.stats.notMergeableNodes>0&&s.jsx(Fe,{label:`${u.stats.notMergeableNodes} not mergeable`,tone:"danger"}),u.stats.mergeReadyNodes>0&&s.jsx(Fe,{label:`${u.stats.mergeReadyNodes} need merge`,tone:"warn"}),u.stats.cleanupCandidateNodes>0&&s.jsx(Fe,{label:`${u.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),u.stats.offlineNodes>0&&s.jsx(Fe,{label:`${u.stats.offlineNodes} offline`,tone:"danger"}),u.stats.incompleteSnapshotNodes>0&&s.jsx(Fe,{label:`${u.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),u.stats.missingGitSnapshotNodes>0&&s.jsx(Fe,{label:`${u.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),u.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Fe,{label:`${u.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),u.stats.staleGitSnapshotNodes>0&&s.jsx(Fe,{label:`${u.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((C==null?void 0:C.active)??0)>0&&s.jsx(Fe,{label:`${(C==null?void 0:C.active)??0} active queue`,tone:"info"}),s.jsx(Fe,{label:`${u.stats.totalNodes} nodes`,tone:"default"}),u.stats.totalActiveSessions>0&&s.jsx(Fe,{label:`${u.stats.totalActiveSessions} attached chats`,tone:"info"})]}),s.jsxs("details",{className:`max-w-full rounded-xl px-3 py-2 text-xs ${o.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 ${o.textSecondary} [&::-webkit-details-marker]:hidden`,children:"Legend & secondary details"}),s.jsxs("div",{className:"mt-3 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Fe,{label:`${u.stats.dirtyNodes} dirty`,tone:u.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Fe,{label:`${u.stats.orphanNodes} orphan`,tone:u.stats.orphanNodes>0?"warn":"good"}),s.jsx(Fe,{label:`${$.recentFailures} recent failures`,tone:$.recentFailures>0?"danger":"good"}),T.length===0?s.jsx(Fe,{label:"no session metadata"}):T.slice(0,2).map(([U,ce])=>s.jsx(Fe,{label:`${ce} ${U}`,tone:Ya(U)},U))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Fe,{label:"Anchor = default branch",tone:"info"}),s.jsx(Fe,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Fe,{label:"Submodule link = child checkout",tone:"warn"})]}),q.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:q.map(U=>s.jsx("span",{className:o.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:U},U))}),s.jsx("div",{className:`text-xs ${o.textMuted}`,children:"Hover nodes or edges for a quick preview. Click a node when you want pinned drill-down details."})]})]})]}),u.nodes.length>0?s.jsx(fw,{data:u,selectedNodeId:m,onNodeHoverChange:U=>{p((U==null?void 0:U.id)??null),U&&b(null)},onEdgeHoverChange:U=>{b((U==null?void 0:U.id)??null),U&&p(null)},onNodeClick:U=>{if((x==null?void 0:x.kind)==="node"&&m===U.id){d(null),k(null);return}d(U.id),k({kind:"node",nodeId:U.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:t}),!A&&W&&s.jsx("div",{className:"pointer-events-none absolute inset-x-3 bottom-3 z-20 flex justify-center p-2 sm:inset-x-auto sm:right-5 sm:top-24 sm:bottom-auto sm:justify-end",children:s.jsxs("section",{"aria-label":"Hovered node preview",className:o.isDark?"w-full max-w-[min(24rem,calc(100vw-2.5rem))] rounded-2xl border border-white/12 bg-slate-950/94 p-4 shadow-2xl shadow-black/35 backdrop-blur-xl":"w-full max-w-[min(24rem,calc(100vw-2.5rem))] rounded-2xl border border-slate-200 bg-white/96 p-4 shadow-2xl shadow-slate-900/12 backdrop-blur-xl",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:`truncate text-sm font-semibold ${o.textPrimary}`,children:W.label}),s.jsx("div",{className:`mt-1 font-mono text-[11px] ${o.textMuted}`,children:W.id.slice(0,16)})]}),s.jsx(Fe,{label:"hover preview",tone:"info"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[s.jsx(Fe,{label:W.health,tone:uc(W.health)}),W.branch&&s.jsx(Fe,{label:W.branch,tone:"default"}),W.ahead>0&&s.jsx(Fe,{label:`ahead ${W.ahead}`,tone:"warn"}),W.behind>0&&s.jsx(Fe,{label:`behind ${W.behind}`,tone:"warn"}),W.dirtyFiles>0&&s.jsx(Fe,{label:`${W.dirtyFiles} dirty`,tone:"warn"}),W.activeSessionCount>0&&s.jsx(Fe,{label:`${W.activeSessionCount} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[s.jsx(nt,{label:"Machine",value:W.machineLabel??"not reported"}),s.jsx(nt,{label:"Locality",value:W.locality}),s.jsx(nt,{label:"Workspace",value:W.workspace}),s.jsx(nt,{label:"Upstream",value:W.upstream??"none"}),s.jsx(nt,{label:"Dirty/ahead/behind",value:`${W.dirtyFiles} dirty · ↑${W.ahead}/↓${W.behind}`}),s.jsx(nt,{label:"Source",value:hc(W)})]})]})}),!A&&!W&&_&&s.jsx("div",{className:"pointer-events-none absolute inset-x-3 bottom-3 z-20 flex justify-center p-2 sm:inset-x-auto sm:right-5 sm:top-24 sm:bottom-auto sm:justify-end",children:s.jsxs("section",{"aria-label":"Hovered edge preview",className:o.isDark?"w-full max-w-[min(22rem,calc(100vw-2.5rem))] rounded-2xl border border-white/12 bg-slate-950/94 p-4 shadow-2xl shadow-black/35 backdrop-blur-xl":"w-full max-w-[min(22rem,calc(100vw-2.5rem))] rounded-2xl border border-slate-200 bg-white/96 p-4 shadow-2xl shadow-slate-900/12 backdrop-blur-xl",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:`truncate text-sm font-semibold ${o.textPrimary}`,children:_.label||pc(_)}),s.jsx("div",{className:`mt-1 text-[11px] ${o.textMuted}`,children:_.id})]}),s.jsx(Fe,{label:"hover preview",tone:"info"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[s.jsx(Fe,{label:pc(_),tone:"default"}),s.jsx(Fe,{label:uj(_),tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs",children:[s.jsx(nt,{label:"From",value:(L==null?void 0:L.label)??_.source}),s.jsx(nt,{label:"To",value:(B==null?void 0:B.label)??_.target}),s.jsx(nt,{label:"Label",value:_.label??"none"})]})]})}),A&&(x==null?void 0:x.kind)==="node"&&s.jsx("div",{className:"absolute inset-x-3 bottom-3 top-20 z-20 flex items-end justify-center p-2 sm:inset-5 sm:top-24 sm:items-start sm:justify-end",onClick:we,role:"presentation",children:s.jsxs("section",{role:"dialog","aria-modal":"false","aria-label":"Selected node",className:o.isDark?"max-h-[min(72vh,540px)] w-full max-w-[min(28rem,calc(100vw-2.5rem))] overflow-y-auto rounded-2xl border border-white/12 bg-slate-950/96 p-4 shadow-2xl shadow-black/40 backdrop-blur-xl":"max-h-[min(72vh,540px)] w-full max-w-[min(28rem,calc(100vw-2.5rem))] overflow-y-auto rounded-2xl border border-slate-200 bg-white/96 p-4 shadow-2xl shadow-slate-900/15 backdrop-blur-xl",onClick:U=>U.stopPropagation(),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:`truncate text-sm font-semibold ${o.textPrimary}`,children:A.label}),s.jsx("div",{className:`mt-1 font-mono text-[11px] ${o.textMuted}`,children:A.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[A.behind>0&&s.jsx("button",{type:"button",onClick:()=>{Me()},disabled:!he||v===A.id,className:o.isDark?"rounded-full border border-emerald-400/25 bg-emerald-500/10 px-2.5 py-1 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.5 py-1 text-xs font-semibold text-emerald-700 transition hover:bg-emerald-100 disabled:cursor-not-allowed disabled:opacity-45",children:v===A.id?"Checking":"Heal"}),s.jsx("button",{type:"button",onClick:we,className:o.isDark?"rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-xs text-slate-200 transition hover:bg-white/[0.08]":"rounded-full border border-slate-200 bg-white px-2.5 py-1 text-xs text-slate-600 transition hover:bg-slate-50",children:"Close"})]})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[s.jsx(Fe,{label:(I==null?void 0:I.health)??A.health,tone:uc((I==null?void 0:I.health)??A.health)}),A.branch&&s.jsx(Fe,{label:A.branch,tone:"default"}),A.ahead>0&&s.jsx(Fe,{label:`ahead ${A.ahead}`,tone:"warn"}),A.behind>0&&s.jsx(Fe,{label:`behind ${A.behind}`,tone:"warn"}),A.dirtyFiles>0&&s.jsx(Fe,{label:`${A.dirtyFiles} dirty`,tone:"warn"}),(I==null?void 0:I.connection)&&s.jsx(Fe,{label:dj(I),tone:sj(I.connection)}),E.length>0&&s.jsx(Fe,{label:`${E.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[s.jsx(nt,{label:"Machine",value:A.machineLabel??"not reported"}),s.jsx(nt,{label:"Locality",value:A.locality}),s.jsx(nt,{label:"Machine id",value:A.machineId??(I==null?void 0:I.machineId)??"not reported"}),s.jsx(nt,{label:"Daemon id",value:A.daemonId??(I==null?void 0:I.daemonId)??"not reported"}),s.jsx(nt,{label:"Workspace",value:(I==null?void 0:I.workspace)??A.workspace}),s.jsx(nt,{label:"Branch",value:A.branch??"unknown"}),s.jsx(nt,{label:"HEAD",value:Q??(I!=null&&I.gitProbePending?"Pending live git probe":"not reported")}),s.jsx(nt,{label:"Upstream",value:A.upstream??"none"}),s.jsx(nt,{label:"Dirty/ahead/behind",value:`${A.dirtyFiles} dirty · ↑${A.ahead}/↓${A.behind}`}),s.jsx(nt,{label:"Source",value:String(((X=I==null?void 0:I.connection)==null?void 0:X.source)??hc(A))}),s.jsx(nt,{label:"Transport",value:((be=I==null?void 0:I.connection)==null?void 0:be.transport)??"unknown"}),s.jsx(nt,{label:"Sessions",value:E.length>0?E.map(U=>bn(U.session)).join(", "):"none active"})]}),E.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${o.textMuted}`,children:"Active Sessions"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:E.map(U=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${o.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 ${o.textMuted}`,title:U.session.sessionId,children:tj(U.session.sessionId)}),s.jsx(Fe,{label:bn(U.session),tone:Ya(bn(U.session))})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 ${o.textMuted}`,children:[s.jsx("span",{className:"truncate",children:U.session.providerType||"provider unknown"}),s.jsx("span",{children:Qw(U.session)}),s.jsx("span",{children:ej(U.session)})]}),U.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${o.textMuted}`,children:U.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${o.textMuted}`,title:U.session.workspace||U.workspace,children:[(U.session.workspace||U.workspace).slice(0,42),U.branch?` · ${U.branch}`:""]})]},U.session.sessionId))})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${o.textMuted}`,children:"Ledger (mesh-wide)"}),s.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[s.jsx(nt,{label:"Completed",value:String($.taskCompleted)}),s.jsx(nt,{label:"Failed",value:s.jsx("span",{className:$.taskFailed>0?o.isDark?"text-rose-300":"text-rose-600":"",children:$.taskFailed})}),s.jsx(nt,{label:"Launched",value:String($.sessionLaunched)}),s.jsx(nt,{label:"Recent failures",value:s.jsx("span",{className:$.recentFailures>0?o.isDark?"text-amber-300":"text-amber-600":"",children:$.recentFailures})})]})]}),(()=>{var ie,de;const U=((ie=i.queue)==null?void 0:ie.tasks)??((de=i.queue)==null?void 0:de.items)??null;if(!Array.isArray(U)||U.length===0)return null;const ce=U.filter(me=>aj(me)===m).slice(0,3);return ce.length===0?null:s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${o.textMuted}`,children:"Queue tasks"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:ce.map(me=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${o.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 ${o.textMuted}`,children:me.id.slice(0,12)}),s.jsx(Fe,{label:me.status??"unknown",tone:Ya(me.status)})]}),me.message&&s.jsx("div",{className:`mt-0.5 truncate ${o.textMuted}`,children:me.message.slice(0,48)})]},me.id))})]})})(),A.snapshotWarnings.length>0&&s.jsxs("div",{className:o.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:"Key warning"}),s.jsx("div",{className:"mt-1",children:A.snapshotWarnings[0]})]}),((ue=A.branchConvergence)==null?void 0:ue.nextStep)&&s.jsxs("div",{className:o.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:"Follow-up"}),s.jsx("div",{className:"mt-1",children:A.branchConvergence.nextStep})]}),w&&s.jsxs("div",{className:o.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:w.phase==="execute"?"Heal result":"Heal preview"}),s.jsx("div",{className:"mt-1",children:w.code??w.error??"No result code returned."})]})]})})]})})})})}function pt(e){return typeof e=="string"?e.trim():""}function Ro(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ni(...e){const t=new Set;for(const r of e){const n=pt(r);n&&t.add(n)}return[...t]}function hj(e,t){var h,p;const r=Ro(e==null?void 0:e.settings),n=pt((h=e==null?void 0:e.coordinator)==null?void 0:h.meshId)||pt(r.meshCoordinatorFor),a=pt(r.meshNodeFor),o=!!n||!!a,i=n===t||a===t;if(o&&!i)return null;const c=Ro(e==null?void 0:e.activeChat),u=Ni(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),m=u[0]||"";if(!m)return null;const d=n===t?pt((p=e==null?void 0:e.coordinator)==null?void 0:p.role)||"coordinator":a===t?pt(r.meshNodeRole)||"worker":pt(e==null?void 0:e.role)||pt(r.meshNodeRole)||void 0;return{sessionId:m,aliases:u,meshId:t,nodeId:i&&pt(r.meshNodeId)||null,providerType:pt(e==null?void 0:e.providerType)||void 0,state:pt(e==null?void 0:e.status)||void 0,chatStatus:pt(c.status)||void 0,lifecycle:pt(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:pt(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:pt(e==null?void 0:e.runtimeRecoveryState)||void 0,...d?{role:d}:{},...i?{isSelfCoordinator:n===t}:{},workspace:pt(e==null?void 0:e.workspace)||null}}function pm(e,t){var n;return t?(Array.isArray((n=e.status)==null?void 0:n.sessions)?e.status.sessions:[]).map(a=>hj(a,t)).filter(a=>a!==null):[]}function ta(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function pj(e,t){const r=new Set(ta(t));return ta(e).some(n=>r.has(n))}function fj(e,t){const r=t.filter(a=>!!a);return r.length===0?e:[...e.filter(a=>!r.some(o=>pj(a,o))),...r]}function xj(e,t){if(t.length===0)return e;const r=new Map;for(const o of t)for(const i of ta(o))r.set(i,o);let n=!1;const a=(e.nodes??[]).map(o=>{const i=Array.isArray(o.activeSessionDetails)?o.activeSessionDetails:Array.isArray(o.sessions)?o.sessions:[],c=new Map;for(const m of i){const d=Ni(m==null?void 0:m.sessionId,m==null?void 0:m.session_id,m==null?void 0:m.id,m==null?void 0:m.providerSessionId,m==null?void 0:m.provider_session_id),h=d[0]||"";if(!h)continue;const p=d.map(y=>r.get(y)).find(Boolean);p&&(n=!0),c.set(h,p?{...m,sessionId:h,providerType:p.providerType||m.providerType,state:p.state||m.state,chatStatus:p.chatStatus||m.chatStatus,lifecycle:p.lifecycle||m.lifecycle,surfaceKind:p.surfaceKind||m.surfaceKind,recoveryState:p.recoveryState||m.recoveryState,role:p.role||m.role,isSelfCoordinator:p.isSelfCoordinator??m.isSelfCoordinator,workspace:p.workspace||m.workspace}:{...m,sessionId:h})}for(const m of o.activeSessions??[])c.has(m)||c.set(m,{sessionId:m,workspace:o.workspace,isCached:!0});for(const m of t)ta(m).some(h=>c.has(h))||m.nodeId===o.nodeId&&(n=!0,c.set(m.sessionId,{sessionId:m.sessionId,providerType:m.providerType,state:m.state,chatStatus:m.chatStatus,lifecycle:m.lifecycle,surfaceKind:m.surfaceKind,recoveryState:m.recoveryState,role:m.role,isSelfCoordinator:m.isSelfCoordinator,workspace:m.workspace||o.workspace}));const u=[...c.values()];return u.length===0?o:{...o,activeSessionDetails:u,activeSessions:u.map(m=>m.sessionId)}});return n?{...e,nodes:a}:e}function bj(e,t){const n=pm(e,t).map(a=>{var u;const o=(Array.isArray((u=e.status)==null?void 0:u.sessions)?e.status.sessions:[]).find(m=>pt(m==null?void 0:m.id)===a.sessionId),i=Ro(o==null?void 0:o.activeInteractivePrompt),c=o!=null&&o.meshQueueStats&&typeof o.meshQueueStats=="object"?JSON.stringify(o.meshQueueStats):"";return[a.sessionId,a.providerType??"",a.state??"",a.chatStatus??"",a.lifecycle??"",a.surfaceKind??"",a.recoveryState??"",pt(i.status)||pt(i.kind)||pt(i.type),a.nodeId??"",a.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(a=>!!a).sort();return n.length>0?n.join(`
|
|
72
|
+
`),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 ${r.textPrimary}`,children:Ga(S.sessionId)}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${za(S,r.isDark)}`,children:Gt(S)})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"truncate",children:S.providerType||"provider unknown"}),s.jsx("span",{children:g}),s.jsx("span",{children:sc(v)})]}),S.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${r.textMuted}`,children:S.statusNote})]},S.sessionId)})})]}),u&&p&&s.jsx("div",{className:`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${r.isDark?"border-cyan-400/15 bg-cyan-500/8 text-cyan-50/90":"border-sky-300 bg-sky-50 text-sky-700"}`,style:Gv,children:p})]}),s.jsx(Qr,{type:"source",position:a==="TB"?Zt.Bottom:Zt.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const Zv={meshNode:Qv},ew=8;function tw(e){if(e.length<2)return null;if(e.length===2){const[m,d]=e;return{d:`M ${m.x},${m.y} L ${d.x},${d.y}`,labelX:(m.x+d.x)/2,labelY:(m.y+d.y)/2}}const t=ew,r=[`M ${e[0].x},${e[0].y}`];for(let m=1;m<e.length-1;m+=1){const d=e[m-1],h=e[m],p=e[m+1],y=Math.sign(h.x-d.x),b=Math.sign(h.y-d.y),x=Math.sign(p.x-h.x),k=Math.sign(p.y-h.y),j=Math.hypot(h.x-d.x,h.y-d.y),f=Math.hypot(p.x-h.x,p.y-h.y),w=Math.min(t,j/2,f/2);if(w<1||y===x&&b===k){r.push(`L ${h.x},${h.y}`);continue}const S=h.x-y*w,v=h.y-b*w,g=h.x+x*w,N=h.y+k*w;r.push(`L ${S},${v}`),r.push(`Q ${h.x},${h.y} ${g},${N}`)}const n=e[e.length-1];r.push(`L ${n.x},${n.y}`);let a=0;const o=[0];for(let m=1;m<e.length;m+=1)a+=Math.hypot(e[m].x-e[m-1].x,e[m].y-e[m-1].y),o.push(a);const i=a/2;let c=e[0].x,u=e[0].y;for(let m=1;m<e.length;m+=1)if(o[m]>=i){const d=o[m]-o[m-1],h=d===0?0:(i-o[m-1])/d;c=e[m-1].x+(e[m].x-e[m-1].x)*h,u=e[m-1].y+(e[m].y-e[m-1].y)*h;break}return{d:r.join(" "),labelX:c,labelY:u}}function sw(e){const t=e.data.routePoints;if(t&&t.length>=2){const o=tw(t);if(o)return[o.d,o.labelX,o.labelY]}const r={sourceX:e.sourceX,sourceY:e.sourceY,sourcePosition:e.sourcePosition,targetX:e.targetX,targetY:e.targetY,targetPosition:e.targetPosition},n=e.data.graphEdge;let a;return n.type==="parentBranch"?a=mh(r):n.type==="worktreeLink"||n.type==="submoduleLink"||n.type==="cloneLink"?a=dh(r):a=uh(r),[a[0],a[1],a[2]]}function rw(e,t){const r="nodrag nopan rounded-md border px-2 py-1 text-[10px] font-semibold shadow-sm backdrop-blur-sm";switch(e.type){case"orphanLink":return t?`${r} border-orange-400/35 bg-orange-500/14 text-orange-100`:`${r} border-orange-300 bg-orange-50 text-orange-700`;case"submoduleLink":return t?`${r} border-violet-400/30 bg-violet-500/14 text-violet-100`:`${r} border-violet-300 bg-violet-50 text-violet-700`;case"sessionLink":return t?`${r} border-emerald-400/30 bg-emerald-500/14 text-emerald-100`:`${r} border-emerald-300 bg-emerald-50 text-emerald-700`;case"cloneLink":return t?`${r} border-teal-400/30 bg-teal-500/14 text-teal-100`:`${r} border-teal-300 bg-teal-50 text-teal-700`;default:return t?`${r} border-sky-400/25 bg-slate-950/78 text-sky-100`:`${r} border-sky-300 bg-white/95 text-sky-700`}}function nw(e){const t=l.useContext(vi),r=e.data.graphEdge,[n,a,o]=sw(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(oh,{id:e.id,path:n,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(ih,{children:s.jsx("div",{className:rw(r,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${a}px, ${o}px)`,pointerEvents:"none",maxWidth:Mv.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const aw={meshEdge:nw};async function ow(e,t=Ys("dark"),r=!1,n="LR"){const a=await Fv(e,r,n),o=new Set(a.nodes.map(d=>d.id)),i=a.nodes.map(d=>({id:d.id,type:d.type,position:d.position,data:{graphNode:d.graphNode,compact:r},selected:d.selected,draggable:d.draggable,selectable:d.selectable})),c=e.edges.filter(d=>o.has(d.source)&&o.has(d.target)),u=cw(c),m=c.map(d=>{var h;return{id:d.id,source:d.source,target:d.target,label:u.has(d.id)?d.label:void 0,type:"meshEdge",data:{graphEdge:d,routePoints:(h=a.edgeRoutes.get(d.id))==null?void 0:h.points},animated:d.type==="orphanLink",markerEnd:d.direction==="directed"?{type:ah.ArrowClosed,width:d.type==="submoduleLink"?16:18,height:d.type==="submoduleLink"?16:18,color:ac(d)}:void 0,style:{stroke:ac(d),strokeWidth:d.type==="orphanLink"?2.25:d.type==="submoduleLink"?1.7:d.type==="worktreeLink"?1.8:d.type==="cloneLink"?1.6:2,strokeDasharray:d.type==="orphanLink"?"5 4":d.type==="submoduleLink"?"4 3":d.type==="cloneLink"?"6 3":void 0},labelStyle:{fill:t.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:t.edgeLabelBackgroundColor,fillOpacity:1,stroke:t.edgeLabelBorderColor},labelBgPadding:[6,4],labelBgBorderRadius:7}});return{nodes:i,edges:m}}const iw=3,lw=2;function nc(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 cw(e){const t=new Set,r=new Map;for(const n of e){if(!n.label)continue;const a=r.get(n.source);a?a.push(n):r.set(n.source,[n])}for(const n of r.values()){if(n.length<iw){for(const o of n)t.add(o.id);continue}const a=[...n].sort((o,i)=>{const c=nc(i)-nc(o);return c!==0?c:o.id.localeCompare(i.id)});for(const o of a.slice(0,lw))t.add(o.id)}return t}function ac(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 dw(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 uw(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 mw({data:e,viewportKey:t}){const r=lh(),n=ch(),a=l.useRef(null),o=l.useMemo(()=>qu(e),[e]),i=l.useMemo(()=>wv(e),[e]);return l.useEffect(()=>{if(!r||e.nodes.length===0||a.current===t)return;let c=!1;const u=requestAnimationFrame(()=>{if(c)return;const m=i.length>0&&i.length<e.nodes.length;n.fitView({nodes:m?i.map(d=>({id:d})):void 0,padding:m?.24:.2,maxZoom:m?.98:.9,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(u)}},[e.nodes.length,i,o,r,n,t]),null}function hw(e){return e>=16?"h-[720px] min-h-[720px] sm:h-[860px] xl:h-[980px]":e>=10?"h-[580px] min-h-[580px] sm:h-[700px] xl:h-[820px]":"h-[460px] min-h-[460px] sm:h-[560px] xl:h-[680px]"}const pw=12;function fw({data:e,selectedNodeId:t=null,onNodeClick:r,onNodeHoverChange:n,onEdgeHoverChange:a}){const{theme:o}=qs(),i=l.useMemo(()=>Ys(o),[o]),c=l.useMemo(()=>Wv(e),[e]),u=l.useMemo(()=>Kv(e),[e]),m=e.nodes.length>=Uv,[d,h]=l.useState("LR"),p=l.useMemo(()=>d==="auto"?Tv(e):d,[d,c,e]),y=e.nodes.length>=pw,[b,x]=l.useState({nodes:[],edges:[]}),k=l.useRef(null),[j,f]=l.useState({width:0,height:0}),w=l.useMemo(()=>`${jv(e,j.width,j.height)}::${p}`,[c,e,j.height,j.width,p]);l.useEffect(()=>{let N=!1;return ow(e,i,m,p).then(M=>{N||x(M)}),()=>{N=!0}},[e,u,i,m,p]);const S=l.useMemo(()=>b.nodes.map(N=>({...N,selected:N.id===t})),[b.nodes,t]);l.useEffect(()=>{const N=k.current;if(!N)return;const M=()=>{const $=Math.max(0,Math.round(N.clientWidth)),R=Math.max(0,Math.round(N.clientHeight));f(T=>T.width===$&&T.height===R?T:{width:$,height:R})};M();const C=typeof ResizeObserver=="function"?new ResizeObserver(()=>M()):null;return C==null||C.observe(N),window.addEventListener("resize",M),()=>{C==null||C.disconnect(),window.removeEventListener("resize",M)}},[]);const v=hw(e.nodes.length),g=N=>N?i.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":i.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(vi.Provider,{value:i,children:s.jsx(Qu.Provider,{value:m,children:s.jsx(Zu.Provider,{value:p,children:s.jsxs("div",{ref:k,className:i.graphShellClass,children:[s.jsxs("div",{className:`flex flex-wrap items-center justify-between gap-2 px-3 pt-3 pb-2 text-[11px] ${i.textSecondary}`,children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs("span",{className:i.graphStatChipClass,children:[e.stats.totalNodes," node",e.stats.totalNodes===1?"":"s"]}),e.stats.totalActiveSessions>0&&s.jsxs("span",{className:i.isDark?"rounded-full border border-emerald-400/25 bg-emerald-500/12 px-3 py-1 text-emerald-100":"rounded-full border border-emerald-300 bg-emerald-50 px-3 py-1 text-emerald-700",children:[e.stats.totalActiveSessions," active session",e.stats.totalActiveSessions===1?"":"s"]}),e.stats.orphanNodes>0&&s.jsxs("span",{className:i.isDark?"rounded-full border border-orange-400/25 bg-orange-500/12 px-3 py-1 text-orange-100":"rounded-full border border-orange-300 bg-orange-50 px-3 py-1 text-orange-700",children:[e.stats.orphanNodes," need attention"]}),m&&s.jsx("span",{className:i.isDark?"rounded-full border border-white/8 bg-white/[0.03] px-3 py-1 text-slate-400":"rounded-full border border-slate-200 bg-slate-50/80 px-3 py-1 text-slate-500",children:"dense view · hover for details"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:i.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:()=>h("auto"),className:g(d==="auto"),title:`Auto (currently ${p==="TB"?"top-bottom":"left-right"})`,children:"Auto"}),s.jsx("button",{type:"button",onClick:()=>h("LR"),className:g(d==="LR"),title:"Left to right",children:"LR"}),s.jsx("button",{type:"button",onClick:()=>h("TB"),className:g(d==="TB"),title:"Top to bottom",children:"TB"})]}),s.jsx("div",{className:i.graphHintChipClass,children:"drag or scroll to pan"})]})]}),s.jsx("div",{className:`w-full min-w-0 ${v}`,children:s.jsxs(eh,{nodes:S,edges:b.edges,nodeTypes:Zv,edgeTypes:aw,minZoom:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(N,M)=>r==null?void 0:r(M.data.graphNode),onNodeMouseEnter:(N,M)=>n==null?void 0:n(M.data.graphNode),onNodeMouseLeave:()=>n==null?void 0:n(null),onEdgeMouseEnter:(N,M)=>{var C;return a==null?void 0:a(((C=M.data)==null?void 0:C.graphEdge)??null)},onEdgeMouseLeave:()=>a==null?void 0:a(null),className:"h-full w-full",colorMode:i.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(mw,{data:e,viewportKey:w}),s.jsx(th,{className:i.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),y&&s.jsx(sh,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:dw,nodeClassName:uw,nodeStrokeWidth:3,className:i.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(rh,{variant:nh.Dots,gap:18,size:1.2,color:i.graphBackgroundDotColor})]})})]})})})})}function at(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function je(...e){for(const t of e){if(typeof t!="string")continue;const r=t.trim();if(r)return r}}function Mt(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function St(...e){for(const t of e)if(typeof t=="boolean")return t}function Va(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function wi(e){switch(e){case"fresh":return 30;case"no_upstream":return 4;case"unchecked":case void 0:return 0;case"stale":return-10;case"unavailable":return-15;default:return 0}}function xw(e,t){const r=typeof e=="string"?e.trim().replace(/[\\/]+$/,""):"",n=typeof t=="string"?t.trim():"";if(n){if(/^(?:[A-Za-z]:[\\/]|\/)/.test(n))return n;if(r)return`${r}/${n.replace(/^[\\/]+/,"")}`}}function bw(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=at(n),o=je(a.path),i=je(a.commit),c=je(a.repoPath,a.repo_root)??xw(t,o);return!o||!i||!c?null:{path:o,commit:i,repoPath:c,dirty:St(a.dirty)??!1,outOfSync:St(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:Mt(a.lastCheckedAt,a.last_checked_at)??Date.now(),...je(a.error)?{error:je(a.error)}:{}}}).filter(n=>n!==null);return r.length>0?r:void 0}function gw(e){return St(e.isGitRepo)!==void 0||!!je(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||Mt(e.ahead,e.behind,e.staged,e.modified,e.untracked,e.deleted,e.renamed,e.lastCheckedAt,e.last_checked_at)!==void 0||Array.isArray(e.submodules)&&e.submodules.length>0}function Ln(e,t,r){const n=St(e.isGitRepo);if(!Object.keys(e).length||!gw(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(w=>typeof w=="string"):[],i=Mt(e.conflicts)??o.length,c=St(e.hasConflicts)??i>0,u=je(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,m=bw(e.submodules,u),d=je(e.upstreamStatus,e.upstream_status),h=Mt(e.upstreamFetchedAt,e.upstream_fetched_at),p=je(e.upstreamFetchError,e.upstream_fetch_error),y=je(e.error),b=Mt(e.staged)??0,x=Mt(e.modified)??0,k=Mt(e.untracked)??0,j=Mt(e.deleted)??0,f=Mt(e.renamed)??0;return{workspace:je(e.workspace,t.workspace)||"",repoRoot:u??null,isGitRepo:a,branch:je(e.branch)??null,headCommit:je(e.headCommit)??null,headMessage:je(e.headMessage)??null,upstream:je(e.upstream)??null,upstreamStatus:d??"unchecked",...h!==void 0?{upstreamFetchedAt:h}:{},...p?{upstreamFetchError:p}:{},ahead:Mt(e.ahead)??0,behind:Mt(e.behind)??0,staged:b,modified:x,untracked:k,deleted:j,renamed:f,dirty:St(e.dirty,e.isDirty,e.is_dirty)??(b+x+k+j+f>0||c),hasConflicts:c,conflictFiles:o,stashCount:Mt(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??Mt(e.lastCheckedAt,e.last_checked_at)??Date.now(),...m?{submodules:m}:{},...y?{error:y}:{}}}function yw(e){if(!e)return Number.NEGATIVE_INFINITY;let t=0;return e.isGitRepo===!0&&(t+=50),e.isGitRepo===!1&&(t-=10),e.branch&&(t+=20),e.headCommit&&(t+=20),e.upstream&&(t+=10),t+=wi(e.upstreamStatus),typeof e.ahead=="number"&&(t+=2),typeof e.behind=="number"&&(t+=2),Array.isArray(e.submodules)&&e.submodules.length>0&&(t+=4+e.submodules.length),e.error&&(t-=20),t}function vw(e){const t=at(e.lastGit??e.last_git),r=at(t.result),n=at(t.status),a=at(r.status),o=at(e.lastProbe??e.last_probe),i=at(o.git),c=at(i.result),u=at(i.status),m=at(c.status);let d=null;for(const h of[n,a,u,m]){const p=Ln(h,e,{lastCheckedAt:Date.now()});if(!p)continue;const y=yw(p);(!d||y>d.score)&&(d={git:p,score:y})}return d==null?void 0:d.git}function ww(e){const t=Array.isArray(e==null?void 0:e.submodules)?e.submodules:[];let r=!1,n=!1;for(const a of t)a!=null&&a.outOfSync&&(n=!0),a!=null&&a.dirty&&(r=!0);return{dirty:r,outOfSync:n}}function jw(e){return e?(e.staged??0)>0||(e.modified??0)>0||(e.untracked??0)>0||(e.deleted??0)>0||(e.renamed??0)>0||e.hasConflicts===!0:!1}function ea(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=ww(e);return t.outOfSync?"degraded":t.dirty||jw(e)?"dirty":"online"}function kw(e,t){const r=t?ea(t):void 0;return!e||e==="unknown"?r:e}function sm(e){const t=at(e),r=je(t.sessionId,t.session_id,t.id);return r?{sessionId:r,...je(t.providerType,t.provider)?{providerType:je(t.providerType,t.provider)}:{},...je(t.state,t.status)?{state:je(t.state,t.status)}:{},...je(t.chatStatus,t.chat_status)?{chatStatus:je(t.chatStatus,t.chat_status)}:{},...je(t.lifecycle)?{lifecycle:je(t.lifecycle)}:{},...je(t.surfaceKind,t.surface_kind)?{surfaceKind:je(t.surfaceKind,t.surface_kind)}:{},...je(t.recoveryState,t.recovery_state)?{recoveryState:je(t.recoveryState,t.recovery_state)}:{},...je(t.workspace)?{workspace:je(t.workspace)}:{},...je(t.title)?{title:je(t.title)}:{},...je(t.role)?{role:je(t.role)}:{},...St(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:St(t.isSelfCoordinator,t.is_self_coordinator)}:{},...je(t.statusNote,t.status_note)?{statusNote:je(t.statusNote,t.status_note)}:{},...je(t.createdAt,t.created_at)?{createdAt:je(t.createdAt,t.created_at)}:{},...je(t.startedAt,t.started_at)?{startedAt:je(t.startedAt,t.started_at)}:{},...je(t.lastActivityAt,t.last_activity_at)?{lastActivityAt:je(t.lastActivityAt,t.last_activity_at)}:{},...St(t.isCached,t.is_cached)!==void 0?{isCached:St(t.isCached,t.is_cached)}:{}}:null}function Sw(e){const t=Array.isArray(e.activeSessionDetails)?e.activeSessionDetails:Array.isArray(e.active_session_details)?e.active_session_details:Array.isArray(e.sessions)?e.sessions:null;if(t){const a=t.map(sm).filter(o=>o!==null);if(a.length>0)return a}const r=at(e.activeSession??e.active_session),n=je(r.id,r.sessionId,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id);if(n)return[{sessionId:n,...je(r.providerType,r.provider)?{providerType:je(r.providerType,r.provider)}:{},...je(r.state,r.status)?{state:je(r.state,r.status)}:{},...je(r.chatStatus,r.chat_status)?{chatStatus:je(r.chatStatus,r.chat_status)}:{},...je(r.statusNote,r.status_note)?{statusNote:je(r.statusNote,r.status_note)}:{},...je(r.createdAt,r.created_at)?{createdAt:je(r.createdAt,r.created_at)}:{},...je(r.startedAt,r.started_at)?{startedAt:je(r.startedAt,r.started_at)}:{}}]}function Nw(e){const t=at(e.connection);return Object.keys(t).length>0?t:void 0}function Cw(e){const t=e==null?void 0:e.source,r=e==null?void 0:e.transport;return{...e,perspective:(e==null?void 0:e.perspective)??"selected_coordinator",source:t&&t!=="not_reported"?t:"mesh_peer_status",state:"connected",transport:r&&r!=="unknown"?r:"direct",reported:!0,reason:"Live peer git snapshot reported by the selected coordinator."}}function ji(e){var r;const t=e.git;return!!(t&&(t.isGitRepo===!0||t.isGitRepo===!1||t.branch||t.upstream||t.headCommit||typeof t.lastCheckedAt=="number"||(((r=t.submodules)==null?void 0:r.length)??0)>0))}function oc(e){var n,a,o,i,c,u;let t=0;const r=e.git;return ji(e)&&(t+=80,(r==null?void 0:r.isGitRepo)===!0&&(t+=20),(r==null?void 0:r.isGitRepo)===!1&&(t+=5),r!=null&&r.branch&&(t+=20),r!=null&&r.upstream&&(t+=12),r!=null&&r.headCommit&&(t+=12),t+=wi(r==null?void 0:r.upstreamStatus),typeof(r==null?void 0:r.lastCheckedAt)=="number"&&(t+=6),t+=(((n=r==null?void 0:r.submodules)==null?void 0:n.length)??0)*6),(a=e.branchConvergence)!=null&&a.status&&(t+=12),(((o=e.connection)==null?void 0:o.state)==="connected"||((i=e.connection)==null?void 0:i.state)==="self")&&(t+=8),((c=e.connection)==null?void 0:c.transport)==="direct"&&(t+=4),((u=e.connection)==null?void 0:u.source)==="mesh_peer_status"&&(t+=4),e.health==="online"&&(t+=4),e.health==="dirty"&&(t+=3),e.health==="degraded"&&(t+=2),e.launchReady&&(t+=2),e.gitProbePending&&(t-=40),e.error&&(t-=10),t}function Mw(e,t){var b,x,k,j;const r=oc(e),a=oc(t)>r?t:e,o=a===t?e:t,i=a.git??o.git,c=(((b=a.providers)==null?void 0:b.length)??0)>0?a.providers:o.providers,u=(((x=a.activeSessions)==null?void 0:x.length)??0)>0?a.activeSessions:o.activeSessions,m=(((k=a.activeSessionDetails)==null?void 0:k.length)??0)>0?a.activeSessionDetails:o.activeSessionDetails,d=(((j=a.providerPriority)==null?void 0:j.length)??0)>0?a.providerPriority:o.providerPriority,h=a.connection??o.connection,p={...o,...a,machineLabel:a.machineLabel||o.machineLabel,workspace:a.workspace||o.workspace,...a.repoRoot||o.repoRoot?{repoRoot:a.repoRoot||o.repoRoot}:{},...a.daemonId||o.daemonId?{daemonId:a.daemonId||o.daemonId}:{},...a.machineId||o.machineId?{machineId:a.machineId||o.machineId}:{},...a.machineStatus||o.machineStatus?{machineStatus:a.machineStatus||o.machineStatus}:{},health:i&&(!a.health||a.health==="unknown")?ea(i):a.health,providers:c??[],activeSessions:u??[],...m&&m.length>0?{activeSessionDetails:m}:{},...d&&d.length>0?{providerPriority:d}:{},...h?{connection:h}:{},...i?{git:i}:{}},y=at(a.branchConvergence);return Object.keys(y).length>0?Object.assign(p,{branchConvergence:y}):delete p.branchConvergence,i&&(delete p.gitProbePending,delete p.error),p}function rm(e){const t=at(e),r=je(t.nodeId,t.id);if(!r)return null;const n=at(t.cachedStatus),a=vw(t),o=a?void 0:Ln(at(t.git),t)??Ln(t,t),i=a??o,c=i?void 0:Ln(at(n.git),t),u=i??c,m=je(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),d=je(t.health),h=a?ea(u):kw(d,i)||(u?ea(u):void 0)||je(n.health)||m||je(t.status)||"unknown",y=(a?void 0:je(t.error))??(i?void 0:je(n.error)),b=Sw(t),x=Va(t.activeSessions),k=(b==null?void 0:b.map(M=>M.sessionId))??[],j=Va(t.providerPriority),f=St(t.gitProbePending,t.git_probe_pending),w=i?void 0:f,S=Nw(t),v=at(t.branchConvergence??t.branch_convergence),g=S==null?void 0:S.state,N=a&&(!(S!=null&&S.reported)||g==="unknown")?Cw(S):S;return{nodeId:r,machineLabel:je(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:je(t.workspace,u==null?void 0:u.workspace)||"",...je(t.repoRoot,t.repo_root,u==null?void 0:u.repoRoot)?{repoRoot:je(t.repoRoot,t.repo_root,u==null?void 0:u.repoRoot)}:{},...je(t.daemonId,t.daemon_id)?{daemonId:je(t.daemonId,t.daemon_id)}:{},...je(t.machineId,t.machine_id)?{machineId:je(t.machineId,t.machine_id)}:{},...m?{machineStatus:m}:{},...St(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:St(t.isLocalWorktree,t.is_local_worktree)}:{},...je(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:je(t.worktreeBranch,t.worktree_branch)}:{},...je(t.clonedFromNodeId,t.cloned_from_node_id)?{clonedFromNodeId:je(t.clonedFromNodeId,t.cloned_from_node_id)}:{},health:h,...u?{git:u}:{},...w!==void 0?{gitProbePending:w}:{},providers:Va(t.providers),activeSessions:x.length>0?x:k,...b&&b.length>0?{activeSessionDetails:b}:{},...j.length>0?{providerPriority:j}:{},...St(t.launchReady)!==void 0?{launchReady:St(t.launchReady)}:a?{launchReady:!0}:{},...je(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:je(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},...je(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:je(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...N?{connection:N}:{},...Object.keys(v).length>0?{branchConvergence:v}:{},...y?{error:y}:{}}}function ic(e){const t=new Map;for(const r of e){const n=t.get(r.sessionId);t.set(r.sessionId,n?{...n,...r}:r)}return[...t.values()]}function nm(e,t){const r=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],n=r.map(sm).filter(a=>a!==null);return n.length===0?t:t.map(a=>{const o=n.filter(c=>{const u=at(r.find(p=>{const y=at(p);return je(y.sessionId,y.session_id,y.id)===c.sessionId})),m=je(u.nodeId,u.node_id),d=je(u.daemonId,u.daemon_id),h=je(u.workspace);return m&&m===a.nodeId?!0:d&&a.daemonId&&d===a.daemonId?!h||!a.workspace||h===a.workspace:!!(h&&a.workspace&&h===a.workspace)});if(o.length===0)return a;const i=ic([...a.activeSessionDetails??[],...o]);return{...a,activeSessionDetails:i,activeSessions:ic([...a.activeSessionDetails??[],...o,...(a.activeSessions??[]).map(c=>({sessionId:c}))]).map(c=>c.sessionId)}})}function Iw(e){const t=at(e);return Array.isArray(t.sessions)||Array.isArray(t.active_session_details)||je(t.daemon_id,t.machine_id,t.repo_root,t.worktree_branch,t.cloned_from_node_id)!==void 0||St(t.is_local_worktree)!==void 0}function am(e){const t=new Map,r=[];for(const n of e){const a=Iw(n)?rm(n)??n:n;if(!(a!=null&&a.nodeId))continue;const o=t.get(a.nodeId);if(!o){t.set(a.nodeId,a),r.push(a);continue}const i=Mw(o,a);t.set(a.nodeId,i);const c=r.findIndex(u=>u.nodeId===a.nodeId);c>=0&&(r[c]=i)}return r}function om(e){const t=am(e.nodes??[]);return{...e,nodes:nm(e,t)}}function Aw(e){var r;const t=e==null?void 0:e.git;return{nodeId:(e==null?void 0:e.nodeId)??null,chosenSource:t?"live_git":e!=null&&e.gitProbePending?"pending_git":"no_git",hasLiveGit:ji(e??{git:void 0}),branch:(t==null?void 0:t.branch)??null,upstream:(t==null?void 0:t.upstream)??null,headCommit:(t==null?void 0:t.headCommit)??null,submoduleCount:((r=t==null?void 0:t.submodules)==null?void 0:r.length)??0,pendingGit:(e==null?void 0:e.gitProbePending)===!0,connection:e!=null&&e.connection?{state:e.connection.state,transport:e.connection.transport,source:e.connection.source}:null}}function Tw(e){const t=je(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(u=>rm(u)).filter(u=>u!==null):null;if(!t||!n)return null;const a=nm(e,am(n)),o=je(e.meshName,e.mesh_name,e.name),i=je(e.repoIdentity,e.repo_identity),c=je(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!o||!i||!c?null:{...e,meshId:t,meshName:o,repoIdentity:i,refreshedAt:c,nodes:a}}function _w(e){var o;let t=0;const r=at(e.sourceOfTruth),n=at(r.directPeerTruth);je(r.currentStatus)==="live_git_and_session_probes"&&(t+=100),r.coordinatorOwnsLiveTruth===!0&&(t+=25),n.satisfied===!0&&(t+=15);for(const i of e.nodes){const c=i.git;if(!c){i.gitProbePending&&(t-=8);continue}t+=10,c.isGitRepo===!0&&(t+=5),c.isGitRepo===!1&&(t+=1),c.branch&&(t+=4),c.upstream&&(t+=3),c.headCommit&&(t+=3),t+=wi(c.upstreamStatus),typeof c.ahead=="number"&&(t+=1),typeof c.behind=="number"&&(t+=1),typeof c.lastCheckedAt=="number"&&(t+=2),t+=(((o=c.submodules)==null?void 0:o.length)??0)*2}return t}function lc(e){let t=null;for(const r of e){const n=Tw(at(r));if(!n)continue;const a=_w(n);(!t||a>t.score)&&(t={status:n,score:a})}return(t==null?void 0:t.status)??null}function im(e){const r=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,n=lc([r==null?void 0:r.status,r]);return n||lc([e==null?void 0:e.status,e])}const Lw=5*60*1e3;function lm(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function cm(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function Rw(e){var t,r,n;return((t=e.connection)==null?void 0:t.state)==="self"||e.isLocalWorktree===!0?"local":((r=e.connection)==null?void 0:r.transport)==="direct"||((n=e.connection)==null?void 0:n.transport)==="relay"||lm(e)||cm(e)?"remote":"unknown"}function Pw(e){return ji(e)}function dm(e){var t;return Pw(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function Dw(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function $w(e){return e.activeSessionDetails&&e.activeSessionDetails.length>0?e.activeSessionDetails:(e.activeSessions??[]).map(t=>({sessionId:t,workspace:e.workspace,isCached:!0}))}function um(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function mm(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function ki(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function Ew(e){return ki(e)?"degraded":mm(e)?"dirty":"online"}function Bw(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function cc(e){switch(e){case"online":return 0;case"dirty":return 1;case"degraded":return 2;case"wrong_branch":return 3;case"offline":return 4;case"unknown":default:return 5}}function qa(e){return e.length===0?"unknown":e.reduce((t,r)=>cc(r)>cc(t)?r:t)}function Ow(e){var o,i,c,u,m;const t=new Map,r=new Map;for(const d of e){const h=(i=(o=d.git)==null?void 0:o.branch)==null?void 0:i.trim();h&&(r.set(h,(r.get(h)??0)+1),(c=d.git)!=null&&c.upstream&&t.set(h,(t.get(h)??0)+1))}const n=[...t.entries()].sort((d,h)=>{if(h[1]!==d[1])return h[1]-d[1];const p=["main","master","develop","dev"],y=p.indexOf(d[0]),b=p.indexOf(h[0]);return y!==-1||b!==-1?y===-1?1:b===-1?-1:y-b:d[0].localeCompare(h[0])});return(u=n[0])!=null&&u[0]?n[0][0]:((m=[...r.entries()].sort((d,h)=>h[1]-d[1])[0])==null?void 0:m[0])??null}function Fw(e,t){const r=[],n=e.git;return n?n.isGitRepo?(!n.branch&&n.headCommit&&r.push("Detached HEAD"),n.hasConflicts&&r.push("Merge conflicts need resolution"),n.branch&&t&&n.branch!==t&&!n.upstream&&r.push(`No upstream tracking for ${n.branch}`),n.upstream&&n.upstreamStatus&&n.upstreamStatus!=="fresh"&&r.push(`Upstream freshness unverified for ${n.branch??"workspace"}`),e.error&&r.push(e.error),r):(r.push("Not a git repository"),r):(r.push("No git status available"),r)}function dc(e){switch(e){case"merged_to_main":return 0;case"pushed_feature_branch_needs_merge":return 1;case"cleanup_candidate":return 2;case"blocked_review":return 3;case"not_mergeable":default:return 4}}function Hw(e){return e.reduce((t,r)=>dc(r.status)>dc(t.status)?r:t)}function Ww(e){const t=e.branchConvergenceSummary;if(Array.isArray(t==null?void 0:t.followUps))return t.followUps;const r=e.followUps;return Array.isArray(r)?r:(t==null?void 0:t.needsFollowUp)===!1||(t==null?void 0:t.unresolvedCount)===0?[]:null}function Kw(e){var a,o,i;const t=e.sourceOfTruth,r=[],n=(a=t==null?void 0:t.fallback)==null?void 0:a.warning;return typeof n=="string"&&n.trim()&&r.push(n.trim()),(t==null?void 0:t.currentStatus)==="bootstrap_inventory_fallback"&&((o=t.directPeerTruth)==null?void 0:o.required)===!0&&((i=t.directPeerTruth)==null?void 0:i.satisfied)!==!0&&!r.some(c=>c.includes("direct mesh truth"))&&r.push("Direct mesh truth is not confirmed yet; this graph is drawn from setup inventory only."),r}function Uw(e,t){return e.type!=="submoduleNode"&&e.branch===t&&e.ahead===0&&e.behind===0&&!e.dirty&&!e.hasConflicts&&(!e.upstreamStatus||e.upstreamStatus==="fresh")&&e.snapshotCompleteness==="complete"}function zw(e,t){var r,n;return{status:"merged_to_main",needsConvergence:!1,reason:"clean_default_branch_aggregate",nextStep:null,branch:e,defaultBranch:e,upstream:((r=t.find(a=>a.upstream))==null?void 0:r.upstream)??null,upstreamStatus:((n=t.find(a=>a.upstreamStatus))==null?void 0:n.upstreamStatus)??null,ahead:0,behind:0,dirty:!1,hasConflicts:!1}}function Gw(e,t){if(dm(e))return null;const r=e.branchConvergence;if(!r||typeof r!="object")return null;const n=r.status;if(!n||!["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"].includes(n))return null;const a=e.git,o=um(a)||mm(a),i=!!(a!=null&&a.hasConflicts)||ki(a),c=(a==null?void 0:a.ahead)??0,u=(a==null?void 0:a.behind)??0,m=(a==null?void 0:a.branch)??null,d=(a==null?void 0:a.upstream)??null,h=(a==null?void 0:a.upstreamStatus)??null,p=r.defaultBranch??t??null;return{status:n,needsConvergence:r.needsConvergence??n!=="merged_to_main",reason:r.reason??"provided_by_coordinator",nextStep:r.nextStep??null,branch:r.branch??m,defaultBranch:p,upstream:r.upstream??d,upstreamStatus:r.upstreamStatus??h,ahead:r.ahead??c,behind:r.behind??u,dirty:r.dirty??o,hasConflicts:r.hasConflicts??i}}function Vw(e,t){const r=Gw(e,t);return r?{...r,defaultBranch:r.defaultBranch??t}:null}function qw(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function Yw(e){var u,m,d;const{nodeStatus:t,expectedSubmodulePaths:r,refreshedAtMs:n}=e,a=[],o=t.machineLabel||t.nodeId,i=t.git;if(!i){if(dm(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const h=t.health==="online"||t.machineStatus==="online"||((u=t.connection)==null?void 0:u.state)==="connected"||((m=t.connection)==null?void 0:m.state)==="self";return a.push(h?`${o} is online but no peer git snapshot is visible yet.`:`${o} has no peer git snapshot visible yet.`),{snapshotCompleteness:"missing_git",snapshotWarnings:a}}const c=new Set((i.submodules??[]).map(h=>h.path));if(r.size>0){const h=[...r].filter(p=>!c.has(p));h.length>0&&a.push(`${o} is missing submodule visibility for ${h.join(", ")} even though another peer reported it.`)}return((d=t.connection)==null?void 0:d.state)!=="self"&&n!==null&&typeof i.lastCheckedAt=="number"&&n-i.lastCheckedAt>Lw&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(h=>h.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(h=>h.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function Xw(e){const t=om(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??Ow(t.nodes),a=Dw(t.refreshedAt),o=new Set(t.nodes.flatMap(I=>{var A;return(((A=I.git)==null?void 0:A.submodules)??[]).map(W=>W.path)})),i=[],c=[],u=Kw(t),m=new Map;for(const I of t.nodes){const A=I.git,W=(A==null?void 0:A.branch)??null,_=Ew(A),L=um(A)||_==="dirty",B=Fw(I,n),F=Vw(I,n),E=Yw({nodeStatus:I,expectedSubmodulePaths:o,refreshedAtMs:a}),D=typeof I.clonedFromNodeId=="string"?I.clonedFromNodeId:null,K=$w(I),J={id:I.nodeId,type:B.length>0?"orphanNode":"worktreeNode",label:I.machineLabel||I.nodeId.slice(0,8),workspace:I.workspace,branch:W,upstream:(A==null?void 0:A.upstream)??null,upstreamStatus:(A==null?void 0:A.upstreamStatus)??null,daemonId:lm(I),machineId:cm(I),machineLabel:I.machineLabel||null,locality:Rw(I),health:qa([I.health,_]),ahead:(A==null?void 0:A.ahead)??0,behind:(A==null?void 0:A.behind)??0,dirty:L,dirtyFiles:Bw(A),hasConflicts:(A==null?void 0:A.hasConflicts)??!1,activeSessionCount:K.length,activeSessions:K.map(Q=>Q.sessionId),sessionDetails:K,providers:I.providers??[],isOrphan:B.length>0,orphanReasons:B,error:I.error,nextStepHint:E.snapshotWarnings[0]??B[0]??(F==null?void 0:F.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:D,worktreeBranch:I.worktreeBranch??null,submodulePath:null,submoduleCommit:(A==null?void 0:A.headCommit)??null,outOfSync:ki(A),snapshotCompleteness:E.snapshotCompleteness,snapshotWarnings:E.snapshotWarnings,branchConvergence:F,source:I};if(i.push(J),W){const Q=m.get(W)??[];Q.push(J.id),m.set(W,Q)}for(const Q of(A==null?void 0:A.submodules)??[]){const Z=`${J.id}::submodule::${Q.path}`,he=Q.path.split("/").filter(Boolean).pop()||Q.path;i.push({id:Z,type:"submoduleNode",label:he,workspace:Q.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:J.daemonId,machineId:J.machineId,machineLabel:J.machineLabel,locality:J.locality,health:qw(Q),ahead:0,behind:0,dirty:Q.dirty,dirtyFiles:Q.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],error:Q.error,nextStepHint:Q.error||(Q.outOfSync?`${Q.path} is out of sync with the parent checkout`:Q.dirty?`${Q.path} has local changes`:`${Q.path} is in sync with the parent checkout`),parentNodeId:J.id,submodulePath:Q.path,submoduleCommit:Q.commit,outOfSync:Q.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:J.id,parentWorkspace:I.workspace,submodule:Q}}),c.push({id:`${J.id}--${Z}`,source:J.id,target:Z,type:"submoduleLink",label:Q.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const d=n?`__branch_${n}`:null;if(d&&n){const A=(m.get(n)??[]).map(D=>i.find(K=>K.id===D)).filter(Boolean),W=A.map(D=>D.branchConvergence).filter(Boolean),_=Ww(t),L=A.length>0&&A.every(D=>Uw(D,n)),B=(_==null?void 0:_.length)===0&&L?zw(n,A):W.length>0?Hw(W):null,F=(_==null?void 0:_.length)===0&&L?0:W.filter(D=>D.needsConvergence).length,E={id:d,type:"defaultBranchNode",label:n,workspace:t.repoIdentity,branch:n,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:"default branch",locality:"unknown",health:qa(A.map(D=>D.health)),ahead:0,behind:0,dirty:A.some(D=>D.dirty),dirtyFiles:A.reduce((D,K)=>D+K.dirtyFiles,0),hasConflicts:A.some(D=>D.hasConflicts),activeSessionCount:A.reduce((D,K)=>D+K.activeSessionCount,0),activeSessions:A.flatMap(D=>D.activeSessions),sessionDetails:A.flatMap(D=>D.sessionDetails),providers:[...new Set(A.flatMap(D=>D.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:F>0?`${F} workspace(s) on ${n} still need follow-up`:A.length>0?`${A.length} workspace(s) currently on ${n}`:"No workspaces currently checked out to the default branch",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:B,source:{nodeId:d,machineLabel:n,workspace:t.repoIdentity,health:qa(A.map(D=>D.health)),providers:[],activeSessions:[],activeSessionDetails:[]}};i.push(E);for(const D of i)if(!(D.id===d||D.type==="submoduleNode")){if(D.branch===n){c.push({id:`${d}--${D.id}`,source:d,target:D.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(D.branch){c.push({id:`${d}--${D.id}`,source:d,target:D.id,type:D.isOrphan?"orphanLink":"parentBranch",label:D.branch,direction:"undirected"});continue}D.isOrphan&&c.push({id:`${d}--${D.id}`,source:d,target:D.id,type:"orphanLink",label:"detached",direction:"undirected"})}}for(const[I,A]of m){if(A.length<2)continue;const W=A.map(_=>i.find(L=>L.id===_)).filter(Boolean);W.sort((_,L)=>_.label.localeCompare(L.label));for(let _=1;_<W.length;_+=1)c.push({id:`wt_${W[_-1].id}--${W[_].id}`,source:W[_-1].id,target:W[_].id,type:"worktreeLink",label:_===1?`${I} peers`:void 0,direction:"undirected"})}const h=new Set(i.map(I=>I.id)),p=new Set;for(const I of i){if(!I.clonedFromNodeId||I.type==="submoduleNode"||!h.has(I.clonedFromNodeId))continue;const A=`clone_${I.clonedFromNodeId}--${I.id}`;if(p.has(A))continue;p.add(A);const W=I.worktreeBranch??I.branch??void 0;c.push({id:A,source:I.clonedFromNodeId,target:I.id,type:"cloneLink",label:W?`cloned · ${W}`:"cloned",direction:"directed"})}const y=i.filter(I=>I.type!=="defaultBranchNode"),b=y.filter(I=>I.isOrphan).length,x=y.filter(I=>I.hasConflicts).length,k=y.filter(I=>I.health==="offline").length,j=y.filter(I=>I.type==="submoduleNode"&&I.outOfSync).length,f=y.filter(I=>{var A;return I.type!=="submoduleNode"&&((A=I.branchConvergence)==null?void 0:A.needsConvergence)}).length,w=y.filter(I=>{var A;return((A=I.branchConvergence)==null?void 0:A.status)==="blocked_review"}).length,S=y.filter(I=>{var A;return((A=I.branchConvergence)==null?void 0:A.status)==="pushed_feature_branch_needs_merge"}).length,v=y.filter(I=>{var A;return((A=I.branchConvergence)==null?void 0:A.status)==="cleanup_candidate"}).length,g=y.filter(I=>{var A;return((A=I.branchConvergence)==null?void 0:A.status)==="not_mergeable"}).length,N=y.filter(I=>I.snapshotWarnings.length>0).length,M=y.filter(I=>I.snapshotCompleteness==="pending_git").length,C=y.filter(I=>I.snapshotCompleteness==="missing_git").length,$=y.filter(I=>I.snapshotCompleteness==="missing_submodule_report").length,R=y.filter(I=>I.snapshotCompleteness==="stale").length,T=[M>0?`${M} node(s) are still waiting for a live peer git snapshot`:null,C>0?`${C} node(s) have no visible peer git snapshot`:null,$>0?`${$} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,R>0?`${R} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return f>0&&u.push(`${f} workspace(s) still need follow-up before the mesh is converged`),b>0&&u.push(`${b} workspace(s) need attention before safe coordination`),w>0&&u.push(`${w} workspace(s) are blocked on branch convergence or upstream sync`),S>0&&u.push(`${S} clean feature branch workspace(s) still need merge follow-up`),v>0&&u.push(`${v} worktree workspace(s) are ready for refine / cleanup`),g>0&&u.push(`${g} workspace(s) have local changes or conflicts blocking convergence`),x>0&&u.push(`${x} workspace(s) report merge conflicts`),k>0&&u.push(`${k} node(s) are currently offline`),j>0&&u.push(`${j} submodule(s) are out of sync with their parent checkout`),u.push(...T),n||u.push("Could not infer a default branch from live mesh status"),{meshId:t.meshId,meshName:t.meshName,repoIdentity:t.repoIdentity,refreshedAt:t.refreshedAt,nodes:i,edges:c,stats:{totalNodes:y.length,onlineNodes:y.filter(I=>I.health==="online").length,dirtyNodes:y.filter(I=>I.dirty).length,orphanNodes:b,errorNodes:y.filter(I=>!!I.error||I.outOfSync).length,offlineNodes:k,followUpNodes:f,blockedReviewNodes:w,mergeReadyNodes:S,cleanupCandidateNodes:v,notMergeableNodes:g,incompleteSnapshotNodes:N,missingGitSnapshotNodes:C,missingSubmoduleSnapshotNodes:$,staleGitSnapshotNodes:R,totalActiveSessions:y.reduce((I,A)=>I+A.activeSessionCount,0)},warnings:u,snapshotWarnings:T}}const Jw={recentFailures:0,taskCompleted:0,taskFailed:0,sessionLaunched:0},Si=l.createContext(Ys("dark"));function Fe({label:e,tone:t="default"}){const r=l.useContext(Si);return s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${r.badge(t)}`,children:e})}function nt({label:e,value:t}){const r=l.useContext(Si);return s.jsxs("div",{className:r.rowClass,children:[s.jsx("span",{className:r.rowLabelClass,children:e}),s.jsx("span",{className:r.rowValueClass,children:t})]})}function uc(e){switch(e){case"online":return"good";case"dirty":return"warn";case"degraded":case"offline":return"danger";case"wrong_branch":return"info";default:return"default"}}function Ya(e){switch((e||"").toLowerCase()){case"idle":return"good";case"generating":case"running":return"info";case"waiting_approval":case"starting":case"pending":return"warn";case"failed":case"stopped":case"interrupted":return"danger";default:return"default"}}function bn(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const r=t.toLowerCase().replace(/[\s-]+/g,"_");return r.includes("approval")?"awaiting approval":r.includes("generating")||r.includes("running")||r.includes("busy")?"generating":r.includes("idle")||r.includes("ready")||r.includes("waiting_input")?"idle":r.replace(/_/g," ")}function Qw(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function Zw(e){return e.startedAt||e.createdAt||null}function ej(e){const t=Zw(e);if(!t)return"runtime age not reported";const r=Date.parse(t);if(!Number.isFinite(r))return"runtime age not reported";const n=Math.max(0,Math.floor((Date.now()-r)/1e3));if(n<60)return`${n}s`;const a=Math.floor(n/60);if(a<60)return`${a}m`;const o=Math.floor(a/60);return o<48?`${o}h ${a%60}m`:`${Math.floor(o/24)}d ${o%24}h`}function tj(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function sj(e){if(!e)return"default";if(e.state==="self")return"info";if(e.transport==="direct"&&e.state==="connected")return"good";if(e.transport==="relay"&&e.state==="connected")return"info";switch(e.state){case"connected":return"good";case"connecting":return"warn";case"disconnected":case"failed":case"closed":return"danger";default:return"default"}}function rj(e){return e?e.state==="self"?"mesh self":e.transport==="direct"&&e.state==="connected"?"mesh direct":e.transport==="relay"&&e.state==="connected"?"mesh relay":!e.reported&&e.source==="not_reported"?"mesh unknown / not reported":`mesh ${e.state}`:"mesh unknown"}function nj(e){var r;const t=[];for(const n of e.nodes){const a=n.activeSessionDetails&&n.activeSessionDetails.length>0?n.activeSessionDetails:(n.activeSessions??[]).map(o=>({sessionId:o,workspace:n.workspace,isCached:!0}));for(const o of a)t.push({nodeId:n.nodeId,machineLabel:n.machineLabel,workspace:n.workspace,branch:((r=n.git)==null?void 0:r.branch)??null,nodeHealth:n.health,session:o})}return t}function aj(e){return e.assignedNodeId||e.targetNodeId||null}function mc(e){return e?e.slice(0,7):null}function oj(e,t){var o,i,c;const r=mc((o=e==null?void 0:e.git)==null?void 0:o.headCommit),n=((c=(i=e==null?void 0:e.git)==null?void 0:i.headMessage)==null?void 0:c.trim())||"";if(r||n)return[r,n].filter(Boolean).join(" · ");const a=t[0];return a?[mc(a.commit),a.message].filter(Boolean).join(" · "):null}function ij(e,t){const r=oj(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function lj(e){const t=(e==null?void 0:e.result)??e,r=(t==null?void 0:t.log)??(e==null?void 0:e.log)??t;return Array.isArray(r==null?void 0:r.entries)?r.entries:[]}function cj(e){var r,n,a,o,i,c;const t=((r=e.selectedSessionEntry)==null?void 0:r.session.workspace)||((n=e.selectedSessionEntry)==null?void 0:n.workspace)||((o=(a=e.selectedNodeStatus)==null?void 0:a.git)==null?void 0:o.workspace)||((i=e.selectedNodeStatus)==null?void 0:i.workspace)||null;if(t&&e.selectedSessionEntry){const u=((c=e.selectedNodeStatus)==null?void 0:c.daemonId)||e.coordinatorDaemonId;return u?{daemonId:u,workspace:t}:null}if(t&&e.selectedNodeStatus){const u=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return u?{daemonId:u,workspace:t}:null}return null}function dj(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":rj(e.connection)}function hc(e){var r;const t=e.source;return t!=null&&t.kind?t.kind:((r=t==null?void 0:t.connection)==null?void 0:r.source)??"mesh_status"}function pc(e){switch(e.type){case"parentBranch":return"default branch link";case"worktreeLink":return"worktree relationship";case"sessionLink":return"session relationship";case"orphanLink":return"orphan relationship";case"submoduleLink":return"submodule relationship";case"cloneLink":return"clone relationship";default:return e.type}}function uj(e){return e.direction==="directed"?"directed":"undirected"}function fc(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function mj(e){var t,r,n,a;return[e.meshId,e.refreshedAt,e.nodes.length,((r=(t=e.queue)==null?void 0:t.summary)==null?void 0:r.active)??"",((a=(n=e.ledger)==null?void 0:n.summary)==null?void 0:a.recentFailures)??"",...e.nodes.map(o=>{var i,c,u,m,d,h,p,y,b,x,k,j,f,w,S,v,g,N,M,C,$,R;return[o.nodeId,o.daemonId??"",o.machineId??"",o.machineLabel,o.machineStatus??"",((i=o.connection)==null?void 0:i.state)??"",((c=o.connection)==null?void 0:c.transport)??"",((u=o.connection)==null?void 0:u.source)??"",o.health,o.gitProbePending?1:0,((m=o.git)==null?void 0:m.branch)??"",((d=o.git)==null?void 0:d.upstream)??"",((h=o.git)==null?void 0:h.upstreamStatus)??"",((p=o.git)==null?void 0:p.ahead)??"",((y=o.git)==null?void 0:y.behind)??"",((b=o.git)==null?void 0:b.headCommit)??"",((x=o.git)==null?void 0:x.staged)??"",((k=o.git)==null?void 0:k.modified)??"",((j=o.git)==null?void 0:j.untracked)??"",((f=o.git)==null?void 0:f.deleted)??"",((w=o.git)==null?void 0:w.renamed)??"",(S=o.git)!=null&&S.hasConflicts?1:0,((v=o.git)==null?void 0:v.lastCheckedAt)??"",((g=o.activeSessions)==null?void 0:g.join(","))??"",((N=o.activeSessionDetails)==null?void 0:N.length)??"",((M=o.activeSessionDetails)==null?void 0:M.map(T=>[T.sessionId,T.providerType??"",T.state??"",T.chatStatus??"",T.lifecycle??"",T.role??"",T.isSelfCoordinator?1:0,T.statusNote??"",T.startedAt??"",T.createdAt??""].join("/")).join(","))??"",((C=o.providers)==null?void 0:C.join(","))??"",(($=o.providerPriority)==null?void 0:$.join(","))??"",o.error??"",(((R=o.git)==null?void 0:R.submodules)??[]).map(T=>[T.path,T.commit,T.dirty?1:0,T.outOfSync?1:0,T.error??""].join("/")).join(",")].join("|")})].join("::")}function hm({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null}){var pe,Ie,X,be,ue;const{theme:a}=qs(),o=l.useMemo(()=>Ys(a),[a]),i=l.useMemo(()=>om(e),[e]),c=l.useMemo(()=>mj(i),[i]),u=l.useMemo(()=>Xw(i),[c]),[m,d]=l.useState(null),[h,p]=l.useState(null),[y,b]=l.useState(null),[x,k]=l.useState(null),[j,f]=l.useState({}),[w,S]=l.useState(null),[v,g]=l.useState(null),N=l.useMemo(()=>new Map(i.nodes.map(U=>[U.nodeId,U])),[i.nodes]),M=l.useMemo(()=>new Map(u.nodes.map(U=>[U.id,U])),[u.nodes]),C=((pe=i.queue)==null?void 0:pe.summary)??null,$=((Ie=i.ledger)==null?void 0:Ie.summary)??Jw,R=l.useMemo(()=>nj(i),[i]),T=l.useMemo(()=>{const U=new Map;for(const ce of R){const ie=bn(ce.session);U.set(ie,(U.get(ie)??0)+1)}return[...U.entries()].sort((ce,ie)=>ie[1]-ce[1])},[R]);l.useEffect(()=>{m&&(M.has(m)||(d(null),k(U=>!U||"nodeId"in U&&U.nodeId===m?null:U)))},[M,m]);const I=m?N.get(m)??null:null,A=fc(u,m),W=fc(u,h),_=y?u.edges.find(U=>U.id===y)??null:null,L=_?u.nodes.find(U=>U.id===_.source)??null:null,B=_?u.nodes.find(U=>U.id===_.target)??null:null;l.useEffect(()=>{var U,ce,ie;if(m)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:i.meshId,selectedNodeId:m,canonicalNode:Aw(I),graphNode:A?{id:A.id,branch:A.branch,upstream:A.upstream,headCommit:A.submoduleCommit,submoduleCount:((ce=(U=I==null?void 0:I.git)==null?void 0:U.submodules)==null?void 0:ce.length)??0,snapshotCompleteness:A.snapshotCompleteness,snapshotWarnings:A.snapshotWarnings,branchConvergence:((ie=A.branchConvergence)==null?void 0:ie.status)??null}:null})}catch{}},[i.meshId,A,m,I]);const F=(x==null?void 0:x.kind)==="session"?R.find(U=>U.nodeId===x.nodeId&&U.session.sessionId===x.sessionId)??null:null,E=l.useMemo(()=>R.filter(U=>U.nodeId===m),[m,R]),D=cj({coordinatorDaemonId:r,selectedNodeStatus:I,selectedSessionEntry:F}),K=(D==null?void 0:D.workspace)??null,J=K?j[K]??null:null,Q=ij(I,(J==null?void 0:J.entries)??[]),Z=(A==null?void 0:A.daemonId)??(I==null?void 0:I.daemonId)??r??null,he=!!(A&&n&&Z&&A.type!=="submoduleNode"&&A.behind>0&&A.ahead===0&&A.dirtyFiles===0&&!A.dirty&&!A.hasConflicts&&A.upstreamStatus==="fresh"),we=l.useCallback(()=>{d(null),k(null),S(null)},[]);l.useEffect(()=>{S(null)},[m]);const Me=l.useCallback(async()=>{if(!(!A||!Z||!n||!he)){g(A.id),S(null);try{const U=await n(Z,"fast_forward_mesh_node",{meshId:i.meshId,nodeId:A.id,dryRun:!0,execute:!1});if(S({phase:"dry_run",code:typeof(U==null?void 0:U.code)=="string"?U.code:void 0,error:typeof(U==null?void 0:U.operationError)=="string"?U.operationError:null,executed:(U==null?void 0:U.executed)===!0}),!(U!=null&&U.success)||U.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${A.label}?`))return;const ie=await n(Z,"fast_forward_mesh_node",{meshId:i.meshId,nodeId:A.id,dryRun:!1,execute:!0});S({phase:"execute",code:typeof(ie==null?void 0:ie.code)=="string"?ie.code:void 0,error:typeof(ie==null?void 0:ie.operationError)=="string"?ie.operationError:null,executed:(ie==null?void 0:ie.executed)===!0})}catch(U){S({phase:"dry_run",error:U instanceof Error?U.message:"fast-forward failed"})}finally{g(null)}}},[he,i.meshId,A,Z,n]);l.useEffect(()=>{if(!A)return;const U=ce=>{ce.key==="Escape"&&we()};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[we,A]),l.useEffect(()=>{if(!D||!n)return;const{daemonId:U,workspace:ce}=D,ie=j[ce];if(ie!=null&&ie.loading||ie&&(ie.entries.length>0||ie.error))return;let de=!1;return f(me=>{var oe;return{...me,[ce]:{loading:!0,error:null,entries:((oe=me[ce])==null?void 0:oe.entries)??[]}}}),n(U,"git_log",{workspace:ce,limit:5}).then(me=>{de||f(oe=>({...oe,[ce]:{loading:!1,error:null,entries:lj(me)}}))}).catch(me=>{de||f(oe=>({...oe,[ce]:{loading:!1,error:me instanceof Error?me.message:"git_log failed",entries:[]}}))}),()=>{de=!0}},[j,D,n]);const q=[...u.warnings??[],...i.nodes.filter(U=>U.machineStatus&&U.machineStatus!=="online").map(U=>`${U.machineLabel}: ${U.machineStatus}`)],ye=u.stats.incompleteSnapshotNodes>0,ge=u.stats.followUpNodes>0?`${u.stats.followUpNodes} need follow-up`:ye?"mesh visibility incomplete":"mesh converged",ve=u.stats.followUpNodes>0?"danger":ye?"warn":"good";return s.jsx(Si.Provider,{value:o,children:s.jsx("div",{className:"flex min-h-0 flex-col gap-4",children:s.jsx("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-4",children:s.jsxs("div",{className:`${o.cardClass} relative flex min-h-0 flex-1 flex-col rounded-[28px] p-3 sm:p-4`,style:{minHeight:420},children:[s.jsxs("div",{className:`absolute inset-x-4 top-4 z-30 flex max-h-[42dvh] flex-wrap items-start justify-between gap-3 overflow-y-auto rounded-2xl px-3.5 py-3 backdrop-blur-xl sm:static sm:mb-3 sm:max-h-none sm:overflow-visible sm:backdrop-blur-none ${o.isDark?"border border-white/10 bg-slate-950/85 sm:bg-slate-950/45":"border border-slate-200 bg-white/95 shadow-lg shadow-slate-900/10 sm:bg-white/95 sm:shadow-sm"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-wrap gap-2 text-xs ${o.textSecondary}`,children:[s.jsx(Fe,{label:ge,tone:ve}),u.stats.blockedReviewNodes>0&&s.jsx(Fe,{label:`${u.stats.blockedReviewNodes} blocked review`,tone:"danger"}),u.stats.notMergeableNodes>0&&s.jsx(Fe,{label:`${u.stats.notMergeableNodes} not mergeable`,tone:"danger"}),u.stats.mergeReadyNodes>0&&s.jsx(Fe,{label:`${u.stats.mergeReadyNodes} need merge`,tone:"warn"}),u.stats.cleanupCandidateNodes>0&&s.jsx(Fe,{label:`${u.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),u.stats.offlineNodes>0&&s.jsx(Fe,{label:`${u.stats.offlineNodes} offline`,tone:"danger"}),u.stats.incompleteSnapshotNodes>0&&s.jsx(Fe,{label:`${u.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),u.stats.missingGitSnapshotNodes>0&&s.jsx(Fe,{label:`${u.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),u.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Fe,{label:`${u.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),u.stats.staleGitSnapshotNodes>0&&s.jsx(Fe,{label:`${u.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((C==null?void 0:C.active)??0)>0&&s.jsx(Fe,{label:`${(C==null?void 0:C.active)??0} active queue`,tone:"info"}),s.jsx(Fe,{label:`${u.stats.totalNodes} nodes`,tone:"default"}),u.stats.totalActiveSessions>0&&s.jsx(Fe,{label:`${u.stats.totalActiveSessions} attached chats`,tone:"info"})]}),s.jsxs("details",{className:`max-w-full rounded-xl px-3 py-2 text-xs ${o.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 ${o.textSecondary} [&::-webkit-details-marker]:hidden`,children:"Legend & secondary details"}),s.jsxs("div",{className:"mt-3 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Fe,{label:`${u.stats.dirtyNodes} dirty`,tone:u.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Fe,{label:`${u.stats.orphanNodes} orphan`,tone:u.stats.orphanNodes>0?"warn":"good"}),s.jsx(Fe,{label:`${$.recentFailures} recent failures`,tone:$.recentFailures>0?"danger":"good"}),T.length===0?s.jsx(Fe,{label:"no session metadata"}):T.slice(0,2).map(([U,ce])=>s.jsx(Fe,{label:`${ce} ${U}`,tone:Ya(U)},U))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Fe,{label:"Anchor = default branch",tone:"info"}),s.jsx(Fe,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Fe,{label:"Submodule link = child checkout",tone:"warn"})]}),q.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:q.map(U=>s.jsx("span",{className:o.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:U},U))}),s.jsx("div",{className:`text-xs ${o.textMuted}`,children:"Hover nodes or edges for a quick preview. Click a node when you want pinned drill-down details."})]})]})]}),u.nodes.length>0?s.jsx(fw,{data:u,selectedNodeId:m,onNodeHoverChange:U=>{p((U==null?void 0:U.id)??null),U&&b(null)},onEdgeHoverChange:U=>{b((U==null?void 0:U.id)??null),U&&p(null)},onNodeClick:U=>{if((x==null?void 0:x.kind)==="node"&&m===U.id){d(null),k(null);return}d(U.id),k({kind:"node",nodeId:U.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:t}),!A&&W&&s.jsx("div",{className:"pointer-events-none absolute inset-x-3 bottom-3 z-20 flex justify-center p-2 sm:inset-x-auto sm:right-5 sm:top-24 sm:bottom-auto sm:justify-end",children:s.jsxs("section",{"aria-label":"Hovered node preview",className:o.isDark?"w-full max-w-[min(24rem,calc(100vw-2.5rem))] rounded-2xl border border-white/12 bg-slate-950/94 p-4 shadow-2xl shadow-black/35 backdrop-blur-xl":"w-full max-w-[min(24rem,calc(100vw-2.5rem))] rounded-2xl border border-slate-200 bg-white/96 p-4 shadow-2xl shadow-slate-900/12 backdrop-blur-xl",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:`truncate text-sm font-semibold ${o.textPrimary}`,children:W.label}),s.jsx("div",{className:`mt-1 font-mono text-[11px] ${o.textMuted}`,children:W.id.slice(0,16)})]}),s.jsx(Fe,{label:"hover preview",tone:"info"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[s.jsx(Fe,{label:W.health,tone:uc(W.health)}),W.branch&&s.jsx(Fe,{label:W.branch,tone:"default"}),W.ahead>0&&s.jsx(Fe,{label:`ahead ${W.ahead}`,tone:"warn"}),W.behind>0&&s.jsx(Fe,{label:`behind ${W.behind}`,tone:"warn"}),W.dirtyFiles>0&&s.jsx(Fe,{label:`${W.dirtyFiles} dirty`,tone:"warn"}),W.activeSessionCount>0&&s.jsx(Fe,{label:`${W.activeSessionCount} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[s.jsx(nt,{label:"Machine",value:W.machineLabel??"not reported"}),s.jsx(nt,{label:"Locality",value:W.locality}),s.jsx(nt,{label:"Workspace",value:W.workspace}),s.jsx(nt,{label:"Upstream",value:W.upstream??"none"}),s.jsx(nt,{label:"Dirty/ahead/behind",value:`${W.dirtyFiles} dirty · ↑${W.ahead}/↓${W.behind}`}),s.jsx(nt,{label:"Source",value:hc(W)})]})]})}),!A&&!W&&_&&s.jsx("div",{className:"pointer-events-none absolute inset-x-3 bottom-3 z-20 flex justify-center p-2 sm:inset-x-auto sm:right-5 sm:top-24 sm:bottom-auto sm:justify-end",children:s.jsxs("section",{"aria-label":"Hovered edge preview",className:o.isDark?"w-full max-w-[min(22rem,calc(100vw-2.5rem))] rounded-2xl border border-white/12 bg-slate-950/94 p-4 shadow-2xl shadow-black/35 backdrop-blur-xl":"w-full max-w-[min(22rem,calc(100vw-2.5rem))] rounded-2xl border border-slate-200 bg-white/96 p-4 shadow-2xl shadow-slate-900/12 backdrop-blur-xl",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:`truncate text-sm font-semibold ${o.textPrimary}`,children:_.label||pc(_)}),s.jsx("div",{className:`mt-1 text-[11px] ${o.textMuted}`,children:_.id})]}),s.jsx(Fe,{label:"hover preview",tone:"info"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[s.jsx(Fe,{label:pc(_),tone:"default"}),s.jsx(Fe,{label:uj(_),tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs",children:[s.jsx(nt,{label:"From",value:(L==null?void 0:L.label)??_.source}),s.jsx(nt,{label:"To",value:(B==null?void 0:B.label)??_.target}),s.jsx(nt,{label:"Label",value:_.label??"none"})]})]})}),A&&(x==null?void 0:x.kind)==="node"&&s.jsx("div",{className:"absolute inset-x-3 bottom-3 top-20 z-20 flex items-end justify-center p-2 sm:inset-5 sm:top-24 sm:items-start sm:justify-end",onClick:we,role:"presentation",children:s.jsxs("section",{role:"dialog","aria-modal":"false","aria-label":"Selected node",className:o.isDark?"max-h-[min(72vh,540px)] w-full max-w-[min(28rem,calc(100vw-2.5rem))] overflow-y-auto rounded-2xl border border-white/12 bg-slate-950/96 p-4 shadow-2xl shadow-black/40 backdrop-blur-xl":"max-h-[min(72vh,540px)] w-full max-w-[min(28rem,calc(100vw-2.5rem))] overflow-y-auto rounded-2xl border border-slate-200 bg-white/96 p-4 shadow-2xl shadow-slate-900/15 backdrop-blur-xl",onClick:U=>U.stopPropagation(),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:`truncate text-sm font-semibold ${o.textPrimary}`,children:A.label}),s.jsx("div",{className:`mt-1 font-mono text-[11px] ${o.textMuted}`,children:A.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[A.behind>0&&s.jsx("button",{type:"button",onClick:()=>{Me()},disabled:!he||v===A.id,className:o.isDark?"rounded-full border border-emerald-400/25 bg-emerald-500/10 px-2.5 py-1 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.5 py-1 text-xs font-semibold text-emerald-700 transition hover:bg-emerald-100 disabled:cursor-not-allowed disabled:opacity-45",children:v===A.id?"Checking":"Heal"}),s.jsx("button",{type:"button",onClick:we,className:o.isDark?"rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-xs text-slate-200 transition hover:bg-white/[0.08]":"rounded-full border border-slate-200 bg-white px-2.5 py-1 text-xs text-slate-600 transition hover:bg-slate-50",children:"Close"})]})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[s.jsx(Fe,{label:(I==null?void 0:I.health)??A.health,tone:uc((I==null?void 0:I.health)??A.health)}),A.branch&&s.jsx(Fe,{label:A.branch,tone:"default"}),A.ahead>0&&s.jsx(Fe,{label:`ahead ${A.ahead}`,tone:"warn"}),A.behind>0&&s.jsx(Fe,{label:`behind ${A.behind}`,tone:"warn"}),A.dirtyFiles>0&&s.jsx(Fe,{label:`${A.dirtyFiles} dirty`,tone:"warn"}),(I==null?void 0:I.connection)&&s.jsx(Fe,{label:dj(I),tone:sj(I.connection)}),E.length>0&&s.jsx(Fe,{label:`${E.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[s.jsx(nt,{label:"Machine",value:A.machineLabel??"not reported"}),s.jsx(nt,{label:"Locality",value:A.locality}),s.jsx(nt,{label:"Machine id",value:A.machineId??(I==null?void 0:I.machineId)??"not reported"}),s.jsx(nt,{label:"Daemon id",value:A.daemonId??(I==null?void 0:I.daemonId)??"not reported"}),s.jsx(nt,{label:"Workspace",value:(I==null?void 0:I.workspace)??A.workspace}),s.jsx(nt,{label:"Branch",value:A.branch??"unknown"}),s.jsx(nt,{label:"HEAD",value:Q??(I!=null&&I.gitProbePending?"Pending live git probe":"not reported")}),s.jsx(nt,{label:"Upstream",value:A.upstream??"none"}),s.jsx(nt,{label:"Dirty/ahead/behind",value:`${A.dirtyFiles} dirty · ↑${A.ahead}/↓${A.behind}`}),s.jsx(nt,{label:"Source",value:String(((X=I==null?void 0:I.connection)==null?void 0:X.source)??hc(A))}),s.jsx(nt,{label:"Transport",value:((be=I==null?void 0:I.connection)==null?void 0:be.transport)??"unknown"}),s.jsx(nt,{label:"Sessions",value:E.length>0?E.map(U=>bn(U.session)).join(", "):"none active"})]}),E.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${o.textMuted}`,children:"Active Sessions"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:E.map(U=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${o.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 ${o.textMuted}`,title:U.session.sessionId,children:tj(U.session.sessionId)}),s.jsx(Fe,{label:bn(U.session),tone:Ya(bn(U.session))})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 ${o.textMuted}`,children:[s.jsx("span",{className:"truncate",children:U.session.providerType||"provider unknown"}),s.jsx("span",{children:Qw(U.session)}),s.jsx("span",{children:ej(U.session)})]}),U.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${o.textMuted}`,children:U.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${o.textMuted}`,title:U.session.workspace||U.workspace,children:[(U.session.workspace||U.workspace).slice(0,42),U.branch?` · ${U.branch}`:""]})]},U.session.sessionId))})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${o.textMuted}`,children:"Ledger (mesh-wide)"}),s.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[s.jsx(nt,{label:"Completed",value:String($.taskCompleted)}),s.jsx(nt,{label:"Failed",value:s.jsx("span",{className:$.taskFailed>0?o.isDark?"text-rose-300":"text-rose-600":"",children:$.taskFailed})}),s.jsx(nt,{label:"Launched",value:String($.sessionLaunched)}),s.jsx(nt,{label:"Recent failures",value:s.jsx("span",{className:$.recentFailures>0?o.isDark?"text-amber-300":"text-amber-600":"",children:$.recentFailures})})]})]}),(()=>{var ie,de;const U=((ie=i.queue)==null?void 0:ie.tasks)??((de=i.queue)==null?void 0:de.items)??null;if(!Array.isArray(U)||U.length===0)return null;const ce=U.filter(me=>aj(me)===m).slice(0,3);return ce.length===0?null:s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${o.textMuted}`,children:"Queue tasks"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:ce.map(me=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${o.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 ${o.textMuted}`,children:me.id.slice(0,12)}),s.jsx(Fe,{label:me.status??"unknown",tone:Ya(me.status)})]}),me.message&&s.jsx("div",{className:`mt-0.5 truncate ${o.textMuted}`,children:me.message.slice(0,48)})]},me.id))})]})})(),A.snapshotWarnings.length>0&&s.jsxs("div",{className:o.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:"Key warning"}),s.jsx("div",{className:"mt-1",children:A.snapshotWarnings[0]})]}),((ue=A.branchConvergence)==null?void 0:ue.nextStep)&&s.jsxs("div",{className:o.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:"Follow-up"}),s.jsx("div",{className:"mt-1",children:A.branchConvergence.nextStep})]}),w&&s.jsxs("div",{className:o.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:w.phase==="execute"?"Heal result":"Heal preview"}),s.jsx("div",{className:"mt-1",children:w.code??w.error??"No result code returned."})]})]})})]})})})})}function pt(e){return typeof e=="string"?e.trim():""}function Ro(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ni(...e){const t=new Set;for(const r of e){const n=pt(r);n&&t.add(n)}return[...t]}function hj(e,t){var h,p;const r=Ro(e==null?void 0:e.settings),n=pt((h=e==null?void 0:e.coordinator)==null?void 0:h.meshId)||pt(r.meshCoordinatorFor),a=pt(r.meshNodeFor),o=!!n||!!a,i=n===t||a===t;if(o&&!i)return null;const c=Ro(e==null?void 0:e.activeChat),u=Ni(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),m=u[0]||"";if(!m)return null;const d=n===t?pt((p=e==null?void 0:e.coordinator)==null?void 0:p.role)||"coordinator":a===t?pt(r.meshNodeRole)||"worker":pt(e==null?void 0:e.role)||pt(r.meshNodeRole)||void 0;return{sessionId:m,aliases:u,meshId:t,nodeId:i&&pt(r.meshNodeId)||null,providerType:pt(e==null?void 0:e.providerType)||void 0,state:pt(e==null?void 0:e.status)||void 0,chatStatus:pt(c.status)||void 0,lifecycle:pt(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:pt(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:pt(e==null?void 0:e.runtimeRecoveryState)||void 0,...d?{role:d}:{},...i?{isSelfCoordinator:n===t}:{},workspace:pt(e==null?void 0:e.workspace)||null}}function pm(e,t){var n;return t?(Array.isArray((n=e.status)==null?void 0:n.sessions)?e.status.sessions:[]).map(a=>hj(a,t)).filter(a=>a!==null):[]}function ta(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function pj(e,t){const r=new Set(ta(t));return ta(e).some(n=>r.has(n))}function fj(e,t){const r=t.filter(a=>!!a);return r.length===0?e:[...e.filter(a=>!r.some(o=>pj(a,o))),...r]}function xj(e,t){if(t.length===0)return e;const r=new Map;for(const o of t)for(const i of ta(o))r.set(i,o);let n=!1;const a=(e.nodes??[]).map(o=>{const i=Array.isArray(o.activeSessionDetails)?o.activeSessionDetails:Array.isArray(o.sessions)?o.sessions:[],c=new Map;for(const m of i){const d=Ni(m==null?void 0:m.sessionId,m==null?void 0:m.session_id,m==null?void 0:m.id,m==null?void 0:m.providerSessionId,m==null?void 0:m.provider_session_id),h=d[0]||"";if(!h)continue;const p=d.map(y=>r.get(y)).find(Boolean);p&&(n=!0),c.set(h,p?{...m,sessionId:h,providerType:p.providerType||m.providerType,state:p.state||m.state,chatStatus:p.chatStatus||m.chatStatus,lifecycle:p.lifecycle||m.lifecycle,surfaceKind:p.surfaceKind||m.surfaceKind,recoveryState:p.recoveryState||m.recoveryState,role:p.role||m.role,isSelfCoordinator:p.isSelfCoordinator??m.isSelfCoordinator,workspace:p.workspace||m.workspace}:{...m,sessionId:h})}for(const m of o.activeSessions??[])c.has(m)||c.set(m,{sessionId:m,workspace:o.workspace,isCached:!0});for(const m of t)ta(m).some(h=>c.has(h))||m.nodeId===o.nodeId&&(n=!0,c.set(m.sessionId,{sessionId:m.sessionId,providerType:m.providerType,state:m.state,chatStatus:m.chatStatus,lifecycle:m.lifecycle,surfaceKind:m.surfaceKind,recoveryState:m.recoveryState,role:m.role,isSelfCoordinator:m.isSelfCoordinator,workspace:m.workspace||o.workspace}));const u=[...c.values()];return u.length===0?o:{...o,activeSessionDetails:u,activeSessions:u.map(m=>m.sessionId)}});return n?{...e,nodes:a}:e}function bj(e,t){const n=pm(e,t).map(a=>{var u;const o=(Array.isArray((u=e.status)==null?void 0:u.sessions)?e.status.sessions:[]).find(m=>pt(m==null?void 0:m.id)===a.sessionId),i=Ro(o==null?void 0:o.activeInteractivePrompt),c=o!=null&&o.meshQueueStats&&typeof o.meshQueueStats=="object"?JSON.stringify(o.meshQueueStats):"";return[a.sessionId,a.providerType??"",a.state??"",a.chatStatus??"",a.lifecycle??"",a.surfaceKind??"",a.recoveryState??"",pt(i.status)||pt(i.kind)||pt(i.type),a.nodeId??"",a.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(a=>!!a).sort();return n.length>0?n.join(`
|
|
73
73
|
`):null}function fm({status:e,daemonId:t,meshId:r,sendData:n,extraLiveSessions:a=[]}){const[o,i]=l.useState([]),c=l.useRef(null);l.useEffect(()=>{c.current=null,i([])},[t,r]),l.useEffect(()=>{if(!t||!r||!n)return;const m=zt.subscribe({sendData:n},t,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${t}`,params:{includeSessions:!0}},d=>{if(d.topic!=="daemon.metadata")return;const h=bj(d,r);h!==c.current&&(c.current=h,i(pm(d,r)))});return()=>{m()}},[t,r,n]);const u=l.useMemo(()=>fj(o,a),[a,o]);return l.useMemo(()=>e?xj(e,u):null,[u,e])}const gn=new Map;function gj(e,t){return!e||!t?null:`${e}::${t}`}function yj(e,t){var o,i,c,u;if(!t||!e.sessionId)return null;const r=((o=e.coordinator)==null?void 0:o.meshId)??(typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),n=typeof((c=e.settings)==null?void 0:c.meshNodeFor)=="string"?e.settings.meshNodeFor:null;if(r!==t&&n!==t)return null;const a=typeof((u=e.settings)==null?void 0:u.meshNodeId)=="string"?e.settings.meshNodeId:null;return{sessionId:e.sessionId,aliases:Ni(e.sessionId,e.providerSessionId,e.historySessionId,e.nativeSessionId),meshId:t,nodeId:a,providerType:e.agentType,state:e.status,chatStatus:e.status,role:r===t?"coordinator":"worker",isSelfCoordinator:r===t,workspace:e.workspacePath??null}}function vj({activeConv:e,sendDaemonCommand:t,onClose:r}){var _,L,B,F,E,D;const n=((_=e.coordinator)==null?void 0:_.meshId)??(typeof((L=e.settings)==null?void 0:L.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),a=e.daemonId??null,o=gj(a,n),i=o?gn.get(o)??null:null,c=wu(),{sendData:u}=it(),{theme:m}=qs(),d=l.useMemo(()=>Ys(m),[m]),h=l.useMemo(()=>yj(e,n),[e.agentType,(B=e.coordinator)==null?void 0:B.meshId,e.sessionId,(F=e.settings)==null?void 0:F.meshCoordinatorFor,(E=e.settings)==null?void 0:E.meshNodeFor,(D=e.settings)==null?void 0:D.meshNodeId,e.status,e.workspacePath,n]),[p,y]=l.useState(i),[b,x]=l.useState(!1),[k,j]=l.useState(!1),[f,w]=l.useState(null),[S,v]=l.useState((i==null?void 0:i.refreshedAt)??null),g=l.useRef(i!==null),N=l.useRef(!1),M=l.useRef(!1),C=l.useRef(!0);l.useEffect(()=>{g.current=p!==null},[p]),l.useEffect(()=>{const K=o?gn.get(o)??null:null;y(K),v((K==null?void 0:K.refreshedAt)??null),g.current=K!==null,M.current=!1,j(!1),w(null)},[o]);const $=l.useCallback(async(K=!1)=>{if(!a||!n){w("This coordinator does not expose a live mesh id."),y(null);return}if(N.current){K&&(M.current=!0);return}if(!K&&o){const Q=gn.get(o);if(Q){y(Q),v(Q.refreshedAt||null),g.current=!0,x(!1),w(null);return}}N.current=!0;const J=!g.current;x(J),j(K&&g.current),w(null);try{const Q=c!=null&&c.loadMeshStatus?await c.loadMeshStatus(a,n,{refresh:K,retryProfile:K?"settled":"interactive"}):await t(a,"mesh_status",{meshId:n,refresh:K}),Z=im(Q);if(!Z){w("mesh_status returned an unexpected payload.");return}o&&gn.set(o,Z),y(Z),g.current=!0,v(Z.refreshedAt||new Date().toISOString())}catch(Q){w(Q instanceof Error?Q.message:"Failed to load live mesh status")}finally{N.current=!1,x(!1),j(!1),M.current&&C.current&&(M.current=!1,window.setTimeout(()=>{C.current&&$(!0)},0))}},[o,a,n,c,t]);l.useEffect(()=>(C.current=!0,$(!1),()=>{C.current=!1}),[$]),l.useEffect(()=>{const K=J=>{J.key==="Escape"&&r()};return window.addEventListener("keydown",K),()=>window.removeEventListener("keydown",K)},[r]);const R=(p==null?void 0:p.meshName)||n||"Repo Mesh",T=l.useMemo(()=>h?[h]:[],[h]),I=fm({status:p,daemonId:a,meshId:n,sendData:u,extraLiveSessions:T}),A=S?new Date(S).toLocaleTimeString():null,W=l.useMemo(()=>b?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[b]);return s.jsx("div",{className:d.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:d.dialogShellClass,onClick:K=>K.stopPropagation(),children:[s.jsxs("div",{className:d.dialogHeaderClass,children:[s.jsx("div",{className:"min-w-0 flex-1",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(ss,{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:d.dialogTitleClass,children:R}),s.jsx("span",{className:d.dialogKickerClass,children:"Mesh observability"})]}),s.jsxs("p",{className:d.dialogSubtitleClass,children:[ot(e),e.workspaceName?` · ${e.workspaceName}`:"",p!=null&&p.repoIdentity?` · ${p.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[A&&s.jsx("span",{className:d.dialogRefreshedChipClass,children:k?"Refreshing mesh...":`Refreshed ${A}`}),!k&&p&&s.jsx("span",{className:d.dialogRefreshedChipClass,children:u&&!f?"Live daemon metadata":"Metadata subscription unavailable"}),s.jsx("button",{type:"button",onClick:()=>{$(!0)},disabled:b||k,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:b||k?"Refreshing...":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:d.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:s.jsx(yt,{size:16})})]})]}),f&&s.jsx("div",{className:d.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:f}),s.jsx("div",{className:d.dialogBodyClass,children:I?s.jsx(hm,{status:I,emptyMessage:W,daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:d.dialogEmptyClass,children:W})})]})})}function wj(e,t){const{sendCommand:r}=it(),[n,a]=l.useState(null),[o,i]=l.useState(!1);l.useEffect(()=>{if(!e||!t){a(null);return}i(!0),r(e,"git_remote_url",{workspace:t}).then(u=>{const m=(u==null?void 0:u.result)??u;a(typeof(m==null?void 0:m.remoteUrl)=="string"?m.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>i(!1))},[e,t,r]);const c=jj(n);return{remoteUrl:n,githubUrl:c,loading:o}}function jj(e){if(!e)return null;const t=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(t)return`https://github.com/${t[1]}`;const r=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return r?`https://github.com/${r[1]}`:null}const xm=5e3;function kj(e){return`git:${e}`}function Sj({workspace:e,includeDiffSummary:t=!1,intervalMs:r=xm}){return{type:"subscribe",topic:"workspace.git",key:kj(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function Ci(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function js(e,t){if(e instanceof Error)return e.message;if(e&&typeof e=="object"){const r=e;if(typeof r.error=="string"&&r.error.trim())return r.error;if(typeof r.message=="string"&&r.message.trim())return r.message}return t}function Nj(e){const t=Ci(e);return(t==null?void 0:t.success)===!1?{status:null,error:js(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:js(t,"Git status response did not include status")}}function Cj(e){const t=Ci(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:js(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:js(t,"Git diff summary response did not include diffSummary")}}function Xa(e){return e===void 0||typeof e=="boolean"}function Mj(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Xa(t.binary)&&Xa(t.truncated)&&Xa(t.staged)}function Ij(e){const t=Ci(e);return(t==null?void 0:t.success)===!1?{diff:null,error:js(t,"Git file diff request failed")}:Mj(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:js(t,"Git file diff response did not include a valid diff object")}}function Aj({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=xm}){const{sendCommand:o,sendData:i}=it(),c=typeof t=="string"?t.trim():"",u=!!(r&&e&&c),[m,d]=l.useState(null),[h,p]=l.useState(null),[y,b]=l.useState(!1),[x,k]=l.useState(null),j=l.useCallback(async()=>{if(!(!u||!e||!c)){b(!0),k(null);try{const w=Nj(await o(e,"git_status",{workspace:c}));if(w.error){d(null),p(null),k(w.error);return}if(d(w.status),!n){p(null);return}const S=Cj(await o(e,"git_diff_summary",{workspace:c}));if(S.error){p(null),k(S.error);return}p(S.diffSummary)}catch(w){k(js(w,"Git status request failed"))}finally{b(!1)}}},[u,e,n,o,c]),f=l.useMemo(()=>c?Sj({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return l.useEffect(()=>{if(!u||!e||!c||!f){d(null),p(null),b(!1),k(null);return}const w=i?zt.subscribe({sendData:i},e,f,S=>{var v,g;S.workspace===c&&(d(S.status),p(S.diffSummary??null),k(((v=S.status)==null?void 0:v.error)||((g=S.diffSummary)==null?void 0:g.error)||null),b(!1))},{retryIntervalMs:1e3}):null;return j(),()=>{w==null||w()}},[u,e,j,f,i,c]),{status:m,diffSummary:h,loading:y,error:x,refresh:j}}const Tj={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},_j={added:"text-emerald-400",modified:"text-orange-400",deleted:"text-red-400",renamed:"text-sky-400",copied:"text-sky-400",untracked:"text-zinc-400",conflict:"text-red-400 font-bold"};function xc(e){return e.split("/").pop()??e}function Lj(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function Rj({files:e,truncated:t,onFileClick:r,selectedPath:n,className:a=""}){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 ${a}`,children:[s.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(o=>{const i=n===o.path,c=Tj[o.status]??"?",u=_j[o.status]??"text-zinc-400",m=Lj(o.path),d=xc(o.path),h=o.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 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 ${i?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(o),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${u}`,title:o.status,children:c}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&s.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),s.jsx("span",{className:"text-text-primary",children:d}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",xc(o.oldPath)]}),h]}),!o.binary&&(o.insertions>0||o.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",o.insertions]}),o.insertions>0&&o.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),o.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",o.deletions]})]}),o.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${o.path}-${o.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function Pj(e,t){let r="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?r="bg-emerald-500/10 text-emerald-300":e.startsWith("-")&&!e.startsWith("---")?r="bg-red-500/10 text-red-300":e.startsWith("@@")?r="text-sky-400":(e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ "))&&(r="text-text-secondary"),s.jsx("div",{className:`px-3 ${r}`,children:s.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},t)}function Dj({diff:e,binary:t,truncated:r,loading:n,error:a,className:o=""}){const i=l.useRef(null);if(l.useEffect(()=>{i.current&&(i.current.scrollTop=0)},[e]),n)return s.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${o}`,children:"Loading diff…"});if(a)return s.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${o}`,children:a});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(`
|
|
74
74
|
`);return s.jsxs("div",{ref:i,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((u,m)=>Pj(u,m))}),r&&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 $j(e,t){const r=[`Branch: ${e||"unknown"}`];r.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const n={};for(const a of t.files)n[a.status]||(n[a.status]=[]),n[a.status].push(a.path);for(const[a,o]of Object.entries(n))r.push(`${a}: ${o.slice(0,5).join(", ")}${o.length>5?` (+${o.length-5} more)`:""}`);return r.join(`
|
|
75
75
|
`)}function bm({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=it(),{status:a,diffSummary:o,loading:i,error:c,refresh:u}=Aj({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,d]=l.useState(null),[h,p]=l.useState(null),[y,b]=l.useState(""),[x,k]=l.useState(!1),[j,f]=l.useState(!1),[w,S]=l.useState(null),[v,g]=l.useState(null),{githubUrl:N}=wj(e,t),M=l.useCallback(async A=>{if(!((m==null?void 0:m.path)===A.path&&!m.loading)){d({path:A.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const W=await n(e,"git_diff_file",{workspace:t,path:A.path,staged:A.staged}),_=Ij(W);if(_.error||!_.diff){d({path:A.path,diff:"",binary:!1,truncated:!1,loading:!1,error:_.error??"Failed to load diff"});return}d({path:A.path,diff:_.diff.diff,binary:_.diff.binary??!1,truncated:_.diff.truncated??!1,loading:!1,error:null})}catch(W){const _=W instanceof Error?W.message:"Failed to load diff";d({path:A.path,diff:"",binary:!1,truncated:!1,loading:!1,error:_})}}},[e,n,m,t]),C=l.useCallback(A=>{b(""),k(!1),S(null),g(null),p(A)},[]),$=l.useCallback(()=>{p(null),S(null),f(!1)},[]),R=l.useCallback(async()=>{var A,W,_;if(h){f(!0),S(null);try{let L;h==="checkpoint"?L=await n(e,"git_checkpoint",{workspace:t,message:y,includeUntracked:x}):h==="stash"?L=await n(e,"git_stash_push",{workspace:t,message:y,includeUntracked:x}):h==="stash_pop"?L=await n(e,"git_stash_pop",{workspace:t}):h==="checkout_files"&&m&&(L=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const B=(L==null?void 0:L.result)??L;if((B==null?void 0:B.success)===!1||B!=null&&B.error){S((B==null?void 0:B.error)??"Action failed"),f(!1);return}h==="checkpoint"?g(`Checkpoint created: ${((W=(A=B==null?void 0:B.checkpoint)==null?void 0:A.commit)==null?void 0:W.slice(0,7))??"done"}`):h==="stash"?g(`Stashed as ${((_=B==null?void 0:B.stash)==null?void 0:_.stashRef)??"stash@{0}"}`):h==="stash_pop"?g("Stash restored"):(g("File reverted"),d(null)),p(null),await u()}catch(L){S(L instanceof Error?L.message:"Action failed")}finally{f(!1)}}},[h,n,e,t,y,x,m,u]),T=!!(a!=null&&a.hasConflicts),I=a?a.staged+a.modified+a.untracked+a.deleted+a.renamed:null;return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:A=>{A.target===A.currentTarget&&r()},children:s.jsxs("div",{className:"relative flex h-[80vh] 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:(a==null?void 0:a.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),N&&s.jsx("a",{href:`${N}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-sky-400 underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:u,disabled:i,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),s.jsx("button",{onClick:r,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(yt,{className:"h-4 w-4"})})]}),a&&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:[a.headCommit&&s.jsxs("span",{title:a.headMessage??void 0,children:[s.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&s.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&s.jsxs("span",{className:"text-orange-400",children:["↑",a.ahead," ahead"]}),a.behind>0&&s.jsxs("span",{className:"text-orange-400",children:["↓",a.behind," behind"]}),a.staged>0&&s.jsxs("span",{className:"text-emerald-400",children:[a.staged," staged"]}),a.modified>0&&s.jsxs("span",{children:[a.modified," modified"]}),a.untracked>0&&s.jsxs("span",{children:[a.untracked," untracked"]}),a.deleted>0&&s.jsxs("span",{className:"text-red-400",children:[a.deleted," deleted"]}),a.stashCount>0&&s.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&s.jsx("span",{className:"font-bold text-red-400",children:"conflicts"}),I===0&&!a.error&&s.jsx("span",{className:"text-emerald-500",children:"clean"}),o&&o.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[o.files.length," file",o.files.length!==1?"s":"",o.totalInsertions>0&&s.jsxs("span",{className:"text-emerald-500",children:[" +",o.totalInsertions]}),o.totalDeletions>0&&s.jsxs("span",{className:"text-red-400",children:[" -",o.totalDeletions]})]})]}),c&&s.jsx("div",{className:"shrink-0 border-b border-border/50 bg-red-500/10 px-4 py-2 text-xs text-red-400",children:c}),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:[i&&!o&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),o&&s.jsx(Rj,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:M}),!i&&!o&&!c&&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:m?s.jsx(Dj,{diff:m.diff,binary:m.binary,truncated:m.truncated,loading:m.loading,error:m.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"})})]}),v&&s.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-emerald-500/10 px-4 py-2 text-xs text-emerald-400 flex items-center justify-between",children:[s.jsx("span",{children:v}),s.jsx("button",{onClick:()=>g(null),className:"ml-2 text-emerald-400 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:()=>C("checkpoint"),disabled:T,title:T?"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:()=>C("stash"),disabled:T,title:T?"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:()=>C("stash_pop"),disabled:T||!(a!=null&&a.stashCount),title:T?"Resolve conflicts before restoring a stash":a!=null&&a.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:()=>C("checkout_files"),disabled:!m,title:m?`Revert changes to ${m.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"}),o&&o.files.length>0&&s.jsx("button",{onClick:()=>{const A=$j((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(A),g("Copied to clipboard"),setTimeout(()=>g(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),h&&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:[h==="checkpoint"&&"Create checkpoint commit",h==="stash"&&"Stash changes",h==="stash_pop"&&"Restore latest stash?",h==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(h==="checkpoint"||h==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:y,onChange:A=>b(A.target.value),maxLength:200,placeholder:"Message (required)",className:"rounded border border-border bg-surface-alt 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:x,onChange:A=>k(A.target.checked)}),"Include untracked files"]})]}),w&&s.jsx("p",{className:"text-xs text-red-400",children:w}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:$,disabled:j,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:R,disabled:j||(h==="checkpoint"||h==="stash")&&!y.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:j?"Working…":"Confirm"})]})]})})]})})}function Ej({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=l.useState(!1),[o,i]=l.useState(!1),[c,u]=l.useState(!1),[m,d]=l.useState(!1),[h,p]=l.useState(!1),[y,b]=l.useState("quickstart"),[x,k]=l.useState("workspace"),j=l.useMemo(()=>!t&&!e,[t,e]),f=l.useCallback(M=>{a(M),M&&i(!1)},[]),w=l.useCallback(M=>{i(M),M&&a(!1)},[]),S=l.useCallback(()=>{b(r===0?"quickstart":"shortcuts"),k("workspace"),u(!0),a(!1),i(!1)},[r]),v=l.useCallback(()=>{u(!1)},[]),g=l.useCallback(()=>{d(!0)},[]),N=l.useCallback(()=>{d(!1)},[]);return l.useEffect(()=>{if(!j){p(!1);return}p(!0);const M=window.setTimeout(()=>{p(!1)},1e4);return()=>window.clearTimeout(M)},[j]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:m,guideNudgeVisible:h,guideTab:y,shortcutSection:x,isDesktopDashboard:j,setGuideTab:b,setShortcutSection:k,handleInboxOpenChange:f,handleHiddenOpenChange:w,handleOpenShortcutHelp:S,closeShortcutHelp:v,openNewSession:g,closeNewSession:N}}function Bj(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 Oj(e){return e instanceof Error?e.message:String(e||"")}function Fj(e){const t=Oj(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Hj({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:i,onStopCli:c,activeCliViewMode:u,onSetActiveCliViewMode:m,mobileChatConversations:d,hiddenConversations:h,ides:p,actionLogs:y,sendDaemonCommand:b,setActionLogs:x,setCliViewModeOverrides:k,isStandalone:j,initialDataLoaded:f,userName:w,requestedMobileTabKey:S,onRequestedMobileTabConsumed:v,requestedMachineId:g,onRequestedMachineConsumed:N,requestedMobileSection:M,onRequestedMobileSectionConsumed:C,containerRef:$,isSplitMode:R,numGroups:T,groupSizes:I,groupedConvs:A,clearedTabs:W,focusedGroup:_,focusGroup:L,moveTabToGroup:B,splitTabRelative:F,closeGroup:E,handleResizeStart:D,groupActiveTabIds:K,setGroupActiveTab:J,groupTabOrders:Q,setGroupTabOrder:Z,toggleHiddenTab:he,visibleConversations:we,requestedDesktopTabKey:Me,onRequestedDesktopTabConsumed:q,onDesktopActiveTabChange:ye,onRequestScrollToBottom:ge,onHideConversation:ve,onShowHiddenConversation:pe,onShowAllHiddenConversations:Ie,scrollToBottomRequest:X,machineEntries:be,layoutProfile:ue,onBrowseMachineDirectory:U,onSaveMachineWorkspace:ce,onLaunchMachineIde:ie,onLaunchMachineProvider:de,onListMachineMeshes:me,onLaunchMeshCoordinator:oe,onListMachineSavedSessions:P,notifications:xe,notificationUnreadCount:Ne,liveSessionInboxState:_e,onMarkNotificationRead:se,onMarkNotificationUnread:De,onDeleteNotification:Te}){const $e=gt.useRef(null),{inboxOpen:Oe,hiddenOpen:Je,shortcutHelpOpen:qe,newSessionOpen:Ze,guideNudgeVisible:et,guideTab:ut,shortcutSection:mt,isDesktopDashboard:bt,setGuideTab:Ae,setShortcutSection:We,handleInboxOpenChange:rt,handleHiddenOpenChange:Ye,handleOpenShortcutHelp:tt,closeShortcutHelp:z,openNewSession:G,closeNewSession:Y}=Ej({isMobile:t,showMobileChatMode:e,visibleConversationCount:we.length}),[re,H]=gt.useState(null),[V,te]=gt.useState(null),le=gt.useCallback((ae,Pe)=>{H({daemonId:ae,workspace:Pe})},[]),Se=gt.useCallback(ae=>{te(ae)},[]),Le=gt.useCallback(ae=>{var Pe;Nr.flushSync(()=>{pe(ae)}),(Pe=$e.current)==null||Pe.restoreHiddenTabToSavedLocation(ae.tabKey)},[pe]),O=gt.useCallback(ae=>{var Nt;const Pe=d.find(Ct=>vo(Ct,ae))||h.find(Ct=>vo(Ct,ae));Pe&&(h.some(Ct=>Ct.tabKey===Pe.tabKey)&&Le(Pe),ye(Pe.tabKey),(Nt=$e.current)==null||Nt.activateConversationTab(Pe.tabKey),ge(Pe.tabKey,"notification-open")),se(ae.id),rt(!1)},[Le,h,d,ye,se,ge]),ne=gt.useCallback(()=>{var Pe;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Pe=$e.current)==null||Pe.resetAllPanelsToMain(),Ye(!1))},[Ye]),fe=gt.useCallback(async ae=>{var os;if(!r)return;const Pe=(os=r.modalButtons)==null?void 0:os[ae];if(!Pe)return;const Nt=ps(r);if(!Nt)return;const Ct=Pe.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Ns=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Ct);try{await b(Nt,"resolve_action",{button:Pe,action:Ns?"approve":"reject",buttonIndex:ae,...hs(r)})}catch(is){Fj(is)||console.error("[Shortcut approval] Failed:",is)}},[r,b]),{isMac:ke,actionDefinitions:Ce,actionShortcuts:Ke,shortcutListening:Ge,shortcutListeningDraft:Be,setShortcutListening:ht,setShortcutListeningDraft:ct,saveShortcuts:ft}=X0({enabled:bt&&!qe,onTrigger:ae=>{var Pe,Nt,Ct,Ns,os,is,Hr,Wr,Kr,Ur,zr,Gr,Vr,qr,Yr,Xr;if(ae==="openShortcutHelp"){tt();return}if(ae==="openNewSession"){G();return}if(ae==="hideCurrentTab"){r&&ve(r);return}if(ae==="toggleHiddenTabs"){Ye(!Je);return}if(ae==="openHistoryForActiveTab"){r&&!Ve(r)&&o(r);return}if(ae==="openRemoteForActiveTab"){r&&!Xe(r)&&!Ve(r)&&i(r);return}if(ae==="splitActiveTabRight"){(Pe=$e.current)==null||Pe.splitActiveTabRight();return}if(ae==="splitActiveTabDown"){(Nt=$e.current)==null||Nt.splitActiveTabDown();return}if(ae==="floatActiveTab"){(Ct=$e.current)==null||Ct.floatActiveTab();return}if(ae==="popoutActiveTab"){(Ns=$e.current)==null||Ns.popoutActiveTab();return}if(ae==="dockActiveTab"){(os=$e.current)==null||os.dockActiveTab();return}if(ae==="focusLeftPane"){(is=$e.current)==null||is.focusLeftPane();return}if(ae==="focusRightPane"){(Hr=$e.current)==null||Hr.focusRightPane();return}if(ae==="focusUpPane"){(Wr=$e.current)==null||Wr.focusUpPane();return}if(ae==="focusDownPane"){(Kr=$e.current)==null||Kr.focusDownPane();return}if(ae==="moveActiveTabToLeftPane"){(Ur=$e.current)==null||Ur.moveActiveTabToLeftPane();return}if(ae==="moveActiveTabToRightPane"){(zr=$e.current)==null||zr.moveActiveTabToRightPane();return}if(ae==="moveActiveTabToUpPane"){(Gr=$e.current)==null||Gr.moveActiveTabToUpPane();return}if(ae==="moveActiveTabToDownPane"){(Vr=$e.current)==null||Vr.moveActiveTabToDownPane();return}if(ae==="triggerPrimaryApprovalAction"){fe(0);return}if(ae==="triggerSecondaryApprovalAction"){fe(1);return}if(ae==="triggerTertiaryApprovalAction"){fe(2);return}if(ae==="setActiveTabShortcut"){(qr=$e.current)==null||qr.setShortcutForActiveTab();return}if(ae==="selectPreviousGroupTab"){(Yr=$e.current)==null||Yr.activatePreviousTabInGroup();return}if(ae==="selectNextGroupTab"){(Xr=$e.current)==null||Xr.activateNextTabInGroup();return}!r||!Xe(r)||Ve(r)||ae==="toggleCliView"&&m(u==="chat"?"terminal":"chat")}}),He=gt.useCallback(()=>{z(),ht(null),ct([])},[z,ht,ct]),Qt=gt.useMemo(()=>mt==="all"?Ce:Ce.filter(ae=>Bj(ae)===mt),[Ce,mt]),ee=gt.useCallback(()=>{const ae=Object.fromEntries(Ce.map(Pe=>[Pe.id,""]));ft(ae)},[Ce,ft]),Re=gt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const ae=Object.fromEntries(Ce.map(Pe=>[Pe.id,Pe.defaultShortcut]));ft(ae)},[Ce,ft]);return gt.useEffect(()=>{const ae=Pe=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Pe.metaKey&&Pe.key.toLowerCase()==="w":Pe.ctrlKey&&Pe.key.toLowerCase()==="w")&&(Pe.preventDefault(),r&&ve&&ve(r))};return window.addEventListener("keydown",ae),()=>window.removeEventListener("keydown",ae)},[r,ve]),gt.useEffect(()=>{if(!qe||Ge)return;const ae=Pe=>{Pe.key==="Escape"&&(Pe.preventDefault(),He())};return window.addEventListener("keydown",ae,!0),()=>window.removeEventListener("keydown",ae,!0)},[He,qe,Ge]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(Db,{activeConv:r,wsStatus:n,isConnected:a,conversations:we,hiddenConversations:h,onOpenHistory:o,onHideConversation:ve,onShowConversation:Le,onShowAllHidden:Ie,onResetPanelsToMain:ne,notifications:xe,notificationUnreadCount:Ne,onOpenNotification:O,onMarkNotificationRead:se,onMarkNotificationUnread:De,onDeleteNotification:Te,inboxOpen:Oe,onInboxOpenChange:rt,hiddenOpen:Je,onHiddenOpenChange:Ye,onOpenNewSession:t?void 0:G,onOpenDashboardGuide:tt,guideNudgeVisible:et,actionShortcuts:Ke,onOpenRemote:()=>{!r||Xe(r)||Ve(r)||i(r)},onStopCli:c,activeCliViewMode:u,onSetCliViewMode:m,onOpenGitDialog:le,onOpenMeshGraph:Se}),e?s.jsx(B0,{conversations:d,hiddenConversations:h,ides:p,actionLogs:y,sendDaemonCommand:b,setActionLogs:x,setCliViewModeOverrides:k,isStandalone:j,userName:w,requestedActiveTabKey:S,onRequestedActiveTabConsumed:v,requestedMachineId:g,onRequestedMachineConsumed:N,requestedMobileSection:M,onRequestedMobileSectionConsumed:C,onOpenHistory:o,onOpenRemote:i,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Ie,onHideConversation:ve,onOpenMeshGraph:Se,onOpenNewSession:G,liveSessionInboxState:_e}):t?s.jsx(G0,{containerRef:$,isSplitMode:R,numGroups:T,groupSizes:I,groupedConvs:A,clearedTabs:W,ides:p,actionLogs:y,sendDaemonCommand:b,setActionLogs:x,isStandalone:j,hasRegisteredMachines:be.length>0,userName:w,focusedGroup:_,focusGroup:L,moveTabToGroup:B,splitTabRelative:F,closeGroup:E,handleResizeStart:D,groupActiveTabIds:K,setGroupActiveTab:J,groupTabOrders:Q,setGroupTabOrder:Z,toggleHiddenTab:he,onOpenNewSession:G,allowTabShortcuts:!1,liveSessionInboxState:_e}):s.jsx(dv,{visibleConversations:we,clearedTabs:W,ides:p,actionLogs:y,sendDaemonCommand:b,setActionLogs:x,isStandalone:j,hasRegisteredMachines:be.length>0,initialDataLoaded:f,userName:w,toggleHiddenTab:he,actionShortcuts:Ke,registerActionHandlers:ae=>{$e.current=ae},onActiveTabChange:ye,requestedActiveTabKey:Me,onRequestedActiveTabConsumed:q,onRequestScrollToBottom:ge,scrollToBottomRequest:X,onOpenNewSession:G,liveSessionInboxState:_e,layoutProfile:ue}),Ze&&s.jsx(vv,{machines:be,ides:p,onClose:Y,onBrowseDirectory:U,onSaveWorkspace:ce,onLaunchIde:ie,onLaunchProvider:de,onListMeshes:me,onLaunchMeshCoordinator:oe,onListSavedSessions:P}),V&&s.jsx(vj,{activeConv:V,sendDaemonCommand:b,onClose:()=>te(null)}),re&&s.jsx(bm,{daemonId:re.daemonId,workspace:re.workspace,onClose:()=>H(null)}),qe&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:He,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:ae=>ae.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:"Dashboard guide"}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:He,"aria-label":"Close dashboard guide",children:s.jsx(yt,{size:14})})]}),s.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(ae=>s.jsx("button",{type:"button",className:`btn btn-sm ${ut===ae.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ae(ae.id),children:ae.label},ae.id))}),ut==="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:"What lives where"}),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:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),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:"Useful flows"}),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:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",ke?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),ut==="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:"Desktop quick start"}),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."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),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:"Mobile quick start"}),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."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),ut==="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:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(ae=>s.jsx("button",{type:"button",className:`btn btn-sm ${mt===ae.id?"btn-primary":"btn-secondary"}`,onClick:()=>We(ae.id),children:ae.label},ae.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ee,children:"Disable all"}),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:Re,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Qt.map(ae=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Ge===ae.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:ae.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ae.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:ae.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-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:Ge===ae.id?Be.length>0?`${Be.join(" ")} ...`:"Listening...":Ke[ae.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{ht(ae.id),ct([])},children:Ge===ae.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Pe={...Ke};Pe[ae.id]="",ft(Pe)},children:"Disable"})]})]})},ae.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",ke?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",", or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs."]})]})]})})]})}const Ja=[{icon:"🦦",title:"Welcome to ADHDev",desc:"Monitor and control your AI coding agents from anywhere — web, mobile, or CLI.",visual:"🎉"},{icon:"💬",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:"📱"},{icon:"🖥️",title:"Remote desktop",desc:"View and control your IDE screen via P2P connection. Click, type, scroll — just like being there.",visual:"🖱️"},{icon:"🚀",title:"Get started",desc:"Install the daemon and link it to your dashboard. It connects automatically.",code:"npm install -g @adhdev/daemon-standalone && adhdev-standalone"}];function Wj({onClose:e}){const[t,r]=l.useState(0),n=Ja[t],a=t===Ja.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:o=>{o.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)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(yt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Ja.map((o,i)=>s.jsx("div",{style:{width:i===t?24:8,height:8,borderRadius:4,background:i===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},i))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),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("span",{children:n.icon})," ",n.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.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:"$"}),n.code]}),a&&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:()=>a?e():r(o=>o+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
|