@adhdev/daemon-standalone 0.9.82-rc.200 → 0.9.82-rc.201
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.
|
@@ -64,14 +64,14 @@ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Mach
|
|
|
64
64
|
<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>
|
|
65
65
|
<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>
|
|
66
66
|
</div>
|
|
67
|
-
`,fe.style.top="52px",fe.style.height="calc(100% - 52px)";const Te=Ie.querySelector("[data-adhdev-popout-focus]");Te&&(Te.onclick=()=>{window.focus()});const Oe=Ie.querySelector("[data-adhdev-popout-dock]");Oe&&(Oe.disabled=!H,Oe.style.opacity=H?"1":"0.5",Oe.style.cursor=H?"pointer":"default",Oe.onclick=()=>{var _e;H&&Ne(H),(_e=me.defaultView)==null||_e.focus()})}},[$,Ne]),ce=l.useCallback(U=>{var oe;const z=N.current,Y=z==null?void 0:z.getPanel(U);if(!(!z||!Y)){Y.group.model.openPanel(Y),Y.api.setActive(),ee(U,"dockview-shortcut");try{const me=Y.group.model.location;me.type==="popout"?me.getWindow().focus():za((oe=Y.group.element)==null?void 0:oe.ownerDocument)}catch{}}},[ee]),K=l.useCallback(U=>{const z=N.current,Y=z==null?void 0:z.activePanel,oe=(z==null?void 0:z.activeGroup)||(Y==null?void 0:Y.group);if(!z||!Y||!oe)return;const me=oe.panels||[];if(me.length<=1)return;const fe=me.findIndex(ie=>ie.id===Y.id);if(fe<0)return;const H=(fe+U+me.length)%me.length,G=me[H];G&&(G.group.model.openPanel(G),G.api.setActive(),Ut(G.id)||ee(G.id,"dockview-shortcut"))},[ee]),ae=l.useCallback(U=>{var Te;const z=N.current,Y=(z==null?void 0:z.activeGroup)||((Te=z==null?void 0:z.activePanel)==null?void 0:Te.group);if(!z||!Y)return;const oe=z.groups||[],me=oe.find(Oe=>Oe.id===Y.id);if(!me)return;const fe=me.element.getBoundingClientRect(),H=fe.left+fe.width/2,G=fe.top+fe.height/2,ie=(Oe,_e,ze,Qe)=>Math.max(0,Math.min(_e,Qe)-Math.max(Oe,ze)),we=Oe=>{const _e=Oe.element.getBoundingClientRect(),ze=_e.left+_e.width/2,Qe=_e.top+_e.height/2;let pt=0,jt=0,yt=0,vt=!1;if(U==="left"?(vt=ze<H,pt=Math.max(0,fe.left-_e.right),jt=Math.abs(Qe-G),yt=ie(fe.top,fe.bottom,_e.top,_e.bottom)):U==="right"?(vt=ze>H,pt=Math.max(0,_e.left-fe.right),jt=Math.abs(Qe-G),yt=ie(fe.top,fe.bottom,_e.top,_e.bottom)):U==="above"?(vt=Qe<G,pt=Math.max(0,fe.top-_e.bottom),jt=Math.abs(ze-H),yt=ie(fe.left,fe.right,_e.left,_e.right)):(vt=Qe>G,pt=Math.max(0,_e.top-fe.bottom),jt=Math.abs(ze-H),yt=ie(fe.left,fe.right,_e.left,_e.right)),!vt)return Number.POSITIVE_INFINITY;const Fe=yt>0?0:120;return pt*3+jt+Fe};let Pe=null,Ie=Number.POSITIVE_INFINITY;for(const Oe of oe){if(Oe.id===me.id)continue;const _e=we(Oe);Number.isFinite(_e)&&(_e>=Ie||(Ie=_e,Pe=Oe))}return Pe||void 0},[]),de=l.useCallback(U=>{var oe;const z=ae(U);if(!z)return;const Y=z.activePanel||z.panels[0];Y&&(z.model.openPanel(Y),Y.api.setActive(),Ut(Y.id)||ee(Y.id,"dockview-focus"),za((oe=z.element)==null?void 0:oe.ownerDocument))},[ae,ee]),le=l.useCallback((U,z)=>{const Y=N.current,oe=Y==null?void 0:Y.activePanel,me=(Y==null?void 0:Y.activeGroup)||(oe==null?void 0:oe.group);if(!Y||!oe||!me)return;let fe=ae(U);!fe&&(z!=null&&z.createGroupIfMissing)&&(fe=Y.addGroup({referenceGroup:me,direction:U})),fe&&(oe.api.moveTo({group:fe,position:"center"}),oe.group.model.openPanel(oe),oe.api.setActive(),Ut(oe.id)||ee(oe.id,z!=null&&z.createGroupIfMissing?"dockview-split":"dockview-move"))},[ae,ee]),{isMac:se,tabShortcuts:J,shortcutListening:D,setShortcutListening:he,saveShortcuts:ke}=zu({sortedTabKeys:e.map(U=>U.tabKey),onFocus:X,onSelectTab:ce}),Se=l.useCallback(()=>{var Y;const U=N.current;if(!U)return;const z=U.activePanel;if(z){if(Ut(z.id)){const oe=((Y=z.params)==null?void 0:Y.routeId)||z.id.slice(7),me=Vt(e,oe);me!=null&&me.tabKey&&he(me.tabKey);return}$.has(z.id)&&he(z.id)}},[$,ce,he,e]),re=l.useCallback(U=>{const z=[];return U.metaKey&&z.push(se?"⌘":"Meta"),U.ctrlKey&&z.push("Ctrl"),U.altKey&&z.push(se?"⌥":"Alt"),U.shiftKey&&U.key.length!==1&&z.push(se?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(U.key)?null:(z.push(Yu(U.key)),z.join("+"))},[se]),De=l.useCallback(U=>{var z,Y;switch(U){case"splitActiveTabRight":le("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":le("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const oe=ue();oe&&xe(oe);return}case"popoutActiveTab":{const oe=ue();oe&&ge(oe);return}case"dockActiveTab":{const oe=ue();if(!oe)return;V(oe)?Ne(oe):ye(oe)&&Ae(oe);return}case"focusLeftPane":de("left");return;case"focusRightPane":de("right");return;case"focusUpPane":de("above");return;case"focusDownPane":de("below");return;case"moveActiveTabToLeftPane":le("left");return;case"moveActiveTabToRightPane":le("right");return;case"moveActiveTabToUpPane":le("above");return;case"moveActiveTabToDownPane":le("below");return;case"selectPreviousGroupTab":K(-1);return;case"selectNextGroupTab":K(1);return;case"setActiveTabShortcut":Se();return;case"hideCurrentTab":{const oe=(Y=(z=N.current)==null?void 0:z.activePanel)==null?void 0:Y.id;oe&&!Ut(oe)&&ve(oe);return}default:return}},[K,Ae,de,xe,ue,ve,ye,V,Ne,le,ge,Se]);l.useEffect(()=>{if(!_)return;const U=_.sourceDocument,z=U.defaultView??window,Y=oe=>{const me=U.querySelector("[data-dockview-tab-context-menu]");me&&me.contains(oe.target)||R(null)};return z.addEventListener("mousedown",Y,!0),z!==window&&window.addEventListener("mousedown",()=>R(null),!0),()=>{z.removeEventListener("mousedown",Y,!0),z!==window&&window.removeEventListener("mousedown",()=>R(null),!0)}},[_]);const He=l.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:$,hasDetachedConversationPanels:F,ides:r,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:g,liveSessionInboxState:j,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:ve,userName:m,scrollToBottomRequest:v,tabShortcuts:J,openTabContextMenu:({x:U,y:z,tabKey:Y,sourceDocument:oe})=>R({x:U,y:z,tabKey:Y,sourceDocument:oe??document}),popoutTab:ge,moveTabBackToMain:Ne,isTabInPopout:V,floatTab:xe,isTabFloating:ye}),[n,t,$,F,r,i,c,g,j,a,o,ve,m,v,J,ge,Ne,V,xe,ye]),Be=_?iv({isTabInPopout:V(_.tabKey),isTabFloating:ye(_.tabKey),tabShortcut:J[_.tabKey],actionShortcuts:h}):[],Ce=l.useCallback(U=>{var oe;const z=N.current;if((((oe=z==null?void 0:z.activePanel)==null?void 0:oe.id)??null)===U.id){U.group.model.openPanel(U);return}U.group.model.openPanel(U),U.api.setActive()},[]),rt=l.useCallback((U,z="requested-tab")=>{if(!U)return!1;const Y=N.current;if(!Y)return!1;const oe=Y.getPanel(U);return oe?(Ce(oe),ee(U,z),f==null||f(),!0):!1},[Ce,f,ee]),st=l.useCallback(()=>{if(M.current)return!1;const U=rt(A.current,"stored-layout-restore");return U&&(M.current=!0),U},[rt]),Ze=l.useCallback(()=>{var z;const U=N.current;U&&Ey(w,{activeTabId:((z=U.activePanel)==null?void 0:z.id)??null,layout:U.toJSON()})},[w]),et=l.useCallback(()=>{Oy(w,E.current)},[w]),it=l.useCallback(U=>{var oe,me,fe,H;const z=N.current;if(!z)return{kind:"grid"};const Y=z.toJSON();for(const G of Y.floatingGroups||[])if((me=(oe=G.data)==null?void 0:oe.views)!=null&&me.includes(U)&&G.position)return{kind:"floating",position:G.position};for(const G of Y.popoutGroups||[])if((H=(fe=G.data)==null?void 0:fe.views)!=null&&H.includes(U))return{kind:"popout",position:G.position,popoutUrl:G.url};return{kind:"grid"}},[]),gt=l.useCallback(U=>{const z=N.current;if(!z)return;const Y=z.getPanel(U),oe=E.current[U];if(!Y||!oe||oe.kind==="grid")return;if(Y.group.model.location.type===oe.kind){delete E.current[U],et();return}if(oe.kind==="floating"){z.addFloatingGroup(Y,{x:oe.position.left??24,y:oe.position.top??24,width:oe.position.width,height:oe.position.height}),delete E.current[U],et();return}delete E.current[U],et()},[et]);l.useEffect(()=>(p==null||p({setShortcutForActiveTab:Se,restoreHiddenTabToSavedLocation:gt,activateConversationTab:ce,resetAllPanelsToMain:q,activatePreviousTabInGroup:()=>K(-1),activateNextTabInGroup:()=>K(1),floatActiveTab:()=>{const U=ue();U&&xe(U)},popoutActiveTab:()=>{const U=ue();U&&ge(U)},dockActiveTab:()=>{const U=ue();U&&(V(U)?Ne(U):ye(U)&&Ae(U))},splitActiveTabRight:()=>le("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>le("below",{createGroupIfMissing:!0}),focusLeftPane:()=>de("left"),focusRightPane:()=>de("right"),focusUpPane:()=>de("above"),focusDownPane:()=>de("below"),moveActiveTabToLeftPane:()=>le("left"),moveActiveTabToRightPane:()=>le("right"),moveActiveTabToUpPane:()=>le("above"),moveActiveTabToDownPane:()=>le("below")}),()=>p==null?void 0:p(null)),[K,Ae,xe,de,ue,ye,V,le,Ne,ge,p,q,gt,ce,Se]),l.useEffect(()=>()=>{var U;(U=B.current)==null||U.call(B),B.current=null},[]);const Tt=l.useCallback(U=>{var Y,oe;N.current=U.api,(Y=B.current)==null||Y.call(B),B.current=null;const z=$y(w);if(A.current=(z==null?void 0:z.activeTabId)??null,z!=null&&z.layout&&U.api.fromJSON(z.layout,{reuseExistingPanels:!1}),T.current=Jl({hasStoredLayout:!!(z!=null&&z.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),T.current||(rc(U.api,e),nc(U.api,e,S)),U.api.totalPanels===0&&e.length>0){const me=fv(U.api,e,k);if(me){const fe=U.api.getPanel(me);fe&&Ce(fe)}}else!T.current&&!rt(k)&&st();if(P.current=!0,U.api.onDidActivePanelChange(me=>{var H;if(A.current=(me==null?void 0:me.id)??null,M.current=!0,be(),me&&Ut(me.id)){const G=((H=me.params)==null?void 0:H.routeId)||me.id.slice(7),ie=Vt(e,G);y((ie==null?void 0:ie.tabKey)??null),Ze();return}if(y((me==null?void 0:me.id)??null),Ze(),!me)return;const fe=$.get(me.id);(fe==null?void 0:fe.streamSource)==="agent-stream"&&fe.agentType&&C(fe.routeId,Ld(),{agentType:fe.agentType,...fe.sessionId&&{targetSessionId:fe.sessionId}}).catch(()=>{})}),U.api.onDidLayoutChange(()=>{Ze(),be(),L(me=>me+1)}),uv()){const me=Ie=>({clientX:Ie.clientX,clientY:Ie.clientY}),fe=Ie=>{const Te=Ie==null?void 0:Ie.getBoundingClientRect();return Te?{left:Te.left,right:Te.right,top:Te.top,bottom:Te.bottom}:null},H=Ie=>{var Oe;const Te=(Oe=I.current)==null?void 0:Oe.getBoundingClientRect();return Te?Ie.clientX<Te.left||Ie.clientX>Te.right||Ie.clientY<Te.top||Ie.clientY>Te.bottom:!1},G=dv({detachDelayMs:Ju,onDetach:({panelId:Ie,clientX:Te,clientY:Oe})=>{var yt,vt;const _e=U.api.getPanel(Ie);if(!_e)return;try{if(_e.group.model.location.type!=="grid")return}catch{return}const ze=(yt=I.current)==null?void 0:yt.getBoundingClientRect(),Qe=(vt=_e.group.element)==null?void 0:vt.getBoundingClientRect(),pt=Math.round(Math.min(Math.max((Qe==null?void 0:Qe.width)??600,360),720)),jt=Math.round(Math.min(Math.max((Qe==null?void 0:Qe.height)??500,260),640));U.api.addFloatingGroup(_e,{x:ze?Math.max(0,Te-ze.left-32):void 0,y:ze?Math.max(0,Oe-ze.top-18):void 0,width:pt,height:jt}),_e.api.setActive(),Ze(),be(),L(Fe=>Fe+1)}}),ie=[U.api.onWillDragPanel(Ie=>{if(!(Ie.nativeEvent.defaultPrevented||Ie.nativeEvent.shiftKey)){try{if(Ie.panel.group.model.location.type!=="grid")return}catch{return}G.startDrag({panelId:Ie.panel.id,selfPanelBounds:fe(Ie.panel.group.element),...me(Ie.nativeEvent)})}}),U.api.onWillShowOverlay(Ie=>{if(G.hasDetached()){Ie.preventDefault();return}G.markDockTarget(me(Ie.nativeEvent))}),U.api.onWillDrop(Ie=>{if(G.hasDetached()){Ie.preventDefault(),G.endDrag();return}G.markDockTarget(me(Ie.nativeEvent))}),U.api.onDidDrop(()=>G.endDrag()),U.api.onUnhandledDragOverEvent(Ie=>{G.isDragging()&&G.markSelfPanel(me(Ie.nativeEvent))})],we=Ie=>{if(!G.isDragging())return;const Te=me(Ie);H(Te)&&G.markNonSelfPanel(Te)},Pe=()=>G.endDrag();window.addEventListener("dragover",we,!0),window.addEventListener("drop",Pe,!0),window.addEventListener("dragend",Pe,!0),B.current=()=>{G.dispose();for(const Ie of ie)Ie.dispose();window.removeEventListener("dragover",we,!0),window.removeEventListener("drop",Pe,!0),window.removeEventListener("dragend",Pe,!0)}}U.api.onDidAddGroup(me=>{requestAnimationFrame(()=>{var fe,H;try{const G=(fe=me.element)==null?void 0:fe.ownerDocument;if(!G||G===document)return;(H=G.getElementById("dv-popout-window"))==null||H.classList.add("adhdev-dockview");const ie=document.documentElement.getAttribute("data-theme");ie&&G.documentElement.setAttribute("data-theme",ie),G.body.className=document.body.className;const we=document.documentElement.getAttribute("style");we&&G.documentElement.setAttribute("style",we)}catch{}be(),L(G=>G+1)})}),y(((oe=U.api.activePanel)==null?void 0:oe.id)??null)},[Ce,rt,$,r,d,w,y,Ze,k,S,C,be,e]);l.useLayoutEffect(()=>{const U=N.current;if(!U||!P.current||T.current&&Jl({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;T.current&&(T.current=!1);const z=W.current,Y=new Set(z),oe=e.map(Pe=>Pe.tabKey),me=new Set(oe),fe=lv({previousVisibleConversationCount:z.length,visibleConversationCount:e.length,ides:r});let H=!1;for(const Pe of z)me.has(Pe)||fe||(E.current[Pe]=it(Pe),H=!0);H&&et(),fe||(rc(U,e),nc(U,e,S));const G=oe.filter(Pe=>!Y.has(Pe));let ie=!1;for(const Pe of G){const Ie=U.getPanel(Pe),Te=E.current[Pe];if(!Ie||!Te||Te.kind==="grid")continue;if(Ie.group.model.location.type===Te.kind){delete E.current[Pe],ie=!0;continue}if(Te.kind==="floating"){U.addFloatingGroup(Ie,{x:Te.position.left??24,y:Te.position.top??24,width:Te.position.width,height:Te.position.height}),delete E.current[Pe],ie=!0;continue}}if(ie&&et(),W.current=oe,k&&rt(k))return;!U.activePanel&&U.panels[0]&&Ce(U.panels[0]),!!(U.activePanel&&U.getPanel(U.activePanel.id))||st()},[Ce,rt,st,r,d,et,it,k,S,e]),l.useEffect(()=>{P.current&&rt(k)},[rt,k]),l.useEffect(()=>{const U=Y=>{const oe=Y.target;if(!oe)return;const me=oe.querySelector("[data-tab-key]")||oe.closest("[data-tab-key]");if(me){const fe=me.getAttribute("data-tab-key");if(fe&&Y.dataTransfer){const H=oe.closest(".dv-tab")||me.closest(".dv-tab")||me;Y.dataTransfer.effectAllowed="move",Y.dataTransfer.setData("text/tab-key",fe),H instanceof HTMLElement&&Y.dataTransfer.setDragImage(H,Math.max(12,Math.round(H.clientWidth/2)),Math.max(10,Math.round(H.clientHeight/2)))}}};window.addEventListener("dragstart",U);const z=sc(N.current);for(const Y of z)Y.addEventListener("dragstart",U);return()=>{window.removeEventListener("dragstart",U);for(const Y of z)Y.removeEventListener("dragstart",U)}},[O]),l.useEffect(()=>{var z;const U=(z=I.current)==null?void 0:z.querySelector(".adhdev-dockview");U instanceof HTMLElement&&Ga(U,b),Z(),be()},[be,Z,b]),l.useEffect(()=>{be()},[be]),l.useEffect(()=>{const U=z=>{if(z.defaultPrevented||D)return;const Y=re(z);if(!Y)return;const oe=z.metaKey||z.ctrlKey||z.altKey;Ro(z.target)&&!oe||ta(se).setActiveTabShortcut!==Y||(z.preventDefault(),z.stopPropagation(),Se())};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[re,se,D,Se]),l.useEffect(()=>{const U=I.current;if(!U)return;const z=Y=>{var G,ie;if(!Y.isTrusted)return;const oe=(ie=(G=Y.target)==null?void 0:G.closest)==null?void 0:ie.call(G,".dv-scrollable");if(!oe)return;Y.preventDefault(),Y.stopPropagation();const me=Math.abs(Y.deltaX),fe=Math.abs(Y.deltaY),H=me>fe?Y.deltaX:Y.deltaY;oe.dispatchEvent(new WheelEvent("wheel",{deltaY:H,deltaMode:Y.deltaMode,bubbles:!1,cancelable:!0}))};return U.addEventListener("wheel",z,{passive:!1,capture:!0}),()=>U.removeEventListener("wheel",z,{capture:!0})},[]),l.useEffect(()=>{const U=sc(N.current);if(U.length===0)return;const z=U.map(Y=>{let oe=[],me=null;const fe=()=>{me!=null&&Y.clearTimeout(me),me=null,oe=[]},H=()=>{me!=null&&Y.clearTimeout(me),me=Y.setTimeout(()=>{me=null,oe=[]},1200)},G=we=>{if(!we.ctrlKey&&!we.metaKey&&!we.altKey)return;const Pe=re(we);if(!Pe)return;const Ie=Uu();for(const[Te,Oe]of Object.entries(Ie))if(e.some(_e=>_e.tabKey===Te)&&Oe===Pe){we.preventDefault(),ce(Te);return}},ie=we=>{if(we.defaultPrevented||D)return;const Pe=re(we);if(!Pe)return;const Ie=we.metaKey||we.ctrlKey||we.altKey;if(Ro(we.target))return;const Te=ta(se),Oe=Object.entries(Te).filter(([Fe,Et])=>!!Et&&(Fe==="splitActiveTabRight"||Fe==="splitActiveTabDown"||Fe==="floatActiveTab"||Fe==="popoutActiveTab"||Fe==="dockActiveTab"||Fe==="focusLeftPane"||Fe==="focusRightPane"||Fe==="focusUpPane"||Fe==="focusDownPane"||Fe==="moveActiveTabToLeftPane"||Fe==="moveActiveTabToRightPane"||Fe==="moveActiveTabToUpPane"||Fe==="moveActiveTabToDownPane"||Fe==="selectPreviousGroupTab"||Fe==="selectNextGroupTab"||Fe==="setActiveTabShortcut"||Fe==="hideCurrentTab")),_e=Ie?[Pe]:[...oe.slice(-1),Pe].slice(-2),ze=_e.join(" "),Qe=_e[_e.length-1],pt=Oe.find(([,Fe])=>Fe===ze);if(pt){we.preventDefault(),fe(),De(pt[0]);return}if(Oe.some(([,Fe])=>Fe.startsWith(`${ze} `))){we.preventDefault(),oe=_e,H();return}const yt=Oe.find(([,Fe])=>Fe===Qe);if(yt){we.preventDefault(),fe(),De(yt[0]);return}if(Oe.some(([,Fe])=>Fe.startsWith(`${Qe} `))){we.preventDefault(),oe=[Qe],H();return}fe()};return Y.addEventListener("keydown",G),Y.addEventListener("keydown",ie),()=>{fe(),Y.removeEventListener("keydown",G),Y.removeEventListener("keydown",ie)}});return()=>{for(const Y of z)Y()}},[re,se,O,ce,D,De,e]);const Le=b==="light"?mo:ho,qe=((kt=(Ye=(lt=N.current)==null?void 0:lt.activePanel)==null?void 0:Ye.group.element)==null?void 0:kt.ownerDocument)??document;return s.jsxs(Qu.Provider,{value:He,children:[s.jsx("div",{ref:I,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(dh,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:xv,remote:bv},defaultTabComponent:yv,watermarkComponent:gv,onReady:Tt,singleTabMode:"default",tabAnimation:"smooth",theme:Le,popoutUrl:"/popout.html"})}),_&&Br.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:Be.map(U=>{if(U.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},U.id);let z=s.jsx(wp,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{};switch(U.id){case"dockInWindow":case"dockBackToGrid":z=s.jsx(kp,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{Ae(_.tabKey),R(null)};break;case"moveBackToMain":z=s.jsx(vp,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{Ne(_.tabKey),R(null)};break;case"floatAsPanel":z=s.jsx(jp,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{xe(_.tabKey),R(null)};break;case"openInNewWindow":z=s.jsx(yp,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{ge(_.tabKey),R(null)};break;case"setShortcut":Y=oe=>{oe.stopPropagation(),he(_.tabKey),R(null)};break;case"removeShortcut":z=s.jsx(Nt,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{const oe={...J};delete oe[_.tabKey],ke(oe),R(null)};break;case"hideTab":z=s.jsx(zo,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{ve(_.tabKey),R(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 ${U.tone==="muted"?"text-text-muted":""}`,onMouseDown:hv,onClick:Y,children:[z,s.jsx("span",{className:"flex-1 min-w-0",children:U.label}),U.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:U.shortcut}):null]},U.id)})}),_.sourceDocument.body),D&&Br.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:()=>he(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:U=>U.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. ",se?"⌘+1":"Ctrl+1",", ",se?"⌥+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"})]})}),qe.body)]})}const Zu="adhdev-recent-launch-args-v1",wv=8;function jv(e){return String(e||"").trim().replace(/\s+/g," ")}function em(e,t){return`${e.trim()}::${t.trim()}`}function tm(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Zu)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function kv(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Zu,JSON.stringify(e))}catch{}}function Sv(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=tm().byKey[em(r,n)])==null?void 0:o.items)||[]}function Nv(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=jv(r);if(!n||!a||!o)return;const i=tm(),c=em(n,a),d=((u=i.byKey[c])==null?void 0:u.items)||[],m=[o,...d.filter(h=>h!==o)].slice(0,wv);i.byKey[c]={items:m},kv(i)}function Cv(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Rn({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 Iv({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 Mv({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:i,onOpenHistory:c,onClearSelection:d}){const m=o?Ou(o):null,u=Iv({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Rn,{title:"Saved history",description:oi(),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:sg()})]}),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:d,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:u}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function sm({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 Av({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 Va(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>er(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>er(a,"acp"))?"acp":null}function gn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Tv({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Fe,Et;const u=Yr(),h=l.useMemo(()=>[...e].sort(Jo),[e]),[p,y]=l.useState(((Fe=h[0])==null?void 0:Fe.id)||""),g=l.useMemo(()=>h.find(Q=>Q.id===p)||h[0],[p,h]),x=l.useMemo(()=>((g==null?void 0:g.workspaces)||[]).map(Q=>({id:Q.id,path:Q.path,label:Q.label})),[g]),k=(g==null?void 0:g.defaultWorkspaceId)||null,[S,f]=l.useState("workspace"),[v,j]=l.useState(""),[w,b]=l.useState(""),[C,N]=l.useState([]),[I,B]=l.useState(""),[P,T]=l.useState(!1),[M,A]=l.useState(null),[W,_]=l.useState(""),[R,O]=l.useState(Va(h[0])),[L,E]=l.useState(""),[$,F]=l.useState(""),[X,ee]=l.useState([]),[ne,Z]=l.useState(""),[ge,Ne]=l.useState([]),[V,ve]=l.useState(!1),[xe,ye]=l.useState(!1),[ue,Ae]=l.useState(""),[q,be]=l.useState(!1),[ce,K]=l.useState(()=>Pt()),[ae,de]=l.useState(null),[le,se]=l.useState(!1),[J,D]=l.useState(""),[he,ke]=l.useState(null),[Se,re]=l.useState(!1),[De,He]=l.useState(""),[Be,Ce]=l.useState([]),[rt,st]=l.useState(!1),[Ze,et]=l.useState(""),[it,gt]=l.useState(!1),Tt=l.useRef(null),Le=l.useRef(0);l.useEffect(()=>{var Q;!p&&((Q=h[0])!=null&&Q.id)&&y(h[0].id)},[p,h]),l.useEffect(()=>{!g||!(!g.workspaces||!g.availableProviders||!g.detectedIdes||!g.recentLaunches)||u(g.id,{minFreshMs:3e4}).catch(()=>{})},[u,g]);const qe=l.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(Q=>er(Q,"cli")),[g]),lt=l.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(Q=>er(Q,"acp")),[g]),Ye=l.useMemo(()=>((g==null?void 0:g.detectedIdes)||[]).map(Q=>({id:Q.type,label:Q.name||Q.type,meta:Q.running?"Detected locally":"Available to open"})),[g]),kt=l.useMemo(()=>R==="cli"?qe.map(Q=>({id:Q.type,label:Q.displayName||Q.type,meta:"CLI provider"})):R==="acp"?lt.map(Q=>({id:Q.type,label:Q.displayName||Q.type,meta:"ACP provider"})):Ye,[lt,R,qe,Ye]),U=l.useMemo(()=>C.find(Q=>Q.id===I)||null,[C,I]),z=l.useMemo(()=>qe.find(Q=>Q.type===L)||null,[qe,L]),Y=l.useMemo(()=>Pu(z==null?void 0:z.meshCoordinator,{meshId:(U==null?void 0:U.id)||"",workspace:(U==null?void 0:U.workspace)||""}),[z,U]),oe=he||Y,me=l.useCallback(async Q=>{T(!0),_("");try{const $e=await c(Q);N($e),B(te=>{var Ee;return $e.some(Ct=>Ct.id===te)?te:((Ee=$e[0])==null?void 0:Ee.id)||""}),A(Q)}catch($e){N([]),B(""),A(Q),_($e instanceof Error?$e.message:"Could not load meshes")}finally{T(!1)}},[c]);l.useEffect(()=>{var $e;if(!g)return;if(Tt.current!==g.id){Tt.current=g.id,f("workspace"),j(k||(($e=x[0])==null?void 0:$e.id)||"__home__"),b(""),N([]),B(""),A(null),_(""),O(Va(g)),E(""),F(""),Z(""),Ne([]),ye(!1),Ae(""),K(Pt()),D(""),ke(null);return}j(te=>{var Ee;return te==="__custom__"||te==="__home__"||x.some(Ct=>Ct.id===te)?te:k||((Ee=x[0])==null?void 0:Ee.id)||"__home__"}),O(te=>te==="ide"&&Ye.length>0||te==="cli"&&qe.length>0||te==="acp"&<.length>0?te:Va(g))},[lt.length,qe.length,k,Ye.length,g,x]),l.useEffect(()=>{!g||S!=="mesh"||M===g.id||P||me(g.id)},[me,M,P,g,S]),l.useEffect(()=>{S==="mesh"&&R!=="cli"&&qe.length>0&&O("cli")},[R,qe.length,S]),l.useEffect(()=>{var Q;R&&(kt.some($e=>$e.id===L)||E(((Q=kt[0])==null?void 0:Q.id)||""))},[R,kt,L]),l.useEffect(()=>{ke(null)},[g==null?void 0:g.id,I,L,S]);const fe=l.useCallback(async(Q,$e)=>{const te=Le.current+1;return Le.current=te,ve(!0),Ae(""),m(Q,$e).then(Ee=>{Le.current===te&&Ne(Ee)}).catch(Ee=>{Le.current===te&&(Ne([]),Ae(Ee instanceof Error?Ee.message:"Could not load saved sessions"))}).finally(()=>{Le.current===te&&(ve(!1),ye(!0))})},[m]),H=l.useCallback((Q,$e)=>{ee(Sv(Q,$e))},[]);l.useEffect(()=>{Le.current+=1,Z(""),K(Pt()),!g||!L||R==="ide"?ee([]):H(g.id,L),ye(!1),Ne([]),Ae(""),ve(!1)},[R,H,fe,g,L]),l.useEffect(()=>{if(!ne)return;const Q=ge.find($e=>$e.providerSessionId===ne);Q!=null&&Q.canResume||Z("")},[ge,ne]);const G=v==="__custom__"?w.trim():v==="__home__"?"":((Et=x.find(Q=>Q.id===v))==null?void 0:Et.path)||"",ie=l.useMemo(()=>g?t.filter(Q=>Q.id!==g.id&&Q.daemonId===g.id).map(Q=>Q.workspace):[],[t,g]),we=l.useMemo(()=>((g==null?void 0:g.recentLaunches)||[]).map(Q=>Q.workspace),[g]),Pe=l.useCallback(Q=>{const $e=String(Q.workspace||"").trim();if(!$e)return;const te=x.find(Ee=>gn(Ee.path)===gn($e));if(te){j(te.id),b("");return}j("__custom__"),b($e)},[x]),Ie=l.useCallback(Q=>{const $e=String(Q.workspace||"").trim();if(!$e)return{workspaceId:null,workspacePath:null};const te=x.find(Ee=>gn(Ee.path)===gn($e));return te?{workspaceId:te.id,workspacePath:null}:{workspaceId:null,workspacePath:$e}},[x]),Te=l.useMemo(()=>ge.find(Q=>Q.providerSessionId===ne)||null,[ge,ne]),Oe=l.useMemo(()=>{var $e;if(R!=="cli"||!g||!L)return null;const Q=(($e=qe.find(te=>te.type===L))==null?void 0:$e.displayName)||L;return{routeId:g.id,daemonId:g.id,providerSessionId:ne||void 0,transport:"pty",mode:"chat",agentName:Q,agentType:L,status:"idle",title:Q,messages:[],ideType:L,workspaceName:G,workspacePath:G,displayPrimary:Q,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${g.id}:${L}`,machineName:$t(g,{fallbackId:g.id})}},[R,qe,G,g,ne,L]),_e=l.useCallback(()=>{var $e;if(!g)return;j("__custom__"),re(!0),et("");const Q=fi(g.platform,pi(w.trim(),G,ie,we,g.defaultWorkspacePath,($e=x.find(te=>te.id===k))==null?void 0:$e.path,x.map(te=>te.path)));st(!0),n(g.id,Q).then(te=>{He(te.path),b(te.path),Ce(te.directories)}).catch(te=>{et(te instanceof Error?te.message:"Could not load folder")}).finally(()=>st(!1))},[w,k,we,ie,n,G,g,x]),ze=l.useCallback(Q=>{g&&(st(!0),et(""),n(g.id,Q).then($e=>{He($e.path),b($e.path),Ce($e.directories)}).catch($e=>{et($e instanceof Error?$e.message:"Could not load folder")}).finally(()=>st(!1)))},[n,g]),Qe=l.useCallback(async()=>{if(!g||!G)return;gt(!0),D("");const Q=await a(g.id,G);if(gt(!1),!Q.ok){D(Q.error||"Could not save workspace");return}D("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,G,g]),pt=l.useCallback(async()=>{if(!g)return;if(S==="mesh"){if(!I||!L)return;se(!0),D(""),ke(null);const te=await d(g.id,I,L);if(se(!1),!te.ok){if(te.code==="mesh_coordinator_manual_mcp_setup_required"&&te.manualSetup){ke(te.manualSetup),D("Manual MCP setup required before this provider can act as mesh coordinator.");return}D(te.error||"Could not start mesh coordinator");return}r();return}if(!R||!L)return;se(!0),D("");const Q=$.trim()?$.trim().split(/\s+/).filter(Boolean):[],$e=R==="ide"?await o(g.id,L,{workspacePath:G||null}):await i(g.id,R,L,{workspaceId:v!=="__home__"&&v!=="__custom__"?v:null,workspacePath:v==="__custom__"&&G||null,resumeSessionId:R==="cli"&&ne?ne:null,cliArgs:Q});if(se(!1),!$e.ok){D($e.error||"Could not start session");return}R!=="ide"&&$.trim()&&(Nv(g.id,L,$),H(g.id,L)),r()},[R,$,H,r,o,d,i,G,g,I,ne,L,v,S]),jt=S==="mesh"?"Start mesh coordinator":R?Zb(R,R==="cli"&&!!ne):"Start",yt=S==="mesh"?"Starting coordinator…":R?eg(R,R==="cli"&&!!ne):"Starting…",vt=h.length>5;return g?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(Nt,{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(Rn,{title:"Machine",children:vt?s.jsx("select",{"aria-label":"Machine",value:g.id,onChange:Q=>y(Q.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:le,children:h.map(Q=>s.jsx("option",{value:Q.id,children:$t(Q,{fallbackId:Q.id})},Q.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:h.map(Q=>{const $e=$t(Q,{fallbackId:Q.id}),te=g.id===Q.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${$e}`,"aria-pressed":te,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${te?"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(Q.id),disabled:le,title:$e,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${Q.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:$e})]},Q.id)})})}),s.jsxs(Rn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:S==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:_e,disabled:le,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(Q=>s.jsxs("button",{type:"button",role:"radio","aria-checked":S===Q.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${S===Q.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(Q.id),D(""),Q.id==="mesh"&&g&&M!==g.id&&!P&&me(g.id)},disabled:le,children:[s.jsx("div",{className:"text-sm font-semibold",children:Q.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:Q.desc})]},Q.id))}),S==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:v,onChange:Q=>{const $e=Q.target.value;j($e),$e==="__custom__"?_e():D("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:le,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),x.map(Q=>s.jsxs("option",{value:Q.id,children:[Q.id===k?"⭐ ":"",bd(Q.path,Q.label)||Q.path]},Q.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v==="__home__"?"Launch without a workspace.":G||"Select a workspace folder."}),v==="__custom__"&&G&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:_e,disabled:le,children:[s.jsx(Xs,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Qe,disabled:le||it,children:it?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[P&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!P&&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}),!P&&!W&&C.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."}),C.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:C.map(Q=>s.jsxs("button",{type:"button",role:"radio","aria-checked":I===Q.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${I===Q.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>B(Q.id),disabled:le,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Q.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[Q.repoIdentity||"Repo mesh",typeof Q.nodesCount=="number"?` · ${Q.nodesCount} node${Q.nodesCount===1?"":"s"}`:""]}),Q.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",Q.workspace]})]},Q.id))}),U&&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(Av,{workspaceMode:S,activeKind:R,cliEnabled:qe.length>0,ideEnabled:Ye.length>0,acpEnabled:lt.length>0,busy:le,onSelect:O}),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:R==="ide"?"Choose IDE":R==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[kt.map(Q=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${L===Q.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>E(Q.id),disabled:le,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Q.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Q.meta})]},Q.id)),kt.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."})]})]}),S==="mesh"&&oe&&s.jsx(sm,{setup:oe,providerName:(z==null?void 0:z.displayName)||(z==null?void 0:z.name)||L}),S!=="mesh"&&R!=="ide"&&s.jsxs(Rn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:$,onChange:Q=>F(Q.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:le}),X.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:X.map(Q=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>F(Q),disabled:le,title:Q,children:Q},Q))})]}),S!=="mesh"&&R==="cli"&&s.jsx(Mv,{busy:le,savedSessionsLoading:V,savedSessionsError:ue,selectedSession:Te,onRefresh:()=>{!g||!L||fe(g.id,L)},onOpenHistory:()=>{!g||!L||(be(!0),Cv({hasLoadedInitialResults:xe,isLoading:V})&&fe(g.id,L))},onClearSelection:()=>Z("")}),J&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${J.includes("saved")||J.includes("requested")||J.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:J})]}),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:le,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:pt,disabled:le||(S==="mesh"?!I||!L||R!=="cli"||P:!R||!L||v==="__custom__"&&!G),children:[s.jsx(td,{size:14}),le?yt:jt]})]})]})}),Se&&s.jsx(gi,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:De,directories:Be,busy:rt,error:Ze,onClose:()=>re(!1),onNavigate:ze,onConfirm:Q=>{b(Q),He(Q),j("__custom__"),re(!1)}}),q&&Oe&&s.jsx(tu,{activeConv:Oe,ides:[],isCreatingChat:!1,isRefreshingHistory:V,savedSessions:ge,isSavedSessionsLoading:V,isResumingSavedSessionId:ae,savedHistoryFilters:ce,missingWorkspaceResumePath:G||null,onSavedHistoryFiltersChange:K,onClose:()=>be(!1),onNewChat:()=>{Z(""),be(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!g||!L||fe(g.id,L)},onResumeSavedSession:Q=>{if(!g||!L||ae||!Q.canResume)return;const $e=Ie(Q);Z(Q.providerSessionId),Pe(Q),de(Q.providerSessionId),be(!1),se(!0),D(""),i(g.id,"cli",L,{workspaceId:$e.workspaceId,workspacePath:$e.workspacePath,resumeSessionId:Q.providerSessionId}).then(te=>{if(!te.ok){D(te.error||"Could not resume session");return}r()}).finally(()=>{se(!1),de(te=>te===Q.providerSessionId?null:te)})}})]}):null}function rm(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 vi(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=rm(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 wi(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function nm(e){var t;return!wi(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 yn(e){return[...new Set(e.filter(t=>!!t))]}function _v(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?yn([t==null?void 0:t.id,...n.map(i=>i.id)]):a.length>0?yn(a.map(i=>i.id)):o.length>0?yn(o.map(i=>i.id)):yn(e.nodes.map(i=>i.id))}function am(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 Lv(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${am(e)}::${n}x${a}`}const Pv={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"},Rv={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"},Dv={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"},$v={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 or(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=>Rv[t],actionButton:t=>$v[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=>Pv[t],actionButton:t=>Dv[t]}}const tr={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,layerGap:220,nodeGap:82,edgeLabelBuffer:180,placeholderTopOffset:0},en={worktreeCardWidth:188,submoduleCardWidth:188,minWorktreeCardHeight:88,minSubmoduleCardHeight:88,maxEstimatedCardHeight:178,layerGap:160,nodeGap:52,edgeLabelBuffer:120},Ev={maxWidth:180};function Bv(e){return e==="TB"?"DOWN":"RIGHT"}function ji(e,t){return{"elk.algorithm":"layered","elk.direction":Bv(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 Ov=ji(tr,"LR");ji(en,"LR");function Fv(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 Hv=new uh;function Kr(e,t=!1){const r=t?en:tr;return e.type==="submoduleNode"?r.submoduleCardWidth:r.worktreeCardWidth}function Dn(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=rm(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 om(e,t=!1){const r=t?en:tr,n=Kr(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(Wv(e)/o),c=vn(e.label,a,2),d=vn(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,a,2),m=vn(Dn(e),a+(t?1:4),t?2:3),u=vi(e),h=nm(e)?wi(e):null,p=t?0:vn(h,Math.max(24,Math.floor(n/8)),4),y=t?40+c*16+d*12+(u?22:0)+Math.max(0,i-1)*18+Math.max(18,m*16):52+c*18+d*14+(u?30:0)+i*24+Math.max(22,m*18)+(p>0?22+p*16:0),g=e.type==="submoduleNode"?r.minSubmoduleCardHeight:r.minWorktreeCardHeight;return Math.min(r.maxEstimatedCardHeight,Math.max(g,Math.ceil(y)))}function vn(e,t,r){const n=(e||"").trim();return n?Math.max(1,Math.min(r,Math.ceil(n.length/t))):0}function Wv(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 Kv(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 Uv(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function zv(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 Gv(e,t,r){return{id:e.id,x:t,y:r,width:Kr(e),height:om(e)}}function Vv(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 im(e){const t=[...e.nodes].sort(Kv),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,Vv(r,e)]}function qv(e,t=Ov,r=!1,n="LR"){const a=im(e),o=new Set(a.map(d=>d.id)),i=a.map(d=>({id:d.id,width:Kr(d,r),height:om(d,r)})),c=e.edges.filter(d=>o.has(d.source)&&o.has(d.target)).sort(Uv).map(d=>({id:d.id,sources:[d.source],targets:[d.target]}));return{id:`${e.meshId||"mesh"}__elk_root`,layoutOptions:{...t},children:i,edges:c}}function Yv(e,t=!1){const r=[...new Set(e.map(a=>Math.round(a.x)))].sort((a,o)=>a-o),n=t?en.layerGap:tr.layerGap;return r.length<2?n:Math.min(...r.slice(1).map((a,o)=>a-r[o]))}async function Xv(e,t=!1,r="LR"){var p,y;const a=ji(t?en:tr,r),o=im(e),i=new Map(o.map(g=>[g.id,g])),c=await Hv.layout(qv(e,a,t,r)),d=(c.children??[]).map(g=>{const x=i.get(g.id);return x?zv(x,Math.round(g.x??0),Math.round(g.y??tr.placeholderTopOffset),!g.id.endsWith("__placeholder")):null}).filter(Boolean),m=new Map(o.map((g,x)=>[g.id,x]));d.sort((g,x)=>(m.get(g.id)??0)-(m.get(x.id)??0));const u=d.map(g=>Gv(g.graphNode,g.position.x,g.position.y)),h=new Map;for(const g of c.edges??[]){const x=g.sections;if(!x||x.length===0)continue;const k=x[0],S=(p=g.sources)==null?void 0:p[0],f=(y=g.targets)==null?void 0:y[0];if(!S||!f)continue;const v=[];v.push({x:Math.round(k.startPoint.x),y:Math.round(k.startPoint.y)});for(const j of k.bendPoints??[])v.push({x:Math.round(j.x),y:Math.round(j.y)});v.push({x:Math.round(k.endPoint.x),y:Math.round(k.endPoint.y)}),h.set(g.id,{id:g.id,source:S,target:f,points:v})}return{nodes:d,bounds:u,edgeRoutes:h,columnGap:Yv(u,t),layoutOptions:{...a}}}function Jv(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 lm(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function Qv(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(Jv),...e.edges.map(lm)].join("::")}function Zv(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(lm)].join("::")}const ew=7,ki=l.createContext(or("dark")),cm=l.createContext(!1),dm=l.createContext("LR"),um={overflowWrap:"anywhere",wordBreak:"break-word"},tw={...um,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},sw={...um,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function mm(e){return e.activeSessionCount>0}function rw(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function ac(e,t,r){const n=mm(e),a=rw(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=vi(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 Bt(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 oc(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 ic(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 nw(e){return e.replace(/_/g," ")}function ns(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 qa(e,t){const r=ns(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":Bt("health",t)}function aw(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function lc(e){const t=aw(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 Ya(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function vr(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function ow(e){if(e.sessionDetails.length===0)return null;const t=e.sessionDetails.filter(o=>ns(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 cc(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function iw(e){return e.locality==="remote"?"meta":"health"}function lw({data:e,selected:t}){const r=l.useContext(ki),n=l.useContext(cm),a=l.useContext(dm),o=e.graphNode,i=o.type==="defaultBranchNode",c=o.type==="submoduleNode",d=nm(o),m=i?"default branch anchor":c?o.submodulePath||"submodule checkout":[o.machineLabel,cc(o.locality)].filter(Boolean).join(" · ")||o.workspace,u=o.submoduleCommit?o.submoduleCommit.slice(0,7):null,h=vi(o),p=wi(o),y=mm(o),g=o.sessionDetails,x=o.sessionDetails,k=ow(o),S=o.sessionDetails.map(j=>{const w=ns(j),b=j.providerType||"provider unknown",C=vr(j),N=j.startedAt||j.createdAt||null,I=j.statusNote?` · ${j.statusNote}`:"";return`Session: ${j.sessionId} · ${b} · ${w} · ${C} · ${lc(N)}${I}`});if(n)return s.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${ac(o,t,r.isDark)}`,style:{width:Kr(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,Dn(o),...S].filter(Boolean).join(`
|
|
67
|
+
`,fe.style.top="52px",fe.style.height="calc(100% - 52px)";const Te=Ie.querySelector("[data-adhdev-popout-focus]");Te&&(Te.onclick=()=>{window.focus()});const Oe=Ie.querySelector("[data-adhdev-popout-dock]");Oe&&(Oe.disabled=!H,Oe.style.opacity=H?"1":"0.5",Oe.style.cursor=H?"pointer":"default",Oe.onclick=()=>{var _e;H&&Ne(H),(_e=me.defaultView)==null||_e.focus()})}},[$,Ne]),ce=l.useCallback(U=>{var oe;const z=N.current,Y=z==null?void 0:z.getPanel(U);if(!(!z||!Y)){Y.group.model.openPanel(Y),Y.api.setActive(),ee(U,"dockview-shortcut");try{const me=Y.group.model.location;me.type==="popout"?me.getWindow().focus():za((oe=Y.group.element)==null?void 0:oe.ownerDocument)}catch{}}},[ee]),K=l.useCallback(U=>{const z=N.current,Y=z==null?void 0:z.activePanel,oe=(z==null?void 0:z.activeGroup)||(Y==null?void 0:Y.group);if(!z||!Y||!oe)return;const me=oe.panels||[];if(me.length<=1)return;const fe=me.findIndex(ie=>ie.id===Y.id);if(fe<0)return;const H=(fe+U+me.length)%me.length,G=me[H];G&&(G.group.model.openPanel(G),G.api.setActive(),Ut(G.id)||ee(G.id,"dockview-shortcut"))},[ee]),ae=l.useCallback(U=>{var Te;const z=N.current,Y=(z==null?void 0:z.activeGroup)||((Te=z==null?void 0:z.activePanel)==null?void 0:Te.group);if(!z||!Y)return;const oe=z.groups||[],me=oe.find(Oe=>Oe.id===Y.id);if(!me)return;const fe=me.element.getBoundingClientRect(),H=fe.left+fe.width/2,G=fe.top+fe.height/2,ie=(Oe,_e,ze,Qe)=>Math.max(0,Math.min(_e,Qe)-Math.max(Oe,ze)),we=Oe=>{const _e=Oe.element.getBoundingClientRect(),ze=_e.left+_e.width/2,Qe=_e.top+_e.height/2;let pt=0,jt=0,yt=0,vt=!1;if(U==="left"?(vt=ze<H,pt=Math.max(0,fe.left-_e.right),jt=Math.abs(Qe-G),yt=ie(fe.top,fe.bottom,_e.top,_e.bottom)):U==="right"?(vt=ze>H,pt=Math.max(0,_e.left-fe.right),jt=Math.abs(Qe-G),yt=ie(fe.top,fe.bottom,_e.top,_e.bottom)):U==="above"?(vt=Qe<G,pt=Math.max(0,fe.top-_e.bottom),jt=Math.abs(ze-H),yt=ie(fe.left,fe.right,_e.left,_e.right)):(vt=Qe>G,pt=Math.max(0,_e.top-fe.bottom),jt=Math.abs(ze-H),yt=ie(fe.left,fe.right,_e.left,_e.right)),!vt)return Number.POSITIVE_INFINITY;const Fe=yt>0?0:120;return pt*3+jt+Fe};let Pe=null,Ie=Number.POSITIVE_INFINITY;for(const Oe of oe){if(Oe.id===me.id)continue;const _e=we(Oe);Number.isFinite(_e)&&(_e>=Ie||(Ie=_e,Pe=Oe))}return Pe||void 0},[]),de=l.useCallback(U=>{var oe;const z=ae(U);if(!z)return;const Y=z.activePanel||z.panels[0];Y&&(z.model.openPanel(Y),Y.api.setActive(),Ut(Y.id)||ee(Y.id,"dockview-focus"),za((oe=z.element)==null?void 0:oe.ownerDocument))},[ae,ee]),le=l.useCallback((U,z)=>{const Y=N.current,oe=Y==null?void 0:Y.activePanel,me=(Y==null?void 0:Y.activeGroup)||(oe==null?void 0:oe.group);if(!Y||!oe||!me)return;let fe=ae(U);!fe&&(z!=null&&z.createGroupIfMissing)&&(fe=Y.addGroup({referenceGroup:me,direction:U})),fe&&(oe.api.moveTo({group:fe,position:"center"}),oe.group.model.openPanel(oe),oe.api.setActive(),Ut(oe.id)||ee(oe.id,z!=null&&z.createGroupIfMissing?"dockview-split":"dockview-move"))},[ae,ee]),{isMac:se,tabShortcuts:J,shortcutListening:D,setShortcutListening:he,saveShortcuts:ke}=zu({sortedTabKeys:e.map(U=>U.tabKey),onFocus:X,onSelectTab:ce}),Se=l.useCallback(()=>{var Y;const U=N.current;if(!U)return;const z=U.activePanel;if(z){if(Ut(z.id)){const oe=((Y=z.params)==null?void 0:Y.routeId)||z.id.slice(7),me=Vt(e,oe);me!=null&&me.tabKey&&he(me.tabKey);return}$.has(z.id)&&he(z.id)}},[$,ce,he,e]),re=l.useCallback(U=>{const z=[];return U.metaKey&&z.push(se?"⌘":"Meta"),U.ctrlKey&&z.push("Ctrl"),U.altKey&&z.push(se?"⌥":"Alt"),U.shiftKey&&U.key.length!==1&&z.push(se?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(U.key)?null:(z.push(Yu(U.key)),z.join("+"))},[se]),De=l.useCallback(U=>{var z,Y;switch(U){case"splitActiveTabRight":le("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":le("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const oe=ue();oe&&xe(oe);return}case"popoutActiveTab":{const oe=ue();oe&&ge(oe);return}case"dockActiveTab":{const oe=ue();if(!oe)return;V(oe)?Ne(oe):ye(oe)&&Ae(oe);return}case"focusLeftPane":de("left");return;case"focusRightPane":de("right");return;case"focusUpPane":de("above");return;case"focusDownPane":de("below");return;case"moveActiveTabToLeftPane":le("left");return;case"moveActiveTabToRightPane":le("right");return;case"moveActiveTabToUpPane":le("above");return;case"moveActiveTabToDownPane":le("below");return;case"selectPreviousGroupTab":K(-1);return;case"selectNextGroupTab":K(1);return;case"setActiveTabShortcut":Se();return;case"hideCurrentTab":{const oe=(Y=(z=N.current)==null?void 0:z.activePanel)==null?void 0:Y.id;oe&&!Ut(oe)&&ve(oe);return}default:return}},[K,Ae,de,xe,ue,ve,ye,V,Ne,le,ge,Se]);l.useEffect(()=>{if(!_)return;const U=_.sourceDocument,z=U.defaultView??window,Y=oe=>{const me=U.querySelector("[data-dockview-tab-context-menu]");me&&me.contains(oe.target)||R(null)};return z.addEventListener("mousedown",Y,!0),z!==window&&window.addEventListener("mousedown",()=>R(null),!0),()=>{z.removeEventListener("mousedown",Y,!0),z!==window&&window.removeEventListener("mousedown",()=>R(null),!0)}},[_]);const He=l.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:$,hasDetachedConversationPanels:F,ides:r,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:g,liveSessionInboxState:j,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:ve,userName:m,scrollToBottomRequest:v,tabShortcuts:J,openTabContextMenu:({x:U,y:z,tabKey:Y,sourceDocument:oe})=>R({x:U,y:z,tabKey:Y,sourceDocument:oe??document}),popoutTab:ge,moveTabBackToMain:Ne,isTabInPopout:V,floatTab:xe,isTabFloating:ye}),[n,t,$,F,r,i,c,g,j,a,o,ve,m,v,J,ge,Ne,V,xe,ye]),Be=_?iv({isTabInPopout:V(_.tabKey),isTabFloating:ye(_.tabKey),tabShortcut:J[_.tabKey],actionShortcuts:h}):[],Ce=l.useCallback(U=>{var oe;const z=N.current;if((((oe=z==null?void 0:z.activePanel)==null?void 0:oe.id)??null)===U.id){U.group.model.openPanel(U);return}U.group.model.openPanel(U),U.api.setActive()},[]),rt=l.useCallback((U,z="requested-tab")=>{if(!U)return!1;const Y=N.current;if(!Y)return!1;const oe=Y.getPanel(U);return oe?(Ce(oe),ee(U,z),f==null||f(),!0):!1},[Ce,f,ee]),st=l.useCallback(()=>{if(M.current)return!1;const U=rt(A.current,"stored-layout-restore");return U&&(M.current=!0),U},[rt]),Ze=l.useCallback(()=>{var z;const U=N.current;U&&Ey(w,{activeTabId:((z=U.activePanel)==null?void 0:z.id)??null,layout:U.toJSON()})},[w]),et=l.useCallback(()=>{Oy(w,E.current)},[w]),it=l.useCallback(U=>{var oe,me,fe,H;const z=N.current;if(!z)return{kind:"grid"};const Y=z.toJSON();for(const G of Y.floatingGroups||[])if((me=(oe=G.data)==null?void 0:oe.views)!=null&&me.includes(U)&&G.position)return{kind:"floating",position:G.position};for(const G of Y.popoutGroups||[])if((H=(fe=G.data)==null?void 0:fe.views)!=null&&H.includes(U))return{kind:"popout",position:G.position,popoutUrl:G.url};return{kind:"grid"}},[]),gt=l.useCallback(U=>{const z=N.current;if(!z)return;const Y=z.getPanel(U),oe=E.current[U];if(!Y||!oe||oe.kind==="grid")return;if(Y.group.model.location.type===oe.kind){delete E.current[U],et();return}if(oe.kind==="floating"){z.addFloatingGroup(Y,{x:oe.position.left??24,y:oe.position.top??24,width:oe.position.width,height:oe.position.height}),delete E.current[U],et();return}delete E.current[U],et()},[et]);l.useEffect(()=>(p==null||p({setShortcutForActiveTab:Se,restoreHiddenTabToSavedLocation:gt,activateConversationTab:ce,resetAllPanelsToMain:q,activatePreviousTabInGroup:()=>K(-1),activateNextTabInGroup:()=>K(1),floatActiveTab:()=>{const U=ue();U&&xe(U)},popoutActiveTab:()=>{const U=ue();U&&ge(U)},dockActiveTab:()=>{const U=ue();U&&(V(U)?Ne(U):ye(U)&&Ae(U))},splitActiveTabRight:()=>le("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>le("below",{createGroupIfMissing:!0}),focusLeftPane:()=>de("left"),focusRightPane:()=>de("right"),focusUpPane:()=>de("above"),focusDownPane:()=>de("below"),moveActiveTabToLeftPane:()=>le("left"),moveActiveTabToRightPane:()=>le("right"),moveActiveTabToUpPane:()=>le("above"),moveActiveTabToDownPane:()=>le("below")}),()=>p==null?void 0:p(null)),[K,Ae,xe,de,ue,ye,V,le,Ne,ge,p,q,gt,ce,Se]),l.useEffect(()=>()=>{var U;(U=B.current)==null||U.call(B),B.current=null},[]);const Tt=l.useCallback(U=>{var Y,oe;N.current=U.api,(Y=B.current)==null||Y.call(B),B.current=null;const z=$y(w);if(A.current=(z==null?void 0:z.activeTabId)??null,z!=null&&z.layout&&U.api.fromJSON(z.layout,{reuseExistingPanels:!1}),T.current=Jl({hasStoredLayout:!!(z!=null&&z.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),T.current||(rc(U.api,e),nc(U.api,e,S)),U.api.totalPanels===0&&e.length>0){const me=fv(U.api,e,k);if(me){const fe=U.api.getPanel(me);fe&&Ce(fe)}}else!T.current&&!rt(k)&&st();if(P.current=!0,U.api.onDidActivePanelChange(me=>{var H;if(A.current=(me==null?void 0:me.id)??null,M.current=!0,be(),me&&Ut(me.id)){const G=((H=me.params)==null?void 0:H.routeId)||me.id.slice(7),ie=Vt(e,G);y((ie==null?void 0:ie.tabKey)??null),Ze();return}if(y((me==null?void 0:me.id)??null),Ze(),!me)return;const fe=$.get(me.id);(fe==null?void 0:fe.streamSource)==="agent-stream"&&fe.agentType&&C(fe.routeId,Ld(),{agentType:fe.agentType,...fe.sessionId&&{targetSessionId:fe.sessionId}}).catch(()=>{})}),U.api.onDidLayoutChange(()=>{Ze(),be(),L(me=>me+1)}),uv()){const me=Ie=>({clientX:Ie.clientX,clientY:Ie.clientY}),fe=Ie=>{const Te=Ie==null?void 0:Ie.getBoundingClientRect();return Te?{left:Te.left,right:Te.right,top:Te.top,bottom:Te.bottom}:null},H=Ie=>{var Oe;const Te=(Oe=I.current)==null?void 0:Oe.getBoundingClientRect();return Te?Ie.clientX<Te.left||Ie.clientX>Te.right||Ie.clientY<Te.top||Ie.clientY>Te.bottom:!1},G=dv({detachDelayMs:Ju,onDetach:({panelId:Ie,clientX:Te,clientY:Oe})=>{var yt,vt;const _e=U.api.getPanel(Ie);if(!_e)return;try{if(_e.group.model.location.type!=="grid")return}catch{return}const ze=(yt=I.current)==null?void 0:yt.getBoundingClientRect(),Qe=(vt=_e.group.element)==null?void 0:vt.getBoundingClientRect(),pt=Math.round(Math.min(Math.max((Qe==null?void 0:Qe.width)??600,360),720)),jt=Math.round(Math.min(Math.max((Qe==null?void 0:Qe.height)??500,260),640));U.api.addFloatingGroup(_e,{x:ze?Math.max(0,Te-ze.left-32):void 0,y:ze?Math.max(0,Oe-ze.top-18):void 0,width:pt,height:jt}),_e.api.setActive(),Ze(),be(),L(Fe=>Fe+1)}}),ie=[U.api.onWillDragPanel(Ie=>{if(!(Ie.nativeEvent.defaultPrevented||Ie.nativeEvent.shiftKey)){try{if(Ie.panel.group.model.location.type!=="grid")return}catch{return}G.startDrag({panelId:Ie.panel.id,selfPanelBounds:fe(Ie.panel.group.element),...me(Ie.nativeEvent)})}}),U.api.onWillShowOverlay(Ie=>{if(G.hasDetached()){Ie.preventDefault();return}G.markDockTarget(me(Ie.nativeEvent))}),U.api.onWillDrop(Ie=>{if(G.hasDetached()){Ie.preventDefault(),G.endDrag();return}G.markDockTarget(me(Ie.nativeEvent))}),U.api.onDidDrop(()=>G.endDrag()),U.api.onUnhandledDragOverEvent(Ie=>{G.isDragging()&&G.markSelfPanel(me(Ie.nativeEvent))})],we=Ie=>{if(!G.isDragging())return;const Te=me(Ie);H(Te)&&G.markNonSelfPanel(Te)},Pe=()=>G.endDrag();window.addEventListener("dragover",we,!0),window.addEventListener("drop",Pe,!0),window.addEventListener("dragend",Pe,!0),B.current=()=>{G.dispose();for(const Ie of ie)Ie.dispose();window.removeEventListener("dragover",we,!0),window.removeEventListener("drop",Pe,!0),window.removeEventListener("dragend",Pe,!0)}}U.api.onDidAddGroup(me=>{requestAnimationFrame(()=>{var fe,H;try{const G=(fe=me.element)==null?void 0:fe.ownerDocument;if(!G||G===document)return;(H=G.getElementById("dv-popout-window"))==null||H.classList.add("adhdev-dockview");const ie=document.documentElement.getAttribute("data-theme");ie&&G.documentElement.setAttribute("data-theme",ie),G.body.className=document.body.className;const we=document.documentElement.getAttribute("style");we&&G.documentElement.setAttribute("style",we)}catch{}be(),L(G=>G+1)})}),y(((oe=U.api.activePanel)==null?void 0:oe.id)??null)},[Ce,rt,$,r,d,w,y,Ze,k,S,C,be,e]);l.useLayoutEffect(()=>{const U=N.current;if(!U||!P.current||T.current&&Jl({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;T.current&&(T.current=!1);const z=W.current,Y=new Set(z),oe=e.map(Pe=>Pe.tabKey),me=new Set(oe),fe=lv({previousVisibleConversationCount:z.length,visibleConversationCount:e.length,ides:r});let H=!1;for(const Pe of z)me.has(Pe)||fe||(E.current[Pe]=it(Pe),H=!0);H&&et(),fe||(rc(U,e),nc(U,e,S));const G=oe.filter(Pe=>!Y.has(Pe));let ie=!1;for(const Pe of G){const Ie=U.getPanel(Pe),Te=E.current[Pe];if(!Ie||!Te||Te.kind==="grid")continue;if(Ie.group.model.location.type===Te.kind){delete E.current[Pe],ie=!0;continue}if(Te.kind==="floating"){U.addFloatingGroup(Ie,{x:Te.position.left??24,y:Te.position.top??24,width:Te.position.width,height:Te.position.height}),delete E.current[Pe],ie=!0;continue}}if(ie&&et(),W.current=oe,k&&rt(k))return;!U.activePanel&&U.panels[0]&&Ce(U.panels[0]),!!(U.activePanel&&U.getPanel(U.activePanel.id))||st()},[Ce,rt,st,r,d,et,it,k,S,e]),l.useEffect(()=>{P.current&&rt(k)},[rt,k]),l.useEffect(()=>{const U=Y=>{const oe=Y.target;if(!oe)return;const me=oe.querySelector("[data-tab-key]")||oe.closest("[data-tab-key]");if(me){const fe=me.getAttribute("data-tab-key");if(fe&&Y.dataTransfer){const H=oe.closest(".dv-tab")||me.closest(".dv-tab")||me;Y.dataTransfer.effectAllowed="move",Y.dataTransfer.setData("text/tab-key",fe),H instanceof HTMLElement&&Y.dataTransfer.setDragImage(H,Math.max(12,Math.round(H.clientWidth/2)),Math.max(10,Math.round(H.clientHeight/2)))}}};window.addEventListener("dragstart",U);const z=sc(N.current);for(const Y of z)Y.addEventListener("dragstart",U);return()=>{window.removeEventListener("dragstart",U);for(const Y of z)Y.removeEventListener("dragstart",U)}},[O]),l.useEffect(()=>{var z;const U=(z=I.current)==null?void 0:z.querySelector(".adhdev-dockview");U instanceof HTMLElement&&Ga(U,b),Z(),be()},[be,Z,b]),l.useEffect(()=>{be()},[be]),l.useEffect(()=>{const U=z=>{if(z.defaultPrevented||D)return;const Y=re(z);if(!Y)return;const oe=z.metaKey||z.ctrlKey||z.altKey;Ro(z.target)&&!oe||ta(se).setActiveTabShortcut!==Y||(z.preventDefault(),z.stopPropagation(),Se())};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[re,se,D,Se]),l.useEffect(()=>{const U=I.current;if(!U)return;const z=Y=>{var G,ie;if(!Y.isTrusted)return;const oe=(ie=(G=Y.target)==null?void 0:G.closest)==null?void 0:ie.call(G,".dv-scrollable");if(!oe)return;Y.preventDefault(),Y.stopPropagation();const me=Math.abs(Y.deltaX),fe=Math.abs(Y.deltaY),H=me>fe?Y.deltaX:Y.deltaY;oe.dispatchEvent(new WheelEvent("wheel",{deltaY:H,deltaMode:Y.deltaMode,bubbles:!1,cancelable:!0}))};return U.addEventListener("wheel",z,{passive:!1,capture:!0}),()=>U.removeEventListener("wheel",z,{capture:!0})},[]),l.useEffect(()=>{const U=sc(N.current);if(U.length===0)return;const z=U.map(Y=>{let oe=[],me=null;const fe=()=>{me!=null&&Y.clearTimeout(me),me=null,oe=[]},H=()=>{me!=null&&Y.clearTimeout(me),me=Y.setTimeout(()=>{me=null,oe=[]},1200)},G=we=>{if(!we.ctrlKey&&!we.metaKey&&!we.altKey)return;const Pe=re(we);if(!Pe)return;const Ie=Uu();for(const[Te,Oe]of Object.entries(Ie))if(e.some(_e=>_e.tabKey===Te)&&Oe===Pe){we.preventDefault(),ce(Te);return}},ie=we=>{if(we.defaultPrevented||D)return;const Pe=re(we);if(!Pe)return;const Ie=we.metaKey||we.ctrlKey||we.altKey;if(Ro(we.target))return;const Te=ta(se),Oe=Object.entries(Te).filter(([Fe,Et])=>!!Et&&(Fe==="splitActiveTabRight"||Fe==="splitActiveTabDown"||Fe==="floatActiveTab"||Fe==="popoutActiveTab"||Fe==="dockActiveTab"||Fe==="focusLeftPane"||Fe==="focusRightPane"||Fe==="focusUpPane"||Fe==="focusDownPane"||Fe==="moveActiveTabToLeftPane"||Fe==="moveActiveTabToRightPane"||Fe==="moveActiveTabToUpPane"||Fe==="moveActiveTabToDownPane"||Fe==="selectPreviousGroupTab"||Fe==="selectNextGroupTab"||Fe==="setActiveTabShortcut"||Fe==="hideCurrentTab")),_e=Ie?[Pe]:[...oe.slice(-1),Pe].slice(-2),ze=_e.join(" "),Qe=_e[_e.length-1],pt=Oe.find(([,Fe])=>Fe===ze);if(pt){we.preventDefault(),fe(),De(pt[0]);return}if(Oe.some(([,Fe])=>Fe.startsWith(`${ze} `))){we.preventDefault(),oe=_e,H();return}const yt=Oe.find(([,Fe])=>Fe===Qe);if(yt){we.preventDefault(),fe(),De(yt[0]);return}if(Oe.some(([,Fe])=>Fe.startsWith(`${Qe} `))){we.preventDefault(),oe=[Qe],H();return}fe()};return Y.addEventListener("keydown",G),Y.addEventListener("keydown",ie),()=>{fe(),Y.removeEventListener("keydown",G),Y.removeEventListener("keydown",ie)}});return()=>{for(const Y of z)Y()}},[re,se,O,ce,D,De,e]);const Le=b==="light"?mo:ho,qe=((kt=(Ye=(lt=N.current)==null?void 0:lt.activePanel)==null?void 0:Ye.group.element)==null?void 0:kt.ownerDocument)??document;return s.jsxs(Qu.Provider,{value:He,children:[s.jsx("div",{ref:I,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(dh,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:xv,remote:bv},defaultTabComponent:yv,watermarkComponent:gv,onReady:Tt,singleTabMode:"default",tabAnimation:"smooth",theme:Le,popoutUrl:"/popout.html"})}),_&&Br.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:Be.map(U=>{if(U.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},U.id);let z=s.jsx(wp,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{};switch(U.id){case"dockInWindow":case"dockBackToGrid":z=s.jsx(kp,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{Ae(_.tabKey),R(null)};break;case"moveBackToMain":z=s.jsx(vp,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{Ne(_.tabKey),R(null)};break;case"floatAsPanel":z=s.jsx(jp,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{xe(_.tabKey),R(null)};break;case"openInNewWindow":z=s.jsx(yp,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{ge(_.tabKey),R(null)};break;case"setShortcut":Y=oe=>{oe.stopPropagation(),he(_.tabKey),R(null)};break;case"removeShortcut":z=s.jsx(Nt,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{const oe={...J};delete oe[_.tabKey],ke(oe),R(null)};break;case"hideTab":z=s.jsx(zo,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{ve(_.tabKey),R(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 ${U.tone==="muted"?"text-text-muted":""}`,onMouseDown:hv,onClick:Y,children:[z,s.jsx("span",{className:"flex-1 min-w-0",children:U.label}),U.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:U.shortcut}):null]},U.id)})}),_.sourceDocument.body),D&&Br.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:()=>he(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:U=>U.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. ",se?"⌘+1":"Ctrl+1",", ",se?"⌥+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"})]})}),qe.body)]})}const Zu="adhdev-recent-launch-args-v1",wv=8;function jv(e){return String(e||"").trim().replace(/\s+/g," ")}function em(e,t){return`${e.trim()}::${t.trim()}`}function tm(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Zu)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function kv(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Zu,JSON.stringify(e))}catch{}}function Sv(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=tm().byKey[em(r,n)])==null?void 0:o.items)||[]}function Nv(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=jv(r);if(!n||!a||!o)return;const i=tm(),c=em(n,a),d=((u=i.byKey[c])==null?void 0:u.items)||[],m=[o,...d.filter(h=>h!==o)].slice(0,wv);i.byKey[c]={items:m},kv(i)}function Cv(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Rn({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 Iv({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 Mv({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:i,onOpenHistory:c,onClearSelection:d}){const m=o?Ou(o):null,u=Iv({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Rn,{title:"Saved history",description:oi(),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:sg()})]}),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:d,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:u}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function sm({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 Av({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 Va(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>er(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>er(a,"acp"))?"acp":null}function gn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Tv({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Fe,Et;const u=Yr(),h=l.useMemo(()=>[...e].sort(Jo),[e]),[p,y]=l.useState(((Fe=h[0])==null?void 0:Fe.id)||""),g=l.useMemo(()=>h.find(Q=>Q.id===p)||h[0],[p,h]),x=l.useMemo(()=>((g==null?void 0:g.workspaces)||[]).map(Q=>({id:Q.id,path:Q.path,label:Q.label})),[g]),k=(g==null?void 0:g.defaultWorkspaceId)||null,[S,f]=l.useState("workspace"),[v,j]=l.useState(""),[w,b]=l.useState(""),[C,N]=l.useState([]),[I,B]=l.useState(""),[P,T]=l.useState(!1),[M,A]=l.useState(null),[W,_]=l.useState(""),[R,O]=l.useState(Va(h[0])),[L,E]=l.useState(""),[$,F]=l.useState(""),[X,ee]=l.useState([]),[ne,Z]=l.useState(""),[ge,Ne]=l.useState([]),[V,ve]=l.useState(!1),[xe,ye]=l.useState(!1),[ue,Ae]=l.useState(""),[q,be]=l.useState(!1),[ce,K]=l.useState(()=>Pt()),[ae,de]=l.useState(null),[le,se]=l.useState(!1),[J,D]=l.useState(""),[he,ke]=l.useState(null),[Se,re]=l.useState(!1),[De,He]=l.useState(""),[Be,Ce]=l.useState([]),[rt,st]=l.useState(!1),[Ze,et]=l.useState(""),[it,gt]=l.useState(!1),Tt=l.useRef(null),Le=l.useRef(0);l.useEffect(()=>{var Q;!p&&((Q=h[0])!=null&&Q.id)&&y(h[0].id)},[p,h]),l.useEffect(()=>{!g||!(!g.workspaces||!g.availableProviders||!g.detectedIdes||!g.recentLaunches)||u(g.id,{minFreshMs:3e4}).catch(()=>{})},[u,g]);const qe=l.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(Q=>er(Q,"cli")),[g]),lt=l.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(Q=>er(Q,"acp")),[g]),Ye=l.useMemo(()=>((g==null?void 0:g.detectedIdes)||[]).map(Q=>({id:Q.type,label:Q.name||Q.type,meta:Q.running?"Detected locally":"Available to open"})),[g]),kt=l.useMemo(()=>R==="cli"?qe.map(Q=>({id:Q.type,label:Q.displayName||Q.type,meta:"CLI provider"})):R==="acp"?lt.map(Q=>({id:Q.type,label:Q.displayName||Q.type,meta:"ACP provider"})):Ye,[lt,R,qe,Ye]),U=l.useMemo(()=>C.find(Q=>Q.id===I)||null,[C,I]),z=l.useMemo(()=>qe.find(Q=>Q.type===L)||null,[qe,L]),Y=l.useMemo(()=>Pu(z==null?void 0:z.meshCoordinator,{meshId:(U==null?void 0:U.id)||"",workspace:(U==null?void 0:U.workspace)||""}),[z,U]),oe=he||Y,me=l.useCallback(async Q=>{T(!0),_("");try{const $e=await c(Q);N($e),B(te=>{var Ee;return $e.some(Ct=>Ct.id===te)?te:((Ee=$e[0])==null?void 0:Ee.id)||""}),A(Q)}catch($e){N([]),B(""),A(Q),_($e instanceof Error?$e.message:"Could not load meshes")}finally{T(!1)}},[c]);l.useEffect(()=>{var $e;if(!g)return;if(Tt.current!==g.id){Tt.current=g.id,f("workspace"),j(k||(($e=x[0])==null?void 0:$e.id)||"__home__"),b(""),N([]),B(""),A(null),_(""),O(Va(g)),E(""),F(""),Z(""),Ne([]),ye(!1),Ae(""),K(Pt()),D(""),ke(null);return}j(te=>{var Ee;return te==="__custom__"||te==="__home__"||x.some(Ct=>Ct.id===te)?te:k||((Ee=x[0])==null?void 0:Ee.id)||"__home__"}),O(te=>te==="ide"&&Ye.length>0||te==="cli"&&qe.length>0||te==="acp"&<.length>0?te:Va(g))},[lt.length,qe.length,k,Ye.length,g,x]),l.useEffect(()=>{!g||S!=="mesh"||M===g.id||P||me(g.id)},[me,M,P,g,S]),l.useEffect(()=>{S==="mesh"&&R!=="cli"&&qe.length>0&&O("cli")},[R,qe.length,S]),l.useEffect(()=>{var Q;R&&(kt.some($e=>$e.id===L)||E(((Q=kt[0])==null?void 0:Q.id)||""))},[R,kt,L]),l.useEffect(()=>{ke(null)},[g==null?void 0:g.id,I,L,S]);const fe=l.useCallback(async(Q,$e)=>{const te=Le.current+1;return Le.current=te,ve(!0),Ae(""),m(Q,$e).then(Ee=>{Le.current===te&&Ne(Ee)}).catch(Ee=>{Le.current===te&&(Ne([]),Ae(Ee instanceof Error?Ee.message:"Could not load saved sessions"))}).finally(()=>{Le.current===te&&(ve(!1),ye(!0))})},[m]),H=l.useCallback((Q,$e)=>{ee(Sv(Q,$e))},[]);l.useEffect(()=>{Le.current+=1,Z(""),K(Pt()),!g||!L||R==="ide"?ee([]):H(g.id,L),ye(!1),Ne([]),Ae(""),ve(!1)},[R,H,fe,g,L]),l.useEffect(()=>{if(!ne)return;const Q=ge.find($e=>$e.providerSessionId===ne);Q!=null&&Q.canResume||Z("")},[ge,ne]);const G=v==="__custom__"?w.trim():v==="__home__"?"":((Et=x.find(Q=>Q.id===v))==null?void 0:Et.path)||"",ie=l.useMemo(()=>g?t.filter(Q=>Q.id!==g.id&&Q.daemonId===g.id).map(Q=>Q.workspace):[],[t,g]),we=l.useMemo(()=>((g==null?void 0:g.recentLaunches)||[]).map(Q=>Q.workspace),[g]),Pe=l.useCallback(Q=>{const $e=String(Q.workspace||"").trim();if(!$e)return;const te=x.find(Ee=>gn(Ee.path)===gn($e));if(te){j(te.id),b("");return}j("__custom__"),b($e)},[x]),Ie=l.useCallback(Q=>{const $e=String(Q.workspace||"").trim();if(!$e)return{workspaceId:null,workspacePath:null};const te=x.find(Ee=>gn(Ee.path)===gn($e));return te?{workspaceId:te.id,workspacePath:null}:{workspaceId:null,workspacePath:$e}},[x]),Te=l.useMemo(()=>ge.find(Q=>Q.providerSessionId===ne)||null,[ge,ne]),Oe=l.useMemo(()=>{var $e;if(R!=="cli"||!g||!L)return null;const Q=(($e=qe.find(te=>te.type===L))==null?void 0:$e.displayName)||L;return{routeId:g.id,daemonId:g.id,providerSessionId:ne||void 0,transport:"pty",mode:"chat",agentName:Q,agentType:L,status:"idle",title:Q,messages:[],ideType:L,workspaceName:G,workspacePath:G,displayPrimary:Q,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${g.id}:${L}`,machineName:$t(g,{fallbackId:g.id})}},[R,qe,G,g,ne,L]),_e=l.useCallback(()=>{var $e;if(!g)return;j("__custom__"),re(!0),et("");const Q=fi(g.platform,pi(w.trim(),G,ie,we,g.defaultWorkspacePath,($e=x.find(te=>te.id===k))==null?void 0:$e.path,x.map(te=>te.path)));st(!0),n(g.id,Q).then(te=>{He(te.path),b(te.path),Ce(te.directories)}).catch(te=>{et(te instanceof Error?te.message:"Could not load folder")}).finally(()=>st(!1))},[w,k,we,ie,n,G,g,x]),ze=l.useCallback(Q=>{g&&(st(!0),et(""),n(g.id,Q).then($e=>{He($e.path),b($e.path),Ce($e.directories)}).catch($e=>{et($e instanceof Error?$e.message:"Could not load folder")}).finally(()=>st(!1)))},[n,g]),Qe=l.useCallback(async()=>{if(!g||!G)return;gt(!0),D("");const Q=await a(g.id,G);if(gt(!1),!Q.ok){D(Q.error||"Could not save workspace");return}D("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,G,g]),pt=l.useCallback(async()=>{if(!g)return;if(S==="mesh"){if(!I||!L)return;se(!0),D(""),ke(null);const te=await d(g.id,I,L);if(se(!1),!te.ok){if(te.code==="mesh_coordinator_manual_mcp_setup_required"&&te.manualSetup){ke(te.manualSetup),D("Manual MCP setup required before this provider can act as mesh coordinator.");return}D(te.error||"Could not start mesh coordinator");return}r();return}if(!R||!L)return;se(!0),D("");const Q=$.trim()?$.trim().split(/\s+/).filter(Boolean):[],$e=R==="ide"?await o(g.id,L,{workspacePath:G||null}):await i(g.id,R,L,{workspaceId:v!=="__home__"&&v!=="__custom__"?v:null,workspacePath:v==="__custom__"&&G||null,resumeSessionId:R==="cli"&&ne?ne:null,cliArgs:Q});if(se(!1),!$e.ok){D($e.error||"Could not start session");return}R!=="ide"&&$.trim()&&(Nv(g.id,L,$),H(g.id,L)),r()},[R,$,H,r,o,d,i,G,g,I,ne,L,v,S]),jt=S==="mesh"?"Start mesh coordinator":R?Zb(R,R==="cli"&&!!ne):"Start",yt=S==="mesh"?"Starting coordinator…":R?eg(R,R==="cli"&&!!ne):"Starting…",vt=h.length>5;return g?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(Nt,{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(Rn,{title:"Machine",children:vt?s.jsx("select",{"aria-label":"Machine",value:g.id,onChange:Q=>y(Q.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:le,children:h.map(Q=>s.jsx("option",{value:Q.id,children:$t(Q,{fallbackId:Q.id})},Q.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:h.map(Q=>{const $e=$t(Q,{fallbackId:Q.id}),te=g.id===Q.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${$e}`,"aria-pressed":te,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${te?"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(Q.id),disabled:le,title:$e,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${Q.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:$e})]},Q.id)})})}),s.jsxs(Rn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:S==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:_e,disabled:le,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(Q=>s.jsxs("button",{type:"button",role:"radio","aria-checked":S===Q.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${S===Q.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(Q.id),D(""),Q.id==="mesh"&&g&&M!==g.id&&!P&&me(g.id)},disabled:le,children:[s.jsx("div",{className:"text-sm font-semibold",children:Q.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:Q.desc})]},Q.id))}),S==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:v,onChange:Q=>{const $e=Q.target.value;j($e),$e==="__custom__"?_e():D("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:le,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),x.map(Q=>s.jsxs("option",{value:Q.id,children:[Q.id===k?"⭐ ":"",bd(Q.path,Q.label)||Q.path]},Q.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v==="__home__"?"Launch without a workspace.":G||"Select a workspace folder."}),v==="__custom__"&&G&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:_e,disabled:le,children:[s.jsx(Xs,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Qe,disabled:le||it,children:it?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[P&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!P&&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}),!P&&!W&&C.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."}),C.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:C.map(Q=>s.jsxs("button",{type:"button",role:"radio","aria-checked":I===Q.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${I===Q.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>B(Q.id),disabled:le,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Q.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[Q.repoIdentity||"Repo mesh",typeof Q.nodesCount=="number"?` · ${Q.nodesCount} node${Q.nodesCount===1?"":"s"}`:""]}),Q.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",Q.workspace]})]},Q.id))}),U&&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(Av,{workspaceMode:S,activeKind:R,cliEnabled:qe.length>0,ideEnabled:Ye.length>0,acpEnabled:lt.length>0,busy:le,onSelect:O}),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:R==="ide"?"Choose IDE":R==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[kt.map(Q=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${L===Q.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>E(Q.id),disabled:le,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Q.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Q.meta})]},Q.id)),kt.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."})]})]}),S==="mesh"&&oe&&s.jsx(sm,{setup:oe,providerName:(z==null?void 0:z.displayName)||(z==null?void 0:z.name)||L}),S!=="mesh"&&R!=="ide"&&s.jsxs(Rn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:$,onChange:Q=>F(Q.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:le}),X.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:X.map(Q=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>F(Q),disabled:le,title:Q,children:Q},Q))})]}),S!=="mesh"&&R==="cli"&&s.jsx(Mv,{busy:le,savedSessionsLoading:V,savedSessionsError:ue,selectedSession:Te,onRefresh:()=>{!g||!L||fe(g.id,L)},onOpenHistory:()=>{!g||!L||(be(!0),Cv({hasLoadedInitialResults:xe,isLoading:V})&&fe(g.id,L))},onClearSelection:()=>Z("")}),J&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${J.includes("saved")||J.includes("requested")||J.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:J})]}),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:le,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:pt,disabled:le||(S==="mesh"?!I||!L||R!=="cli"||P:!R||!L||v==="__custom__"&&!G),children:[s.jsx(td,{size:14}),le?yt:jt]})]})]})}),Se&&s.jsx(gi,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:De,directories:Be,busy:rt,error:Ze,onClose:()=>re(!1),onNavigate:ze,onConfirm:Q=>{b(Q),He(Q),j("__custom__"),re(!1)}}),q&&Oe&&s.jsx(tu,{activeConv:Oe,ides:[],isCreatingChat:!1,isRefreshingHistory:V,savedSessions:ge,isSavedSessionsLoading:V,isResumingSavedSessionId:ae,savedHistoryFilters:ce,missingWorkspaceResumePath:G||null,onSavedHistoryFiltersChange:K,onClose:()=>be(!1),onNewChat:()=>{Z(""),be(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!g||!L||fe(g.id,L)},onResumeSavedSession:Q=>{if(!g||!L||ae||!Q.canResume)return;const $e=Ie(Q);Z(Q.providerSessionId),Pe(Q),de(Q.providerSessionId),be(!1),se(!0),D(""),i(g.id,"cli",L,{workspaceId:$e.workspaceId,workspacePath:$e.workspacePath,resumeSessionId:Q.providerSessionId}).then(te=>{if(!te.ok){D(te.error||"Could not resume session");return}r()}).finally(()=>{se(!1),de(te=>te===Q.providerSessionId?null:te)})}})]}):null}function rm(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 vi(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=rm(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 wi(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function nm(e){var t;return!wi(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 yn(e){return[...new Set(e.filter(t=>!!t))]}function _v(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?yn([t==null?void 0:t.id,...n.map(i=>i.id)]):a.length>0?yn(a.map(i=>i.id)):o.length>0?yn(o.map(i=>i.id)):yn(e.nodes.map(i=>i.id))}function am(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 Lv(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${am(e)}::${n}x${a}`}const Pv={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"},Rv={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"},Dv={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"},$v={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 or(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 flex flex-col 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=>Rv[t],actionButton:t=>$v[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 flex flex-col 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=>Pv[t],actionButton:t=>Dv[t]}}const tr={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,layerGap:220,nodeGap:82,edgeLabelBuffer:180,placeholderTopOffset:0},en={worktreeCardWidth:188,submoduleCardWidth:188,minWorktreeCardHeight:88,minSubmoduleCardHeight:88,maxEstimatedCardHeight:178,layerGap:160,nodeGap:52,edgeLabelBuffer:120},Ev={maxWidth:180};function Bv(e){return e==="TB"?"DOWN":"RIGHT"}function ji(e,t){return{"elk.algorithm":"layered","elk.direction":Bv(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 Ov=ji(tr,"LR");ji(en,"LR");function Fv(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 Hv=new uh;function Kr(e,t=!1){const r=t?en:tr;return e.type==="submoduleNode"?r.submoduleCardWidth:r.worktreeCardWidth}function Dn(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=rm(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 om(e,t=!1){const r=t?en:tr,n=Kr(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(Wv(e)/o),c=vn(e.label,a,2),d=vn(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,a,2),m=vn(Dn(e),a+(t?1:4),t?2:3),u=vi(e),h=nm(e)?wi(e):null,p=t?0:vn(h,Math.max(24,Math.floor(n/8)),4),y=t?40+c*16+d*12+(u?22:0)+Math.max(0,i-1)*18+Math.max(18,m*16):52+c*18+d*14+(u?30:0)+i*24+Math.max(22,m*18)+(p>0?22+p*16:0),g=e.type==="submoduleNode"?r.minSubmoduleCardHeight:r.minWorktreeCardHeight;return Math.min(r.maxEstimatedCardHeight,Math.max(g,Math.ceil(y)))}function vn(e,t,r){const n=(e||"").trim();return n?Math.max(1,Math.min(r,Math.ceil(n.length/t))):0}function Wv(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 Kv(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 Uv(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function zv(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 Gv(e,t,r){return{id:e.id,x:t,y:r,width:Kr(e),height:om(e)}}function Vv(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 im(e){const t=[...e.nodes].sort(Kv),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,Vv(r,e)]}function qv(e,t=Ov,r=!1,n="LR"){const a=im(e),o=new Set(a.map(d=>d.id)),i=a.map(d=>({id:d.id,width:Kr(d,r),height:om(d,r)})),c=e.edges.filter(d=>o.has(d.source)&&o.has(d.target)).sort(Uv).map(d=>({id:d.id,sources:[d.source],targets:[d.target]}));return{id:`${e.meshId||"mesh"}__elk_root`,layoutOptions:{...t},children:i,edges:c}}function Yv(e,t=!1){const r=[...new Set(e.map(a=>Math.round(a.x)))].sort((a,o)=>a-o),n=t?en.layerGap:tr.layerGap;return r.length<2?n:Math.min(...r.slice(1).map((a,o)=>a-r[o]))}async function Xv(e,t=!1,r="LR"){var p,y;const a=ji(t?en:tr,r),o=im(e),i=new Map(o.map(g=>[g.id,g])),c=await Hv.layout(qv(e,a,t,r)),d=(c.children??[]).map(g=>{const x=i.get(g.id);return x?zv(x,Math.round(g.x??0),Math.round(g.y??tr.placeholderTopOffset),!g.id.endsWith("__placeholder")):null}).filter(Boolean),m=new Map(o.map((g,x)=>[g.id,x]));d.sort((g,x)=>(m.get(g.id)??0)-(m.get(x.id)??0));const u=d.map(g=>Gv(g.graphNode,g.position.x,g.position.y)),h=new Map;for(const g of c.edges??[]){const x=g.sections;if(!x||x.length===0)continue;const k=x[0],S=(p=g.sources)==null?void 0:p[0],f=(y=g.targets)==null?void 0:y[0];if(!S||!f)continue;const v=[];v.push({x:Math.round(k.startPoint.x),y:Math.round(k.startPoint.y)});for(const j of k.bendPoints??[])v.push({x:Math.round(j.x),y:Math.round(j.y)});v.push({x:Math.round(k.endPoint.x),y:Math.round(k.endPoint.y)}),h.set(g.id,{id:g.id,source:S,target:f,points:v})}return{nodes:d,bounds:u,edgeRoutes:h,columnGap:Yv(u,t),layoutOptions:{...a}}}function Jv(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 lm(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function Qv(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(Jv),...e.edges.map(lm)].join("::")}function Zv(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(lm)].join("::")}const ew=7,ki=l.createContext(or("dark")),cm=l.createContext(!1),dm=l.createContext("LR"),um={overflowWrap:"anywhere",wordBreak:"break-word"},tw={...um,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},sw={...um,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function mm(e){return e.activeSessionCount>0}function rw(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function ac(e,t,r){const n=mm(e),a=rw(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=vi(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 Bt(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 oc(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 ic(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 nw(e){return e.replace(/_/g," ")}function ns(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 qa(e,t){const r=ns(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":Bt("health",t)}function aw(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function lc(e){const t=aw(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 Ya(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function vr(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function ow(e){if(e.sessionDetails.length===0)return null;const t=e.sessionDetails.filter(o=>ns(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 cc(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function iw(e){return e.locality==="remote"?"meta":"health"}function lw({data:e,selected:t}){const r=l.useContext(ki),n=l.useContext(cm),a=l.useContext(dm),o=e.graphNode,i=o.type==="defaultBranchNode",c=o.type==="submoduleNode",d=nm(o),m=i?"default branch anchor":c?o.submodulePath||"submodule checkout":[o.machineLabel,cc(o.locality)].filter(Boolean).join(" · ")||o.workspace,u=o.submoduleCommit?o.submoduleCommit.slice(0,7):null,h=vi(o),p=wi(o),y=mm(o),g=o.sessionDetails,x=o.sessionDetails,k=ow(o),S=o.sessionDetails.map(j=>{const w=ns(j),b=j.providerType||"provider unknown",C=vr(j),N=j.startedAt||j.createdAt||null,I=j.statusNote?` · ${j.statusNote}`:"";return`Session: ${j.sessionId} · ${b} · ${w} · ${C} · ${lc(N)}${I}`});if(n)return s.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${ac(o,t,r.isDark)}`,style:{width:Kr(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,Dn(o),...S].filter(Boolean).join(`
|
|
68
68
|
`),children:[s.jsx(sn,{type:"target",position:a==="TB"?us.Top:us.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:ic(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] ${oc(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] ${Bt("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:S.join(`
|
|
69
69
|
`),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(j=>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: ${j.sessionId}`,j.providerType?`Provider: ${j.providerType}`:null,`Status: ${ns(j)}`,`Role: ${vr(j)}`].filter(Boolean).join(`
|
|
70
70
|
`),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:j.providerType||"provider unknown"}),s.jsx("span",{className:`shrink-0 rounded-full border px-1 py-0 text-[8px] font-semibold uppercase tracking-[0.1em] ${qa(j,r.isDark)}`,children:ns(j)})]}),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:Ya(j.sessionId)}),s.jsx("span",{className:"shrink-0",children:vr(j)})]})]},j.sessionId))}),s.jsx(sn,{type:"source",position:a==="TB"?us.Bottom:us.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]});const f=t,v=[o.label,m,h?`Status: ${h.label}`:null,Dn(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,d&&p?`Note: ${p}`:null,...S].filter(Boolean).join(`
|
|
71
71
|
`);return s.jsxs("div",{className:`group rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all ${ac(o,t,r.isDark)}`,style:{width:Kr(o)},title:v,children:[s.jsx(sn,{type:"target",position:a==="TB"?us.Top:us.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:ic(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] ${oc(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] ${Bt("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:S.join(`
|
|
72
72
|
`),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(j=>{const w=vr(j);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: ${j.sessionId}`,j.providerType?`Provider: ${j.providerType}`:null,`Status: ${ns(j)}`,`Role: ${w}`].filter(Boolean).join(`
|
|
73
73
|
`),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:j.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] ${qa(j,r.isDark)}`,children:ns(j)})]}),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:Ya(j.sessionId)}),s.jsx("span",{children:w})]})]},j.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 ${Bt("health",r.isDark)}`,children:nw(o.health)}),c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Bt("submodule",r.isDark)}`,children:"submodule"}),!i&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Bt(iw(o),r.isDark)}`,children:cc(o.locality)}),u&&c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Bt("meta",r.isDark)}`,children:u}),o.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Bt("dirty",r.isDark)}`,children:c?"local changes":`${o.dirtyFiles} dirty`}),o.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Bt("conflict",r.isDark)}`,children:"out of sync"}),o.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Bt("conflict",r.isDark)}`,children:"conflicts"}),!c&&o.upstream&&o.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Bt("orphan",r.isDark)}`,children:"upstream unverified"}),o.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Bt("orphan",r.isDark)}`,children:"needs follow-up"})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,style:tw,children:Dn(o)}),g.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:g.map(j=>{const w=j.startedAt||j.createdAt||null,b=vr(j);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: ${j.sessionId}`,j.providerType?`Provider: ${j.providerType}`:null,`Status: ${ns(j)}`,`Role: ${b}`,w?`Started: ${w}`:"Started: not reported",j.statusNote?`Note: ${j.statusNote}`:null].filter(Boolean).join(`
|
|
74
|
-
`),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:Ya(j.sessionId)}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${qa(j,r.isDark)}`,children:ns(j)})]}),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:j.providerType||"provider unknown"}),s.jsx("span",{children:b}),s.jsx("span",{children:lc(w)})]}),j.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${r.textMuted}`,children:j.statusNote})]},j.sessionId)})})]}),d&&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:sw,children:p})]}),s.jsx(sn,{type:"source",position:a==="TB"?us.Bottom:us.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const cw={meshNode:lw},dw=8;function uw(e){if(e.length<2)return null;if(e.length===2){const[m,u]=e;return{d:`M ${m.x},${m.y} L ${u.x},${u.y}`,labelX:(m.x+u.x)/2,labelY:(m.y+u.y)/2}}const t=dw,r=[`M ${e[0].x},${e[0].y}`];for(let m=1;m<e.length-1;m+=1){const u=e[m-1],h=e[m],p=e[m+1],y=Math.sign(h.x-u.x),g=Math.sign(h.y-u.y),x=Math.sign(p.x-h.x),k=Math.sign(p.y-h.y),S=Math.hypot(h.x-u.x,h.y-u.y),f=Math.hypot(p.x-h.x,p.y-h.y),v=Math.min(t,S/2,f/2);if(v<1||y===x&&g===k){r.push(`L ${h.x},${h.y}`);continue}const j=h.x-y*v,w=h.y-g*v,b=h.x+x*v,C=h.y+k*v;r.push(`L ${j},${w}`),r.push(`Q ${h.x},${h.y} ${b},${C}`)}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,d=e[0].y;for(let m=1;m<e.length;m+=1)if(o[m]>=i){const u=o[m]-o[m-1],h=u===0?0:(i-o[m-1])/u;c=e[m-1].x+(e[m].x-e[m-1].x)*h,d=e[m-1].y+(e[m].y-e[m-1].y)*h;break}return{d:r.join(" "),labelX:c,labelY:d}}function mw(e){const t=e.data.routePoints;if(t&&t.length>=2){const o=uw(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=Sh(r):n.type==="worktreeLink"||n.type==="submoduleLink"||n.type==="cloneLink"?a=jh(r):a=kh(r),[a[0],a[1],a[2]]}function hw(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 pw(e){const t=l.useContext(ki),r=e.data.graphEdge,[n,a,o]=mw(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(gh,{id:e.id,path:n,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(yh,{children:s.jsx("div",{className:hw(r,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${a}px, ${o}px)`,pointerEvents:"none",maxWidth:Ev.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const fw={meshEdge:pw};async function xw(e,t=or("dark"),r=!1,n="LR"){const a=await Xv(e,r,n),o=new Set(a.nodes.map(u=>u.id)),i=a.nodes.map(u=>({id:u.id,type:u.type,position:u.position,data:{graphNode:u.graphNode,compact:r},selected:u.selected,draggable:u.draggable,selectable:u.selectable})),c=e.edges.filter(u=>o.has(u.source)&&o.has(u.target)),d=yw(c),m=c.map(u=>{var h;return{id:u.id,source:u.source,target:u.target,label:d.has(u.id)?u.label:void 0,type:"meshEdge",data:{graphEdge:u,routePoints:(h=a.edgeRoutes.get(u.id))==null?void 0:h.points},animated:u.type==="orphanLink",markerEnd:u.direction==="directed"?{type:bh.ArrowClosed,width:u.type==="submoduleLink"?16:18,height:u.type==="submoduleLink"?16:18,color:uc(u)}:void 0,style:{stroke:uc(u),strokeWidth:u.type==="orphanLink"?2.25:u.type==="submoduleLink"?1.7:u.type==="worktreeLink"?1.8:u.type==="cloneLink"?1.6:2,strokeDasharray:u.type==="orphanLink"?"5 4":u.type==="submoduleLink"?"4 3":u.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 bw=3,gw=2;function dc(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 yw(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<bw){for(const o of n)t.add(o.id);continue}const a=[...n].sort((o,i)=>{const c=dc(i)-dc(o);return c!==0?c:o.id.localeCompare(i.id)});for(const o of a.slice(0,gw))t.add(o.id)}return t}function uc(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 vw(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 ww(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 jw({data:e,viewportKey:t}){const r=vh(),n=wh(),a=l.useRef(null),o=l.useMemo(()=>am(e),[e]),i=l.useMemo(()=>_v(e),[e]);return l.useEffect(()=>{if(!r||e.nodes.length===0||a.current===t)return;let c=!1;const d=requestAnimationFrame(()=>{if(c)return;const m=i.length>0&&i.length<e.nodes.length;n.fitView({nodes:m?i.map(u=>({id:u})):void 0,padding:m?.24:.2,maxZoom:m?.98:.9,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(d)}},[e.nodes.length,i,o,r,n,t]),null}function kw(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 Sw=12;function Nw({data:e,selectedNodeId:t=null,onNodeClick:r,onNodeHoverChange:n,onEdgeHoverChange:a}){const{theme:o}=ar(),i=l.useMemo(()=>or(o),[o]),c=l.useMemo(()=>Qv(e),[e]),d=l.useMemo(()=>Zv(e),[e]),m=e.nodes.length>=ew,[u,h]=l.useState("LR"),p=l.useMemo(()=>u==="auto"?Fv(e):u,[u,c,e]),y=e.nodes.length>=Sw,[g,x]=l.useState({nodes:[],edges:[]}),k=l.useRef(null),[S,f]=l.useState({width:0,height:0}),v=l.useMemo(()=>`${Lv(e,S.width,S.height)}::${p}`,[c,e,S.height,S.width,p]);l.useEffect(()=>{let C=!1;return xw(e,i,m,p).then(N=>{C||x(N)}),()=>{C=!0}},[e,d,i,m,p]);const j=l.useMemo(()=>g.nodes.map(C=>({...C,selected:C.id===t})),[g.nodes,t]);l.useEffect(()=>{const C=k.current;if(!C)return;const N=()=>{const B=Math.max(0,Math.round(C.clientWidth)),P=Math.max(0,Math.round(C.clientHeight));f(T=>T.width===B&&T.height===P?T:{width:B,height:P})};N();const I=typeof ResizeObserver=="function"?new ResizeObserver(()=>N()):null;return I==null||I.observe(C),window.addEventListener("resize",N),()=>{I==null||I.disconnect(),window.removeEventListener("resize",N)}},[]);const w=kw(e.nodes.length),b=C=>C?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(ki.Provider,{value:i,children:s.jsx(cm.Provider,{value:m,children:s.jsx(dm.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:b(u==="auto"),title:`Auto (currently ${p==="TB"?"top-bottom":"left-right"})`,children:"Auto"}),s.jsx("button",{type:"button",onClick:()=>h("LR"),className:b(u==="LR"),title:"Left to right",children:"LR"}),s.jsx("button",{type:"button",onClick:()=>h("TB"),className:b(u==="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 ${w}`,children:s.jsxs(mh,{nodes:j,edges:g.edges,nodeTypes:cw,edgeTypes:fw,minZoom:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(C,N)=>r==null?void 0:r(N.data.graphNode),onNodeMouseEnter:(C,N)=>n==null?void 0:n(N.data.graphNode),onNodeMouseLeave:()=>n==null?void 0:n(null),onEdgeMouseEnter:(C,N)=>{var I;return a==null?void 0:a(((I=N.data)==null?void 0:I.graphEdge)??null)},onEdgeMouseLeave:()=>a==null?void 0:a(null),className:"h-full w-full",colorMode:i.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(jw,{data:e,viewportKey:v}),s.jsx(hh,{className:i.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),y&&s.jsx(ph,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:vw,nodeClassName:ww,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(fh,{variant:xh.Dots,gap:18,size:1.2,color:i.graphBackgroundDotColor})]})})]})})})})}function ut(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 Dt(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function Rt(...e){for(const t of e)if(typeof t=="boolean")return t}function Xa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function Si(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 Cw(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 Iw(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=ut(n),o=je(a.path),i=je(a.commit),c=je(a.repoPath,a.repo_root)??Cw(t,o);return!o||!i||!c?null:{path:o,commit:i,repoPath:c,dirty:Rt(a.dirty)??!1,outOfSync:Rt(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:Dt(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 Mw(e){return Rt(e.isGitRepo)!==void 0||!!je(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||Dt(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 $n(e,t,r){const n=Rt(e.isGitRepo);if(!Object.keys(e).length||!Mw(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(v=>typeof v=="string"):[],i=Dt(e.conflicts)??o.length,c=Rt(e.hasConflicts)??i>0,d=je(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,m=Iw(e.submodules,d),u=je(e.upstreamStatus,e.upstream_status),h=Dt(e.upstreamFetchedAt,e.upstream_fetched_at),p=je(e.upstreamFetchError,e.upstream_fetch_error),y=je(e.error),g=Dt(e.staged)??0,x=Dt(e.modified)??0,k=Dt(e.untracked)??0,S=Dt(e.deleted)??0,f=Dt(e.renamed)??0;return{workspace:je(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:a,branch:je(e.branch)??null,headCommit:je(e.headCommit)??null,headMessage:je(e.headMessage)??null,upstream:je(e.upstream)??null,upstreamStatus:u??"unchecked",...h!==void 0?{upstreamFetchedAt:h}:{},...p?{upstreamFetchError:p}:{},ahead:Dt(e.ahead)??0,behind:Dt(e.behind)??0,staged:g,modified:x,untracked:k,deleted:S,renamed:f,dirty:Rt(e.dirty,e.isDirty,e.is_dirty)??(g+x+k+S+f>0||c),hasConflicts:c,conflictFiles:o,stashCount:Dt(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??Dt(e.lastCheckedAt,e.last_checked_at)??Date.now(),...m?{submodules:m}:{},...y?{error:y}:{}}}function Aw(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+=Si(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 Tw(e){const t=ut(e.lastGit??e.last_git),r=ut(t.result),n=ut(t.status),a=ut(r.status),o=ut(e.lastProbe??e.last_probe),i=ut(o.git),c=ut(i.result),d=ut(i.status),m=ut(c.status);let u=null;for(const h of[n,a,d,m]){const p=$n(h,e,{lastCheckedAt:Date.now()});if(!p)continue;const y=Aw(p);(!u||y>u.score)&&(u={git:p,score:y})}return u==null?void 0:u.git}function _w(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 Lw(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 sa(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=_w(e);return t.outOfSync?"degraded":t.dirty||Lw(e)?"dirty":"online"}function Pw(e,t){const r=t?sa(t):void 0;return!e||e==="unknown"?r:e}function hm(e){const t=ut(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)}:{},...Rt(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:Rt(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)}:{},...Rt(t.isCached,t.is_cached)!==void 0?{isCached:Rt(t.isCached,t.is_cached)}:{}}:null}function Rw(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(hm).filter(o=>o!==null);if(a.length>0)return a}const r=ut(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 Dw(e){const t=ut(e.connection);return Object.keys(t).length>0?t:void 0}function $w(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 Ni(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 mc(e){var n,a,o,i,c,d;let t=0;const r=e.git;return Ni(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+=Si(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),((d=e.connection)==null?void 0:d.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 Ew(e,t){var g,x,k,S;const r=mc(e),a=mc(t)>r?t:e,o=a===t?e:t,i=a.git??o.git,c=(((g=a.providers)==null?void 0:g.length)??0)>0?a.providers:o.providers,d=(((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,u=(((S=a.providerPriority)==null?void 0:S.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")?sa(i):a.health,providers:c??[],activeSessions:d??[],...m&&m.length>0?{activeSessionDetails:m}:{},...u&&u.length>0?{providerPriority:u}:{},...h?{connection:h}:{},...i?{git:i}:{}},y=ut(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 pm(e){const t=ut(e),r=je(t.nodeId,t.id);if(!r)return null;const n=ut(t.cachedStatus),a=Tw(t),o=a?void 0:$n(ut(t.git),t)??$n(t,t),i=a??o,c=i?void 0:$n(ut(n.git),t),d=i??c,m=je(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),u=je(t.health),h=a?sa(d):Pw(u,i)||(d?sa(d):void 0)||je(n.health)||m||je(t.status)||"unknown",y=(a?void 0:je(t.error))??(i?void 0:je(n.error)),g=Rw(t),x=Xa(t.activeSessions),k=(g==null?void 0:g.map(N=>N.sessionId))??[],S=Xa(t.providerPriority),f=Rt(t.gitProbePending,t.git_probe_pending),v=i?void 0:f,j=Dw(t),w=ut(t.branchConvergence??t.branch_convergence),b=j==null?void 0:j.state,C=a&&(!(j!=null&&j.reported)||b==="unknown")?$w(j):j;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,d==null?void 0:d.workspace)||"",...je(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:je(t.repoRoot,t.repo_root,d==null?void 0:d.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}:{},...Rt(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Rt(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,...d?{git:d}:{},...v!==void 0?{gitProbePending:v}:{},providers:Xa(t.providers),activeSessions:x.length>0?x:k,...g&&g.length>0?{activeSessionDetails:g}:{},...S.length>0?{providerPriority:S}:{},...Rt(t.launchReady)!==void 0?{launchReady:Rt(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)}:{},...C?{connection:C}:{},...Object.keys(w).length>0?{branchConvergence:w}:{},...y?{error:y}:{}}}function hc(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 fm(e,t){const r=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],n=r.map(hm).filter(a=>a!==null);return n.length===0?t:t.map(a=>{const o=n.filter(c=>{const d=ut(r.find(p=>{const y=ut(p);return je(y.sessionId,y.session_id,y.id)===c.sessionId})),m=je(d.nodeId,d.node_id),u=je(d.daemonId,d.daemon_id),h=je(d.workspace);return m&&m===a.nodeId?!0:u&&a.daemonId&&u===a.daemonId?!h||!a.workspace||h===a.workspace:!!(h&&a.workspace&&h===a.workspace)});if(o.length===0)return a;const i=hc([...a.activeSessionDetails??[],...o]);return{...a,activeSessionDetails:i,activeSessions:hc([...a.activeSessionDetails??[],...o,...(a.activeSessions??[]).map(c=>({sessionId:c}))]).map(c=>c.sessionId)}})}function Bw(e){const t=ut(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||Rt(t.is_local_worktree)!==void 0}function xm(e){const t=new Map,r=[];for(const n of e){const a=Bw(n)?pm(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=Ew(o,a);t.set(a.nodeId,i);const c=r.findIndex(d=>d.nodeId===a.nodeId);c>=0&&(r[c]=i)}return r}function bm(e){const t=xm(e.nodes??[]);return{...e,nodes:fm(e,t)}}function Ow(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:Ni(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 Fw(e){const t=je(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(d=>pm(d)).filter(d=>d!==null):null;if(!t||!n)return null;const a=fm(e,xm(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 Hw(e){var o;let t=0;const r=ut(e.sourceOfTruth),n=ut(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+=Si(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 pc(e){let t=null;for(const r of e){const n=Fw(ut(r));if(!n)continue;const a=Hw(n);(!t||a>t.score)&&(t={status:n,score:a})}return(t==null?void 0:t.status)??null}function gm(e){const r=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,n=pc([r==null?void 0:r.status,r]);return n||pc([e==null?void 0:e.status,e])}const Ww=5*60*1e3;function ym(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function vm(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function Kw(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"||ym(e)||vm(e)?"remote":"unknown"}function Uw(e){return Ni(e)}function wm(e){var t;return Uw(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function zw(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function Gw(e){return e.activeSessionDetails&&e.activeSessionDetails.length>0?e.activeSessionDetails:(e.activeSessions??[]).map(t=>({sessionId:t,workspace:e.workspace,isCached:!0}))}function jm(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function km(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function Ci(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function Vw(e){return Ci(e)?"degraded":km(e)?"dirty":"online"}function qw(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function fc(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 Ja(e){return e.length===0?"unknown":e.reduce((t,r)=>fc(r)>fc(t)?r:t)}function Yw(e){var o,i,c,d,m;const t=new Map,r=new Map;for(const u of e){const h=(i=(o=u.git)==null?void 0:o.branch)==null?void 0:i.trim();h&&(r.set(h,(r.get(h)??0)+1),(c=u.git)!=null&&c.upstream&&t.set(h,(t.get(h)??0)+1))}const n=[...t.entries()].sort((u,h)=>{if(h[1]!==u[1])return h[1]-u[1];const p=["main","master","develop","dev"],y=p.indexOf(u[0]),g=p.indexOf(h[0]);return y!==-1||g!==-1?y===-1?1:g===-1?-1:y-g:u[0].localeCompare(h[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((m=[...r.entries()].sort((u,h)=>h[1]-u[1])[0])==null?void 0:m[0])??null}function Xw(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 xc(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 Jw(e){return e.reduce((t,r)=>xc(r.status)>xc(t.status)?r:t)}function Qw(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 Zw(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 ej(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 tj(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 sj(e,t){if(wm(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=jm(a)||km(a),i=!!(a!=null&&a.hasConflicts)||Ci(a),c=(a==null?void 0:a.ahead)??0,d=(a==null?void 0:a.behind)??0,m=(a==null?void 0:a.branch)??null,u=(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??u,upstreamStatus:r.upstreamStatus??h,ahead:r.ahead??c,behind:r.behind??d,dirty:r.dirty??o,hasConflicts:r.hasConflicts??i}}function rj(e,t){const r=sj(e,t);return r?{...r,defaultBranch:r.defaultBranch??t}:null}function nj(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function aj(e){var d,m,u;const{nodeStatus:t,expectedSubmodulePaths:r,refreshedAtMs:n}=e,a=[],o=t.machineLabel||t.nodeId,i=t.git;if(!i){if(wm(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"||((d=t.connection)==null?void 0:d.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((u=t.connection)==null?void 0:u.state)!=="self"&&n!==null&&typeof i.lastCheckedAt=="number"&&n-i.lastCheckedAt>Ww&&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 oj(e){const t=bm(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??Yw(t.nodes),a=zw(t.refreshedAt),o=new Set(t.nodes.flatMap(M=>{var A;return(((A=M.git)==null?void 0:A.submodules)??[]).map(W=>W.path)})),i=[],c=[],d=Zw(t),m=new Map;for(const M of t.nodes){const A=M.git,W=(A==null?void 0:A.branch)??null,_=Vw(A),R=jm(A)||_==="dirty",O=Xw(M,n),L=rj(M,n),E=aj({nodeStatus:M,expectedSubmodulePaths:o,refreshedAtMs:a}),$=typeof M.clonedFromNodeId=="string"?M.clonedFromNodeId:null,F=Gw(M),X={id:M.nodeId,type:O.length>0?"orphanNode":"worktreeNode",label:M.machineLabel||M.nodeId.slice(0,8),workspace:M.workspace,branch:W,upstream:(A==null?void 0:A.upstream)??null,upstreamStatus:(A==null?void 0:A.upstreamStatus)??null,daemonId:ym(M),machineId:vm(M),machineLabel:M.machineLabel||null,locality:Kw(M),health:Ja([M.health,_]),ahead:(A==null?void 0:A.ahead)??0,behind:(A==null?void 0:A.behind)??0,dirty:R,dirtyFiles:qw(A),hasConflicts:(A==null?void 0:A.hasConflicts)??!1,activeSessionCount:F.length,activeSessions:F.map(ee=>ee.sessionId),sessionDetails:F,providers:M.providers??[],isOrphan:O.length>0,orphanReasons:O,error:M.error,nextStepHint:E.snapshotWarnings[0]??O[0]??(L==null?void 0:L.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:$,worktreeBranch:M.worktreeBranch??null,submodulePath:null,submoduleCommit:(A==null?void 0:A.headCommit)??null,outOfSync:Ci(A),snapshotCompleteness:E.snapshotCompleteness,snapshotWarnings:E.snapshotWarnings,branchConvergence:L,source:M};if(i.push(X),W){const ee=m.get(W)??[];ee.push(X.id),m.set(W,ee)}for(const ee of(A==null?void 0:A.submodules)??[]){const ne=`${X.id}::submodule::${ee.path}`,Z=ee.path.split("/").filter(Boolean).pop()||ee.path;i.push({id:ne,type:"submoduleNode",label:Z,workspace:ee.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:X.daemonId,machineId:X.machineId,machineLabel:X.machineLabel,locality:X.locality,health:nj(ee),ahead:0,behind:0,dirty:ee.dirty,dirtyFiles:ee.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],error:ee.error,nextStepHint:ee.error||(ee.outOfSync?`${ee.path} is out of sync with the parent checkout`:ee.dirty?`${ee.path} has local changes`:`${ee.path} is in sync with the parent checkout`),parentNodeId:X.id,submodulePath:ee.path,submoduleCommit:ee.commit,outOfSync:ee.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:X.id,parentWorkspace:M.workspace,submodule:ee}}),c.push({id:`${X.id}--${ne}`,source:X.id,target:ne,type:"submoduleLink",label:ee.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const u=n?`__branch_${n}`:null;if(u&&n){const A=(m.get(n)??[]).map($=>i.find(F=>F.id===$)).filter(Boolean),W=A.map($=>$.branchConvergence).filter(Boolean),_=Qw(t),R=A.length>0&&A.every($=>ej($,n)),O=(_==null?void 0:_.length)===0&&R?tj(n,A):W.length>0?Jw(W):null,L=(_==null?void 0:_.length)===0&&R?0:W.filter($=>$.needsConvergence).length,E={id:u,type:"defaultBranchNode",label:n,workspace:t.repoIdentity,branch:n,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:"default branch",locality:"unknown",health:Ja(A.map($=>$.health)),ahead:0,behind:0,dirty:A.some($=>$.dirty),dirtyFiles:A.reduce(($,F)=>$+F.dirtyFiles,0),hasConflicts:A.some($=>$.hasConflicts),activeSessionCount:A.reduce(($,F)=>$+F.activeSessionCount,0),activeSessions:A.flatMap($=>$.activeSessions),sessionDetails:A.flatMap($=>$.sessionDetails),providers:[...new Set(A.flatMap($=>$.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:L>0?`${L} 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:O,source:{nodeId:u,machineLabel:n,workspace:t.repoIdentity,health:Ja(A.map($=>$.health)),providers:[],activeSessions:[],activeSessionDetails:[]}};i.push(E);for(const $ of i)if(!($.id===u||$.type==="submoduleNode")){if($.branch===n){c.push({id:`${u}--${$.id}`,source:u,target:$.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if($.branch){c.push({id:`${u}--${$.id}`,source:u,target:$.id,type:$.isOrphan?"orphanLink":"parentBranch",label:$.branch,direction:"undirected"});continue}$.isOrphan&&c.push({id:`${u}--${$.id}`,source:u,target:$.id,type:"orphanLink",label:"detached",direction:"undirected"})}}for(const[M,A]of m){if(A.length<2)continue;const W=A.map(_=>i.find(R=>R.id===_)).filter(Boolean);W.sort((_,R)=>_.label.localeCompare(R.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?`${M} peers`:void 0,direction:"undirected"})}const h=new Set(i.map(M=>M.id)),p=new Set;for(const M of i){if(!M.clonedFromNodeId||M.type==="submoduleNode"||!h.has(M.clonedFromNodeId))continue;const A=`clone_${M.clonedFromNodeId}--${M.id}`;if(p.has(A))continue;p.add(A);const W=M.worktreeBranch??M.branch??void 0;c.push({id:A,source:M.clonedFromNodeId,target:M.id,type:"cloneLink",label:W?`cloned · ${W}`:"cloned",direction:"directed"})}const y=i.filter(M=>M.type!=="defaultBranchNode"),g=y.filter(M=>M.isOrphan).length,x=y.filter(M=>M.hasConflicts).length,k=y.filter(M=>M.health==="offline").length,S=y.filter(M=>M.type==="submoduleNode"&&M.outOfSync).length,f=y.filter(M=>{var A;return M.type!=="submoduleNode"&&((A=M.branchConvergence)==null?void 0:A.needsConvergence)}).length,v=y.filter(M=>{var A;return((A=M.branchConvergence)==null?void 0:A.status)==="blocked_review"}).length,j=y.filter(M=>{var A;return((A=M.branchConvergence)==null?void 0:A.status)==="pushed_feature_branch_needs_merge"}).length,w=y.filter(M=>{var A;return((A=M.branchConvergence)==null?void 0:A.status)==="cleanup_candidate"}).length,b=y.filter(M=>{var A;return((A=M.branchConvergence)==null?void 0:A.status)==="not_mergeable"}).length,C=y.filter(M=>M.snapshotWarnings.length>0).length,N=y.filter(M=>M.snapshotCompleteness==="pending_git").length,I=y.filter(M=>M.snapshotCompleteness==="missing_git").length,B=y.filter(M=>M.snapshotCompleteness==="missing_submodule_report").length,P=y.filter(M=>M.snapshotCompleteness==="stale").length,T=[N>0?`${N} node(s) are still waiting for a live peer git snapshot`:null,I>0?`${I} node(s) have no visible peer git snapshot`:null,B>0?`${B} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,P>0?`${P} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return f>0&&d.push(`${f} workspace(s) still need follow-up before the mesh is converged`),g>0&&d.push(`${g} workspace(s) need attention before safe coordination`),v>0&&d.push(`${v} workspace(s) are blocked on branch convergence or upstream sync`),j>0&&d.push(`${j} clean feature branch workspace(s) still need merge follow-up`),w>0&&d.push(`${w} worktree workspace(s) are ready for refine / cleanup`),b>0&&d.push(`${b} workspace(s) have local changes or conflicts blocking convergence`),x>0&&d.push(`${x} workspace(s) report merge conflicts`),k>0&&d.push(`${k} node(s) are currently offline`),S>0&&d.push(`${S} submodule(s) are out of sync with their parent checkout`),d.push(...T),n||d.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(M=>M.health==="online").length,dirtyNodes:y.filter(M=>M.dirty).length,orphanNodes:g,errorNodes:y.filter(M=>!!M.error||M.outOfSync).length,offlineNodes:k,followUpNodes:f,blockedReviewNodes:v,mergeReadyNodes:j,cleanupCandidateNodes:w,notMergeableNodes:b,incompleteSnapshotNodes:C,missingGitSnapshotNodes:I,missingSubmoduleSnapshotNodes:B,staleGitSnapshotNodes:P,totalActiveSessions:y.reduce((M,A)=>M+A.activeSessionCount,0)},warnings:d,snapshotWarnings:T}}const ij={recentFailures:0,taskCompleted:0,taskFailed:0,sessionLaunched:0},Ii=l.createContext(or("dark"));function Ge({label:e,tone:t="default"}){const r=l.useContext(Ii);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 dt({label:e,value:t}){const r=l.useContext(Ii);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 bc(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 Qa(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 wn(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 lj(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function cj(e){return e.startedAt||e.createdAt||null}function dj(e){const t=cj(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 uj(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function mj(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 hj(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 pj(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 fj(e){return e.assignedNodeId||e.targetNodeId||null}function gc(e){return e?e.slice(0,7):null}function xj(e,t){var o,i,c;const r=gc((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?[gc(a.commit),a.message].filter(Boolean).join(" · "):null}function bj(e,t){const r=xj(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function gj(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 yj(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 d=((c=e.selectedNodeStatus)==null?void 0:c.daemonId)||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}if(t&&e.selectedNodeStatus){const d=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}return null}function vj(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":hj(e.connection)}function yc(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 vc(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 wj(e){return e.direction==="directed"?"directed":"undirected"}function wc(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function jj(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,d,m,u,h,p,y,g,x,k,S,f,v,j,w,b,C,N,I,B,P;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)??"",((d=o.connection)==null?void 0:d.source)??"",o.health,o.gitProbePending?1:0,((m=o.git)==null?void 0:m.branch)??"",((u=o.git)==null?void 0:u.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)??"",((g=o.git)==null?void 0:g.headCommit)??"",((x=o.git)==null?void 0:x.staged)??"",((k=o.git)==null?void 0:k.modified)??"",((S=o.git)==null?void 0:S.untracked)??"",((f=o.git)==null?void 0:f.deleted)??"",((v=o.git)==null?void 0:v.renamed)??"",(j=o.git)!=null&&j.hasConflicts?1:0,((w=o.git)==null?void 0:w.lastCheckedAt)??"",((b=o.activeSessions)==null?void 0:b.join(","))??"",((C=o.activeSessionDetails)==null?void 0:C.length)??"",((N=o.activeSessionDetails)==null?void 0:N.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(","))??"",((I=o.providers)==null?void 0:I.join(","))??"",((B=o.providerPriority)==null?void 0:B.join(","))??"",o.error??"",(((P=o.git)==null?void 0:P.submodules)??[]).map(T=>[T.path,T.commit,T.dirty?1:0,T.outOfSync?1:0,T.error??""].join("/")).join(",")].join("|")})].join("::")}function Sm({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null}){var ue,Ae,q,be,ce;const{theme:a}=ar(),o=l.useMemo(()=>or(a),[a]),i=l.useMemo(()=>bm(e),[e]),c=l.useMemo(()=>jj(i),[i]),d=l.useMemo(()=>oj(i),[c]),[m,u]=l.useState(null),[h,p]=l.useState(null),[y,g]=l.useState(null),[x,k]=l.useState(null),[S,f]=l.useState({}),[v,j]=l.useState(null),[w,b]=l.useState(null),C=l.useMemo(()=>new Map(i.nodes.map(K=>[K.nodeId,K])),[i.nodes]),N=l.useMemo(()=>new Map(d.nodes.map(K=>[K.id,K])),[d.nodes]),I=((ue=i.queue)==null?void 0:ue.summary)??null,B=((Ae=i.ledger)==null?void 0:Ae.summary)??ij,P=l.useMemo(()=>pj(i),[i]),T=l.useMemo(()=>{const K=new Map;for(const ae of P){const de=wn(ae.session);K.set(de,(K.get(de)??0)+1)}return[...K.entries()].sort((ae,de)=>de[1]-ae[1])},[P]);l.useEffect(()=>{m&&(N.has(m)||(u(null),k(K=>!K||"nodeId"in K&&K.nodeId===m?null:K)))},[N,m]);const M=m?C.get(m)??null:null,A=wc(d,m),W=wc(d,h),_=y?d.edges.find(K=>K.id===y)??null:null,R=_?d.nodes.find(K=>K.id===_.source)??null:null,O=_?d.nodes.find(K=>K.id===_.target)??null:null;l.useEffect(()=>{var K,ae,de;if(m)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:i.meshId,selectedNodeId:m,canonicalNode:Ow(M),graphNode:A?{id:A.id,branch:A.branch,upstream:A.upstream,headCommit:A.submoduleCommit,submoduleCount:((ae=(K=M==null?void 0:M.git)==null?void 0:K.submodules)==null?void 0:ae.length)??0,snapshotCompleteness:A.snapshotCompleteness,snapshotWarnings:A.snapshotWarnings,branchConvergence:((de=A.branchConvergence)==null?void 0:de.status)??null}:null})}catch{}},[i.meshId,A,m,M]);const L=(x==null?void 0:x.kind)==="session"?P.find(K=>K.nodeId===x.nodeId&&K.session.sessionId===x.sessionId)??null:null,E=l.useMemo(()=>P.filter(K=>K.nodeId===m),[m,P]),$=yj({coordinatorDaemonId:r,selectedNodeStatus:M,selectedSessionEntry:L}),F=($==null?void 0:$.workspace)??null,X=F?S[F]??null:null,ee=bj(M,(X==null?void 0:X.entries)??[]),ne=(A==null?void 0:A.daemonId)??(M==null?void 0:M.daemonId)??r??null,Z=!!(A&&n&&ne&&A.type!=="submoduleNode"&&A.behind>0&&A.ahead===0&&A.dirtyFiles===0&&!A.dirty&&!A.hasConflicts&&A.upstreamStatus==="fresh"),ge=l.useCallback(()=>{u(null),k(null),j(null)},[]);l.useEffect(()=>{j(null)},[m]);const Ne=l.useCallback(async()=>{if(!(!A||!ne||!n||!Z)){b(A.id),j(null);try{const K=await n(ne,"fast_forward_mesh_node",{meshId:i.meshId,nodeId:A.id,dryRun:!0,execute:!1});if(j({phase:"dry_run",code:typeof(K==null?void 0:K.code)=="string"?K.code:void 0,error:typeof(K==null?void 0:K.operationError)=="string"?K.operationError:null,executed:(K==null?void 0:K.executed)===!0}),!(K!=null&&K.success)||K.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${A.label}?`))return;const de=await n(ne,"fast_forward_mesh_node",{meshId:i.meshId,nodeId:A.id,dryRun:!1,execute:!0});j({phase:"execute",code:typeof(de==null?void 0:de.code)=="string"?de.code:void 0,error:typeof(de==null?void 0:de.operationError)=="string"?de.operationError:null,executed:(de==null?void 0:de.executed)===!0})}catch(K){j({phase:"dry_run",error:K instanceof Error?K.message:"fast-forward failed"})}finally{b(null)}}},[Z,i.meshId,A,ne,n]);l.useEffect(()=>{if(!A)return;const K=ae=>{ae.key==="Escape"&&ge()};return window.addEventListener("keydown",K),()=>window.removeEventListener("keydown",K)},[ge,A]),l.useEffect(()=>{if(!$||!n)return;const{daemonId:K,workspace:ae}=$,de=S[ae];if(de!=null&&de.loading||de&&(de.entries.length>0||de.error))return;let le=!1;return f(se=>{var J;return{...se,[ae]:{loading:!0,error:null,entries:((J=se[ae])==null?void 0:J.entries)??[]}}}),n(K,"git_log",{workspace:ae,limit:5}).then(se=>{le||f(J=>({...J,[ae]:{loading:!1,error:null,entries:gj(se)}}))}).catch(se=>{le||f(J=>({...J,[ae]:{loading:!1,error:se instanceof Error?se.message:"git_log failed",entries:[]}}))}),()=>{le=!0}},[S,$,n]);const V=[...d.warnings??[],...i.nodes.filter(K=>K.machineStatus&&K.machineStatus!=="online").map(K=>`${K.machineLabel}: ${K.machineStatus}`)],ve=d.stats.incompleteSnapshotNodes>0,xe=d.stats.followUpNodes>0?`${d.stats.followUpNodes} need follow-up`:ve?"mesh visibility incomplete":"mesh converged",ye=d.stats.followUpNodes>0?"danger":ve?"warn":"good";return s.jsx(Ii.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(Ge,{label:xe,tone:ye}),d.stats.blockedReviewNodes>0&&s.jsx(Ge,{label:`${d.stats.blockedReviewNodes} blocked review`,tone:"danger"}),d.stats.notMergeableNodes>0&&s.jsx(Ge,{label:`${d.stats.notMergeableNodes} not mergeable`,tone:"danger"}),d.stats.mergeReadyNodes>0&&s.jsx(Ge,{label:`${d.stats.mergeReadyNodes} need merge`,tone:"warn"}),d.stats.cleanupCandidateNodes>0&&s.jsx(Ge,{label:`${d.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),d.stats.offlineNodes>0&&s.jsx(Ge,{label:`${d.stats.offlineNodes} offline`,tone:"danger"}),d.stats.incompleteSnapshotNodes>0&&s.jsx(Ge,{label:`${d.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),d.stats.missingGitSnapshotNodes>0&&s.jsx(Ge,{label:`${d.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),d.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Ge,{label:`${d.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),d.stats.staleGitSnapshotNodes>0&&s.jsx(Ge,{label:`${d.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((I==null?void 0:I.active)??0)>0&&s.jsx(Ge,{label:`${(I==null?void 0:I.active)??0} active queue`,tone:"info"}),s.jsx(Ge,{label:`${d.stats.totalNodes} nodes`,tone:"default"}),d.stats.totalActiveSessions>0&&s.jsx(Ge,{label:`${d.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(Ge,{label:`${d.stats.dirtyNodes} dirty`,tone:d.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Ge,{label:`${d.stats.orphanNodes} orphan`,tone:d.stats.orphanNodes>0?"warn":"good"}),s.jsx(Ge,{label:`${B.recentFailures} recent failures`,tone:B.recentFailures>0?"danger":"good"}),T.length===0?s.jsx(Ge,{label:"no session metadata"}):T.slice(0,2).map(([K,ae])=>s.jsx(Ge,{label:`${ae} ${K}`,tone:Qa(K)},K))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ge,{label:"Anchor = default branch",tone:"info"}),s.jsx(Ge,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Ge,{label:"Submodule link = child checkout",tone:"warn"})]}),V.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:V.map(K=>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:K},K))}),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."})]})]})]}),d.nodes.length>0?s.jsx(Nw,{data:d,selectedNodeId:m,onNodeHoverChange:K=>{p((K==null?void 0:K.id)??null),K&&g(null)},onEdgeHoverChange:K=>{g((K==null?void 0:K.id)??null),K&&p(null)},onNodeClick:K=>{if((x==null?void 0:x.kind)==="node"&&m===K.id){u(null),k(null);return}u(K.id),k({kind:"node",nodeId:K.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(Ge,{label:"hover preview",tone:"info"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[s.jsx(Ge,{label:W.health,tone:bc(W.health)}),W.branch&&s.jsx(Ge,{label:W.branch,tone:"default"}),W.ahead>0&&s.jsx(Ge,{label:`ahead ${W.ahead}`,tone:"warn"}),W.behind>0&&s.jsx(Ge,{label:`behind ${W.behind}`,tone:"warn"}),W.dirtyFiles>0&&s.jsx(Ge,{label:`${W.dirtyFiles} dirty`,tone:"warn"}),W.activeSessionCount>0&&s.jsx(Ge,{label:`${W.activeSessionCount} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[s.jsx(dt,{label:"Machine",value:W.machineLabel??"not reported"}),s.jsx(dt,{label:"Locality",value:W.locality}),s.jsx(dt,{label:"Workspace",value:W.workspace}),s.jsx(dt,{label:"Upstream",value:W.upstream??"none"}),s.jsx(dt,{label:"Dirty/ahead/behind",value:`${W.dirtyFiles} dirty · ↑${W.ahead}/↓${W.behind}`}),s.jsx(dt,{label:"Source",value:yc(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||vc(_)}),s.jsx("div",{className:`mt-1 text-[11px] ${o.textMuted}`,children:_.id})]}),s.jsx(Ge,{label:"hover preview",tone:"info"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[s.jsx(Ge,{label:vc(_),tone:"default"}),s.jsx(Ge,{label:wj(_),tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs",children:[s.jsx(dt,{label:"From",value:(R==null?void 0:R.label)??_.source}),s.jsx(dt,{label:"To",value:(O==null?void 0:O.label)??_.target}),s.jsx(dt,{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:ge,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:K=>K.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:()=>{Ne()},disabled:!Z||w===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:w===A.id?"Checking":"Heal"}),s.jsx("button",{type:"button",onClick:ge,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(Ge,{label:(M==null?void 0:M.health)??A.health,tone:bc((M==null?void 0:M.health)??A.health)}),A.branch&&s.jsx(Ge,{label:A.branch,tone:"default"}),A.ahead>0&&s.jsx(Ge,{label:`ahead ${A.ahead}`,tone:"warn"}),A.behind>0&&s.jsx(Ge,{label:`behind ${A.behind}`,tone:"warn"}),A.dirtyFiles>0&&s.jsx(Ge,{label:`${A.dirtyFiles} dirty`,tone:"warn"}),(M==null?void 0:M.connection)&&s.jsx(Ge,{label:vj(M),tone:mj(M.connection)}),E.length>0&&s.jsx(Ge,{label:`${E.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[s.jsx(dt,{label:"Machine",value:A.machineLabel??"not reported"}),s.jsx(dt,{label:"Locality",value:A.locality}),s.jsx(dt,{label:"Machine id",value:A.machineId??(M==null?void 0:M.machineId)??"not reported"}),s.jsx(dt,{label:"Daemon id",value:A.daemonId??(M==null?void 0:M.daemonId)??"not reported"}),s.jsx(dt,{label:"Workspace",value:(M==null?void 0:M.workspace)??A.workspace}),s.jsx(dt,{label:"Branch",value:A.branch??"unknown"}),s.jsx(dt,{label:"HEAD",value:ee??(M!=null&&M.gitProbePending?"Pending live git probe":"not reported")}),s.jsx(dt,{label:"Upstream",value:A.upstream??"none"}),s.jsx(dt,{label:"Dirty/ahead/behind",value:`${A.dirtyFiles} dirty · ↑${A.ahead}/↓${A.behind}`}),s.jsx(dt,{label:"Source",value:String(((q=M==null?void 0:M.connection)==null?void 0:q.source)??yc(A))}),s.jsx(dt,{label:"Transport",value:((be=M==null?void 0:M.connection)==null?void 0:be.transport)??"unknown"}),s.jsx(dt,{label:"Sessions",value:E.length>0?E.map(K=>wn(K.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(K=>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:K.session.sessionId,children:uj(K.session.sessionId)}),s.jsx(Ge,{label:wn(K.session),tone:Qa(wn(K.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:K.session.providerType||"provider unknown"}),s.jsx("span",{children:lj(K.session)}),s.jsx("span",{children:dj(K.session)})]}),K.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${o.textMuted}`,children:K.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${o.textMuted}`,title:K.session.workspace||K.workspace,children:[(K.session.workspace||K.workspace).slice(0,42),K.branch?` · ${K.branch}`:""]})]},K.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(dt,{label:"Completed",value:String(B.taskCompleted)}),s.jsx(dt,{label:"Failed",value:s.jsx("span",{className:B.taskFailed>0?o.isDark?"text-rose-300":"text-rose-600":"",children:B.taskFailed})}),s.jsx(dt,{label:"Launched",value:String(B.sessionLaunched)}),s.jsx(dt,{label:"Recent failures",value:s.jsx("span",{className:B.recentFailures>0?o.isDark?"text-amber-300":"text-amber-600":"",children:B.recentFailures})})]})]}),(()=>{var de,le;const K=((de=i.queue)==null?void 0:de.tasks)??((le=i.queue)==null?void 0:le.items)??null;if(!Array.isArray(K)||K.length===0)return null;const ae=K.filter(se=>fj(se)===m).slice(0,3);return ae.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:ae.map(se=>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:se.id.slice(0,12)}),s.jsx(Ge,{label:se.status??"unknown",tone:Qa(se.status)})]}),se.message&&s.jsx("div",{className:`mt-0.5 truncate ${o.textMuted}`,children:se.message.slice(0,48)})]},se.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]})]}),((ce=A.branchConvergence)==null?void 0:ce.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})]}),v&&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:v.phase==="execute"?"Heal result":"Heal preview"}),s.jsx("div",{className:"mt-1",children:v.code??v.error??"No result code returned."})]})]})})]})})})})}function wt(e){return typeof e=="string"?e.trim():""}function Do(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Mi(...e){const t=new Set;for(const r of e){const n=wt(r);n&&t.add(n)}return[...t]}function kj(e,t){var h,p;const r=Do(e==null?void 0:e.settings),n=wt((h=e==null?void 0:e.coordinator)==null?void 0:h.meshId)||wt(r.meshCoordinatorFor),a=wt(r.meshNodeFor),o=!!n||!!a,i=n===t||a===t;if(o&&!i)return null;const c=Do(e==null?void 0:e.activeChat),d=Mi(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=d[0]||"";if(!m)return null;const u=n===t?wt((p=e==null?void 0:e.coordinator)==null?void 0:p.role)||"coordinator":a===t?wt(r.meshNodeRole)||"worker":wt(e==null?void 0:e.role)||wt(r.meshNodeRole)||void 0;return{sessionId:m,aliases:d,meshId:t,nodeId:i&&wt(r.meshNodeId)||null,providerType:wt(e==null?void 0:e.providerType)||void 0,state:wt(e==null?void 0:e.status)||void 0,chatStatus:wt(c.status)||void 0,lifecycle:wt(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:wt(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:wt(e==null?void 0:e.runtimeRecoveryState)||void 0,...u?{role:u}:{},...i?{isSelfCoordinator:n===t}:{},workspace:wt(e==null?void 0:e.workspace)||null}}function Nm(e,t){var n;return t?(Array.isArray((n=e.status)==null?void 0:n.sessions)?e.status.sessions:[]).map(a=>kj(a,t)).filter(a=>a!==null):[]}function ra(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function Sj(e,t){const r=new Set(ra(t));return ra(e).some(n=>r.has(n))}function Nj(e,t){const r=t.filter(a=>!!a);return r.length===0?e:[...e.filter(a=>!r.some(o=>Sj(a,o))),...r]}function Cj(e,t){if(t.length===0)return e;const r=new Map;for(const o of t)for(const i of ra(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 u=Mi(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=u[0]||"";if(!h)continue;const p=u.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)ra(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 d=[...c.values()];return d.length===0?o:{...o,activeSessionDetails:d,activeSessions:d.map(m=>m.sessionId)}});return n?{...e,nodes:a}:e}function Ij(e,t){const n=Nm(e,t).map(a=>{var d;const o=(Array.isArray((d=e.status)==null?void 0:d.sessions)?e.status.sessions:[]).find(m=>wt(m==null?void 0:m.id)===a.sessionId),i=Do(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??"",wt(i.status)||wt(i.kind)||wt(i.type),a.nodeId??"",a.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(a=>!!a).sort();return n.length>0?n.join(`
|
|
74
|
+
`),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:Ya(j.sessionId)}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${qa(j,r.isDark)}`,children:ns(j)})]}),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:j.providerType||"provider unknown"}),s.jsx("span",{children:b}),s.jsx("span",{children:lc(w)})]}),j.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${r.textMuted}`,children:j.statusNote})]},j.sessionId)})})]}),d&&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:sw,children:p})]}),s.jsx(sn,{type:"source",position:a==="TB"?us.Bottom:us.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const cw={meshNode:lw},dw=8;function uw(e){if(e.length<2)return null;if(e.length===2){const[m,u]=e;return{d:`M ${m.x},${m.y} L ${u.x},${u.y}`,labelX:(m.x+u.x)/2,labelY:(m.y+u.y)/2}}const t=dw,r=[`M ${e[0].x},${e[0].y}`];for(let m=1;m<e.length-1;m+=1){const u=e[m-1],h=e[m],p=e[m+1],y=Math.sign(h.x-u.x),g=Math.sign(h.y-u.y),x=Math.sign(p.x-h.x),k=Math.sign(p.y-h.y),S=Math.hypot(h.x-u.x,h.y-u.y),f=Math.hypot(p.x-h.x,p.y-h.y),v=Math.min(t,S/2,f/2);if(v<1||y===x&&g===k){r.push(`L ${h.x},${h.y}`);continue}const j=h.x-y*v,w=h.y-g*v,b=h.x+x*v,C=h.y+k*v;r.push(`L ${j},${w}`),r.push(`Q ${h.x},${h.y} ${b},${C}`)}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,d=e[0].y;for(let m=1;m<e.length;m+=1)if(o[m]>=i){const u=o[m]-o[m-1],h=u===0?0:(i-o[m-1])/u;c=e[m-1].x+(e[m].x-e[m-1].x)*h,d=e[m-1].y+(e[m].y-e[m-1].y)*h;break}return{d:r.join(" "),labelX:c,labelY:d}}function mw(e){const t=e.data.routePoints;if(t&&t.length>=2){const o=uw(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=Sh(r):n.type==="worktreeLink"||n.type==="submoduleLink"||n.type==="cloneLink"?a=jh(r):a=kh(r),[a[0],a[1],a[2]]}function hw(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 pw(e){const t=l.useContext(ki),r=e.data.graphEdge,[n,a,o]=mw(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(gh,{id:e.id,path:n,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(yh,{children:s.jsx("div",{className:hw(r,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${a}px, ${o}px)`,pointerEvents:"none",maxWidth:Ev.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const fw={meshEdge:pw};async function xw(e,t=or("dark"),r=!1,n="LR"){const a=await Xv(e,r,n),o=new Set(a.nodes.map(u=>u.id)),i=a.nodes.map(u=>({id:u.id,type:u.type,position:u.position,data:{graphNode:u.graphNode,compact:r},selected:u.selected,draggable:u.draggable,selectable:u.selectable})),c=e.edges.filter(u=>o.has(u.source)&&o.has(u.target)),d=yw(c),m=c.map(u=>{var h;return{id:u.id,source:u.source,target:u.target,label:d.has(u.id)?u.label:void 0,type:"meshEdge",data:{graphEdge:u,routePoints:(h=a.edgeRoutes.get(u.id))==null?void 0:h.points},animated:u.type==="orphanLink",markerEnd:u.direction==="directed"?{type:bh.ArrowClosed,width:u.type==="submoduleLink"?16:18,height:u.type==="submoduleLink"?16:18,color:uc(u)}:void 0,style:{stroke:uc(u),strokeWidth:u.type==="orphanLink"?2.25:u.type==="submoduleLink"?1.7:u.type==="worktreeLink"?1.8:u.type==="cloneLink"?1.6:2,strokeDasharray:u.type==="orphanLink"?"5 4":u.type==="submoduleLink"?"4 3":u.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 bw=3,gw=2;function dc(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 yw(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<bw){for(const o of n)t.add(o.id);continue}const a=[...n].sort((o,i)=>{const c=dc(i)-dc(o);return c!==0?c:o.id.localeCompare(i.id)});for(const o of a.slice(0,gw))t.add(o.id)}return t}function uc(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 vw(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 ww(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 jw({data:e,viewportKey:t}){const r=vh(),n=wh(),a=l.useRef(null),o=l.useMemo(()=>am(e),[e]),i=l.useMemo(()=>_v(e),[e]);return l.useEffect(()=>{if(!r||e.nodes.length===0||a.current===t)return;let c=!1;const d=requestAnimationFrame(()=>{if(c)return;const m=i.length>0&&i.length<e.nodes.length;n.fitView({nodes:m?i.map(u=>({id:u})):void 0,padding:m?.24:.2,maxZoom:m?.98:.9,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(d)}},[e.nodes.length,i,o,r,n,t]),null}function kw(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 Sw=12;function Nw({data:e,selectedNodeId:t=null,onNodeClick:r,onNodeHoverChange:n,onEdgeHoverChange:a}){const{theme:o}=ar(),i=l.useMemo(()=>or(o),[o]),c=l.useMemo(()=>Qv(e),[e]),d=l.useMemo(()=>Zv(e),[e]),m=e.nodes.length>=ew,[u,h]=l.useState("LR"),p=l.useMemo(()=>u==="auto"?Fv(e):u,[u,c,e]),y=e.nodes.length>=Sw,[g,x]=l.useState({nodes:[],edges:[]}),k=l.useRef(null),[S,f]=l.useState({width:0,height:0}),v=l.useMemo(()=>`${Lv(e,S.width,S.height)}::${p}`,[c,e,S.height,S.width,p]);l.useEffect(()=>{let C=!1;return xw(e,i,m,p).then(N=>{C||x(N)}),()=>{C=!0}},[e,d,i,m,p]);const j=l.useMemo(()=>g.nodes.map(C=>({...C,selected:C.id===t})),[g.nodes,t]);l.useEffect(()=>{const C=k.current;if(!C)return;const N=()=>{const B=Math.max(0,Math.round(C.clientWidth)),P=Math.max(0,Math.round(C.clientHeight));f(T=>T.width===B&&T.height===P?T:{width:B,height:P})};N();const I=typeof ResizeObserver=="function"?new ResizeObserver(()=>N()):null;return I==null||I.observe(C),window.addEventListener("resize",N),()=>{I==null||I.disconnect(),window.removeEventListener("resize",N)}},[]);const w=kw(e.nodes.length),b=C=>C?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(ki.Provider,{value:i,children:s.jsx(cm.Provider,{value:m,children:s.jsx(dm.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:b(u==="auto"),title:`Auto (currently ${p==="TB"?"top-bottom":"left-right"})`,children:"Auto"}),s.jsx("button",{type:"button",onClick:()=>h("LR"),className:b(u==="LR"),title:"Left to right",children:"LR"}),s.jsx("button",{type:"button",onClick:()=>h("TB"),className:b(u==="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 ${w}`,children:s.jsxs(mh,{nodes:j,edges:g.edges,nodeTypes:cw,edgeTypes:fw,minZoom:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(C,N)=>r==null?void 0:r(N.data.graphNode),onNodeMouseEnter:(C,N)=>n==null?void 0:n(N.data.graphNode),onNodeMouseLeave:()=>n==null?void 0:n(null),onEdgeMouseEnter:(C,N)=>{var I;return a==null?void 0:a(((I=N.data)==null?void 0:I.graphEdge)??null)},onEdgeMouseLeave:()=>a==null?void 0:a(null),className:"h-full w-full",colorMode:i.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(jw,{data:e,viewportKey:v}),s.jsx(hh,{className:i.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),y&&s.jsx(ph,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:vw,nodeClassName:ww,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(fh,{variant:xh.Dots,gap:18,size:1.2,color:i.graphBackgroundDotColor})]})})]})})})})}function ut(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 Dt(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function Rt(...e){for(const t of e)if(typeof t=="boolean")return t}function Xa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function Si(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 Cw(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 Iw(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=ut(n),o=je(a.path),i=je(a.commit),c=je(a.repoPath,a.repo_root)??Cw(t,o);return!o||!i||!c?null:{path:o,commit:i,repoPath:c,dirty:Rt(a.dirty)??!1,outOfSync:Rt(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:Dt(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 Mw(e){return Rt(e.isGitRepo)!==void 0||!!je(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||Dt(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 $n(e,t,r){const n=Rt(e.isGitRepo);if(!Object.keys(e).length||!Mw(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(v=>typeof v=="string"):[],i=Dt(e.conflicts)??o.length,c=Rt(e.hasConflicts)??i>0,d=je(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,m=Iw(e.submodules,d),u=je(e.upstreamStatus,e.upstream_status),h=Dt(e.upstreamFetchedAt,e.upstream_fetched_at),p=je(e.upstreamFetchError,e.upstream_fetch_error),y=je(e.error),g=Dt(e.staged)??0,x=Dt(e.modified)??0,k=Dt(e.untracked)??0,S=Dt(e.deleted)??0,f=Dt(e.renamed)??0;return{workspace:je(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:a,branch:je(e.branch)??null,headCommit:je(e.headCommit)??null,headMessage:je(e.headMessage)??null,upstream:je(e.upstream)??null,upstreamStatus:u??"unchecked",...h!==void 0?{upstreamFetchedAt:h}:{},...p?{upstreamFetchError:p}:{},ahead:Dt(e.ahead)??0,behind:Dt(e.behind)??0,staged:g,modified:x,untracked:k,deleted:S,renamed:f,dirty:Rt(e.dirty,e.isDirty,e.is_dirty)??(g+x+k+S+f>0||c),hasConflicts:c,conflictFiles:o,stashCount:Dt(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??Dt(e.lastCheckedAt,e.last_checked_at)??Date.now(),...m?{submodules:m}:{},...y?{error:y}:{}}}function Aw(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+=Si(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 Tw(e){const t=ut(e.lastGit??e.last_git),r=ut(t.result),n=ut(t.status),a=ut(r.status),o=ut(e.lastProbe??e.last_probe),i=ut(o.git),c=ut(i.result),d=ut(i.status),m=ut(c.status);let u=null;for(const h of[n,a,d,m]){const p=$n(h,e,{lastCheckedAt:Date.now()});if(!p)continue;const y=Aw(p);(!u||y>u.score)&&(u={git:p,score:y})}return u==null?void 0:u.git}function _w(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 Lw(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 sa(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=_w(e);return t.outOfSync?"degraded":t.dirty||Lw(e)?"dirty":"online"}function Pw(e,t){const r=t?sa(t):void 0;return!e||e==="unknown"?r:e}function hm(e){const t=ut(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)}:{},...Rt(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:Rt(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)}:{},...Rt(t.isCached,t.is_cached)!==void 0?{isCached:Rt(t.isCached,t.is_cached)}:{}}:null}function Rw(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(hm).filter(o=>o!==null);if(a.length>0)return a}const r=ut(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 Dw(e){const t=ut(e.connection);return Object.keys(t).length>0?t:void 0}function $w(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 Ni(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 mc(e){var n,a,o,i,c,d;let t=0;const r=e.git;return Ni(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+=Si(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),((d=e.connection)==null?void 0:d.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 Ew(e,t){var g,x,k,S;const r=mc(e),a=mc(t)>r?t:e,o=a===t?e:t,i=a.git??o.git,c=(((g=a.providers)==null?void 0:g.length)??0)>0?a.providers:o.providers,d=(((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,u=(((S=a.providerPriority)==null?void 0:S.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")?sa(i):a.health,providers:c??[],activeSessions:d??[],...m&&m.length>0?{activeSessionDetails:m}:{},...u&&u.length>0?{providerPriority:u}:{},...h?{connection:h}:{},...i?{git:i}:{}},y=ut(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 pm(e){const t=ut(e),r=je(t.nodeId,t.id);if(!r)return null;const n=ut(t.cachedStatus),a=Tw(t),o=a?void 0:$n(ut(t.git),t)??$n(t,t),i=a??o,c=i?void 0:$n(ut(n.git),t),d=i??c,m=je(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),u=je(t.health),h=a?sa(d):Pw(u,i)||(d?sa(d):void 0)||je(n.health)||m||je(t.status)||"unknown",y=(a?void 0:je(t.error))??(i?void 0:je(n.error)),g=Rw(t),x=Xa(t.activeSessions),k=(g==null?void 0:g.map(N=>N.sessionId))??[],S=Xa(t.providerPriority),f=Rt(t.gitProbePending,t.git_probe_pending),v=i?void 0:f,j=Dw(t),w=ut(t.branchConvergence??t.branch_convergence),b=j==null?void 0:j.state,C=a&&(!(j!=null&&j.reported)||b==="unknown")?$w(j):j;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,d==null?void 0:d.workspace)||"",...je(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:je(t.repoRoot,t.repo_root,d==null?void 0:d.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}:{},...Rt(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Rt(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,...d?{git:d}:{},...v!==void 0?{gitProbePending:v}:{},providers:Xa(t.providers),activeSessions:x.length>0?x:k,...g&&g.length>0?{activeSessionDetails:g}:{},...S.length>0?{providerPriority:S}:{},...Rt(t.launchReady)!==void 0?{launchReady:Rt(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)}:{},...C?{connection:C}:{},...Object.keys(w).length>0?{branchConvergence:w}:{},...y?{error:y}:{}}}function hc(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 fm(e,t){const r=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],n=r.map(hm).filter(a=>a!==null);return n.length===0?t:t.map(a=>{const o=n.filter(c=>{const d=ut(r.find(p=>{const y=ut(p);return je(y.sessionId,y.session_id,y.id)===c.sessionId})),m=je(d.nodeId,d.node_id),u=je(d.daemonId,d.daemon_id),h=je(d.workspace);return m&&m===a.nodeId?!0:u&&a.daemonId&&u===a.daemonId?!h||!a.workspace||h===a.workspace:!!(h&&a.workspace&&h===a.workspace)});if(o.length===0)return a;const i=hc([...a.activeSessionDetails??[],...o]);return{...a,activeSessionDetails:i,activeSessions:hc([...a.activeSessionDetails??[],...o,...(a.activeSessions??[]).map(c=>({sessionId:c}))]).map(c=>c.sessionId)}})}function Bw(e){const t=ut(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||Rt(t.is_local_worktree)!==void 0}function xm(e){const t=new Map,r=[];for(const n of e){const a=Bw(n)?pm(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=Ew(o,a);t.set(a.nodeId,i);const c=r.findIndex(d=>d.nodeId===a.nodeId);c>=0&&(r[c]=i)}return r}function bm(e){const t=xm(e.nodes??[]);return{...e,nodes:fm(e,t)}}function Ow(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:Ni(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 Fw(e){const t=je(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(d=>pm(d)).filter(d=>d!==null):null;if(!t||!n)return null;const a=fm(e,xm(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 Hw(e){var o;let t=0;const r=ut(e.sourceOfTruth),n=ut(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+=Si(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 pc(e){let t=null;for(const r of e){const n=Fw(ut(r));if(!n)continue;const a=Hw(n);(!t||a>t.score)&&(t={status:n,score:a})}return(t==null?void 0:t.status)??null}function gm(e){const r=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,n=pc([r==null?void 0:r.status,r]);return n||pc([e==null?void 0:e.status,e])}const Ww=5*60*1e3;function ym(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function vm(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function Kw(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"||ym(e)||vm(e)?"remote":"unknown"}function Uw(e){return Ni(e)}function wm(e){var t;return Uw(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function zw(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function Gw(e){return e.activeSessionDetails&&e.activeSessionDetails.length>0?e.activeSessionDetails:(e.activeSessions??[]).map(t=>({sessionId:t,workspace:e.workspace,isCached:!0}))}function jm(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function km(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function Ci(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function Vw(e){return Ci(e)?"degraded":km(e)?"dirty":"online"}function qw(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function fc(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 Ja(e){return e.length===0?"unknown":e.reduce((t,r)=>fc(r)>fc(t)?r:t)}function Yw(e){var o,i,c,d,m;const t=new Map,r=new Map;for(const u of e){const h=(i=(o=u.git)==null?void 0:o.branch)==null?void 0:i.trim();h&&(r.set(h,(r.get(h)??0)+1),(c=u.git)!=null&&c.upstream&&t.set(h,(t.get(h)??0)+1))}const n=[...t.entries()].sort((u,h)=>{if(h[1]!==u[1])return h[1]-u[1];const p=["main","master","develop","dev"],y=p.indexOf(u[0]),g=p.indexOf(h[0]);return y!==-1||g!==-1?y===-1?1:g===-1?-1:y-g:u[0].localeCompare(h[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((m=[...r.entries()].sort((u,h)=>h[1]-u[1])[0])==null?void 0:m[0])??null}function Xw(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 xc(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 Jw(e){return e.reduce((t,r)=>xc(r.status)>xc(t.status)?r:t)}function Qw(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 Zw(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 ej(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 tj(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 sj(e,t){if(wm(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=jm(a)||km(a),i=!!(a!=null&&a.hasConflicts)||Ci(a),c=(a==null?void 0:a.ahead)??0,d=(a==null?void 0:a.behind)??0,m=(a==null?void 0:a.branch)??null,u=(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??u,upstreamStatus:r.upstreamStatus??h,ahead:r.ahead??c,behind:r.behind??d,dirty:r.dirty??o,hasConflicts:r.hasConflicts??i}}function rj(e,t){const r=sj(e,t);return r?{...r,defaultBranch:r.defaultBranch??t}:null}function nj(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function aj(e){var d,m,u;const{nodeStatus:t,expectedSubmodulePaths:r,refreshedAtMs:n}=e,a=[],o=t.machineLabel||t.nodeId,i=t.git;if(!i){if(wm(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"||((d=t.connection)==null?void 0:d.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((u=t.connection)==null?void 0:u.state)!=="self"&&n!==null&&typeof i.lastCheckedAt=="number"&&n-i.lastCheckedAt>Ww&&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 oj(e){const t=bm(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??Yw(t.nodes),a=zw(t.refreshedAt),o=new Set(t.nodes.flatMap(M=>{var A;return(((A=M.git)==null?void 0:A.submodules)??[]).map(W=>W.path)})),i=[],c=[],d=Zw(t),m=new Map;for(const M of t.nodes){const A=M.git,W=(A==null?void 0:A.branch)??null,_=Vw(A),R=jm(A)||_==="dirty",O=Xw(M,n),L=rj(M,n),E=aj({nodeStatus:M,expectedSubmodulePaths:o,refreshedAtMs:a}),$=typeof M.clonedFromNodeId=="string"?M.clonedFromNodeId:null,F=Gw(M),X={id:M.nodeId,type:O.length>0?"orphanNode":"worktreeNode",label:M.machineLabel||M.nodeId.slice(0,8),workspace:M.workspace,branch:W,upstream:(A==null?void 0:A.upstream)??null,upstreamStatus:(A==null?void 0:A.upstreamStatus)??null,daemonId:ym(M),machineId:vm(M),machineLabel:M.machineLabel||null,locality:Kw(M),health:Ja([M.health,_]),ahead:(A==null?void 0:A.ahead)??0,behind:(A==null?void 0:A.behind)??0,dirty:R,dirtyFiles:qw(A),hasConflicts:(A==null?void 0:A.hasConflicts)??!1,activeSessionCount:F.length,activeSessions:F.map(ee=>ee.sessionId),sessionDetails:F,providers:M.providers??[],isOrphan:O.length>0,orphanReasons:O,error:M.error,nextStepHint:E.snapshotWarnings[0]??O[0]??(L==null?void 0:L.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:$,worktreeBranch:M.worktreeBranch??null,submodulePath:null,submoduleCommit:(A==null?void 0:A.headCommit)??null,outOfSync:Ci(A),snapshotCompleteness:E.snapshotCompleteness,snapshotWarnings:E.snapshotWarnings,branchConvergence:L,source:M};if(i.push(X),W){const ee=m.get(W)??[];ee.push(X.id),m.set(W,ee)}for(const ee of(A==null?void 0:A.submodules)??[]){const ne=`${X.id}::submodule::${ee.path}`,Z=ee.path.split("/").filter(Boolean).pop()||ee.path;i.push({id:ne,type:"submoduleNode",label:Z,workspace:ee.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:X.daemonId,machineId:X.machineId,machineLabel:X.machineLabel,locality:X.locality,health:nj(ee),ahead:0,behind:0,dirty:ee.dirty,dirtyFiles:ee.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],error:ee.error,nextStepHint:ee.error||(ee.outOfSync?`${ee.path} is out of sync with the parent checkout`:ee.dirty?`${ee.path} has local changes`:`${ee.path} is in sync with the parent checkout`),parentNodeId:X.id,submodulePath:ee.path,submoduleCommit:ee.commit,outOfSync:ee.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:X.id,parentWorkspace:M.workspace,submodule:ee}}),c.push({id:`${X.id}--${ne}`,source:X.id,target:ne,type:"submoduleLink",label:ee.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const u=n?`__branch_${n}`:null;if(u&&n){const A=(m.get(n)??[]).map($=>i.find(F=>F.id===$)).filter(Boolean),W=A.map($=>$.branchConvergence).filter(Boolean),_=Qw(t),R=A.length>0&&A.every($=>ej($,n)),O=(_==null?void 0:_.length)===0&&R?tj(n,A):W.length>0?Jw(W):null,L=(_==null?void 0:_.length)===0&&R?0:W.filter($=>$.needsConvergence).length,E={id:u,type:"defaultBranchNode",label:n,workspace:t.repoIdentity,branch:n,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:"default branch",locality:"unknown",health:Ja(A.map($=>$.health)),ahead:0,behind:0,dirty:A.some($=>$.dirty),dirtyFiles:A.reduce(($,F)=>$+F.dirtyFiles,0),hasConflicts:A.some($=>$.hasConflicts),activeSessionCount:A.reduce(($,F)=>$+F.activeSessionCount,0),activeSessions:A.flatMap($=>$.activeSessions),sessionDetails:A.flatMap($=>$.sessionDetails),providers:[...new Set(A.flatMap($=>$.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:L>0?`${L} 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:O,source:{nodeId:u,machineLabel:n,workspace:t.repoIdentity,health:Ja(A.map($=>$.health)),providers:[],activeSessions:[],activeSessionDetails:[]}};i.push(E);for(const $ of i)if(!($.id===u||$.type==="submoduleNode")){if($.branch===n){c.push({id:`${u}--${$.id}`,source:u,target:$.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if($.branch){c.push({id:`${u}--${$.id}`,source:u,target:$.id,type:$.isOrphan?"orphanLink":"parentBranch",label:$.branch,direction:"undirected"});continue}$.isOrphan&&c.push({id:`${u}--${$.id}`,source:u,target:$.id,type:"orphanLink",label:"detached",direction:"undirected"})}}for(const[M,A]of m){if(A.length<2)continue;const W=A.map(_=>i.find(R=>R.id===_)).filter(Boolean);W.sort((_,R)=>_.label.localeCompare(R.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?`${M} peers`:void 0,direction:"undirected"})}const h=new Set(i.map(M=>M.id)),p=new Set;for(const M of i){if(!M.clonedFromNodeId||M.type==="submoduleNode"||!h.has(M.clonedFromNodeId))continue;const A=`clone_${M.clonedFromNodeId}--${M.id}`;if(p.has(A))continue;p.add(A);const W=M.worktreeBranch??M.branch??void 0;c.push({id:A,source:M.clonedFromNodeId,target:M.id,type:"cloneLink",label:W?`cloned · ${W}`:"cloned",direction:"directed"})}const y=i.filter(M=>M.type!=="defaultBranchNode"),g=y.filter(M=>M.isOrphan).length,x=y.filter(M=>M.hasConflicts).length,k=y.filter(M=>M.health==="offline").length,S=y.filter(M=>M.type==="submoduleNode"&&M.outOfSync).length,f=y.filter(M=>{var A;return M.type!=="submoduleNode"&&((A=M.branchConvergence)==null?void 0:A.needsConvergence)}).length,v=y.filter(M=>{var A;return((A=M.branchConvergence)==null?void 0:A.status)==="blocked_review"}).length,j=y.filter(M=>{var A;return((A=M.branchConvergence)==null?void 0:A.status)==="pushed_feature_branch_needs_merge"}).length,w=y.filter(M=>{var A;return((A=M.branchConvergence)==null?void 0:A.status)==="cleanup_candidate"}).length,b=y.filter(M=>{var A;return((A=M.branchConvergence)==null?void 0:A.status)==="not_mergeable"}).length,C=y.filter(M=>M.snapshotWarnings.length>0).length,N=y.filter(M=>M.snapshotCompleteness==="pending_git").length,I=y.filter(M=>M.snapshotCompleteness==="missing_git").length,B=y.filter(M=>M.snapshotCompleteness==="missing_submodule_report").length,P=y.filter(M=>M.snapshotCompleteness==="stale").length,T=[N>0?`${N} node(s) are still waiting for a live peer git snapshot`:null,I>0?`${I} node(s) have no visible peer git snapshot`:null,B>0?`${B} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,P>0?`${P} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return f>0&&d.push(`${f} workspace(s) still need follow-up before the mesh is converged`),g>0&&d.push(`${g} workspace(s) need attention before safe coordination`),v>0&&d.push(`${v} workspace(s) are blocked on branch convergence or upstream sync`),j>0&&d.push(`${j} clean feature branch workspace(s) still need merge follow-up`),w>0&&d.push(`${w} worktree workspace(s) are ready for refine / cleanup`),b>0&&d.push(`${b} workspace(s) have local changes or conflicts blocking convergence`),x>0&&d.push(`${x} workspace(s) report merge conflicts`),k>0&&d.push(`${k} node(s) are currently offline`),S>0&&d.push(`${S} submodule(s) are out of sync with their parent checkout`),d.push(...T),n||d.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(M=>M.health==="online").length,dirtyNodes:y.filter(M=>M.dirty).length,orphanNodes:g,errorNodes:y.filter(M=>!!M.error||M.outOfSync).length,offlineNodes:k,followUpNodes:f,blockedReviewNodes:v,mergeReadyNodes:j,cleanupCandidateNodes:w,notMergeableNodes:b,incompleteSnapshotNodes:C,missingGitSnapshotNodes:I,missingSubmoduleSnapshotNodes:B,staleGitSnapshotNodes:P,totalActiveSessions:y.reduce((M,A)=>M+A.activeSessionCount,0)},warnings:d,snapshotWarnings:T}}const ij={recentFailures:0,taskCompleted:0,taskFailed:0,sessionLaunched:0},Ii=l.createContext(or("dark"));function Ge({label:e,tone:t="default"}){const r=l.useContext(Ii);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 dt({label:e,value:t}){const r=l.useContext(Ii);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 bc(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 Qa(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 wn(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 lj(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function cj(e){return e.startedAt||e.createdAt||null}function dj(e){const t=cj(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 uj(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function mj(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 hj(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 pj(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 fj(e){return e.assignedNodeId||e.targetNodeId||null}function gc(e){return e?e.slice(0,7):null}function xj(e,t){var o,i,c;const r=gc((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?[gc(a.commit),a.message].filter(Boolean).join(" · "):null}function bj(e,t){const r=xj(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function gj(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 yj(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 d=((c=e.selectedNodeStatus)==null?void 0:c.daemonId)||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}if(t&&e.selectedNodeStatus){const d=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}return null}function vj(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":hj(e.connection)}function yc(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 vc(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 wj(e){return e.direction==="directed"?"directed":"undirected"}function wc(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function jj(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,d,m,u,h,p,y,g,x,k,S,f,v,j,w,b,C,N,I,B,P;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)??"",((d=o.connection)==null?void 0:d.source)??"",o.health,o.gitProbePending?1:0,((m=o.git)==null?void 0:m.branch)??"",((u=o.git)==null?void 0:u.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)??"",((g=o.git)==null?void 0:g.headCommit)??"",((x=o.git)==null?void 0:x.staged)??"",((k=o.git)==null?void 0:k.modified)??"",((S=o.git)==null?void 0:S.untracked)??"",((f=o.git)==null?void 0:f.deleted)??"",((v=o.git)==null?void 0:v.renamed)??"",(j=o.git)!=null&&j.hasConflicts?1:0,((w=o.git)==null?void 0:w.lastCheckedAt)??"",((b=o.activeSessions)==null?void 0:b.join(","))??"",((C=o.activeSessionDetails)==null?void 0:C.length)??"",((N=o.activeSessionDetails)==null?void 0:N.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(","))??"",((I=o.providers)==null?void 0:I.join(","))??"",((B=o.providerPriority)==null?void 0:B.join(","))??"",o.error??"",(((P=o.git)==null?void 0:P.submodules)??[]).map(T=>[T.path,T.commit,T.dirty?1:0,T.outOfSync?1:0,T.error??""].join("/")).join(",")].join("|")})].join("::")}function Sm({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null}){var ue,Ae,q,be,ce;const{theme:a}=ar(),o=l.useMemo(()=>or(a),[a]),i=l.useMemo(()=>bm(e),[e]),c=l.useMemo(()=>jj(i),[i]),d=l.useMemo(()=>oj(i),[c]),[m,u]=l.useState(null),[h,p]=l.useState(null),[y,g]=l.useState(null),[x,k]=l.useState(null),[S,f]=l.useState({}),[v,j]=l.useState(null),[w,b]=l.useState(null),C=l.useMemo(()=>new Map(i.nodes.map(K=>[K.nodeId,K])),[i.nodes]),N=l.useMemo(()=>new Map(d.nodes.map(K=>[K.id,K])),[d.nodes]),I=((ue=i.queue)==null?void 0:ue.summary)??null,B=((Ae=i.ledger)==null?void 0:Ae.summary)??ij,P=l.useMemo(()=>pj(i),[i]),T=l.useMemo(()=>{const K=new Map;for(const ae of P){const de=wn(ae.session);K.set(de,(K.get(de)??0)+1)}return[...K.entries()].sort((ae,de)=>de[1]-ae[1])},[P]);l.useEffect(()=>{m&&(N.has(m)||(u(null),k(K=>!K||"nodeId"in K&&K.nodeId===m?null:K)))},[N,m]);const M=m?C.get(m)??null:null,A=wc(d,m),W=wc(d,h),_=y?d.edges.find(K=>K.id===y)??null:null,R=_?d.nodes.find(K=>K.id===_.source)??null:null,O=_?d.nodes.find(K=>K.id===_.target)??null:null;l.useEffect(()=>{var K,ae,de;if(m)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:i.meshId,selectedNodeId:m,canonicalNode:Ow(M),graphNode:A?{id:A.id,branch:A.branch,upstream:A.upstream,headCommit:A.submoduleCommit,submoduleCount:((ae=(K=M==null?void 0:M.git)==null?void 0:K.submodules)==null?void 0:ae.length)??0,snapshotCompleteness:A.snapshotCompleteness,snapshotWarnings:A.snapshotWarnings,branchConvergence:((de=A.branchConvergence)==null?void 0:de.status)??null}:null})}catch{}},[i.meshId,A,m,M]);const L=(x==null?void 0:x.kind)==="session"?P.find(K=>K.nodeId===x.nodeId&&K.session.sessionId===x.sessionId)??null:null,E=l.useMemo(()=>P.filter(K=>K.nodeId===m),[m,P]),$=yj({coordinatorDaemonId:r,selectedNodeStatus:M,selectedSessionEntry:L}),F=($==null?void 0:$.workspace)??null,X=F?S[F]??null:null,ee=bj(M,(X==null?void 0:X.entries)??[]),ne=(A==null?void 0:A.daemonId)??(M==null?void 0:M.daemonId)??r??null,Z=!!(A&&n&&ne&&A.type!=="submoduleNode"&&A.behind>0&&A.ahead===0&&A.dirtyFiles===0&&!A.dirty&&!A.hasConflicts&&A.upstreamStatus==="fresh"),ge=l.useCallback(()=>{u(null),k(null),j(null)},[]);l.useEffect(()=>{j(null)},[m]);const Ne=l.useCallback(async()=>{if(!(!A||!ne||!n||!Z)){b(A.id),j(null);try{const K=await n(ne,"fast_forward_mesh_node",{meshId:i.meshId,nodeId:A.id,dryRun:!0,execute:!1});if(j({phase:"dry_run",code:typeof(K==null?void 0:K.code)=="string"?K.code:void 0,error:typeof(K==null?void 0:K.operationError)=="string"?K.operationError:null,executed:(K==null?void 0:K.executed)===!0}),!(K!=null&&K.success)||K.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${A.label}?`))return;const de=await n(ne,"fast_forward_mesh_node",{meshId:i.meshId,nodeId:A.id,dryRun:!1,execute:!0});j({phase:"execute",code:typeof(de==null?void 0:de.code)=="string"?de.code:void 0,error:typeof(de==null?void 0:de.operationError)=="string"?de.operationError:null,executed:(de==null?void 0:de.executed)===!0})}catch(K){j({phase:"dry_run",error:K instanceof Error?K.message:"fast-forward failed"})}finally{b(null)}}},[Z,i.meshId,A,ne,n]);l.useEffect(()=>{if(!A)return;const K=ae=>{ae.key==="Escape"&&ge()};return window.addEventListener("keydown",K),()=>window.removeEventListener("keydown",K)},[ge,A]),l.useEffect(()=>{if(!$||!n)return;const{daemonId:K,workspace:ae}=$,de=S[ae];if(de!=null&&de.loading||de&&(de.entries.length>0||de.error))return;let le=!1;return f(se=>{var J;return{...se,[ae]:{loading:!0,error:null,entries:((J=se[ae])==null?void 0:J.entries)??[]}}}),n(K,"git_log",{workspace:ae,limit:5}).then(se=>{le||f(J=>({...J,[ae]:{loading:!1,error:null,entries:gj(se)}}))}).catch(se=>{le||f(J=>({...J,[ae]:{loading:!1,error:se instanceof Error?se.message:"git_log failed",entries:[]}}))}),()=>{le=!0}},[S,$,n]);const V=[...d.warnings??[],...i.nodes.filter(K=>K.machineStatus&&K.machineStatus!=="online").map(K=>`${K.machineLabel}: ${K.machineStatus}`)],ve=d.stats.incompleteSnapshotNodes>0,xe=d.stats.followUpNodes>0?`${d.stats.followUpNodes} need follow-up`:ve?"mesh visibility incomplete":"mesh converged",ye=d.stats.followUpNodes>0?"danger":ve?"warn":"good";return s.jsx(Ii.Provider,{value:o,children:s.jsx("div",{className:"flex min-h-0 flex-1 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(Ge,{label:xe,tone:ye}),d.stats.blockedReviewNodes>0&&s.jsx(Ge,{label:`${d.stats.blockedReviewNodes} blocked review`,tone:"danger"}),d.stats.notMergeableNodes>0&&s.jsx(Ge,{label:`${d.stats.notMergeableNodes} not mergeable`,tone:"danger"}),d.stats.mergeReadyNodes>0&&s.jsx(Ge,{label:`${d.stats.mergeReadyNodes} need merge`,tone:"warn"}),d.stats.cleanupCandidateNodes>0&&s.jsx(Ge,{label:`${d.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),d.stats.offlineNodes>0&&s.jsx(Ge,{label:`${d.stats.offlineNodes} offline`,tone:"danger"}),d.stats.incompleteSnapshotNodes>0&&s.jsx(Ge,{label:`${d.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),d.stats.missingGitSnapshotNodes>0&&s.jsx(Ge,{label:`${d.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),d.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Ge,{label:`${d.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),d.stats.staleGitSnapshotNodes>0&&s.jsx(Ge,{label:`${d.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((I==null?void 0:I.active)??0)>0&&s.jsx(Ge,{label:`${(I==null?void 0:I.active)??0} active queue`,tone:"info"}),s.jsx(Ge,{label:`${d.stats.totalNodes} nodes`,tone:"default"}),d.stats.totalActiveSessions>0&&s.jsx(Ge,{label:`${d.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(Ge,{label:`${d.stats.dirtyNodes} dirty`,tone:d.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Ge,{label:`${d.stats.orphanNodes} orphan`,tone:d.stats.orphanNodes>0?"warn":"good"}),s.jsx(Ge,{label:`${B.recentFailures} recent failures`,tone:B.recentFailures>0?"danger":"good"}),T.length===0?s.jsx(Ge,{label:"no session metadata"}):T.slice(0,2).map(([K,ae])=>s.jsx(Ge,{label:`${ae} ${K}`,tone:Qa(K)},K))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ge,{label:"Anchor = default branch",tone:"info"}),s.jsx(Ge,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Ge,{label:"Submodule link = child checkout",tone:"warn"})]}),V.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:V.map(K=>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:K},K))}),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."})]})]})]}),d.nodes.length>0?s.jsx(Nw,{data:d,selectedNodeId:m,onNodeHoverChange:K=>{p((K==null?void 0:K.id)??null),K&&g(null)},onEdgeHoverChange:K=>{g((K==null?void 0:K.id)??null),K&&p(null)},onNodeClick:K=>{if((x==null?void 0:x.kind)==="node"&&m===K.id){u(null),k(null);return}u(K.id),k({kind:"node",nodeId:K.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(Ge,{label:"hover preview",tone:"info"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[s.jsx(Ge,{label:W.health,tone:bc(W.health)}),W.branch&&s.jsx(Ge,{label:W.branch,tone:"default"}),W.ahead>0&&s.jsx(Ge,{label:`ahead ${W.ahead}`,tone:"warn"}),W.behind>0&&s.jsx(Ge,{label:`behind ${W.behind}`,tone:"warn"}),W.dirtyFiles>0&&s.jsx(Ge,{label:`${W.dirtyFiles} dirty`,tone:"warn"}),W.activeSessionCount>0&&s.jsx(Ge,{label:`${W.activeSessionCount} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[s.jsx(dt,{label:"Machine",value:W.machineLabel??"not reported"}),s.jsx(dt,{label:"Locality",value:W.locality}),s.jsx(dt,{label:"Workspace",value:W.workspace}),s.jsx(dt,{label:"Upstream",value:W.upstream??"none"}),s.jsx(dt,{label:"Dirty/ahead/behind",value:`${W.dirtyFiles} dirty · ↑${W.ahead}/↓${W.behind}`}),s.jsx(dt,{label:"Source",value:yc(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||vc(_)}),s.jsx("div",{className:`mt-1 text-[11px] ${o.textMuted}`,children:_.id})]}),s.jsx(Ge,{label:"hover preview",tone:"info"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[s.jsx(Ge,{label:vc(_),tone:"default"}),s.jsx(Ge,{label:wj(_),tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs",children:[s.jsx(dt,{label:"From",value:(R==null?void 0:R.label)??_.source}),s.jsx(dt,{label:"To",value:(O==null?void 0:O.label)??_.target}),s.jsx(dt,{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:ge,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:K=>K.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:()=>{Ne()},disabled:!Z||w===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:w===A.id?"Checking":"Heal"}),s.jsx("button",{type:"button",onClick:ge,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(Ge,{label:(M==null?void 0:M.health)??A.health,tone:bc((M==null?void 0:M.health)??A.health)}),A.branch&&s.jsx(Ge,{label:A.branch,tone:"default"}),A.ahead>0&&s.jsx(Ge,{label:`ahead ${A.ahead}`,tone:"warn"}),A.behind>0&&s.jsx(Ge,{label:`behind ${A.behind}`,tone:"warn"}),A.dirtyFiles>0&&s.jsx(Ge,{label:`${A.dirtyFiles} dirty`,tone:"warn"}),(M==null?void 0:M.connection)&&s.jsx(Ge,{label:vj(M),tone:mj(M.connection)}),E.length>0&&s.jsx(Ge,{label:`${E.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[s.jsx(dt,{label:"Machine",value:A.machineLabel??"not reported"}),s.jsx(dt,{label:"Locality",value:A.locality}),s.jsx(dt,{label:"Machine id",value:A.machineId??(M==null?void 0:M.machineId)??"not reported"}),s.jsx(dt,{label:"Daemon id",value:A.daemonId??(M==null?void 0:M.daemonId)??"not reported"}),s.jsx(dt,{label:"Workspace",value:(M==null?void 0:M.workspace)??A.workspace}),s.jsx(dt,{label:"Branch",value:A.branch??"unknown"}),s.jsx(dt,{label:"HEAD",value:ee??(M!=null&&M.gitProbePending?"Pending live git probe":"not reported")}),s.jsx(dt,{label:"Upstream",value:A.upstream??"none"}),s.jsx(dt,{label:"Dirty/ahead/behind",value:`${A.dirtyFiles} dirty · ↑${A.ahead}/↓${A.behind}`}),s.jsx(dt,{label:"Source",value:String(((q=M==null?void 0:M.connection)==null?void 0:q.source)??yc(A))}),s.jsx(dt,{label:"Transport",value:((be=M==null?void 0:M.connection)==null?void 0:be.transport)??"unknown"}),s.jsx(dt,{label:"Sessions",value:E.length>0?E.map(K=>wn(K.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(K=>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:K.session.sessionId,children:uj(K.session.sessionId)}),s.jsx(Ge,{label:wn(K.session),tone:Qa(wn(K.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:K.session.providerType||"provider unknown"}),s.jsx("span",{children:lj(K.session)}),s.jsx("span",{children:dj(K.session)})]}),K.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${o.textMuted}`,children:K.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${o.textMuted}`,title:K.session.workspace||K.workspace,children:[(K.session.workspace||K.workspace).slice(0,42),K.branch?` · ${K.branch}`:""]})]},K.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(dt,{label:"Completed",value:String(B.taskCompleted)}),s.jsx(dt,{label:"Failed",value:s.jsx("span",{className:B.taskFailed>0?o.isDark?"text-rose-300":"text-rose-600":"",children:B.taskFailed})}),s.jsx(dt,{label:"Launched",value:String(B.sessionLaunched)}),s.jsx(dt,{label:"Recent failures",value:s.jsx("span",{className:B.recentFailures>0?o.isDark?"text-amber-300":"text-amber-600":"",children:B.recentFailures})})]})]}),(()=>{var de,le;const K=((de=i.queue)==null?void 0:de.tasks)??((le=i.queue)==null?void 0:le.items)??null;if(!Array.isArray(K)||K.length===0)return null;const ae=K.filter(se=>fj(se)===m).slice(0,3);return ae.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:ae.map(se=>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:se.id.slice(0,12)}),s.jsx(Ge,{label:se.status??"unknown",tone:Qa(se.status)})]}),se.message&&s.jsx("div",{className:`mt-0.5 truncate ${o.textMuted}`,children:se.message.slice(0,48)})]},se.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]})]}),((ce=A.branchConvergence)==null?void 0:ce.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})]}),v&&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:v.phase==="execute"?"Heal result":"Heal preview"}),s.jsx("div",{className:"mt-1",children:v.code??v.error??"No result code returned."})]})]})})]})})})})}function wt(e){return typeof e=="string"?e.trim():""}function Do(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Mi(...e){const t=new Set;for(const r of e){const n=wt(r);n&&t.add(n)}return[...t]}function kj(e,t){var h,p;const r=Do(e==null?void 0:e.settings),n=wt((h=e==null?void 0:e.coordinator)==null?void 0:h.meshId)||wt(r.meshCoordinatorFor),a=wt(r.meshNodeFor),o=!!n||!!a,i=n===t||a===t;if(o&&!i)return null;const c=Do(e==null?void 0:e.activeChat),d=Mi(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=d[0]||"";if(!m)return null;const u=n===t?wt((p=e==null?void 0:e.coordinator)==null?void 0:p.role)||"coordinator":a===t?wt(r.meshNodeRole)||"worker":wt(e==null?void 0:e.role)||wt(r.meshNodeRole)||void 0;return{sessionId:m,aliases:d,meshId:t,nodeId:i&&wt(r.meshNodeId)||null,providerType:wt(e==null?void 0:e.providerType)||void 0,state:wt(e==null?void 0:e.status)||void 0,chatStatus:wt(c.status)||void 0,lifecycle:wt(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:wt(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:wt(e==null?void 0:e.runtimeRecoveryState)||void 0,...u?{role:u}:{},...i?{isSelfCoordinator:n===t}:{},workspace:wt(e==null?void 0:e.workspace)||null}}function Nm(e,t){var n;return t?(Array.isArray((n=e.status)==null?void 0:n.sessions)?e.status.sessions:[]).map(a=>kj(a,t)).filter(a=>a!==null):[]}function ra(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function Sj(e,t){const r=new Set(ra(t));return ra(e).some(n=>r.has(n))}function Nj(e,t){const r=t.filter(a=>!!a);return r.length===0?e:[...e.filter(a=>!r.some(o=>Sj(a,o))),...r]}function Cj(e,t){if(t.length===0)return e;const r=new Map;for(const o of t)for(const i of ra(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 u=Mi(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=u[0]||"";if(!h)continue;const p=u.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)ra(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 d=[...c.values()];return d.length===0?o:{...o,activeSessionDetails:d,activeSessions:d.map(m=>m.sessionId)}});return n?{...e,nodes:a}:e}function Ij(e,t){const n=Nm(e,t).map(a=>{var d;const o=(Array.isArray((d=e.status)==null?void 0:d.sessions)?e.status.sessions:[]).find(m=>wt(m==null?void 0:m.id)===a.sessionId),i=Do(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??"",wt(i.status)||wt(i.kind)||wt(i.type),a.nodeId??"",a.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(a=>!!a).sort();return n.length>0?n.join(`
|
|
75
75
|
`):null}function Cm({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=es.subscribe({sendData:n},t,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${t}`,params:{includeSessions:!0}},u=>{if(u.topic!=="daemon.metadata")return;const h=Ij(u,r);h!==c.current&&(c.current=h,i(Nm(u,r)))});return()=>{m()}},[t,r,n]);const d=l.useMemo(()=>Nj(o,a),[a,o]);return l.useMemo(()=>e?Cj(e,d):null,[d,e])}const jn=new Map;function Mj(e,t){return!e||!t?null:`${e}::${t}`}function Aj(e,t){var o,i,c,d;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((d=e.settings)==null?void 0:d.meshNodeId)=="string"?e.settings.meshNodeId:null;return{sessionId:e.sessionId,aliases:Mi(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 Tj({activeConv:e,sendDaemonCommand:t,onClose:r}){var _,R,O,L,E,$;const n=((_=e.coordinator)==null?void 0:_.meshId)??(typeof((R=e.settings)==null?void 0:R.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),a=e.daemonId??null,o=Mj(a,n),i=o?jn.get(o)??null:null,c=Lu(),{sendData:d}=ht(),{theme:m}=ar(),u=l.useMemo(()=>or(m),[m]),h=l.useMemo(()=>Aj(e,n),[e.agentType,(O=e.coordinator)==null?void 0:O.meshId,e.sessionId,(L=e.settings)==null?void 0:L.meshCoordinatorFor,(E=e.settings)==null?void 0:E.meshNodeFor,($=e.settings)==null?void 0:$.meshNodeId,e.status,e.workspacePath,n]),[p,y]=l.useState(i),[g,x]=l.useState(!1),[k,S]=l.useState(!1),[f,v]=l.useState(null),[j,w]=l.useState((i==null?void 0:i.refreshedAt)??null),b=l.useRef(i!==null),C=l.useRef(!1),N=l.useRef(!1),I=l.useRef(!0);l.useEffect(()=>{b.current=p!==null},[p]),l.useEffect(()=>{const F=o?jn.get(o)??null:null;y(F),w((F==null?void 0:F.refreshedAt)??null),b.current=F!==null,N.current=!1,S(!1),v(null)},[o]);const B=l.useCallback(async(F=!1)=>{if(!a||!n){v("This coordinator does not expose a live mesh id."),y(null);return}if(C.current){F&&(N.current=!0);return}if(!F&&o){const ee=jn.get(o);if(ee){y(ee),w(ee.refreshedAt||null),b.current=!0,x(!1),v(null);return}}C.current=!0;const X=!b.current;x(X),S(F&&b.current),v(null);try{const ee=c!=null&&c.loadMeshStatus?await c.loadMeshStatus(a,n,{refresh:F,retryProfile:F?"settled":"interactive"}):await t(a,"mesh_status",{meshId:n,refresh:F}),ne=gm(ee);if(!ne){v("mesh_status returned an unexpected payload.");return}o&&jn.set(o,ne),y(ne),b.current=!0,w(ne.refreshedAt||new Date().toISOString())}catch(ee){v(ee instanceof Error?ee.message:"Failed to load live mesh status")}finally{C.current=!1,x(!1),S(!1),N.current&&I.current&&(N.current=!1,window.setTimeout(()=>{I.current&&B(!0)},0))}},[o,a,n,c,t]);l.useEffect(()=>(I.current=!0,B(!1),()=>{I.current=!1}),[B]),l.useEffect(()=>{const F=X=>{X.key==="Escape"&&r()};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[r]);const P=(p==null?void 0:p.meshName)||n||"Repo Mesh",T=l.useMemo(()=>h?[h]:[],[h]),M=Cm({status:p,daemonId:a,meshId:n,sendData:d,extraLiveSessions:T}),A=j?new Date(j).toLocaleTimeString():null,W=l.useMemo(()=>g?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[g]);return s.jsx("div",{className:u.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:u.dialogShellClass,onClick:F=>F.stopPropagation(),children:[s.jsxs("div",{className:u.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(is,{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:u.dialogTitleClass,children:P}),s.jsx("span",{className:u.dialogKickerClass,children:"Mesh observability"})]}),s.jsxs("p",{className:u.dialogSubtitleClass,children:[mt(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:u.dialogRefreshedChipClass,children:k?"Refreshing mesh...":`Refreshed ${A}`}),!k&&p&&s.jsx("span",{className:u.dialogRefreshedChipClass,children:d&&!f?"Live daemon metadata":"Metadata subscription unavailable"}),s.jsx("button",{type:"button",onClick:()=>{B(!0)},disabled:g||k,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:g||k?"Refreshing...":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:u.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:s.jsx(Nt,{size:16})})]})]}),f&&s.jsx("div",{className:u.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:u.dialogBodyClass,children:M?s.jsx(Sm,{status:M,emptyMessage:W,daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:u.dialogEmptyClass,children:W})})]})})}function _j(e,t){const{sendCommand:r}=ht(),[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(d=>{const m=(d==null?void 0:d.result)??d;a(typeof(m==null?void 0:m.remoteUrl)=="string"?m.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>i(!1))},[e,t,r]);const c=Lj(n);return{remoteUrl:n,githubUrl:c,loading:o}}function Lj(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 Im=5e3;function Pj(e){return`git:${e}`}function Rj({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Im}){return{type:"subscribe",topic:"workspace.git",key:Pj(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function Ai(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Ls(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 Dj(e){const t=Ai(e);return(t==null?void 0:t.success)===!1?{status:null,error:Ls(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Ls(t,"Git status response did not include status")}}function $j(e){const t=Ai(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Ls(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Ls(t,"Git diff summary response did not include diffSummary")}}function Za(e){return e===void 0||typeof e=="boolean"}function Ej(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Za(t.binary)&&Za(t.truncated)&&Za(t.staged)}function Bj(e){const t=Ai(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Ls(t,"Git file diff request failed")}:Ej(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Ls(t,"Git file diff response did not include a valid diff object")}}function Oj({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Im}){const{sendCommand:o,sendData:i}=ht(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[m,u]=l.useState(null),[h,p]=l.useState(null),[y,g]=l.useState(!1),[x,k]=l.useState(null),S=l.useCallback(async()=>{if(!(!d||!e||!c)){g(!0),k(null);try{const v=Dj(await o(e,"git_status",{workspace:c}));if(v.error){u(null),p(null),k(v.error);return}if(u(v.status),!n){p(null);return}const j=$j(await o(e,"git_diff_summary",{workspace:c}));if(j.error){p(null),k(j.error);return}p(j.diffSummary)}catch(v){k(Ls(v,"Git status request failed"))}finally{g(!1)}}},[d,e,n,o,c]),f=l.useMemo(()=>c?Rj({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return l.useEffect(()=>{if(!d||!e||!c||!f){u(null),p(null),g(!1),k(null);return}const v=i?es.subscribe({sendData:i},e,f,j=>{var w,b;j.workspace===c&&(u(j.status),p(j.diffSummary??null),k(((w=j.status)==null?void 0:w.error)||((b=j.diffSummary)==null?void 0:b.error)||null),g(!1))},{retryIntervalMs:1e3}):null;return S(),()=>{v==null||v()}},[d,e,S,f,i,c]),{status:m,diffSummary:h,loading:y,error:x,refresh:S}}const Fj={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},Hj={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 jc(e){return e.split("/").pop()??e}function Wj(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function Kj({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=Fj[o.status]??"?",d=Hj[o.status]??"text-zinc-400",m=Wj(o.path),u=jc(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 ${d}`,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:u}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",jc(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 Uj(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 zj({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(`
|
|
76
76
|
`);return s.jsxs("div",{ref:i,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((d,m)=>Uj(d,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 Gj(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(`
|
|
77
77
|
`)}function Mm({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=ht(),{status:a,diffSummary:o,loading:i,error:c,refresh:d}=Oj({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=l.useState(null),[h,p]=l.useState(null),[y,g]=l.useState(""),[x,k]=l.useState(!1),[S,f]=l.useState(!1),[v,j]=l.useState(null),[w,b]=l.useState(null),{githubUrl:C}=_j(e,t),N=l.useCallback(async A=>{if(!((m==null?void 0:m.path)===A.path&&!m.loading)){u({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}),_=Bj(W);if(_.error||!_.diff){u({path:A.path,diff:"",binary:!1,truncated:!1,loading:!1,error:_.error??"Failed to load diff"});return}u({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";u({path:A.path,diff:"",binary:!1,truncated:!1,loading:!1,error:_})}}},[e,n,m,t]),I=l.useCallback(A=>{g(""),k(!1),j(null),b(null),p(A)},[]),B=l.useCallback(()=>{p(null),j(null),f(!1)},[]),P=l.useCallback(async()=>{var A,W,_;if(h){f(!0),j(null);try{let R;h==="checkpoint"?R=await n(e,"git_checkpoint",{workspace:t,message:y,includeUntracked:x}):h==="stash"?R=await n(e,"git_stash_push",{workspace:t,message:y,includeUntracked:x}):h==="stash_pop"?R=await n(e,"git_stash_pop",{workspace:t}):h==="checkout_files"&&m&&(R=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const O=(R==null?void 0:R.result)??R;if((O==null?void 0:O.success)===!1||O!=null&&O.error){j((O==null?void 0:O.error)??"Action failed"),f(!1);return}h==="checkpoint"?b(`Checkpoint created: ${((W=(A=O==null?void 0:O.checkpoint)==null?void 0:A.commit)==null?void 0:W.slice(0,7))??"done"}`):h==="stash"?b(`Stashed as ${((_=O==null?void 0:O.stash)==null?void 0:_.stashRef)??"stash@{0}"}`):h==="stash_pop"?b("Stash restored"):(b("File reverted"),u(null)),p(null),await d()}catch(R){j(R instanceof Error?R.message:"Action failed")}finally{f(!1)}}},[h,n,e,t,y,x,m,d]),T=!!(a!=null&&a.hasConflicts),M=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}),C&&s.jsx("a",{href:`${C}/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:d,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(Nt,{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"}),M===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(Kj,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:N}),!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(zj,{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"})})]}),w&&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:w}),s.jsx("button",{onClick:()=>b(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:()=>I("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:()=>I("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:()=>I("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:()=>I("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=Gj((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(A),b("Copied to clipboard"),setTimeout(()=>b(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=>g(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"]})]}),v&&s.jsx("p",{className:"text-xs text-red-400",children:v}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:B,disabled:S,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),s.jsx("button",{onClick:P,disabled:S||(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:S?"Working…":"Confirm"})]})]})})]})})}function Vj({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=l.useState(!1),[o,i]=l.useState(!1),[c,d]=l.useState(!1),[m,u]=l.useState(!1),[h,p]=l.useState(!1),[y,g]=l.useState("quickstart"),[x,k]=l.useState("workspace"),S=l.useMemo(()=>!t&&!e,[t,e]),f=l.useCallback(N=>{a(N),N&&i(!1)},[]),v=l.useCallback(N=>{i(N),N&&a(!1)},[]),j=l.useCallback(()=>{g(r===0?"quickstart":"shortcuts"),k("workspace"),d(!0),a(!1),i(!1)},[r]),w=l.useCallback(()=>{d(!1)},[]),b=l.useCallback(()=>{u(!0)},[]),C=l.useCallback(()=>{u(!1)},[]);return l.useEffect(()=>{if(!S){p(!1);return}p(!0);const N=window.setTimeout(()=>{p(!1)},1e4);return()=>window.clearTimeout(N)},[S]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:m,guideNudgeVisible:h,guideTab:y,shortcutSection:x,isDesktopDashboard:S,setGuideTab:g,setShortcutSection:k,handleInboxOpenChange:f,handleHiddenOpenChange:v,handleOpenShortcutHelp:j,closeShortcutHelp:w,openNewSession:b,closeNewSession:C}}function qj(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 Yj(e){return e instanceof Error?e.message:String(e||"")}function Xj(e){const t=Yj(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Jj({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:i,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:h,ides:p,actionLogs:y,sendDaemonCommand:g,setActionLogs:x,setCliViewModeOverrides:k,isStandalone:S,initialDataLoaded:f,userName:v,requestedMobileTabKey:j,onRequestedMobileTabConsumed:w,requestedMachineId:b,onRequestedMachineConsumed:C,requestedMobileSection:N,onRequestedMobileSectionConsumed:I,containerRef:B,isSplitMode:P,numGroups:T,groupSizes:M,groupedConvs:A,clearedTabs:W,focusedGroup:_,focusGroup:R,moveTabToGroup:O,splitTabRelative:L,closeGroup:E,handleResizeStart:$,groupActiveTabIds:F,setGroupActiveTab:X,groupTabOrders:ee,setGroupTabOrder:ne,toggleHiddenTab:Z,visibleConversations:ge,requestedDesktopTabKey:Ne,onRequestedDesktopTabConsumed:V,onDesktopActiveTabChange:ve,onRequestScrollToBottom:xe,onHideConversation:ye,onShowHiddenConversation:ue,onShowAllHiddenConversations:Ae,scrollToBottomRequest:q,machineEntries:be,layoutProfile:ce,onBrowseMachineDirectory:K,onSaveMachineWorkspace:ae,onLaunchMachineIde:de,onLaunchMachineProvider:le,onListMachineMeshes:se,onLaunchMeshCoordinator:J,onListMachineSavedSessions:D,notifications:he,notificationUnreadCount:ke,liveSessionInboxState:Se,onMarkNotificationRead:re,onMarkNotificationUnread:De,onDeleteNotification:He}){const Be=St.useRef(null),{inboxOpen:Ce,hiddenOpen:rt,shortcutHelpOpen:st,newSessionOpen:Ze,guideNudgeVisible:et,guideTab:it,shortcutSection:gt,isDesktopDashboard:Tt,setGuideTab:Le,setShortcutSection:qe,handleInboxOpenChange:lt,handleHiddenOpenChange:Ye,handleOpenShortcutHelp:kt,closeShortcutHelp:U,openNewSession:z,closeNewSession:Y}=Vj({isMobile:t,showMobileChatMode:e,visibleConversationCount:ge.length}),[oe,me]=St.useState(null),[fe,H]=St.useState(null),G=St.useCallback((te,Ee)=>{me({daemonId:te,workspace:Ee})},[]),ie=St.useCallback(te=>{H(te)},[]),we=St.useCallback(te=>{var Ee;Br.flushSync(()=>{ue(te)}),(Ee=Be.current)==null||Ee.restoreHiddenTabToSavedLocation(te.tabKey)},[ue]),Pe=St.useCallback(te=>{var Ct;const Ee=u.find(_t=>ko(_t,te))||h.find(_t=>ko(_t,te));Ee&&(h.some(_t=>_t.tabKey===Ee.tabKey)&&we(Ee),ve(Ee.tabKey),(Ct=Be.current)==null||Ct.activateConversationTab(Ee.tabKey),xe(Ee.tabKey,"notification-open")),re(te.id),lt(!1)},[we,h,u,ve,re,xe]),Ie=St.useCallback(()=>{var Ee;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Ee=Be.current)==null||Ee.resetAllPanelsToMain(),Ye(!1))},[Ye]),Te=St.useCallback(async te=>{var ss;if(!r)return;const Ee=(ss=r.modalButtons)==null?void 0:ss[te];if(!Ee)return;const Ct=Ss(r);if(!Ct)return;const _t=Ee.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),ds=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(_t);try{await g(Ct,"resolve_action",{button:Ee,action:ds?"approve":"reject",buttonIndex:te,...ks(r)})}catch(rs){Xj(rs)||console.error("[Shortcut approval] Failed:",rs)}},[r,g]),{isMac:Oe,actionDefinitions:_e,actionShortcuts:ze,shortcutListening:Qe,shortcutListeningDraft:pt,setShortcutListening:jt,setShortcutListeningDraft:yt,saveShortcuts:vt}=ov({enabled:Tt&&!st,onTrigger:te=>{var Ee,Ct,_t,ds,ss,rs,Ds,$s,pe,Me,Re,We,Ve,Ke,ft,at;if(te==="openShortcutHelp"){kt();return}if(te==="openNewSession"){z();return}if(te==="hideCurrentTab"){r&&ye(r);return}if(te==="toggleHiddenTabs"){Ye(!rt);return}if(te==="openHistoryForActiveTab"){r&&!tt(r)&&o(r);return}if(te==="openRemoteForActiveTab"){r&&!nt(r)&&!tt(r)&&i(r);return}if(te==="splitActiveTabRight"){(Ee=Be.current)==null||Ee.splitActiveTabRight();return}if(te==="splitActiveTabDown"){(Ct=Be.current)==null||Ct.splitActiveTabDown();return}if(te==="floatActiveTab"){(_t=Be.current)==null||_t.floatActiveTab();return}if(te==="popoutActiveTab"){(ds=Be.current)==null||ds.popoutActiveTab();return}if(te==="dockActiveTab"){(ss=Be.current)==null||ss.dockActiveTab();return}if(te==="focusLeftPane"){(rs=Be.current)==null||rs.focusLeftPane();return}if(te==="focusRightPane"){(Ds=Be.current)==null||Ds.focusRightPane();return}if(te==="focusUpPane"){($s=Be.current)==null||$s.focusUpPane();return}if(te==="focusDownPane"){(pe=Be.current)==null||pe.focusDownPane();return}if(te==="moveActiveTabToLeftPane"){(Me=Be.current)==null||Me.moveActiveTabToLeftPane();return}if(te==="moveActiveTabToRightPane"){(Re=Be.current)==null||Re.moveActiveTabToRightPane();return}if(te==="moveActiveTabToUpPane"){(We=Be.current)==null||We.moveActiveTabToUpPane();return}if(te==="moveActiveTabToDownPane"){(Ve=Be.current)==null||Ve.moveActiveTabToDownPane();return}if(te==="triggerPrimaryApprovalAction"){Te(0);return}if(te==="triggerSecondaryApprovalAction"){Te(1);return}if(te==="triggerTertiaryApprovalAction"){Te(2);return}if(te==="setActiveTabShortcut"){(Ke=Be.current)==null||Ke.setShortcutForActiveTab();return}if(te==="selectPreviousGroupTab"){(ft=Be.current)==null||ft.activatePreviousTabInGroup();return}if(te==="selectNextGroupTab"){(at=Be.current)==null||at.activateNextTabInGroup();return}!r||!nt(r)||tt(r)||te==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),Fe=St.useCallback(()=>{U(),jt(null),yt([])},[U,jt,yt]),Et=St.useMemo(()=>gt==="all"?_e:_e.filter(te=>qj(te)===gt),[_e,gt]),Q=St.useCallback(()=>{const te=Object.fromEntries(_e.map(Ee=>[Ee.id,""]));vt(te)},[_e,vt]),$e=St.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const te=Object.fromEntries(_e.map(Ee=>[Ee.id,Ee.defaultShortcut]));vt(te)},[_e,vt]);return St.useEffect(()=>{const te=Ee=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Ee.metaKey&&Ee.key.toLowerCase()==="w":Ee.ctrlKey&&Ee.key.toLowerCase()==="w")&&(Ee.preventDefault(),r&&ye&&ye(r))};return window.addEventListener("keydown",te),()=>window.removeEventListener("keydown",te)},[r,ye]),St.useEffect(()=>{if(!st||Qe)return;const te=Ee=>{Ee.key==="Escape"&&(Ee.preventDefault(),Fe())};return window.addEventListener("keydown",te,!0),()=>window.removeEventListener("keydown",te,!0)},[Fe,st,Qe]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(qb,{activeConv:r,wsStatus:n,isConnected:a,conversations:ge,hiddenConversations:h,onOpenHistory:o,onHideConversation:ye,onShowConversation:we,onShowAllHidden:Ae,onResetPanelsToMain:Ie,notifications:he,notificationUnreadCount:ke,onOpenNotification:Pe,onMarkNotificationRead:re,onMarkNotificationUnread:De,onDeleteNotification:He,inboxOpen:Ce,onInboxOpenChange:lt,hiddenOpen:rt,onHiddenOpenChange:Ye,onOpenNewSession:t?void 0:z,onOpenDashboardGuide:kt,guideNudgeVisible:et,actionShortcuts:ze,onOpenRemote:()=>{!r||nt(r)||tt(r)||i(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:G,onOpenMeshGraph:ie}),e?s.jsx(q0,{conversations:u,hiddenConversations:h,ides:p,actionLogs:y,sendDaemonCommand:g,setActionLogs:x,setCliViewModeOverrides:k,isStandalone:S,userName:v,requestedActiveTabKey:j,onRequestedActiveTabConsumed:w,requestedMachineId:b,onRequestedMachineConsumed:C,requestedMobileSection:N,onRequestedMobileSectionConsumed:I,onOpenHistory:o,onOpenRemote:i,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Ae,onHideConversation:ye,onOpenMeshGraph:ie,onOpenNewSession:z,liveSessionInboxState:Se}):t?s.jsx(sv,{containerRef:B,isSplitMode:P,numGroups:T,groupSizes:M,groupedConvs:A,clearedTabs:W,ides:p,actionLogs:y,sendDaemonCommand:g,setActionLogs:x,isStandalone:S,hasRegisteredMachines:be.length>0,userName:v,focusedGroup:_,focusGroup:R,moveTabToGroup:O,splitTabRelative:L,closeGroup:E,handleResizeStart:$,groupActiveTabIds:F,setGroupActiveTab:X,groupTabOrders:ee,setGroupTabOrder:ne,toggleHiddenTab:Z,onOpenNewSession:z,allowTabShortcuts:!1,liveSessionInboxState:Se}):s.jsx(vv,{visibleConversations:ge,clearedTabs:W,ides:p,actionLogs:y,sendDaemonCommand:g,setActionLogs:x,isStandalone:S,hasRegisteredMachines:be.length>0,initialDataLoaded:f,userName:v,toggleHiddenTab:Z,actionShortcuts:ze,registerActionHandlers:te=>{Be.current=te},onActiveTabChange:ve,requestedActiveTabKey:Ne,onRequestedActiveTabConsumed:V,onRequestScrollToBottom:xe,scrollToBottomRequest:q,onOpenNewSession:z,liveSessionInboxState:Se,layoutProfile:ce}),Ze&&s.jsx(Tv,{machines:be,ides:p,onClose:Y,onBrowseDirectory:K,onSaveWorkspace:ae,onLaunchIde:de,onLaunchProvider:le,onListMeshes:se,onLaunchMeshCoordinator:J,onListSavedSessions:D}),fe&&s.jsx(Tj,{activeConv:fe,sendDaemonCommand:g,onClose:()=>H(null)}),oe&&s.jsx(Mm,{daemonId:oe.daemonId,workspace:oe.workspace,onClose:()=>me(null)}),st&&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:Fe,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:te=>te.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:Fe,"aria-label":"Close dashboard guide",children:s.jsx(Nt,{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(te=>s.jsx("button",{type:"button",className:`btn btn-sm ${it===te.id?"btn-primary":"btn-secondary"}`,onClick:()=>Le(te.id),children:te.label},te.id))}),it==="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 ",Oe?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),it==="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."]})]})]})]}),it==="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(te=>s.jsx("button",{type:"button",className:`btn btn-sm ${gt===te.id?"btn-primary":"btn-secondary"}`,onClick:()=>qe(te.id),children:te.label},te.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Q,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:$e,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Et.map(te=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Qe===te.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:te.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:te.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:te.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:Qe===te.id?pt.length>0?`${pt.join(" ")} ...`:"Listening...":ze[te.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{jt(te.id),yt([])},children:Qe===te.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Ee={...ze};Ee[te.id]="",vt(Ee)},children:"Disable"})]})]})},te.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Oe?"⌘⇧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 eo=[{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 Qj({onClose:e}){const[t,r]=l.useState(0),n=eo[t],a=t===eo.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(Nt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:eo.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:`
|