@adhdev/daemon-standalone 0.9.82-rc.57 → 0.9.82-rc.58

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.
@@ -61,7 +61,7 @@ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Mach
61
61
  <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>
62
62
  <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>
63
63
  </div>
64
- `,V.style.top="52px",V.style.height="calc(100% - 52px)";const Fe=Re.querySelector("[data-adhdev-popout-focus]");Fe&&(Fe.onclick=()=>{window.focus()});const Ue=Re.querySelector("[data-adhdev-popout-dock]");Ue&&(Ue.disabled=!te,Ue.style.opacity=te?"1":"0.5",Ue.style.cursor=te?"pointer":"default",Ue.onclick=()=>{var Le;te&&Ne(te),(Le=W.defaultView)==null||Le.focus()})}},[z,Ne]),ae=i.useCallback(G=>{var se;const U=k.current,X=U==null?void 0:U.getPanel(G);if(!(!U||!X)){X.group.model.openPanel(X),X.api.setActive(),ie(G,"dockview-shortcut");try{const W=X.group.model.location;W.type==="popout"?W.getWindow().focus():Aa((se=X.group.element)==null?void 0:se.ownerDocument)}catch{}}},[ie]),ue=i.useCallback(G=>{const U=k.current,X=U==null?void 0:U.activePanel,se=(U==null?void 0:U.activeGroup)||(X==null?void 0:X.group);if(!U||!X||!se)return;const W=se.panels||[];if(W.length<=1)return;const V=W.findIndex(ke=>ke.id===X.id);if(V<0)return;const te=(V+G+W.length)%W.length,re=W[te];re&&(re.group.model.openPanel(re),re.api.setActive(),Bt(re.id)||ie(re.id,"dockview-shortcut"))},[ie]),oe=i.useCallback(G=>{var Fe;const U=k.current,X=(U==null?void 0:U.activeGroup)||((Fe=U==null?void 0:U.activePanel)==null?void 0:Fe.group);if(!U||!X)return;const se=U.groups||[],W=se.find(Ue=>Ue.id===X.id);if(!W)return;const V=W.element.getBoundingClientRect(),te=V.left+V.width/2,re=V.top+V.height/2,ke=(Ue,Le,Qe,et)=>Math.max(0,Math.min(Le,et)-Math.max(Ue,Qe)),Ee=Ue=>{const Le=Ue.element.getBoundingClientRect(),Qe=Le.left+Le.width/2,et=Le.top+Le.height/2;let gt=0,yt=0,dt=0,ht=!1;if(G==="left"?(ht=Qe<te,gt=Math.max(0,V.left-Le.right),yt=Math.abs(et-re),dt=ke(V.top,V.bottom,Le.top,Le.bottom)):G==="right"?(ht=Qe>te,gt=Math.max(0,Le.left-V.right),yt=Math.abs(et-re),dt=ke(V.top,V.bottom,Le.top,Le.bottom)):G==="above"?(ht=et<re,gt=Math.max(0,V.top-Le.bottom),yt=Math.abs(Qe-te),dt=ke(V.left,V.right,Le.left,Le.right)):(ht=et>re,gt=Math.max(0,Le.top-V.bottom),yt=Math.abs(Qe-te),dt=ke(V.left,V.right,Le.left,Le.right)),!ht)return Number.POSITIVE_INFINITY;const Ve=dt>0?0:120;return gt*3+yt+Ve};let Oe=null,Re=Number.POSITIVE_INFINITY;for(const Ue of se){if(Ue.id===W.id)continue;const Le=Ee(Ue);Number.isFinite(Le)&&(Le>=Re||(Re=Le,Oe=Ue))}return Oe||void 0},[]),de=i.useCallback(G=>{var se;const U=oe(G);if(!U)return;const X=U.activePanel||U.panels[0];X&&(U.model.openPanel(X),X.api.setActive(),Bt(X.id)||ie(X.id,"dockview-focus"),Aa((se=U.element)==null?void 0:se.ownerDocument))},[oe,ie]),Q=i.useCallback((G,U)=>{const X=k.current,se=X==null?void 0:X.activePanel,W=(X==null?void 0:X.activeGroup)||(se==null?void 0:se.group);if(!X||!se||!W)return;let V=oe(G);!V&&(U!=null&&U.createGroupIfMissing)&&(V=X.addGroup({referenceGroup:W,direction:G})),V&&(se.api.moveTo({group:V,position:"center"}),se.group.model.openPanel(se),se.api.setActive(),Bt(se.id)||ie(se.id,U!=null&&U.createGroupIfMissing?"dockview-split":"dockview-move"))},[oe,ie]),{isMac:ve,tabShortcuts:le,shortcutListening:pe,setShortcutListening:ne,saveShortcuts:Ie}=Yd({sortedTabKeys:e.map(G=>G.tabKey),onFocus:me,onSelectTab:ae}),Ce=i.useCallback(()=>{var X;const G=k.current;if(!G)return;const U=G.activePanel;if(U){if(Bt(U.id)){const se=((X=U.params)==null?void 0:X.routeId)||U.id.slice(7),W=Ht(e,se);W!=null&&W.tabKey&&ne(W.tabKey);return}z.has(U.id)&&ne(U.id)}},[z,ae,ne,e]),_e=i.useCallback(G=>{const U=[];return G.metaKey&&U.push(ve?"⌘":"Meta"),G.ctrlKey&&U.push("Ctrl"),G.altKey&&U.push(ve?"⌥":"Alt"),G.shiftKey&&G.key.length!==1&&U.push(ve?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(G.key)?null:(U.push(Zd(G.key)),U.join("+"))},[ve]),K=i.useCallback(G=>{var U,X;switch(G){case"splitActiveTabRight":Q("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Q("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const se=xe();se&&he(se);return}case"popoutActiveTab":{const se=xe();se&&je(se);return}case"dockActiveTab":{const se=xe();if(!se)return;q(se)?Ne(se):we(se)&&Se(se);return}case"focusLeftPane":de("left");return;case"focusRightPane":de("right");return;case"focusUpPane":de("above");return;case"focusDownPane":de("below");return;case"moveActiveTabToLeftPane":Q("left");return;case"moveActiveTabToRightPane":Q("right");return;case"moveActiveTabToUpPane":Q("above");return;case"moveActiveTabToDownPane":Q("below");return;case"selectPreviousGroupTab":ue(-1);return;case"selectNextGroupTab":ue(1);return;case"setActiveTabShortcut":Ce();return;case"hideCurrentTab":{const se=(X=(U=k.current)==null?void 0:U.activePanel)==null?void 0:X.id;se&&!Bt(se)&&ge(se);return}default:return}},[ue,Se,de,he,xe,ge,we,q,Ne,Q,je,Ce]);i.useEffect(()=>{if(!C)return;const G=C.sourceDocument,U=G.defaultView??window,X=se=>{const W=G.querySelector("[data-dockview-tab-context-menu]");W&&W.contains(se.target)||I(null)};return U.addEventListener("mousedown",X,!0),U!==window&&window.addEventListener("mousedown",()=>I(null),!0),()=>{U.removeEventListener("mousedown",X,!0),U!==window&&window.removeEventListener("mousedown",()=>I(null),!0)}},[C]);const Me=i.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:z,hasDetachedConversationPanels:H,ides:r,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:g,liveSessionInboxState:S,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:ge,userName:m,scrollToBottomRequest:M,tabShortcuts:le,openTabContextMenu:({x:G,y:U,tabKey:X,sourceDocument:se})=>I({x:G,y:U,tabKey:X,sourceDocument:se??document}),popoutTab:je,moveTabBackToMain:Ne,isTabInPopout:q,floatTab:he,isTabFloating:we}),[n,t,z,H,r,l,c,g,S,a,o,ge,m,M,le,je,Ne,q,he,we]),Te=C?py({isTabInPopout:q(C.tabKey),isTabFloating:we(C.tabKey),tabShortcut:le[C.tabKey],actionShortcuts:p}):[],We=i.useCallback(G=>{var se;const U=k.current;if((((se=U==null?void 0:U.activePanel)==null?void 0:se.id)??null)===G.id){G.group.model.openPanel(G);return}G.group.model.openPanel(G),G.api.setActive()},[]),Ge=i.useCallback((G,U="requested-tab")=>{if(!G)return!1;const X=k.current;if(!X)return!1;const se=X.getPanel(G);return se?(We(se),ie(G,U),h==null||h(),!0):!1},[We,h,ie]),Xe=i.useCallback(()=>{if(P.current)return!1;const G=Ge(B.current,"stored-layout-restore");return G&&(P.current=!0),G},[Ge]),Ye=i.useCallback(()=>{var U;const G=k.current;G&&Ub(v,{activeTabId:((U=G.activePanel)==null?void 0:U.id)??null,layout:G.toJSON()})},[v]),tt=i.useCallback(()=>{Gb(v,$.current)},[v]),ct=i.useCallback(G=>{var se,W,V,te;const U=k.current;if(!U)return{kind:"grid"};const X=U.toJSON();for(const re of X.floatingGroups||[])if((W=(se=re.data)==null?void 0:se.views)!=null&&W.includes(G)&&re.position)return{kind:"floating",position:re.position};for(const re of X.popoutGroups||[])if((te=(V=re.data)==null?void 0:V.views)!=null&&te.includes(G))return{kind:"popout",position:re.position,popoutUrl:re.url};return{kind:"grid"}},[]),mt=i.useCallback(G=>{const U=k.current;if(!U)return;const X=U.getPanel(G),se=$.current[G];if(!X||!se||se.kind==="grid")return;if(X.group.model.location.type===se.kind){delete $.current[G],tt();return}if(se.kind==="floating"){U.addFloatingGroup(X,{x:se.position.left??24,y:se.position.top??24,width:se.position.width,height:se.position.height}),delete $.current[G],tt();return}delete $.current[G],tt()},[tt]);i.useEffect(()=>(b==null||b({setShortcutForActiveTab:Ce,restoreHiddenTabToSavedLocation:mt,activateConversationTab:ae,resetAllPanelsToMain:J,activatePreviousTabInGroup:()=>ue(-1),activateNextTabInGroup:()=>ue(1),floatActiveTab:()=>{const G=xe();G&&he(G)},popoutActiveTab:()=>{const G=xe();G&&je(G)},dockActiveTab:()=>{const G=xe();G&&(q(G)?Ne(G):we(G)&&Se(G))},splitActiveTabRight:()=>Q("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Q("below",{createGroupIfMissing:!0}),focusLeftPane:()=>de("left"),focusRightPane:()=>de("right"),focusUpPane:()=>de("above"),focusDownPane:()=>de("below"),moveActiveTabToLeftPane:()=>Q("left"),moveActiveTabToRightPane:()=>Q("right"),moveActiveTabToUpPane:()=>Q("above"),moveActiveTabToDownPane:()=>Q("below")}),()=>b==null?void 0:b(null)),[ue,Se,he,de,xe,we,q,Q,Ne,je,b,J,mt,ae,Ce]),i.useEffect(()=>()=>{var G;(G=O.current)==null||G.call(O),O.current=null},[]);const pt=i.useCallback(G=>{var X,se;k.current=G.api,(X=O.current)==null||X.call(O),O.current=null;const U=Kb(v);if(B.current=(U==null?void 0:U.activeTabId)??null,U!=null&&U.layout&&G.api.fromJSON(U.layout,{reuseExistingPanels:!1}),N.current=Nl({hasStoredLayout:!!(U!=null&&U.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),N.current||(_l(G.api,e),Ll(G.api,e,y)),G.api.totalPanels===0&&e.length>0){const W=wy(G.api,e,x);if(W){const V=G.api.getPanel(W);V&&We(V)}}else!N.current&&!Ge(x)&&Xe();if(L.current=!0,G.api.onDidActivePanelChange(W=>{var te;if(B.current=(W==null?void 0:W.id)??null,P.current=!0,fe(),W&&Bt(W.id)){const re=((te=W.params)==null?void 0:te.routeId)||W.id.slice(7),ke=Ht(e,re);w((ke==null?void 0:ke.tabKey)??null),Ye();return}if(w((W==null?void 0:W.id)??null),Ye(),!W)return;const V=z.get(W.id);(V==null?void 0:V.streamSource)==="agent-stream"&&V.agentType&&A(V.routeId,Bc(),{agentType:V.agentType,...V.sessionId&&{targetSessionId:V.sessionId}}).catch(()=>{})}),G.api.onDidLayoutChange(()=>{Ye(),fe(),R(W=>W+1)}),by()){const W=Re=>({clientX:Re.clientX,clientY:Re.clientY}),V=Re=>{const Fe=Re==null?void 0:Re.getBoundingClientRect();return Fe?{left:Fe.left,right:Fe.right,top:Fe.top,bottom:Fe.bottom}:null},te=Re=>{var Ue;const Fe=(Ue=j.current)==null?void 0:Ue.getBoundingClientRect();return Fe?Re.clientX<Fe.left||Re.clientX>Fe.right||Re.clientY<Fe.top||Re.clientY>Fe.bottom:!1},re=xy({detachDelayMs:tu,onDetach:({panelId:Re,clientX:Fe,clientY:Ue})=>{var dt,ht;const Le=G.api.getPanel(Re);if(!Le)return;try{if(Le.group.model.location.type!=="grid")return}catch{return}const Qe=(dt=j.current)==null?void 0:dt.getBoundingClientRect(),et=(ht=Le.group.element)==null?void 0:ht.getBoundingClientRect(),gt=Math.round(Math.min(Math.max((et==null?void 0:et.width)??600,360),720)),yt=Math.round(Math.min(Math.max((et==null?void 0:et.height)??500,260),640));G.api.addFloatingGroup(Le,{x:Qe?Math.max(0,Fe-Qe.left-32):void 0,y:Qe?Math.max(0,Ue-Qe.top-18):void 0,width:gt,height:yt}),Le.api.setActive(),Ye(),fe(),R(Ve=>Ve+1)}}),ke=[G.api.onWillDragPanel(Re=>{if(!(Re.nativeEvent.defaultPrevented||Re.nativeEvent.shiftKey)){try{if(Re.panel.group.model.location.type!=="grid")return}catch{return}re.startDrag({panelId:Re.panel.id,selfPanelBounds:V(Re.panel.group.element),...W(Re.nativeEvent)})}}),G.api.onWillShowOverlay(Re=>{if(re.hasDetached()){Re.preventDefault();return}re.markDockTarget(W(Re.nativeEvent))}),G.api.onWillDrop(Re=>{if(re.hasDetached()){Re.preventDefault(),re.endDrag();return}re.markDockTarget(W(Re.nativeEvent))}),G.api.onDidDrop(()=>re.endDrag()),G.api.onUnhandledDragOverEvent(Re=>{re.isDragging()&&re.markSelfPanel(W(Re.nativeEvent))})],Ee=Re=>{if(!re.isDragging())return;const Fe=W(Re);te(Fe)&&re.markNonSelfPanel(Fe)},Oe=()=>re.endDrag();window.addEventListener("dragover",Ee,!0),window.addEventListener("drop",Oe,!0),window.addEventListener("dragend",Oe,!0),O.current=()=>{re.dispose();for(const Re of ke)Re.dispose();window.removeEventListener("dragover",Ee,!0),window.removeEventListener("drop",Oe,!0),window.removeEventListener("dragend",Oe,!0)}}G.api.onDidAddGroup(W=>{requestAnimationFrame(()=>{var V,te;try{const re=(V=W.element)==null?void 0:V.ownerDocument;if(!re||re===document)return;(te=re.getElementById("dv-popout-window"))==null||te.classList.add("adhdev-dockview");const ke=document.documentElement.getAttribute("data-theme");ke&&re.documentElement.setAttribute("data-theme",ke),re.body.className=document.body.className;const Ee=document.documentElement.getAttribute("style");Ee&&re.documentElement.setAttribute("style",Ee)}catch{}fe(),R(re=>re+1)})}),w(((se=G.api.activePanel)==null?void 0:se.id)??null)},[We,Ge,z,r,d,v,w,Ye,x,y,A,fe,e]);i.useLayoutEffect(()=>{const G=k.current;if(!G||!L.current||N.current&&Nl({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;N.current&&(N.current=!1);const U=D.current,X=new Set(U),se=e.map(Oe=>Oe.tabKey),W=new Set(se),V=fy({previousVisibleConversationCount:U.length,visibleConversationCount:e.length,ides:r});let te=!1;for(const Oe of U)W.has(Oe)||V||($.current[Oe]=ct(Oe),te=!0);te&&tt(),V||(_l(G,e),Ll(G,e,y));const re=se.filter(Oe=>!X.has(Oe));let ke=!1;for(const Oe of re){const Re=G.getPanel(Oe),Fe=$.current[Oe];if(!Re||!Fe||Fe.kind==="grid")continue;if(Re.group.model.location.type===Fe.kind){delete $.current[Oe],ke=!0;continue}if(Fe.kind==="floating"){G.addFloatingGroup(Re,{x:Fe.position.left??24,y:Fe.position.top??24,width:Fe.position.width,height:Fe.position.height}),delete $.current[Oe],ke=!0;continue}}if(ke&&tt(),D.current=se,x&&Ge(x))return;!G.activePanel&&G.panels[0]&&We(G.panels[0]),!!(G.activePanel&&G.getPanel(G.activePanel.id))||Xe()},[We,Ge,Xe,r,d,tt,ct,x,y,e]),i.useEffect(()=>{L.current&&Ge(x)},[Ge,x]),i.useEffect(()=>{const G=X=>{const se=X.target;if(!se)return;const W=se.querySelector("[data-tab-key]")||se.closest("[data-tab-key]");if(W){const V=W.getAttribute("data-tab-key");if(V&&X.dataTransfer){const te=se.closest(".dv-tab")||W.closest(".dv-tab")||W;X.dataTransfer.effectAllowed="move",X.dataTransfer.setData("text/tab-key",V),te instanceof HTMLElement&&X.dataTransfer.setDragImage(te,Math.max(12,Math.round(te.clientWidth/2)),Math.max(10,Math.round(te.clientHeight/2)))}}};window.addEventListener("dragstart",G);const U=Al(k.current);for(const X of U)X.addEventListener("dragstart",G);return()=>{window.removeEventListener("dragstart",G);for(const X of U)X.removeEventListener("dragstart",G)}},[E]),i.useEffect(()=>{var U;const G=(U=j.current)==null?void 0:U.querySelector(".adhdev-dockview");G instanceof HTMLElement&&_a(G,T),ce(),fe()},[fe,ce,T]),i.useEffect(()=>{fe()},[fe]),i.useEffect(()=>{const G=U=>{if(U.defaultPrevented||pe)return;const X=_e(U);if(!X)return;const se=U.metaKey||U.ctrlKey||U.altKey;xo(U.target)&&!se||On(ve).setActiveTabShortcut!==X||(U.preventDefault(),U.stopPropagation(),Ce())};return window.addEventListener("keydown",G,!0),()=>window.removeEventListener("keydown",G,!0)},[_e,ve,pe,Ce]),i.useEffect(()=>{const G=j.current;if(!G)return;const U=X=>{var re,ke;if(!X.isTrusted)return;const se=(ke=(re=X.target)==null?void 0:re.closest)==null?void 0:ke.call(re,".dv-scrollable");if(!se)return;X.preventDefault(),X.stopPropagation();const W=Math.abs(X.deltaX),V=Math.abs(X.deltaY),te=W>V?X.deltaX:X.deltaY;se.dispatchEvent(new WheelEvent("wheel",{deltaY:te,deltaMode:X.deltaMode,bubbles:!1,cancelable:!0}))};return G.addEventListener("wheel",U,{passive:!1,capture:!0}),()=>G.removeEventListener("wheel",U,{capture:!0})},[]),i.useEffect(()=>{const G=Al(k.current);if(G.length===0)return;const U=G.map(X=>{let se=[],W=null;const V=()=>{W!=null&&X.clearTimeout(W),W=null,se=[]},te=()=>{W!=null&&X.clearTimeout(W),W=X.setTimeout(()=>{W=null,se=[]},1200)},re=Ee=>{if(!Ee.ctrlKey&&!Ee.metaKey&&!Ee.altKey)return;const Oe=_e(Ee);if(!Oe)return;const Re=qd();for(const[Fe,Ue]of Object.entries(Re))if(e.some(Le=>Le.tabKey===Fe)&&Ue===Oe){Ee.preventDefault(),ae(Fe);return}},ke=Ee=>{if(Ee.defaultPrevented||pe)return;const Oe=_e(Ee);if(!Oe)return;const Re=Ee.metaKey||Ee.ctrlKey||Ee.altKey;if(xo(Ee.target))return;const Fe=On(ve),Ue=Object.entries(Fe).filter(([Ve,Wt])=>!!Wt&&(Ve==="splitActiveTabRight"||Ve==="splitActiveTabDown"||Ve==="floatActiveTab"||Ve==="popoutActiveTab"||Ve==="dockActiveTab"||Ve==="focusLeftPane"||Ve==="focusRightPane"||Ve==="focusUpPane"||Ve==="focusDownPane"||Ve==="moveActiveTabToLeftPane"||Ve==="moveActiveTabToRightPane"||Ve==="moveActiveTabToUpPane"||Ve==="moveActiveTabToDownPane"||Ve==="selectPreviousGroupTab"||Ve==="selectNextGroupTab"||Ve==="setActiveTabShortcut"||Ve==="hideCurrentTab")),Le=Re?[Oe]:[...se.slice(-1),Oe].slice(-2),Qe=Le.join(" "),et=Le[Le.length-1],gt=Ue.find(([,Ve])=>Ve===Qe);if(gt){Ee.preventDefault(),V(),K(gt[0]);return}if(Ue.some(([,Ve])=>Ve.startsWith(`${Qe} `))){Ee.preventDefault(),se=Le,te();return}const dt=Ue.find(([,Ve])=>Ve===et);if(dt){Ee.preventDefault(),V(),K(dt[0]);return}if(Ue.some(([,Ve])=>Ve.startsWith(`${et} `))){Ee.preventDefault(),se=[et],te();return}V()};return X.addEventListener("keydown",re),X.addEventListener("keydown",ke),()=>{V(),X.removeEventListener("keydown",re),X.removeEventListener("keydown",ke)}});return()=>{for(const X of U)X()}},[_e,ve,E,ae,pe,K,e]);const F=T==="light"?Ya:Xa,be=((qe=(Be=(Ae=k.current)==null?void 0:Ae.activePanel)==null?void 0:Be.group.element)==null?void 0:qe.ownerDocument)??document;return s.jsxs(su.Provider,{value:Me,children:[s.jsx("div",{ref:j,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(Zu,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:jy,remote:ky},defaultTabComponent:Ny,watermarkComponent:Sy,onReady:pt,singleTabMode:"default",tabAnimation:"smooth",theme:F,popoutUrl:"/popout.html"})}),C&&Nr.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:C.x,top:C.y},children:Te.map(G=>{if(G.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},G.id);let U=s.jsx(tp,{size:13,className:"shrink-0 opacity-70"}),X=()=>{};switch(G.id){case"dockInWindow":case"dockBackToGrid":U=s.jsx(rp,{size:13,className:"shrink-0 opacity-70"}),X=()=>{Se(C.tabKey),I(null)};break;case"moveBackToMain":U=s.jsx(ep,{size:13,className:"shrink-0 opacity-70"}),X=()=>{Ne(C.tabKey),I(null)};break;case"floatAsPanel":U=s.jsx(sp,{size:13,className:"shrink-0 opacity-70"}),X=()=>{he(C.tabKey),I(null)};break;case"openInNewWindow":U=s.jsx(Zm,{size:13,className:"shrink-0 opacity-70"}),X=()=>{je(C.tabKey),I(null)};break;case"setShortcut":X=se=>{se.stopPropagation(),ne(C.tabKey),I(null)};break;case"removeShortcut":U=s.jsx(jt,{size:13,className:"shrink-0 opacity-70"}),X=()=>{const se={...le};delete se[C.tabKey],Ie(se),I(null)};break;case"hideTab":U=s.jsx(Co,{size:13,className:"shrink-0 opacity-70"}),X=()=>{ge(C.tabKey),I(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 ${G.tone==="muted"?"text-text-muted":""}`,onMouseDown:yy,onClick:X,children:[U,s.jsx("span",{className:"flex-1 min-w-0",children:G.label}),G.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:G.shortcut}):null]},G.id)})}),C.sourceDocument.body),pe&&Nr.createPortal(s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>ne(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:G=>G.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. ",ve?"⌘+1":"Ctrl+1",", ",ve?"⌥+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"})]})}),be.body)]})}const ru="adhdev-recent-launch-args-v1",Iy=8;function nu(e){return String(e||"").trim().replace(/\s+/g," ")}function ni(e,t){return`${e.trim()}::${t.trim()}`}function ai(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(ru)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function au(e){if(!(typeof window>"u"))try{window.localStorage.setItem(ru,JSON.stringify(e))}catch{}}function bo(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=ai().byKey[ni(r,n)])==null?void 0:o.items)||[]}function ou(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=nu(r);if(!n||!a||!o)return;const l=ai(),c=ni(n,a),d=((u=l.byKey[c])==null?void 0:u.items)||[],m=[o,...d.filter(p=>p!==o)].slice(0,Iy);l.byKey[c]={items:m},au(l)}function My(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=nu(r);if(!n||!a||!o)return;const l=ai(),c=ni(n,a),m=(((u=l.byKey[c])==null?void 0:u.items)||[]).filter(p=>p!==o);m.length>0?l.byKey[c]={items:m}:delete l.byKey[c],au(l)}function iu(e){return!e.hasLoadedInitialResults&&!e.isLoading}function yn({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 Ty({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 lu({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:l,onOpenHistory:c,onClearSelection:d}){const m=o?zd(o):null,u=Ty({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(yn,{title:"Saved history",description:zo(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:l,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:c,children:xx()})]}),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 cu({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 Ay({workspaceMode:e,activeKind:t,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:o,onSelect:l}){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:"IDE",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:()=>l(c.id),disabled:!c.enabled||o,children:c.label},c.id))})]})}function La(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>Is(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>Is(a,"acp"))?"acp":null}function rn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function _y({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:l,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Ve,Wt;const u=Pr(),p=i.useMemo(()=>[...e].sort(Po),[e]),[b,w]=i.useState(((Ve=p[0])==null?void 0:Ve.id)||""),g=i.useMemo(()=>p.find(Z=>Z.id===b)||p[0],[b,p]),f=i.useMemo(()=>((g==null?void 0:g.workspaces)||[]).map(Z=>({id:Z.id,path:Z.path,label:Z.label})),[g]),x=(g==null?void 0:g.defaultWorkspaceId)||null,[y,h]=i.useState("workspace"),[M,S]=i.useState(""),[v,T]=i.useState(""),[A,k]=i.useState([]),[j,O]=i.useState(""),[L,N]=i.useState(!1),[P,B]=i.useState(null),[D,C]=i.useState(""),[I,E]=i.useState(La(p[0])),[R,$]=i.useState(""),[z,H]=i.useState(""),[me,ie]=i.useState([]),[ee,ce]=i.useState(""),[je,Ne]=i.useState([]),[q,ge]=i.useState(!1),[he,we]=i.useState(!1),[xe,Se]=i.useState(""),[J,fe]=i.useState(!1),[ae,ue]=i.useState(()=>Nt()),[oe,de]=i.useState(null),[Q,ve]=i.useState(!1),[le,pe]=i.useState(""),[ne,Ie]=i.useState(null),[Ce,_e]=i.useState(!1),[K,Me]=i.useState(""),[Te,We]=i.useState([]),[Ge,Xe]=i.useState(!1),[Ye,tt]=i.useState(""),[ct,mt]=i.useState(!1),pt=i.useRef(null),F=i.useRef(0);i.useEffect(()=>{var Z;!b&&((Z=p[0])!=null&&Z.id)&&w(p[0].id)},[b,p]),i.useEffect(()=>{!g||!(!g.workspaces||!g.availableProviders||!g.detectedIdes||!g.recentLaunches)||u(g.id,{minFreshMs:3e4}).catch(()=>{})},[u,g]);const be=i.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(Z=>Is(Z,"cli")),[g]),Ae=i.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(Z=>Is(Z,"acp")),[g]),Be=i.useMemo(()=>((g==null?void 0:g.detectedIdes)||[]).map(Z=>({id:Z.type,label:Z.name||Z.type,meta:Z.running?"Detected locally":"Available to open"})),[g]),qe=i.useMemo(()=>I==="cli"?be.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"CLI provider"})):I==="acp"?Ae.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"ACP provider"})):Be,[Ae,I,be,Be]),G=i.useMemo(()=>A.find(Z=>Z.id===j)||null,[A,j]),U=i.useMemo(()=>be.find(Z=>Z.type===R)||null,[be,R]),X=i.useMemo(()=>Bd(U==null?void 0:U.meshCoordinator,{meshId:(G==null?void 0:G.id)||"",workspace:(G==null?void 0:G.workspace)||""}),[U,G]),se=ne||X,W=i.useCallback(async Z=>{N(!0),C("");try{const $e=await c(Z);k($e),O(_=>{var Y;return $e.some(ye=>ye.id===_)?_:((Y=$e[0])==null?void 0:Y.id)||""}),B(Z)}catch($e){k([]),O(""),B(Z),C($e instanceof Error?$e.message:"Could not load meshes")}finally{N(!1)}},[c]);i.useEffect(()=>{var $e;if(!g)return;if(pt.current!==g.id){pt.current=g.id,h("workspace"),S(x||(($e=f[0])==null?void 0:$e.id)||"__home__"),T(""),k([]),O(""),B(null),C(""),E(La(g)),$(""),H(""),ce(""),Ne([]),we(!1),Se(""),ue(Nt()),pe(""),Ie(null);return}S(_=>{var Y;return _==="__custom__"||_==="__home__"||f.some(ye=>ye.id===_)?_:x||((Y=f[0])==null?void 0:Y.id)||"__home__"}),E(_=>_==="ide"&&Be.length>0||_==="cli"&&be.length>0||_==="acp"&&Ae.length>0?_:La(g))},[Ae.length,be.length,x,Be.length,g,f]),i.useEffect(()=>{!g||y!=="mesh"||P===g.id||L||W(g.id)},[W,P,L,g,y]),i.useEffect(()=>{y==="mesh"&&I!=="cli"&&be.length>0&&E("cli")},[I,be.length,y]),i.useEffect(()=>{var Z;I&&(qe.some($e=>$e.id===R)||$(((Z=qe[0])==null?void 0:Z.id)||""))},[I,qe,R]),i.useEffect(()=>{Ie(null)},[g==null?void 0:g.id,j,R,y]);const V=i.useCallback(async(Z,$e)=>{const _=F.current+1;return F.current=_,ge(!0),Se(""),m(Z,$e).then(Y=>{F.current===_&&Ne(Y)}).catch(Y=>{F.current===_&&(Ne([]),Se(Y instanceof Error?Y.message:"Could not load saved sessions"))}).finally(()=>{F.current===_&&(ge(!1),we(!0))})},[m]),te=i.useCallback((Z,$e)=>{ie(bo(Z,$e))},[]);i.useEffect(()=>{F.current+=1,ce(""),ue(Nt()),!g||!R||I==="ide"?ie([]):te(g.id,R),we(!1),Ne([]),Se(""),ge(!1)},[I,te,V,g,R]),i.useEffect(()=>{if(!ee)return;const Z=je.find($e=>$e.providerSessionId===ee);Z!=null&&Z.canResume||ce("")},[je,ee]);const re=M==="__custom__"?v.trim():M==="__home__"?"":((Wt=f.find(Z=>Z.id===M))==null?void 0:Wt.path)||"",ke=i.useMemo(()=>g?t.filter(Z=>Z.id!==g.id&&Z.daemonId===g.id).map(Z=>Z.workspace):[],[t,g]),Ee=i.useMemo(()=>((g==null?void 0:g.recentLaunches)||[]).map(Z=>Z.workspace),[g]),Oe=i.useCallback(Z=>{const $e=String(Z.workspace||"").trim();if(!$e)return;const _=f.find(Y=>rn(Y.path)===rn($e));if(_){S(_.id),T("");return}S("__custom__"),T($e)},[f]),Re=i.useCallback(Z=>{const $e=String(Z.workspace||"").trim();if(!$e)return{workspaceId:null,workspacePath:null};const _=f.find(Y=>rn(Y.path)===rn($e));return _?{workspaceId:_.id,workspacePath:null}:{workspaceId:null,workspacePath:$e}},[f]),Fe=i.useMemo(()=>je.find(Z=>Z.providerSessionId===ee)||null,[je,ee]),Ue=i.useMemo(()=>{var $e;if(I!=="cli"||!g||!R)return null;const Z=(($e=be.find(_=>_.type===R))==null?void 0:$e.displayName)||R;return{routeId:g.id,daemonId:g.id,providerSessionId:ee||void 0,transport:"pty",mode:"chat",agentName:Z,agentType:R,status:"idle",title:Z,messages:[],ideType:R,workspaceName:re,workspacePath:re,displayPrimary:Z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${g.id}:${R}`,machineName:_t(g,{fallbackId:g.id})}},[I,be,re,g,ee,R]),Le=i.useCallback(()=>{var $e;if(!g)return;S("__custom__"),_e(!0),tt("");const Z=Qn(g.platform,Jn(v.trim(),re,ke,Ee,g.defaultWorkspacePath,($e=f.find(_=>_.id===x))==null?void 0:$e.path,f.map(_=>_.path)));Xe(!0),n(g.id,Z).then(_=>{Me(_.path),T(_.path),We(_.directories)}).catch(_=>{tt(_ instanceof Error?_.message:"Could not load folder")}).finally(()=>Xe(!1))},[v,x,Ee,ke,n,re,g,f]),Qe=i.useCallback(Z=>{g&&(Xe(!0),tt(""),n(g.id,Z).then($e=>{Me($e.path),T($e.path),We($e.directories)}).catch($e=>{tt($e instanceof Error?$e.message:"Could not load folder")}).finally(()=>Xe(!1)))},[n,g]),et=i.useCallback(async()=>{if(!g||!re)return;mt(!0),pe("");const Z=await a(g.id,re);if(mt(!1),!Z.ok){pe(Z.error||"Could not save workspace");return}pe("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,re,g]),gt=i.useCallback(async()=>{if(!g)return;if(y==="mesh"){if(!j||!R)return;ve(!0),pe(""),Ie(null);const _=await d(g.id,j,R);if(ve(!1),!_.ok){if(_.code==="mesh_coordinator_manual_mcp_setup_required"&&_.manualSetup){Ie(_.manualSetup),pe("Manual MCP setup required before this provider can act as mesh coordinator.");return}pe(_.error||"Could not start mesh coordinator");return}r();return}if(!I||!R)return;ve(!0),pe("");const Z=z.trim()?z.trim().split(/\s+/).filter(Boolean):[],$e=I==="ide"?await o(g.id,R,{workspacePath:re||null}):await l(g.id,I,R,{workspaceId:M!=="__home__"&&M!=="__custom__"?M:null,workspacePath:M==="__custom__"&&re||null,resumeSessionId:I==="cli"&&ee?ee:null,cliArgs:Z});if(ve(!1),!$e.ok){pe($e.error||"Could not start session");return}I!=="ide"&&z.trim()&&(ou(g.id,R,z),te(g.id,R)),r()},[I,z,te,r,o,d,l,re,g,j,ee,R,M,y]),yt=y==="mesh"?"Start mesh coordinator":I?nd(I,I==="cli"&&!!ee):"Start",dt=y==="mesh"?"Starting coordinator…":I?ad(I,I==="cli"&&!!ee):"Starting…",ht=p.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(jt,{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:[s.jsx(yn,{title:"Machine",children:ht?s.jsx("select",{"aria-label":"Machine",value:g.id,onChange:Z=>w(Z.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:Q,children:p.map(Z=>s.jsx("option",{value:Z.id,children:_t(Z,{fallbackId:Z.id})},Z.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:p.map(Z=>{const $e=_t(Z,{fallbackId:Z.id}),_=g.id===Z.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${$e}`,"aria-pressed":_,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${_?"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:()=>w(Z.id),disabled:Q,title:$e,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${Z.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:$e})]},Z.id)})})}),s.jsxs(yn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:y==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Le,disabled:Q,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(Z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":y===Z.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${y===Z.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:()=>{h(Z.id),pe(""),Z.id==="mesh"&&g&&P!==g.id&&!L&&W(g.id)},disabled:Q,children:[s.jsx("div",{className:"text-sm font-semibold",children:Z.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:Z.desc})]},Z.id))}),y==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:M,onChange:Z=>{const $e=Z.target.value;S($e),$e==="__custom__"?Le():pe("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Q,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),f.map(Z=>s.jsxs("option",{value:Z.id,children:[Z.id===x?"⭐ ":"",Gn(Z.path,Z.label)||Z.path]},Z.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:M==="__home__"?"Launch without a workspace.":re||"Select a workspace folder."}),M==="__custom__"&&re&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Le,disabled:Q,children:[s.jsx(Ss,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:et,disabled:Q||ct,children:ct?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[L&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!L&&D&&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:D}),!L&&!D&&A.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."}),A.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:A.map(Z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":j===Z.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${j===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>O(Z.id),disabled:Q,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[Z.repoIdentity||"Repo mesh",typeof Z.nodesCount=="number"?` · ${Z.nodesCount} node${Z.nodesCount===1?"":"s"}`:""]}),Z.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",Z.workspace]})]},Z.id))}),G&&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(Ay,{workspaceMode:y,activeKind:I,cliEnabled:be.length>0,ideEnabled:Be.length>0,acpEnabled:Ae.length>0,busy:Q,onSelect:E}),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:I==="ide"?"Choose IDE":I==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[qe.map(Z=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${R===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(Z.id),disabled:Q,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Z.meta})]},Z.id)),qe.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."})]})]}),y==="mesh"&&se&&s.jsx(cu,{setup:se,providerName:(U==null?void 0:U.displayName)||(U==null?void 0:U.name)||R}),y!=="mesh"&&I!=="ide"&&s.jsxs(yn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:z,onChange:Z=>H(Z.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:Q}),me.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:me.map(Z=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>H(Z),disabled:Q,title:Z,children:Z},Z))})]}),y!=="mesh"&&I==="cli"&&s.jsx(lu,{busy:Q,savedSessionsLoading:q,savedSessionsError:xe,selectedSession:Fe,onRefresh:()=>{!g||!R||V(g.id,R)},onOpenHistory:()=>{!g||!R||(fe(!0),iu({hasLoadedInitialResults:he,isLoading:q})&&V(g.id,R))},onClearSelection:()=>ce("")}),le&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${le.includes("saved")||le.includes("requested")||le.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:le})]}),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:Q,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:gt,disabled:Q||(y==="mesh"?!j||!R||I!=="cli"||L:!I||!R||M==="__custom__"&&!re),children:[s.jsx(Mo,{size:14}),Q?dt:yt]})]})]})}),Ce&&s.jsx(ea,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:K,directories:Te,busy:Ge,error:Ye,onClose:()=>_e(!1),onNavigate:Qe,onConfirm:Z=>{T(Z),Me(Z),S("__custom__"),_e(!1)}}),J&&Ue&&s.jsx(qo,{activeConv:Ue,ides:[],isCreatingChat:!1,isRefreshingHistory:q,savedSessions:je,isSavedSessionsLoading:q,isResumingSavedSessionId:oe,savedHistoryFilters:ae,missingWorkspaceResumePath:re||null,onSavedHistoryFiltersChange:ue,onClose:()=>fe(!1),onNewChat:()=>{ce(""),fe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!g||!R||V(g.id,R)},onResumeSavedSession:Z=>{if(!g||!R||oe||!Z.canResume)return;const $e=Re(Z);ce(Z.providerSessionId),Oe(Z),de(Z.providerSessionId),fe(!1),ve(!0),pe(""),l(g.id,"cli",R,{workspaceId:$e.workspaceId,workspacePath:$e.workspacePath,resumeSessionId:Z.providerSessionId}).then(_=>{if(!_.ok){pe(_.error||"Could not resume session");return}r()}).finally(()=>{ve(!1),de(_=>_===Z.providerSessionId?null:_)})}})]}):null}function du(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 oi(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=du(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 ii(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function uu(e){var t;return!ii(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 nn(e){return[...new Set(e.filter(t=>!!t))]}function Ly(e){const t=e.nodes.find(l=>l.type==="defaultBranchNode")??null,r=(t==null?void 0:t.branch)??null,n=e.nodes.filter(l=>l.type!=="defaultBranchNode"&&l.type!=="submoduleNode"&&!l.isOrphan&&!!r&&l.branch===r),a=e.nodes.filter(l=>l.type!=="submoduleNode"&&!l.isOrphan),o=e.nodes.filter(l=>l.type!=="submoduleNode");return t||n.length>0?nn([t==null?void 0:t.id,...n.map(l=>l.id)]):a.length>0?nn(a.map(l=>l.id)):o.length>0?nn(o.map(l=>l.id)):nn(e.nodes.map(l=>l.id))}function mu(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 Ry(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${mu(e)}::${n}x${a}`}const Py={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"},Dy={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"},Ey={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"},$y={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 Zs(e){return e==="light"?{theme:e,isDark:!1,flowColorMode:"light",textPrimary:"text-slate-900",textSecondary:"text-slate-700",textMuted:"text-slate-500",graphShellClass:"relative w-full min-w-0 overflow-hidden rounded-2xl border border-slate-200 bg-[radial-gradient(circle_at_top,_rgba(14,165,233,0.16),_rgba(248,250,252,0.98)_42%,_rgba(255,255,255,1))]",graphStatChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-slate-700 shadow-sm",graphHintChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-[10px] text-slate-500 shadow-sm",graphControlsClass:"!bottom-4 !left-4 !shadow-md",graphBackgroundDotColor:"rgba(148, 163, 184, 0.34)",edgeLabelTextColor:"#334155",edgeLabelBackgroundColor:"rgba(255, 255, 255, 0.96)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.45)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[rgba(148,163,184,0.22)] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"flex h-[100dvh] w-full flex-col overflow-hidden bg-white md:h-[min(90vh,960px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-slate-200 md:bg-white/98 md:shadow-[0_28px_120px_rgba(148,163,184,0.28)]",dialogHeaderClass:"flex shrink-0 flex-col gap-3 border-b border-slate-200 bg-white/96 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-slate-900 md:text-xl",dialogKickerClass:"rounded-full border border-slate-300 bg-slate-50 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-600",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-500",dialogRefreshedChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1.5 text-xs text-slate-600",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-300 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",dialogBodyClass:"min-h-0 flex-1 overflow-y-auto bg-[linear-gradient(180deg,rgba(248,250,252,0.98),rgba(241,245,249,0.96))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-slate-300 bg-white/90 px-6 text-center text-sm text-slate-500",cardClass:"rounded-2xl border border-slate-200 bg-white/95 shadow-sm",cardHeaderClass:"border-b border-slate-200 px-4 py-3",cardTitleClass:"text-sm font-semibold text-slate-900",cardSubtitleClass:"mt-1 text-xs text-slate-500",rowClass:"flex items-start justify-between gap-3 border-b border-slate-200/80 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"text-slate-500",rowValueClass:"max-w-[65%] break-all text-right text-slate-800",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-slate-200 bg-white/95 p-4 shadow-md md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-slate-200 bg-white/95 p-4 text-xs text-slate-500 shadow-sm md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-900",panelCloseButtonClass:"text-xs text-slate-500 hover:text-slate-900",panelFieldRowClass:"flex justify-between gap-3 border-b border-slate-200/80 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-500",panelFieldValueClass:"break-all text-right font-medium text-slate-700",infoCalloutClass:"mt-1 rounded border border-sky-300 bg-sky-50 px-2 py-1.5 text-[10px] text-sky-700",badge:t=>Dy[t],actionButton:t=>$y[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative w-full min-w-0 overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",graphStatChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-slate-200",graphHintChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-[10px] text-slate-300",graphControlsClass:"!bottom-4 !left-4 !shadow-lg",graphBackgroundDotColor:"rgba(148, 163, 184, 0.22)",edgeLabelTextColor:"#cbd5e1",edgeLabelBackgroundColor:"rgba(2, 6, 23, 0.86)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.2)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[#030617]/[0.58] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"flex h-[100dvh] w-full flex-col overflow-hidden bg-slate-950 md:h-[min(90vh,960px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-white/10 md:bg-slate-950/96 md:shadow-[0_28px_120px_rgba(2,6,23,0.46)]",dialogHeaderClass:"flex shrink-0 flex-col gap-3 border-b border-white/10 bg-slate-950/92 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-white md:text-xl",dialogKickerClass:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-300",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-400",dialogRefreshedChipClass:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 bg-white/6 text-slate-300 transition hover:bg-white/10 hover:text-white",dialogBodyClass:"min-h-0 flex-1 overflow-y-auto bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-white/10 bg-white/[0.03] px-6 text-center text-sm text-slate-400",cardClass:"rounded-2xl border border-white/10 bg-white/[0.04]",cardHeaderClass:"border-b border-white/10 px-4 py-3",cardTitleClass:"text-sm font-semibold text-white",cardSubtitleClass:"mt-1 text-xs text-slate-400",rowClass:"flex items-start justify-between gap-3 border-b border-white/5 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"text-slate-400",rowValueClass:"max-w-[65%] break-all text-right text-slate-100",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-white/10 bg-white/[0.04] p-4 shadow-lg md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-white/10 bg-white/[0.04] p-4 text-xs text-slate-400 md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-100",panelCloseButtonClass:"text-xs text-slate-400 hover:text-slate-100",panelFieldRowClass:"flex justify-between gap-3 border-b border-white/6 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-400",panelFieldValueClass:"break-all text-right font-medium text-slate-200",infoCalloutClass:"mt-1 rounded bg-blue-500/10 border border-blue-500/20 px-2 py-1.5 text-[10px] text-blue-300",badge:t=>Py[t],actionButton:t=>Ey[t]}}const It={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,columnGap:540,edgeLabelBuffer:180,defaultToContentGap:136,worktreeStackGap:82,parentToSubmoduleGap:48,submoduleStackGap:36,submoduleIndentX:72,placeholderTopOffset:0};function an(e,t,r){const n=(e||"").trim();return n?Math.max(1,Math.min(r,Math.ceil(n.length/t))):0}function By(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 li(e){return e.type==="submoduleNode"?It.submoduleCardWidth:It.worktreeCardWidth}function pu(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=du(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 vn(e){const t=li(e),r=e.type==="submoduleNode"?24:30,n=Math.ceil(By(e)/(e.type==="submoduleNode"?2:3)),a=an(e.label,r,2),o=an(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,r,2),l=an(pu(e),r+4,3),c=oi(e),d=uu(e)?ii(e):null,m=an(d,Math.max(24,Math.floor(t/8)),4),u=52+a*18+o*14+(c?30:0)+n*24+Math.max(22,l*18)+(m>0?22+m*16:0),p=e.type==="submoduleNode"?It.minSubmoduleCardHeight:It.minWorktreeCardHeight;return Math.min(It.maxEstimatedCardHeight,Math.max(p,Math.ceil(u)))}function Ra(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)}function Oy(e){return e?Math.min(260,Math.max(72,e.length*7+26)):0}function Fy(e){const t=e.edges.reduce((r,n)=>Math.max(r,Oy(n.label)),0);return Math.max(It.columnGap,It.worktreeCardWidth+t+It.edgeLabelBuffer)}function on(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 ln(e,t,r){return{id:e.id,x:t,y:r,width:li(e),height:vn(e)}}function Hy(e,t){return{id:`${e.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:t.repoIdentity,branch:e.branch,upstream:null,upstreamStatus:null,machineLabel:null,health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],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 Wy(e){const t=[...e.nodes].sort(Ra),r=t.find(x=>x.type==="defaultBranchNode")??null,n=new Map;for(const x of t){if(x.type!=="submoduleNode"||!x.parentNodeId)continue;const y=n.get(x.parentNodeId)??[];y.push(x),n.set(x.parentNodeId,y)}const a=t.filter(x=>x.id!==(r==null?void 0:r.id)&&x.type!=="submoduleNode"),o=new Map,l=[];for(const x of a){if(x.isOrphan||!x.branch){l.push(x);continue}const y=o.get(x.branch)??[];y.push(x),o.set(x.branch,y)}const c=[...o.entries()].sort(([x],[y])=>r!=null&&r.branch&&x===r.branch&&y!==r.branch?-1:r!=null&&r.branch&&y===r.branch&&x!==r.branch?1:x.localeCompare(y));l.length>0&&c.push(["__orphans__",[...l].sort(Ra)]),c.length===0&&c.push(["__nodes__",[]]);const d=[],m=[],u=c.length,p=Fy(e),b=Math.max(1,u-1)*p,w=r?0:96,g=r?vn(r):0,f=r?w+g+It.defaultToContentGap:0;if(r){const x=b/2;d.push(on(r,x,w)),m.push(ln(r,x,w))}return c.forEach(([x,y],h)=>{const M=h*p,S=y.length>0?y:a.length>0?a:[];let v=f;if(S.forEach(T=>{const A=vn(T);d.push(on(T,M,v)),m.push(ln(T,M,v));const k=[...n.get(T.id)??[]].sort(Ra);if(k.length>0){let j=v+A+It.parentToSubmoduleGap;k.forEach(O=>{const L=M+It.submoduleIndentX,N=vn(O);d.push(on(O,L,j)),m.push(ln(O,L,j)),j+=N+It.submoduleStackGap}),v=j+It.worktreeStackGap-It.submoduleStackGap;return}v+=A+It.worktreeStackGap}),x==="__nodes__"&&a.length===0&&r){const T=Hy(r,e),A=f+It.placeholderTopOffset;d.push(on(T,M,A,!1)),m.push(ln(T,M,A))}}),{nodes:d,bounds:m,columnGap:p}}const fu=i.createContext(Zs("dark"));function Ky(e,t,r){const n=t?"border-cyan-400/70 shadow-[0_0_0_1px_rgba(34,211,238,0.35),0_24px_60px_rgba(8,145,178,0.18)]":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)]",a=oi(e);if((a==null?void 0:a.tone)==="danger")return`${n} ${r?"bg-rose-500/12":"bg-rose-50/95"}`;if((a==null?void 0:a.tone)==="warn")return`${n} ${r?"bg-amber-500/10":"bg-amber-50/95"}`;if((a==null?void 0:a.tone)==="info")return`${n} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;switch(e.health){case"online":return`${n} ${r?"bg-emerald-500/8":"bg-emerald-50/95"}`;case"dirty":return`${n} ${r?"bg-amber-500/8":"bg-amber-50/95"}`;case"degraded":return`${n} ${r?"bg-rose-500/10":"bg-rose-50/95"}`;case"wrong_branch":return`${n} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;case"offline":return`${n} ${r?"bg-slate-500/12":"bg-slate-100/95"}`;default:return`${n} ${r?"bg-slate-950/78":"bg-white/96"}`}}function Vt(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 Uy(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 zy(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 Gy(e){return e.replace(/_/g," ")}function Vy({data:e,selected:t}){const r=i.useContext(fu),n=e.graphNode,a=n.type==="defaultBranchNode",o=n.type==="submoduleNode",l=uu(n),c=a?"default branch anchor":o?n.submodulePath||"submodule checkout":n.machineLabel||n.workspace,d=n.submoduleCommit?n.submoduleCommit.slice(0,7):null,m=oi(n),u=pu(n),p=ii(n);return s.jsxs("div",{className:`${o?"w-[228px]":"w-[256px]"} rounded-2xl border px-4 py-3.5 backdrop-blur-sm transition-all ${Ky(n,t,r.isDark)}`,style:{width:li(n)},children:[s.jsx(Ni,{type:"target",position:Ci.Top,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:n.label}),s.jsx("div",{className:`truncate text-[11px] ${r.textMuted}`,children:c})]}),s.jsx("span",{className:"mt-0.5 h-2.5 w-2.5 shrink-0 rounded-full",style:{backgroundColor:zy(n.health)},"aria-hidden":!0})]}),m&&s.jsx("div",{className:`mt-3 inline-flex max-w-full items-center rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] ${Uy(m.tone,r.isDark)}`,children:s.jsx("span",{className:"truncate",children:m.label})}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-1.5 text-[10px]",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${Vt("health",r.isDark)}`,children:Gy(n.health)}),o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("submodule",r.isDark)}`,children:"submodule"}),n.branch&&!o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("meta",r.isDark)}`,children:n.branch}),d&&o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("meta",r.isDark)}`,children:d}),n.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("dirty",r.isDark)}`,children:o?"local changes":`${n.dirtyFiles} dirty`}),n.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("conflict",r.isDark)}`,children:"out of sync"}),n.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("conflict",r.isDark)}`,children:"conflicts"}),!o&&n.upstream&&n.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("orphan",r.isDark)}`,children:"upstream unverified"}),n.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("orphan",r.isDark)}`,children:"needs follow-up"})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,children:u}),l&&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"}`,children:p}),s.jsx(Ni,{type:"source",position:Ci.Bottom,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const qy={meshNode:Vy};function Yy(e,t=Zs("dark")){const n=Wy(e).nodes.map(o=>({id:o.id,type:o.type,position:o.position,data:{graphNode:o.graphNode},selected:o.selected,draggable:o.draggable,selectable:o.selectable})),a=e.edges.map(o=>({id:o.id,source:o.source,target:o.target,label:o.label,type:o.type==="worktreeLink"||o.type==="submoduleLink"?"smoothstep":"bezier",animated:o.type==="orphanLink",markerEnd:{type:nm.ArrowClosed,width:o.type==="submoduleLink"?16:18,height:o.type==="submoduleLink"?16:18,color:Rl(o)},style:{stroke:Rl(o),strokeWidth:o.type==="orphanLink"?2.25:o.type==="submoduleLink"?1.7:o.type==="worktreeLink"?1.8:2,strokeDasharray:o.type==="orphanLink"?"5 4":o.type==="submoduleLink"?"4 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:n,edges:a}}function Rl(e){switch(e.type){case"parentBranch":return"#38bdf8";case"worktreeLink":return"#a78bfa";case"sessionLink":return"#34d399";case"orphanLink":return"#f97316";case"submoduleLink":return"#c084fc";default:return"#64748b"}}function Xy({data:e,viewportKey:t}){const r=am(),n=om(),a=i.useRef(null),o=i.useMemo(()=>mu(e),[e]),l=i.useMemo(()=>Ly(e),[e]);return i.useEffect(()=>{if(!r||e.nodes.length===0||a.current===t)return;let c=!1;const d=requestAnimationFrame(()=>{if(c)return;const m=l.length>0&&l.length<e.nodes.length;n.fitView({nodes:m?l.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,l,o,r,n,t]),null}function Jy({data:e,selectedNodeId:t=null,onNodeClick:r}){const{theme:n}=Qs(),a=i.useMemo(()=>Zs(n),[n]),o=i.useMemo(()=>Yy(e,a),[e,a]),l=i.useRef(null),[c,d]=i.useState({width:0,height:0}),m=i.useMemo(()=>Ry(e,c.width,c.height),[e,c.height,c.width]),u=i.useMemo(()=>o.nodes.map(p=>({...p,selected:p.id===t})),[o.nodes,t]);return i.useEffect(()=>{const p=l.current;if(!p)return;const b=()=>{const g=Math.max(0,Math.round(p.clientWidth)),f=Math.max(0,Math.round(p.clientHeight));d(x=>x.width===g&&x.height===f?x:{width:g,height:f})};b();const w=typeof ResizeObserver=="function"?new ResizeObserver(()=>b()):null;return w==null||w.observe(p),window.addEventListener("resize",b),()=>{w==null||w.disconnect(),window.removeEventListener("resize",b)}},[]),s.jsx(fu.Provider,{value:a,children:s.jsxs("div",{ref:l,className:a.graphShellClass,children:[s.jsxs("div",{className:`absolute inset-x-3 top-3 z-10 flex flex-wrap items-center justify-between gap-2 text-[11px] ${a.textSecondary}`,children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs("span",{className:a.graphStatChipClass,children:[e.stats.totalNodes," node",e.stats.totalNodes===1?"":"s"]}),s.jsxs("span",{className:a.graphStatChipClass,children:[e.stats.totalActiveSessions," active session",e.stats.totalActiveSessions===1?"":"s"]}),e.stats.orphanNodes>0&&s.jsxs("span",{className:a.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"]})]}),s.jsx("div",{className:a.graphHintChipClass,children:"Focused on the main path first · drag or scroll to pan"})]}),s.jsx("div",{className:"h-[460px] w-full min-w-0 min-h-[460px] sm:h-[560px] xl:h-[680px]",children:s.jsxs(em,{nodes:u,edges:o.edges,nodeTypes:qy,minZoom:.25,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(p,b)=>r==null?void 0:r(b.data.graphNode),className:"h-full w-full",colorMode:a.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(Xy,{data:e,viewportKey:m}),s.jsx(tm,{className:a.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),s.jsx(sm,{variant:rm.Dots,gap:18,size:1.2,color:a.graphBackgroundDotColor})]})})]})})}function bt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function De(...e){for(const t of e){if(typeof t!="string")continue;const r=t.trim();if(r)return r}}function Rt(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function Et(...e){for(const t of e)if(typeof t=="boolean")return t}function Pa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function Qy(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 Zy(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=bt(n),o=De(a.path),l=De(a.commit),c=De(a.repoPath,a.repo_root)??Qy(t,o);return!o||!l||!c?null:{path:o,commit:l,repoPath:c,dirty:Et(a.dirty)??!1,outOfSync:Et(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:Rt(a.lastCheckedAt,a.last_checked_at)??Date.now(),...De(a.error)?{error:De(a.error)}:{}}}).filter(n=>n!==null);return r.length>0?r:void 0}function e0(e){return Et(e.isGitRepo)!==void 0||!!De(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||Rt(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 wn(e,t,r){const n=Et(e.isGitRepo);if(!Object.keys(e).length||!e0(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(b=>typeof b=="string"):[],l=Rt(e.conflicts)??o.length,c=Et(e.hasConflicts)??l>0,d=De(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,m=Zy(e.submodules,d),u=De(e.upstreamStatus,e.upstream_status),p=De(e.error);return{workspace:De(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:a,branch:De(e.branch)??null,headCommit:De(e.headCommit)??null,headMessage:De(e.headMessage)??null,upstream:De(e.upstream)??null,upstreamStatus:u??"unchecked",ahead:Rt(e.ahead)??0,behind:Rt(e.behind)??0,staged:Rt(e.staged)??0,modified:Rt(e.modified)??0,untracked:Rt(e.untracked)??0,deleted:Rt(e.deleted)??0,renamed:Rt(e.renamed)??0,hasConflicts:c,conflictFiles:o,stashCount:Rt(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??Rt(e.lastCheckedAt,e.last_checked_at)??Date.now(),...m?{submodules:m}:{},...p?{error:p}:{}}}function t0(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),e.upstreamStatus&&e.upstreamStatus!=="unchecked"&&(t+=5),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 s0(e){const t=bt(e.lastGit??e.last_git),r=bt(t.result),n=bt(t.status),a=bt(r.status),o=bt(e.lastProbe??e.last_probe),l=bt(o.git),c=bt(l.result),d=bt(l.status),m=bt(c.status);let u=null;for(const p of[n,a,d,m]){const b=wn(p,e,{lastCheckedAt:Date.now()});if(!b)continue;const w=t0(b);(!u||w>u.score)&&(u={git:b,score:w})}return u==null?void 0:u.git}function r0(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 n0(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 Fn(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=r0(e);return t.outOfSync?"degraded":t.dirty||n0(e)?"dirty":"online"}function a0(e,t){const r=t?Fn(t):void 0;return!e||e==="unknown"?r:e}function o0(e){const t=Array.isArray(e.activeSessionDetails)?e.activeSessionDetails:Array.isArray(e.active_session_details)?e.active_session_details:null;if(t){const a=t.map(o=>{const l=bt(o),c=De(l.sessionId,l.session_id,l.id);return c?{sessionId:c,...De(l.providerType,l.provider)?{providerType:De(l.providerType,l.provider)}:{},...De(l.state,l.status)?{state:De(l.state,l.status)}:{},...De(l.lifecycle)?{lifecycle:De(l.lifecycle)}:{},...De(l.surfaceKind,l.surface_kind)?{surfaceKind:De(l.surfaceKind,l.surface_kind)}:{},...De(l.recoveryState,l.recovery_state)?{recoveryState:De(l.recoveryState,l.recovery_state)}:{},...De(l.workspace)?{workspace:De(l.workspace)}:{},...De(l.title)?{title:De(l.title)}:{},...De(l.lastActivityAt,l.last_activity_at)?{lastActivityAt:De(l.lastActivityAt,l.last_activity_at)}:{},...Et(l.isCached,l.is_cached)!==void 0?{isCached:Et(l.isCached,l.is_cached)}:{}}:null}).filter(o=>o!==null);if(a.length>0)return a}const r=bt(e.activeSession??e.active_session),n=De(r.id,r.sessionId,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id);if(n)return[{sessionId:n,...De(r.providerType,r.provider)?{providerType:De(r.providerType,r.provider)}:{},...De(r.state,r.status)?{state:De(r.state,r.status)}:{}}]}function i0(e){const t=bt(e.connection);return Object.keys(t).length>0?t:void 0}function l0(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 ci(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 Pl(e){var n,a,o,l,c,d;let t=0;const r=e.git;return ci(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),r!=null&&r.upstreamStatus&&r.upstreamStatus!=="unchecked"&&(t+=6),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"||((l=e.connection)==null?void 0:l.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 c0(e,t){var w,g,f,x;const r=Pl(e),a=Pl(t)>r?t:e,o=a===t?e:t,l=a.git??o.git,c=(((w=a.providers)==null?void 0:w.length)??0)>0?a.providers:o.providers,d=(((g=a.activeSessions)==null?void 0:g.length)??0)>0?a.activeSessions:o.activeSessions,m=(((f=a.activeSessionDetails)==null?void 0:f.length)??0)>0?a.activeSessionDetails:o.activeSessionDetails,u=(((x=a.providerPriority)==null?void 0:x.length)??0)>0?a.providerPriority:o.providerPriority,p=a.connection??o.connection,b={...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:l&&(!a.health||a.health==="unknown")?Fn(l):a.health,providers:c??[],activeSessions:d??[],...m&&m.length>0?{activeSessionDetails:m}:{},...u&&u.length>0?{providerPriority:u}:{},...p?{connection:p}:{},...l?{git:l}:{}};return l&&(delete b.gitProbePending,delete b.error),b}function d0(e){const t=bt(e),r=De(t.nodeId,t.id);if(!r)return null;const n=bt(t.cachedStatus),a=s0(t),o=a?void 0:wn(bt(t.git),t)??wn(t,t),l=a??o,c=l?void 0:wn(bt(n.git),t),d=l??c,m=De(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),u=De(t.health),p=a?Fn(d):a0(u,l)||(d?Fn(d):void 0)||De(n.health)||m||De(t.status)||"unknown",w=(a?void 0:De(t.error))??(l?void 0:De(n.error)),g=o0(t),f=Pa(t.activeSessions),x=(g==null?void 0:g.map(k=>k.sessionId))??[],y=Pa(t.providerPriority),h=Et(t.gitProbePending,t.git_probe_pending),M=l?void 0:h,S=i0(t),v=bt(t.branchConvergence??t.branch_convergence),T=S==null?void 0:S.state,A=a&&(!(S!=null&&S.reported)||T==="unknown")?l0(S):S;return{nodeId:r,machineLabel:De(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:De(t.workspace,d==null?void 0:d.workspace)||"",...De(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:De(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},...De(t.daemonId,t.daemon_id)?{daemonId:De(t.daemonId,t.daemon_id)}:{},...De(t.machineId,t.machine_id)?{machineId:De(t.machineId,t.machine_id)}:{},...m?{machineStatus:m}:{},...Et(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Et(t.isLocalWorktree,t.is_local_worktree)}:{},...De(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:De(t.worktreeBranch,t.worktree_branch)}:{},health:p,...d?{git:d}:{},...M!==void 0?{gitProbePending:M}:{},providers:Pa(t.providers),activeSessions:f.length>0?f:x,...g&&g.length>0?{activeSessionDetails:g}:{},...y.length>0?{providerPriority:y}:{},...Et(t.launchReady)!==void 0?{launchReady:Et(t.launchReady)}:a?{launchReady:!0}:{},...De(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:De(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},...De(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:De(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...A?{connection:A}:{},...Object.keys(v).length>0?{branchConvergence:v}:{},...w?{error:w}:{}}}function hu(e){const t=new Map,r=[];for(const n of e){const a=t.get(n.nodeId);if(!a){t.set(n.nodeId,n),r.push(n);continue}const o=c0(a,n);t.set(n.nodeId,o);const l=r.findIndex(c=>c.nodeId===n.nodeId);l>=0&&(r[l]=o)}return r}function xu(e){return{...e,nodes:hu(e.nodes??[])}}function u0(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:ci(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 m0(e){const t=De(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(d=>d0(d)).filter(d=>d!==null):null;if(!t||!n)return null;const a=hu(n),o=De(e.meshName,e.mesh_name,e.name),l=De(e.repoIdentity,e.repo_identity),c=De(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!o||!l||!c?null:{...e,meshId:t,meshName:o,repoIdentity:l,refreshedAt:c,nodes:a}}function p0(e){var o;let t=0;const r=bt(e.sourceOfTruth),n=bt(r.directPeerTruth);De(r.currentStatus)==="live_git_and_session_probes"&&(t+=100),r.coordinatorOwnsLiveTruth===!0&&(t+=25),n.satisfied===!0&&(t+=15);for(const l of e.nodes){const c=l.git;if(!c){l.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),c.upstreamStatus&&c.upstreamStatus!=="unchecked"&&(t+=2),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 bu(e){const t=(e==null?void 0:e.result)??e,r=[e==null?void 0:e.status,t==null?void 0:t.status,t,e];let n=null;for(const a of r){const o=m0(bt(a));if(!o)continue;const l=p0(o);(!n||l>n.score)&&(n={status:o,score:l})}return(n==null?void 0:n.status)??null}const f0=5*60*1e3;function h0(e){return ci(e)}function di(e){var t;return h0(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function x0(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function ui(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function mi(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function Tr(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function b0(e){return Tr(e)?"degraded":mi(e)?"dirty":"online"}function g0(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function Dl(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 Da(e){return e.length===0?"unknown":e.reduce((t,r)=>Dl(r)>Dl(t)?r:t)}function y0(e){var o,l,c,d,m;const t=new Map,r=new Map;for(const u of e){const p=(l=(o=u.git)==null?void 0:o.branch)==null?void 0:l.trim();p&&(r.set(p,(r.get(p)??0)+1),(c=u.git)!=null&&c.upstream&&t.set(p,(t.get(p)??0)+1))}const n=[...t.entries()].sort((u,p)=>{if(p[1]!==u[1])return p[1]-u[1];const b=["main","master","develop","dev"],w=b.indexOf(u[0]),g=b.indexOf(p[0]);return w!==-1||g!==-1?w===-1?1:g===-1?-1:w-g:u[0].localeCompare(p[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((m=[...r.entries()].sort((u,p)=>p[1]-u[1])[0])==null?void 0:m[0])??null}function v0(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 El(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 w0(e){return e.reduce((t,r)=>El(r.status)>El(t.status)?r:t)}function j0(e){if(di(e))return null;const t=e.branchConvergence;if(!t||typeof t!="object")return null;const r=t.status;if(!r||!["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"].includes(r))return null;const n=e.git;return{status:r,needsConvergence:t.needsConvergence??r!=="merged_to_main",reason:t.reason??"provided_by_coordinator",nextStep:t.nextStep??null,branch:t.branch??(n==null?void 0:n.branch)??null,defaultBranch:t.defaultBranch??null,upstream:t.upstream??(n==null?void 0:n.upstream)??null,upstreamStatus:t.upstreamStatus??(n==null?void 0:n.upstreamStatus)??null,ahead:t.ahead??(n==null?void 0:n.ahead)??0,behind:t.behind??(n==null?void 0:n.behind)??0,dirty:t.dirty??(ui(n)||mi(n)),hasConflicts:t.hasConflicts??(!!(n!=null&&n.hasConflicts)||Tr(n))}}function k0(e,t){const r=j0(e);if(r)return{...r,defaultBranch:r.defaultBranch??t};if(!t||di(e))return null;const n=e.git,a=(n==null?void 0:n.branch)??null,o=(n==null?void 0:n.upstream)??null,l=(n==null?void 0:n.upstreamStatus)??null,c=(n==null?void 0:n.ahead)??0,d=(n==null?void 0:n.behind)??0,m=ui(n)||mi(n),u=!!(n!=null&&n.hasConflicts)||Tr(n),p={branch:a,defaultBranch:t,upstream:o,upstreamStatus:l,ahead:c,behind:d,dirty:m,hasConflicts:u};return(n==null?void 0:n.isGitRepo)!==!0?{...p,status:"blocked_review",needsConvergence:!0,reason:"git_status_unavailable",nextStep:`Resolve git status for '${e.machineLabel||e.nodeId}' before declaring the mesh converged.`}:a?u||m?{...p,status:"not_mergeable",needsConvergence:!0,reason:n!=null&&n.hasConflicts?"conflicts_present":Tr(n)?"submodule_out_of_sync":"dirty_workspace",nextStep:`Commit, checkpoint, or resolve '${a}' before any convergence step into ${t}.`}:o&&l&&l!=="fresh"?{...p,status:"blocked_review",needsConvergence:!0,reason:"upstream_unverified",nextStep:`Refresh '${a}' against ${o} before claiming the mesh is converged.`}:a===t?c>0||d>0?{...p,status:"blocked_review",needsConvergence:!0,reason:"default_branch_not_even_with_upstream",nextStep:`Bring ${t} even with ${o??"its upstream"} before declaring convergence complete.`}:{...p,status:"merged_to_main",needsConvergence:!1,reason:"clean_default_branch",nextStep:null}:e.isLocalWorktree?{...p,status:"cleanup_candidate",needsConvergence:!0,reason:"clean_non_default_worktree_branch",nextStep:`Run refine / cleanup for '${a}' or explicitly classify the worktree before ending the task.`}:!o||c>0||d>0?{...p,status:"blocked_review",needsConvergence:!0,reason:o?"feature_branch_not_even_with_upstream":"feature_branch_missing_upstream",nextStep:`Push or reconcile '${a}', then merge it into ${t} or mark it blocked with a reason.`}:{...p,status:"pushed_feature_branch_needs_merge",needsConvergence:!0,reason:"clean_non_default_branch",nextStep:`Review and merge '${a}' into ${t}; do not treat it as fully complete while it remains off ${t}.`}:{...p,status:"blocked_review",needsConvergence:!0,reason:"branch_unknown",nextStep:`Inspect '${e.machineLabel||e.nodeId}' and confirm which branch should converge into ${t}.`}}function S0(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function N0(e){var d,m,u;const{nodeStatus:t,expectedSubmodulePaths:r,refreshedAtMs:n}=e,a=[],o=t.machineLabel||t.nodeId,l=t.git;if(!l){if(di(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const p=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(p?`${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((l.submodules??[]).map(p=>p.path));if(r.size>0){const p=[...r].filter(b=>!c.has(b));p.length>0&&a.push(`${o} is missing submodule visibility for ${p.join(", ")} even though another peer reported it.`)}return((u=t.connection)==null?void 0:u.state)!=="self"&&n!==null&&typeof l.lastCheckedAt=="number"&&n-l.lastCheckedAt>f0&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(p=>p.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(p=>p.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function C0(e){var L;const t=xu(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??y0(t.nodes),a=x0(t.refreshedAt),o=new Set(t.nodes.flatMap(N=>{var P;return(((P=N.git)==null?void 0:P.submodules)??[]).map(B=>B.path)})),l=[],c=[],d=[],m=new Map;for(const N of t.nodes){const P=N.git,B=(P==null?void 0:P.branch)??null,D=b0(P),C=ui(P)||D==="dirty",I=v0(N,n),E=k0(N,n),R=N0({nodeStatus:N,expectedSubmodulePaths:o,refreshedAtMs:a}),$={id:N.nodeId,type:I.length>0?"orphanNode":"worktreeNode",label:N.machineLabel||N.nodeId.slice(0,8),workspace:N.workspace,branch:B,upstream:(P==null?void 0:P.upstream)??null,upstreamStatus:(P==null?void 0:P.upstreamStatus)??null,machineLabel:N.machineLabel||null,health:Da([N.health,D]),ahead:(P==null?void 0:P.ahead)??0,behind:(P==null?void 0:P.behind)??0,dirty:C,dirtyFiles:g0(P),hasConflicts:(P==null?void 0:P.hasConflicts)??!1,activeSessionCount:((L=N.activeSessions)==null?void 0:L.length)??0,activeSessions:N.activeSessions??[],providers:N.providers??[],isOrphan:I.length>0,orphanReasons:I,error:N.error,nextStepHint:R.snapshotWarnings[0]??I[0]??(E==null?void 0:E.nextStep)??void 0,parentNodeId:null,submodulePath:null,submoduleCommit:(P==null?void 0:P.headCommit)??null,outOfSync:Tr(P),snapshotCompleteness:R.snapshotCompleteness,snapshotWarnings:R.snapshotWarnings,branchConvergence:E,source:N};if(l.push($),B){const z=m.get(B)??[];z.push($.id),m.set(B,z)}for(const z of(P==null?void 0:P.submodules)??[]){const H=`${$.id}::submodule::${z.path}`,me=z.path.split("/").filter(Boolean).pop()||z.path;l.push({id:H,type:"submoduleNode",label:me,workspace:z.repoPath,branch:null,upstream:null,upstreamStatus:null,machineLabel:$.machineLabel,health:S0(z),ahead:0,behind:0,dirty:z.dirty,dirtyFiles:z.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],error:z.error,nextStepHint:z.error||(z.outOfSync?`${z.path} is out of sync with the parent checkout`:z.dirty?`${z.path} has local changes`:`${z.path} is in sync with the parent checkout`),parentNodeId:$.id,submodulePath:z.path,submoduleCommit:z.commit,outOfSync:z.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:$.id,parentWorkspace:N.workspace,submodule:z}}),c.push({id:`${$.id}--${H}`,source:$.id,target:H,type:"submoduleLink",label:z.outOfSync?"submodule out of sync":"submodule"})}}const u=n?`__branch_${n}`:null;if(u&&n){const P=(m.get(n)??[]).map(E=>l.find(R=>R.id===E)).filter(Boolean),B=P.map(E=>E.branchConvergence).filter(Boolean),D=B.length>0?w0(B):null,C=B.filter(E=>E.needsConvergence).length,I={id:u,type:"defaultBranchNode",label:n,workspace:t.repoIdentity,branch:n,upstream:null,upstreamStatus:null,machineLabel:"default branch",health:Da(P.map(E=>E.health)),ahead:0,behind:0,dirty:P.some(E=>E.dirty),dirtyFiles:P.reduce((E,R)=>E+R.dirtyFiles,0),hasConflicts:P.some(E=>E.hasConflicts),activeSessionCount:P.reduce((E,R)=>E+R.activeSessionCount,0),activeSessions:P.flatMap(E=>E.activeSessions),providers:[...new Set(P.flatMap(E=>E.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:C>0?`${C} workspace(s) on ${n} still need follow-up`:P.length>0?`${P.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:D,source:{nodeId:u,machineLabel:n,workspace:t.repoIdentity,health:Da(P.map(E=>E.health)),providers:[],activeSessions:[]}};l.push(I);for(const E of l)if(!(E.id===u||E.type==="submoduleNode")){if(E.branch===n){c.push({id:`${u}--${E.id}`,source:u,target:E.id,type:"parentBranch",label:"checked out"});continue}if(E.branch){c.push({id:`${u}--${E.id}`,source:u,target:E.id,type:E.isOrphan?"orphanLink":"parentBranch",label:E.branch});continue}E.isOrphan&&c.push({id:`${u}--${E.id}`,source:u,target:E.id,type:"orphanLink",label:"detached"})}}for(const[N,P]of m){if(P.length<2)continue;const B=P.map(D=>l.find(C=>C.id===D)).filter(Boolean);B.sort((D,C)=>D.label.localeCompare(C.label));for(let D=1;D<B.length;D+=1)c.push({id:`wt_${B[D-1].id}--${B[D].id}`,source:B[D-1].id,target:B[D].id,type:"worktreeLink",label:D===1?`${N} peers`:void 0})}const p=l.filter(N=>N.type!=="defaultBranchNode"),b=p.filter(N=>N.isOrphan).length,w=p.filter(N=>N.hasConflicts).length,g=p.filter(N=>N.health==="offline").length,f=p.filter(N=>N.type==="submoduleNode"&&N.outOfSync).length,x=p.filter(N=>{var P;return N.type!=="submoduleNode"&&((P=N.branchConvergence)==null?void 0:P.needsConvergence)}).length,y=p.filter(N=>{var P;return((P=N.branchConvergence)==null?void 0:P.status)==="blocked_review"}).length,h=p.filter(N=>{var P;return((P=N.branchConvergence)==null?void 0:P.status)==="pushed_feature_branch_needs_merge"}).length,M=p.filter(N=>{var P;return((P=N.branchConvergence)==null?void 0:P.status)==="cleanup_candidate"}).length,S=p.filter(N=>{var P;return((P=N.branchConvergence)==null?void 0:P.status)==="not_mergeable"}).length,v=p.filter(N=>N.snapshotWarnings.length>0).length,T=p.filter(N=>N.snapshotCompleteness==="pending_git").length,A=p.filter(N=>N.snapshotCompleteness==="missing_git").length,k=p.filter(N=>N.snapshotCompleteness==="missing_submodule_report").length,j=p.filter(N=>N.snapshotCompleteness==="stale").length,O=[T>0?`${T} node(s) are still waiting for a live peer git snapshot`:null,A>0?`${A} node(s) have no visible peer git snapshot`:null,k>0?`${k} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,j>0?`${j} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return x>0&&d.push(`${x} workspace(s) still need follow-up before the mesh is converged`),b>0&&d.push(`${b} workspace(s) need attention before safe coordination`),y>0&&d.push(`${y} workspace(s) are blocked on branch convergence or upstream sync`),h>0&&d.push(`${h} clean feature branch workspace(s) still need merge follow-up`),M>0&&d.push(`${M} worktree workspace(s) are ready for refine / cleanup`),S>0&&d.push(`${S} workspace(s) have local changes or conflicts blocking convergence`),w>0&&d.push(`${w} workspace(s) report merge conflicts`),g>0&&d.push(`${g} node(s) are currently offline`),f>0&&d.push(`${f} submodule(s) are out of sync with their parent checkout`),d.push(...O),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:l,edges:c,stats:{totalNodes:p.length,onlineNodes:p.filter(N=>N.health==="online").length,dirtyNodes:p.filter(N=>N.dirty).length,orphanNodes:b,errorNodes:p.filter(N=>!!N.error||N.outOfSync).length,offlineNodes:g,followUpNodes:x,blockedReviewNodes:y,mergeReadyNodes:h,cleanupCandidateNodes:M,notMergeableNodes:S,incompleteSnapshotNodes:v,missingGitSnapshotNodes:A,missingSubmoduleSnapshotNodes:k,staleGitSnapshotNodes:j,totalActiveSessions:p.reduce((N,P)=>N+P.activeSessionCount,0)},warnings:d,snapshotWarnings:O}}const I0={recentFailures:0},pi=i.createContext(Zs("dark"));function nt({label:e,tone:t="default"}){const r=i.useContext(pi);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 ss({label:e,value:t}){const r=i.useContext(pi);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 M0(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 T0(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 A0(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 _0(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 L0(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 $l(e){return e?e.slice(0,7):null}function R0(e,t){var o,l,c;const r=$l((o=e==null?void 0:e.git)==null?void 0:o.headCommit),n=((c=(l=e==null?void 0:e.git)==null?void 0:l.headMessage)==null?void 0:c.trim())||"";if(r||n)return[r,n].filter(Boolean).join(" · ");const a=t[0];return a?[$l(a.commit),a.message].filter(Boolean).join(" · "):null}function P0(e,t){const r=R0(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function D0(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 E0(e){var r,n,a,o,l,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)||((l=e.selectedNodeStatus)==null?void 0:l.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 $0(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":_0(e.connection)}function B0(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 O0(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function gu({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null}){var I,E,R,$,z;const{theme:a}=Qs(),o=i.useMemo(()=>Zs(a),[a]),l=i.useMemo(()=>xu(e),[e]),c=i.useMemo(()=>C0(l),[l]),[d,m]=i.useState(null),[u,p]=i.useState(null),[b,w]=i.useState({}),g=i.useMemo(()=>new Map(l.nodes.map(H=>[H.nodeId,H])),[l.nodes]),f=i.useMemo(()=>new Map(c.nodes.map(H=>[H.id,H])),[c.nodes]),x=((I=l.queue)==null?void 0:I.summary)??null,y=((E=l.ledger)==null?void 0:E.summary)??I0,h=i.useMemo(()=>L0(l),[l]),M=i.useMemo(()=>{const H=new Map;for(const me of h){const ie=me.session.state||me.session.lifecycle||"unknown";H.set(ie,(H.get(ie)??0)+1)}return[...H.entries()].sort((me,ie)=>ie[1]-me[1])},[h]);i.useEffect(()=>{d&&(f.has(d)||(m(null),p(H=>!H||"nodeId"in H&&H.nodeId===d?null:H)))},[f,d]);const S=d?g.get(d)??null:null,v=O0(c,d);i.useEffect(()=>{var H,me,ie;if(d)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:l.meshId,selectedNodeId:d,canonicalNode:u0(S),graphNode:v?{id:v.id,branch:v.branch,upstream:v.upstream,headCommit:v.submoduleCommit,submoduleCount:((me=(H=S==null?void 0:S.git)==null?void 0:H.submodules)==null?void 0:me.length)??0,snapshotCompleteness:v.snapshotCompleteness,snapshotWarnings:v.snapshotWarnings,branchConvergence:((ie=v.branchConvergence)==null?void 0:ie.status)??null}:null})}catch{}},[l.meshId,v,d,S]);const T=(u==null?void 0:u.kind)==="session"?h.find(H=>H.nodeId===u.nodeId&&H.session.sessionId===u.sessionId)??null:null,A=i.useMemo(()=>h.filter(H=>H.nodeId===d),[d,h]),k=E0({coordinatorDaemonId:r,selectedNodeStatus:S,selectedSessionEntry:T}),j=(k==null?void 0:k.workspace)??null,O=j?b[j]??null:null,L=P0(S,(O==null?void 0:O.entries)??[]),N=i.useCallback(()=>{m(null),p(null)},[]);i.useEffect(()=>{if(!v)return;const H=me=>{me.key==="Escape"&&N()};return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[N,v]),i.useEffect(()=>{if(!k||!n)return;const{daemonId:H,workspace:me}=k,ie=b[me];if(ie!=null&&ie.loading||ie&&(ie.entries.length>0||ie.error))return;let ee=!1;return w(ce=>{var je;return{...ce,[me]:{loading:!0,error:null,entries:((je=ce[me])==null?void 0:je.entries)??[]}}}),n(H,"git_log",{workspace:me,limit:5}).then(ce=>{ee||w(je=>({...je,[me]:{loading:!1,error:null,entries:D0(ce)}}))}).catch(ce=>{ee||w(je=>({...je,[me]:{loading:!1,error:ce instanceof Error?ce.message:"git_log failed",entries:[]}}))}),()=>{ee=!0}},[b,k,n]);const P=[...c.warnings??[],...l.nodes.filter(H=>H.machineStatus&&H.machineStatus!=="online").map(H=>`${H.machineLabel}: ${H.machineStatus}`)],B=c.stats.incompleteSnapshotNodes>0,D=c.stats.followUpNodes>0?`${c.stats.followUpNodes} need follow-up`:B?"mesh visibility incomplete":"mesh converged",C=c.stats.followUpNodes>0?"danger":B?"warn":"good";return s.jsx(pi.Provider,{value:o,children:s.jsx("div",{className:"flex min-h-0 flex-col gap-4",children:s.jsx("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-4",children:s.jsxs("div",{className:`${o.cardClass} relative min-h-0 flex-1 rounded-[28px] p-3 sm:p-4`,style:{minHeight:420},children:[s.jsxs("div",{className:`absolute inset-x-4 top-4 z-30 flex max-h-[42dvh] flex-wrap items-start justify-between gap-3 overflow-y-auto rounded-2xl px-3.5 py-3 backdrop-blur-xl sm:static sm:mb-3 sm:max-h-none sm:overflow-visible sm:backdrop-blur-none ${o.isDark?"border border-white/10 bg-slate-950/85 sm:bg-slate-950/45":"border border-slate-200 bg-white/95 shadow-lg shadow-slate-900/10 sm:bg-white/95 sm:shadow-sm"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-wrap gap-2 text-xs ${o.textSecondary}`,children:[s.jsx(nt,{label:D,tone:C}),c.stats.blockedReviewNodes>0&&s.jsx(nt,{label:`${c.stats.blockedReviewNodes} blocked review`,tone:"danger"}),c.stats.notMergeableNodes>0&&s.jsx(nt,{label:`${c.stats.notMergeableNodes} not mergeable`,tone:"danger"}),c.stats.mergeReadyNodes>0&&s.jsx(nt,{label:`${c.stats.mergeReadyNodes} need merge`,tone:"warn"}),c.stats.cleanupCandidateNodes>0&&s.jsx(nt,{label:`${c.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),c.stats.offlineNodes>0&&s.jsx(nt,{label:`${c.stats.offlineNodes} offline`,tone:"danger"}),c.stats.incompleteSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),c.stats.missingGitSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),c.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),c.stats.staleGitSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((x==null?void 0:x.active)??0)>0&&s.jsx(nt,{label:`${(x==null?void 0:x.active)??0} active queue`,tone:"info"}),s.jsx(nt,{label:`${c.stats.totalNodes} nodes`,tone:"default"}),c.stats.totalActiveSessions>0&&s.jsx(nt,{label:`${c.stats.totalActiveSessions} active sessions`,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(nt,{label:`${c.stats.dirtyNodes} dirty`,tone:c.stats.dirtyNodes>0?"warn":"good"}),s.jsx(nt,{label:`${c.stats.orphanNodes} orphan`,tone:c.stats.orphanNodes>0?"warn":"good"}),s.jsx(nt,{label:`${y.recentFailures} recent failures`,tone:y.recentFailures>0?"danger":"good"}),M.length===0?s.jsx(nt,{label:"no session metadata"}):M.slice(0,2).map(([H,me])=>s.jsx(nt,{label:`${me} ${H}`,tone:T0(H)},H))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(nt,{label:"Anchor = default branch",tone:"info"}),s.jsx(nt,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(nt,{label:"Submodule link = child checkout",tone:"warn"})]}),P.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:P.map(H=>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:H},H))}),s.jsx("div",{className:`text-xs ${o.textMuted}`,children:"Click a node only when you want drill-down details. The graph itself now carries the convergence state."})]})]})]}),c.nodes.length>0?s.jsx(Jy,{data:c,selectedNodeId:d,onNodeClick:H=>{if((u==null?void 0:u.kind)==="node"&&d===H.id){m(null),p(null);return}m(H.id),p({kind:"node",nodeId:H.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}),v&&(u==null?void 0:u.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:N,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:H=>H.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:v.label}),s.jsx("div",{className:`mt-1 font-mono text-[11px] ${o.textMuted}`,children:v.id.slice(0,16)})]}),s.jsx("button",{type:"button",onClick:N,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(nt,{label:(S==null?void 0:S.health)??v.health,tone:M0((S==null?void 0:S.health)??v.health)}),v.branch&&s.jsx(nt,{label:v.branch,tone:"default"}),v.ahead>0&&s.jsx(nt,{label:`ahead ${v.ahead}`,tone:"warn"}),v.behind>0&&s.jsx(nt,{label:`behind ${v.behind}`,tone:"warn"}),v.dirtyFiles>0&&s.jsx(nt,{label:`${v.dirtyFiles} dirty`,tone:"warn"}),(S==null?void 0:S.connection)&&s.jsx(nt,{label:$0(S),tone:A0(S.connection)}),A.length>0&&s.jsx(nt,{label:`${A.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[s.jsx(ss,{label:"Workspace",value:(S==null?void 0:S.workspace)??v.workspace}),s.jsx(ss,{label:"Branch",value:v.branch??"unknown"}),s.jsx(ss,{label:"HEAD",value:L??(S!=null&&S.gitProbePending?"Pending live git probe":"not reported")}),s.jsx(ss,{label:"Upstream",value:v.upstream??"none"}),s.jsx(ss,{label:"Dirty/ahead/behind",value:`${v.dirtyFiles} dirty · ↑${v.ahead}/↓${v.behind}`}),s.jsx(ss,{label:"Source",value:String(((R=S==null?void 0:S.connection)==null?void 0:R.source)??B0(v))}),s.jsx(ss,{label:"Transport",value:(($=S==null?void 0:S.connection)==null?void 0:$.transport)??"unknown"}),s.jsx(ss,{label:"Sessions",value:A.length>0?A.map(H=>H.session.state||H.session.lifecycle||"unknown").join(", "):"none active"})]}),v.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:v.snapshotWarnings[0]})]}),((z=v.branchConvergence)==null?void 0:z.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:v.branchConvergence.nextStep})]})]})})]})})})})}function F0({activeConv:e,sendDaemonCommand:t,onClose:r}){var v;const n=typeof((v=e.settings)==null?void 0:v.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null,a=e.daemonId??null,o=$d(),{theme:l}=Qs(),c=i.useMemo(()=>Zs(l),[l]),[d,m]=i.useState(null),[u,p]=i.useState(!1),[b,w]=i.useState(null),[g,f]=i.useState(null),x=i.useRef(!1);i.useEffect(()=>{x.current=d!==null},[d]);const y=i.useCallback(async(T=!1)=>{if(!a||!n){w("This coordinator does not expose a live mesh id."),m(null);return}p(!x.current),w(null);try{const A=o!=null&&o.loadMeshStatus?await o.loadMeshStatus(a,n,{refresh:T}):await t(a,"mesh_status",{meshId:n,refresh:T}),k=bu(A);if(!k){w("mesh_status returned an unexpected payload.");return}m(k),f(k.refreshedAt||new Date().toISOString())}catch(A){w(A instanceof Error?A.message:"Failed to load live mesh status")}finally{p(!1)}},[a,n,o,t]);i.useEffect(()=>{y(!1)},[y]),i.useEffect(()=>{const T=A=>{A.key==="Escape"&&r()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[r]);const h=(d==null?void 0:d.meshName)||n||"Repo Mesh",M=g?new Date(g).toLocaleTimeString():null,S=i.useMemo(()=>u?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[u]);return s.jsx("div",{className:c.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:c.dialogShellClass,onClick:T=>T.stopPropagation(),children:[s.jsxs("div",{className:c.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(ns,{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:c.dialogTitleClass,children:h}),s.jsx("span",{className:c.dialogKickerClass,children:"Mesh observability"})]}),s.jsxs("p",{className:c.dialogSubtitleClass,children:[ut(e),e.workspaceName?` · ${e.workspaceName}`:"",d!=null&&d.repoIdentity?` · ${d.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[M&&s.jsxs("span",{className:c.dialogRefreshedChipClass,children:["Refreshed ",M]}),s.jsx("button",{type:"button",onClick:()=>{y(!0)},disabled:u,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:u?"Refreshing…":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:c.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:s.jsx(jt,{size:16})})]})]}),b&&s.jsx("div",{className:c.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:b}),s.jsx("div",{className:c.dialogBodyClass,children:d?s.jsx(gu,{status:d,emptyMessage:S,daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:c.dialogEmptyClass,children:S})})]})})}function H0(e,t){const{sendCommand:r}=kt(),[n,a]=i.useState(null),[o,l]=i.useState(!1);i.useEffect(()=>{if(!e||!t){a(null);return}l(!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(()=>l(!1))},[e,t,r]);const c=W0(n);return{remoteUrl:n,githubUrl:c,loading:o}}function W0(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 yu=5e3;function K0(e){return`git:${e}`}function U0({workspace:e,includeDiffSummary:t=!1,intervalMs:r=yu}){return{type:"subscribe",topic:"workspace.git",key:K0(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function fi(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Ms(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 z0(e){const t=fi(e);return(t==null?void 0:t.success)===!1?{status:null,error:Ms(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Ms(t,"Git status response did not include status")}}function G0(e){const t=fi(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Ms(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Ms(t,"Git diff summary response did not include diffSummary")}}function Ea(e){return e===void 0||typeof e=="boolean"}function V0(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Ea(t.binary)&&Ea(t.truncated)&&Ea(t.staged)}function q0(e){const t=fi(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Ms(t,"Git file diff request failed")}:V0(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Ms(t,"Git file diff response did not include a valid diff object")}}function Y0({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=yu}){const{sendCommand:o,sendData:l}=kt(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[m,u]=i.useState(null),[p,b]=i.useState(null),[w,g]=i.useState(!1),[f,x]=i.useState(null),y=i.useCallback(async()=>{if(!(!d||!e||!c)){g(!0),x(null);try{const M=z0(await o(e,"git_status",{workspace:c}));if(M.error){u(null),b(null),x(M.error);return}if(u(M.status),!n){b(null);return}const S=G0(await o(e,"git_diff_summary",{workspace:c}));if(S.error){b(null),x(S.error);return}b(S.diffSummary)}catch(M){x(Ms(M,"Git status request failed"))}finally{g(!1)}}},[d,e,n,o,c]),h=i.useMemo(()=>c?U0({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return i.useEffect(()=>{if(!d||!e||!c||!h){u(null),b(null),g(!1),x(null);return}const M=l?Jt.subscribe({sendData:l},e,h,S=>{var v,T;S.workspace===c&&(u(S.status),b(S.diffSummary??null),x(((v=S.status)==null?void 0:v.error)||((T=S.diffSummary)==null?void 0:T.error)||null),g(!1))},{retryIntervalMs:1e3}):null;return y(),()=>{M==null||M()}},[d,e,y,h,l,c]),{status:m,diffSummary:p,loading:w,error:f,refresh:y}}const X0={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},J0={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 Bl(e){return e.split("/").pop()??e}function Q0(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function Z0({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 l=n===o.path,c=X0[o.status]??"?",d=J0[o.status]??"text-zinc-400",m=Q0(o.path),u=Bl(o.path),p=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 ${l?"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:["← ",Bl(o.oldPath)]}),p]}),!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 ev(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 tv({diff:e,binary:t,truncated:r,loading:n,error:a,className:o=""}){const l=i.useRef(null);if(i.useEffect(()=>{l.current&&(l.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(`
64
+ `,V.style.top="52px",V.style.height="calc(100% - 52px)";const Fe=Re.querySelector("[data-adhdev-popout-focus]");Fe&&(Fe.onclick=()=>{window.focus()});const Ue=Re.querySelector("[data-adhdev-popout-dock]");Ue&&(Ue.disabled=!te,Ue.style.opacity=te?"1":"0.5",Ue.style.cursor=te?"pointer":"default",Ue.onclick=()=>{var Le;te&&Ne(te),(Le=W.defaultView)==null||Le.focus()})}},[z,Ne]),ae=i.useCallback(G=>{var se;const U=k.current,X=U==null?void 0:U.getPanel(G);if(!(!U||!X)){X.group.model.openPanel(X),X.api.setActive(),ie(G,"dockview-shortcut");try{const W=X.group.model.location;W.type==="popout"?W.getWindow().focus():Aa((se=X.group.element)==null?void 0:se.ownerDocument)}catch{}}},[ie]),ue=i.useCallback(G=>{const U=k.current,X=U==null?void 0:U.activePanel,se=(U==null?void 0:U.activeGroup)||(X==null?void 0:X.group);if(!U||!X||!se)return;const W=se.panels||[];if(W.length<=1)return;const V=W.findIndex(ke=>ke.id===X.id);if(V<0)return;const te=(V+G+W.length)%W.length,re=W[te];re&&(re.group.model.openPanel(re),re.api.setActive(),Bt(re.id)||ie(re.id,"dockview-shortcut"))},[ie]),oe=i.useCallback(G=>{var Fe;const U=k.current,X=(U==null?void 0:U.activeGroup)||((Fe=U==null?void 0:U.activePanel)==null?void 0:Fe.group);if(!U||!X)return;const se=U.groups||[],W=se.find(Ue=>Ue.id===X.id);if(!W)return;const V=W.element.getBoundingClientRect(),te=V.left+V.width/2,re=V.top+V.height/2,ke=(Ue,Le,Qe,et)=>Math.max(0,Math.min(Le,et)-Math.max(Ue,Qe)),Ee=Ue=>{const Le=Ue.element.getBoundingClientRect(),Qe=Le.left+Le.width/2,et=Le.top+Le.height/2;let gt=0,yt=0,dt=0,ht=!1;if(G==="left"?(ht=Qe<te,gt=Math.max(0,V.left-Le.right),yt=Math.abs(et-re),dt=ke(V.top,V.bottom,Le.top,Le.bottom)):G==="right"?(ht=Qe>te,gt=Math.max(0,Le.left-V.right),yt=Math.abs(et-re),dt=ke(V.top,V.bottom,Le.top,Le.bottom)):G==="above"?(ht=et<re,gt=Math.max(0,V.top-Le.bottom),yt=Math.abs(Qe-te),dt=ke(V.left,V.right,Le.left,Le.right)):(ht=et>re,gt=Math.max(0,Le.top-V.bottom),yt=Math.abs(Qe-te),dt=ke(V.left,V.right,Le.left,Le.right)),!ht)return Number.POSITIVE_INFINITY;const Ve=dt>0?0:120;return gt*3+yt+Ve};let Oe=null,Re=Number.POSITIVE_INFINITY;for(const Ue of se){if(Ue.id===W.id)continue;const Le=Ee(Ue);Number.isFinite(Le)&&(Le>=Re||(Re=Le,Oe=Ue))}return Oe||void 0},[]),de=i.useCallback(G=>{var se;const U=oe(G);if(!U)return;const X=U.activePanel||U.panels[0];X&&(U.model.openPanel(X),X.api.setActive(),Bt(X.id)||ie(X.id,"dockview-focus"),Aa((se=U.element)==null?void 0:se.ownerDocument))},[oe,ie]),Q=i.useCallback((G,U)=>{const X=k.current,se=X==null?void 0:X.activePanel,W=(X==null?void 0:X.activeGroup)||(se==null?void 0:se.group);if(!X||!se||!W)return;let V=oe(G);!V&&(U!=null&&U.createGroupIfMissing)&&(V=X.addGroup({referenceGroup:W,direction:G})),V&&(se.api.moveTo({group:V,position:"center"}),se.group.model.openPanel(se),se.api.setActive(),Bt(se.id)||ie(se.id,U!=null&&U.createGroupIfMissing?"dockview-split":"dockview-move"))},[oe,ie]),{isMac:ve,tabShortcuts:le,shortcutListening:pe,setShortcutListening:ne,saveShortcuts:Ie}=Yd({sortedTabKeys:e.map(G=>G.tabKey),onFocus:me,onSelectTab:ae}),Ce=i.useCallback(()=>{var X;const G=k.current;if(!G)return;const U=G.activePanel;if(U){if(Bt(U.id)){const se=((X=U.params)==null?void 0:X.routeId)||U.id.slice(7),W=Ht(e,se);W!=null&&W.tabKey&&ne(W.tabKey);return}z.has(U.id)&&ne(U.id)}},[z,ae,ne,e]),_e=i.useCallback(G=>{const U=[];return G.metaKey&&U.push(ve?"⌘":"Meta"),G.ctrlKey&&U.push("Ctrl"),G.altKey&&U.push(ve?"⌥":"Alt"),G.shiftKey&&G.key.length!==1&&U.push(ve?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(G.key)?null:(U.push(Zd(G.key)),U.join("+"))},[ve]),K=i.useCallback(G=>{var U,X;switch(G){case"splitActiveTabRight":Q("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Q("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const se=xe();se&&he(se);return}case"popoutActiveTab":{const se=xe();se&&je(se);return}case"dockActiveTab":{const se=xe();if(!se)return;q(se)?Ne(se):we(se)&&Se(se);return}case"focusLeftPane":de("left");return;case"focusRightPane":de("right");return;case"focusUpPane":de("above");return;case"focusDownPane":de("below");return;case"moveActiveTabToLeftPane":Q("left");return;case"moveActiveTabToRightPane":Q("right");return;case"moveActiveTabToUpPane":Q("above");return;case"moveActiveTabToDownPane":Q("below");return;case"selectPreviousGroupTab":ue(-1);return;case"selectNextGroupTab":ue(1);return;case"setActiveTabShortcut":Ce();return;case"hideCurrentTab":{const se=(X=(U=k.current)==null?void 0:U.activePanel)==null?void 0:X.id;se&&!Bt(se)&&ge(se);return}default:return}},[ue,Se,de,he,xe,ge,we,q,Ne,Q,je,Ce]);i.useEffect(()=>{if(!C)return;const G=C.sourceDocument,U=G.defaultView??window,X=se=>{const W=G.querySelector("[data-dockview-tab-context-menu]");W&&W.contains(se.target)||I(null)};return U.addEventListener("mousedown",X,!0),U!==window&&window.addEventListener("mousedown",()=>I(null),!0),()=>{U.removeEventListener("mousedown",X,!0),U!==window&&window.removeEventListener("mousedown",()=>I(null),!0)}},[C]);const Me=i.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:z,hasDetachedConversationPanels:H,ides:r,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:g,liveSessionInboxState:S,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:ge,userName:m,scrollToBottomRequest:M,tabShortcuts:le,openTabContextMenu:({x:G,y:U,tabKey:X,sourceDocument:se})=>I({x:G,y:U,tabKey:X,sourceDocument:se??document}),popoutTab:je,moveTabBackToMain:Ne,isTabInPopout:q,floatTab:he,isTabFloating:we}),[n,t,z,H,r,l,c,g,S,a,o,ge,m,M,le,je,Ne,q,he,we]),Te=C?py({isTabInPopout:q(C.tabKey),isTabFloating:we(C.tabKey),tabShortcut:le[C.tabKey],actionShortcuts:p}):[],We=i.useCallback(G=>{var se;const U=k.current;if((((se=U==null?void 0:U.activePanel)==null?void 0:se.id)??null)===G.id){G.group.model.openPanel(G);return}G.group.model.openPanel(G),G.api.setActive()},[]),Ge=i.useCallback((G,U="requested-tab")=>{if(!G)return!1;const X=k.current;if(!X)return!1;const se=X.getPanel(G);return se?(We(se),ie(G,U),h==null||h(),!0):!1},[We,h,ie]),Xe=i.useCallback(()=>{if(P.current)return!1;const G=Ge(B.current,"stored-layout-restore");return G&&(P.current=!0),G},[Ge]),Ye=i.useCallback(()=>{var U;const G=k.current;G&&Ub(v,{activeTabId:((U=G.activePanel)==null?void 0:U.id)??null,layout:G.toJSON()})},[v]),tt=i.useCallback(()=>{Gb(v,$.current)},[v]),ct=i.useCallback(G=>{var se,W,V,te;const U=k.current;if(!U)return{kind:"grid"};const X=U.toJSON();for(const re of X.floatingGroups||[])if((W=(se=re.data)==null?void 0:se.views)!=null&&W.includes(G)&&re.position)return{kind:"floating",position:re.position};for(const re of X.popoutGroups||[])if((te=(V=re.data)==null?void 0:V.views)!=null&&te.includes(G))return{kind:"popout",position:re.position,popoutUrl:re.url};return{kind:"grid"}},[]),mt=i.useCallback(G=>{const U=k.current;if(!U)return;const X=U.getPanel(G),se=$.current[G];if(!X||!se||se.kind==="grid")return;if(X.group.model.location.type===se.kind){delete $.current[G],tt();return}if(se.kind==="floating"){U.addFloatingGroup(X,{x:se.position.left??24,y:se.position.top??24,width:se.position.width,height:se.position.height}),delete $.current[G],tt();return}delete $.current[G],tt()},[tt]);i.useEffect(()=>(b==null||b({setShortcutForActiveTab:Ce,restoreHiddenTabToSavedLocation:mt,activateConversationTab:ae,resetAllPanelsToMain:J,activatePreviousTabInGroup:()=>ue(-1),activateNextTabInGroup:()=>ue(1),floatActiveTab:()=>{const G=xe();G&&he(G)},popoutActiveTab:()=>{const G=xe();G&&je(G)},dockActiveTab:()=>{const G=xe();G&&(q(G)?Ne(G):we(G)&&Se(G))},splitActiveTabRight:()=>Q("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Q("below",{createGroupIfMissing:!0}),focusLeftPane:()=>de("left"),focusRightPane:()=>de("right"),focusUpPane:()=>de("above"),focusDownPane:()=>de("below"),moveActiveTabToLeftPane:()=>Q("left"),moveActiveTabToRightPane:()=>Q("right"),moveActiveTabToUpPane:()=>Q("above"),moveActiveTabToDownPane:()=>Q("below")}),()=>b==null?void 0:b(null)),[ue,Se,he,de,xe,we,q,Q,Ne,je,b,J,mt,ae,Ce]),i.useEffect(()=>()=>{var G;(G=O.current)==null||G.call(O),O.current=null},[]);const pt=i.useCallback(G=>{var X,se;k.current=G.api,(X=O.current)==null||X.call(O),O.current=null;const U=Kb(v);if(B.current=(U==null?void 0:U.activeTabId)??null,U!=null&&U.layout&&G.api.fromJSON(U.layout,{reuseExistingPanels:!1}),N.current=Nl({hasStoredLayout:!!(U!=null&&U.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),N.current||(_l(G.api,e),Ll(G.api,e,y)),G.api.totalPanels===0&&e.length>0){const W=wy(G.api,e,x);if(W){const V=G.api.getPanel(W);V&&We(V)}}else!N.current&&!Ge(x)&&Xe();if(L.current=!0,G.api.onDidActivePanelChange(W=>{var te;if(B.current=(W==null?void 0:W.id)??null,P.current=!0,fe(),W&&Bt(W.id)){const re=((te=W.params)==null?void 0:te.routeId)||W.id.slice(7),ke=Ht(e,re);w((ke==null?void 0:ke.tabKey)??null),Ye();return}if(w((W==null?void 0:W.id)??null),Ye(),!W)return;const V=z.get(W.id);(V==null?void 0:V.streamSource)==="agent-stream"&&V.agentType&&A(V.routeId,Bc(),{agentType:V.agentType,...V.sessionId&&{targetSessionId:V.sessionId}}).catch(()=>{})}),G.api.onDidLayoutChange(()=>{Ye(),fe(),R(W=>W+1)}),by()){const W=Re=>({clientX:Re.clientX,clientY:Re.clientY}),V=Re=>{const Fe=Re==null?void 0:Re.getBoundingClientRect();return Fe?{left:Fe.left,right:Fe.right,top:Fe.top,bottom:Fe.bottom}:null},te=Re=>{var Ue;const Fe=(Ue=j.current)==null?void 0:Ue.getBoundingClientRect();return Fe?Re.clientX<Fe.left||Re.clientX>Fe.right||Re.clientY<Fe.top||Re.clientY>Fe.bottom:!1},re=xy({detachDelayMs:tu,onDetach:({panelId:Re,clientX:Fe,clientY:Ue})=>{var dt,ht;const Le=G.api.getPanel(Re);if(!Le)return;try{if(Le.group.model.location.type!=="grid")return}catch{return}const Qe=(dt=j.current)==null?void 0:dt.getBoundingClientRect(),et=(ht=Le.group.element)==null?void 0:ht.getBoundingClientRect(),gt=Math.round(Math.min(Math.max((et==null?void 0:et.width)??600,360),720)),yt=Math.round(Math.min(Math.max((et==null?void 0:et.height)??500,260),640));G.api.addFloatingGroup(Le,{x:Qe?Math.max(0,Fe-Qe.left-32):void 0,y:Qe?Math.max(0,Ue-Qe.top-18):void 0,width:gt,height:yt}),Le.api.setActive(),Ye(),fe(),R(Ve=>Ve+1)}}),ke=[G.api.onWillDragPanel(Re=>{if(!(Re.nativeEvent.defaultPrevented||Re.nativeEvent.shiftKey)){try{if(Re.panel.group.model.location.type!=="grid")return}catch{return}re.startDrag({panelId:Re.panel.id,selfPanelBounds:V(Re.panel.group.element),...W(Re.nativeEvent)})}}),G.api.onWillShowOverlay(Re=>{if(re.hasDetached()){Re.preventDefault();return}re.markDockTarget(W(Re.nativeEvent))}),G.api.onWillDrop(Re=>{if(re.hasDetached()){Re.preventDefault(),re.endDrag();return}re.markDockTarget(W(Re.nativeEvent))}),G.api.onDidDrop(()=>re.endDrag()),G.api.onUnhandledDragOverEvent(Re=>{re.isDragging()&&re.markSelfPanel(W(Re.nativeEvent))})],Ee=Re=>{if(!re.isDragging())return;const Fe=W(Re);te(Fe)&&re.markNonSelfPanel(Fe)},Oe=()=>re.endDrag();window.addEventListener("dragover",Ee,!0),window.addEventListener("drop",Oe,!0),window.addEventListener("dragend",Oe,!0),O.current=()=>{re.dispose();for(const Re of ke)Re.dispose();window.removeEventListener("dragover",Ee,!0),window.removeEventListener("drop",Oe,!0),window.removeEventListener("dragend",Oe,!0)}}G.api.onDidAddGroup(W=>{requestAnimationFrame(()=>{var V,te;try{const re=(V=W.element)==null?void 0:V.ownerDocument;if(!re||re===document)return;(te=re.getElementById("dv-popout-window"))==null||te.classList.add("adhdev-dockview");const ke=document.documentElement.getAttribute("data-theme");ke&&re.documentElement.setAttribute("data-theme",ke),re.body.className=document.body.className;const Ee=document.documentElement.getAttribute("style");Ee&&re.documentElement.setAttribute("style",Ee)}catch{}fe(),R(re=>re+1)})}),w(((se=G.api.activePanel)==null?void 0:se.id)??null)},[We,Ge,z,r,d,v,w,Ye,x,y,A,fe,e]);i.useLayoutEffect(()=>{const G=k.current;if(!G||!L.current||N.current&&Nl({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;N.current&&(N.current=!1);const U=D.current,X=new Set(U),se=e.map(Oe=>Oe.tabKey),W=new Set(se),V=fy({previousVisibleConversationCount:U.length,visibleConversationCount:e.length,ides:r});let te=!1;for(const Oe of U)W.has(Oe)||V||($.current[Oe]=ct(Oe),te=!0);te&&tt(),V||(_l(G,e),Ll(G,e,y));const re=se.filter(Oe=>!X.has(Oe));let ke=!1;for(const Oe of re){const Re=G.getPanel(Oe),Fe=$.current[Oe];if(!Re||!Fe||Fe.kind==="grid")continue;if(Re.group.model.location.type===Fe.kind){delete $.current[Oe],ke=!0;continue}if(Fe.kind==="floating"){G.addFloatingGroup(Re,{x:Fe.position.left??24,y:Fe.position.top??24,width:Fe.position.width,height:Fe.position.height}),delete $.current[Oe],ke=!0;continue}}if(ke&&tt(),D.current=se,x&&Ge(x))return;!G.activePanel&&G.panels[0]&&We(G.panels[0]),!!(G.activePanel&&G.getPanel(G.activePanel.id))||Xe()},[We,Ge,Xe,r,d,tt,ct,x,y,e]),i.useEffect(()=>{L.current&&Ge(x)},[Ge,x]),i.useEffect(()=>{const G=X=>{const se=X.target;if(!se)return;const W=se.querySelector("[data-tab-key]")||se.closest("[data-tab-key]");if(W){const V=W.getAttribute("data-tab-key");if(V&&X.dataTransfer){const te=se.closest(".dv-tab")||W.closest(".dv-tab")||W;X.dataTransfer.effectAllowed="move",X.dataTransfer.setData("text/tab-key",V),te instanceof HTMLElement&&X.dataTransfer.setDragImage(te,Math.max(12,Math.round(te.clientWidth/2)),Math.max(10,Math.round(te.clientHeight/2)))}}};window.addEventListener("dragstart",G);const U=Al(k.current);for(const X of U)X.addEventListener("dragstart",G);return()=>{window.removeEventListener("dragstart",G);for(const X of U)X.removeEventListener("dragstart",G)}},[E]),i.useEffect(()=>{var U;const G=(U=j.current)==null?void 0:U.querySelector(".adhdev-dockview");G instanceof HTMLElement&&_a(G,T),ce(),fe()},[fe,ce,T]),i.useEffect(()=>{fe()},[fe]),i.useEffect(()=>{const G=U=>{if(U.defaultPrevented||pe)return;const X=_e(U);if(!X)return;const se=U.metaKey||U.ctrlKey||U.altKey;xo(U.target)&&!se||On(ve).setActiveTabShortcut!==X||(U.preventDefault(),U.stopPropagation(),Ce())};return window.addEventListener("keydown",G,!0),()=>window.removeEventListener("keydown",G,!0)},[_e,ve,pe,Ce]),i.useEffect(()=>{const G=j.current;if(!G)return;const U=X=>{var re,ke;if(!X.isTrusted)return;const se=(ke=(re=X.target)==null?void 0:re.closest)==null?void 0:ke.call(re,".dv-scrollable");if(!se)return;X.preventDefault(),X.stopPropagation();const W=Math.abs(X.deltaX),V=Math.abs(X.deltaY),te=W>V?X.deltaX:X.deltaY;se.dispatchEvent(new WheelEvent("wheel",{deltaY:te,deltaMode:X.deltaMode,bubbles:!1,cancelable:!0}))};return G.addEventListener("wheel",U,{passive:!1,capture:!0}),()=>G.removeEventListener("wheel",U,{capture:!0})},[]),i.useEffect(()=>{const G=Al(k.current);if(G.length===0)return;const U=G.map(X=>{let se=[],W=null;const V=()=>{W!=null&&X.clearTimeout(W),W=null,se=[]},te=()=>{W!=null&&X.clearTimeout(W),W=X.setTimeout(()=>{W=null,se=[]},1200)},re=Ee=>{if(!Ee.ctrlKey&&!Ee.metaKey&&!Ee.altKey)return;const Oe=_e(Ee);if(!Oe)return;const Re=qd();for(const[Fe,Ue]of Object.entries(Re))if(e.some(Le=>Le.tabKey===Fe)&&Ue===Oe){Ee.preventDefault(),ae(Fe);return}},ke=Ee=>{if(Ee.defaultPrevented||pe)return;const Oe=_e(Ee);if(!Oe)return;const Re=Ee.metaKey||Ee.ctrlKey||Ee.altKey;if(xo(Ee.target))return;const Fe=On(ve),Ue=Object.entries(Fe).filter(([Ve,Wt])=>!!Wt&&(Ve==="splitActiveTabRight"||Ve==="splitActiveTabDown"||Ve==="floatActiveTab"||Ve==="popoutActiveTab"||Ve==="dockActiveTab"||Ve==="focusLeftPane"||Ve==="focusRightPane"||Ve==="focusUpPane"||Ve==="focusDownPane"||Ve==="moveActiveTabToLeftPane"||Ve==="moveActiveTabToRightPane"||Ve==="moveActiveTabToUpPane"||Ve==="moveActiveTabToDownPane"||Ve==="selectPreviousGroupTab"||Ve==="selectNextGroupTab"||Ve==="setActiveTabShortcut"||Ve==="hideCurrentTab")),Le=Re?[Oe]:[...se.slice(-1),Oe].slice(-2),Qe=Le.join(" "),et=Le[Le.length-1],gt=Ue.find(([,Ve])=>Ve===Qe);if(gt){Ee.preventDefault(),V(),K(gt[0]);return}if(Ue.some(([,Ve])=>Ve.startsWith(`${Qe} `))){Ee.preventDefault(),se=Le,te();return}const dt=Ue.find(([,Ve])=>Ve===et);if(dt){Ee.preventDefault(),V(),K(dt[0]);return}if(Ue.some(([,Ve])=>Ve.startsWith(`${et} `))){Ee.preventDefault(),se=[et],te();return}V()};return X.addEventListener("keydown",re),X.addEventListener("keydown",ke),()=>{V(),X.removeEventListener("keydown",re),X.removeEventListener("keydown",ke)}});return()=>{for(const X of U)X()}},[_e,ve,E,ae,pe,K,e]);const F=T==="light"?Ya:Xa,be=((qe=(Be=(Ae=k.current)==null?void 0:Ae.activePanel)==null?void 0:Be.group.element)==null?void 0:qe.ownerDocument)??document;return s.jsxs(su.Provider,{value:Me,children:[s.jsx("div",{ref:j,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(Zu,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:jy,remote:ky},defaultTabComponent:Ny,watermarkComponent:Sy,onReady:pt,singleTabMode:"default",tabAnimation:"smooth",theme:F,popoutUrl:"/popout.html"})}),C&&Nr.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:C.x,top:C.y},children:Te.map(G=>{if(G.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},G.id);let U=s.jsx(tp,{size:13,className:"shrink-0 opacity-70"}),X=()=>{};switch(G.id){case"dockInWindow":case"dockBackToGrid":U=s.jsx(rp,{size:13,className:"shrink-0 opacity-70"}),X=()=>{Se(C.tabKey),I(null)};break;case"moveBackToMain":U=s.jsx(ep,{size:13,className:"shrink-0 opacity-70"}),X=()=>{Ne(C.tabKey),I(null)};break;case"floatAsPanel":U=s.jsx(sp,{size:13,className:"shrink-0 opacity-70"}),X=()=>{he(C.tabKey),I(null)};break;case"openInNewWindow":U=s.jsx(Zm,{size:13,className:"shrink-0 opacity-70"}),X=()=>{je(C.tabKey),I(null)};break;case"setShortcut":X=se=>{se.stopPropagation(),ne(C.tabKey),I(null)};break;case"removeShortcut":U=s.jsx(jt,{size:13,className:"shrink-0 opacity-70"}),X=()=>{const se={...le};delete se[C.tabKey],Ie(se),I(null)};break;case"hideTab":U=s.jsx(Co,{size:13,className:"shrink-0 opacity-70"}),X=()=>{ge(C.tabKey),I(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 ${G.tone==="muted"?"text-text-muted":""}`,onMouseDown:yy,onClick:X,children:[U,s.jsx("span",{className:"flex-1 min-w-0",children:G.label}),G.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:G.shortcut}):null]},G.id)})}),C.sourceDocument.body),pe&&Nr.createPortal(s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>ne(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:G=>G.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. ",ve?"⌘+1":"Ctrl+1",", ",ve?"⌥+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"})]})}),be.body)]})}const ru="adhdev-recent-launch-args-v1",Iy=8;function nu(e){return String(e||"").trim().replace(/\s+/g," ")}function ni(e,t){return`${e.trim()}::${t.trim()}`}function ai(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(ru)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function au(e){if(!(typeof window>"u"))try{window.localStorage.setItem(ru,JSON.stringify(e))}catch{}}function bo(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=ai().byKey[ni(r,n)])==null?void 0:o.items)||[]}function ou(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=nu(r);if(!n||!a||!o)return;const l=ai(),c=ni(n,a),d=((u=l.byKey[c])==null?void 0:u.items)||[],m=[o,...d.filter(p=>p!==o)].slice(0,Iy);l.byKey[c]={items:m},au(l)}function My(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=nu(r);if(!n||!a||!o)return;const l=ai(),c=ni(n,a),m=(((u=l.byKey[c])==null?void 0:u.items)||[]).filter(p=>p!==o);m.length>0?l.byKey[c]={items:m}:delete l.byKey[c],au(l)}function iu(e){return!e.hasLoadedInitialResults&&!e.isLoading}function yn({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 Ty({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 lu({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:l,onOpenHistory:c,onClearSelection:d}){const m=o?zd(o):null,u=Ty({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(yn,{title:"Saved history",description:zo(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:l,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:c,children:xx()})]}),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 cu({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 Ay({workspaceMode:e,activeKind:t,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:o,onSelect:l}){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:"IDE",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:()=>l(c.id),disabled:!c.enabled||o,children:c.label},c.id))})]})}function La(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>Is(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>Is(a,"acp"))?"acp":null}function rn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function _y({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:l,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Ve,Wt;const u=Pr(),p=i.useMemo(()=>[...e].sort(Po),[e]),[b,w]=i.useState(((Ve=p[0])==null?void 0:Ve.id)||""),g=i.useMemo(()=>p.find(Z=>Z.id===b)||p[0],[b,p]),f=i.useMemo(()=>((g==null?void 0:g.workspaces)||[]).map(Z=>({id:Z.id,path:Z.path,label:Z.label})),[g]),x=(g==null?void 0:g.defaultWorkspaceId)||null,[y,h]=i.useState("workspace"),[M,S]=i.useState(""),[v,T]=i.useState(""),[A,k]=i.useState([]),[j,O]=i.useState(""),[L,N]=i.useState(!1),[P,B]=i.useState(null),[D,C]=i.useState(""),[I,E]=i.useState(La(p[0])),[R,$]=i.useState(""),[z,H]=i.useState(""),[me,ie]=i.useState([]),[ee,ce]=i.useState(""),[je,Ne]=i.useState([]),[q,ge]=i.useState(!1),[he,we]=i.useState(!1),[xe,Se]=i.useState(""),[J,fe]=i.useState(!1),[ae,ue]=i.useState(()=>Nt()),[oe,de]=i.useState(null),[Q,ve]=i.useState(!1),[le,pe]=i.useState(""),[ne,Ie]=i.useState(null),[Ce,_e]=i.useState(!1),[K,Me]=i.useState(""),[Te,We]=i.useState([]),[Ge,Xe]=i.useState(!1),[Ye,tt]=i.useState(""),[ct,mt]=i.useState(!1),pt=i.useRef(null),F=i.useRef(0);i.useEffect(()=>{var Z;!b&&((Z=p[0])!=null&&Z.id)&&w(p[0].id)},[b,p]),i.useEffect(()=>{!g||!(!g.workspaces||!g.availableProviders||!g.detectedIdes||!g.recentLaunches)||u(g.id,{minFreshMs:3e4}).catch(()=>{})},[u,g]);const be=i.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(Z=>Is(Z,"cli")),[g]),Ae=i.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(Z=>Is(Z,"acp")),[g]),Be=i.useMemo(()=>((g==null?void 0:g.detectedIdes)||[]).map(Z=>({id:Z.type,label:Z.name||Z.type,meta:Z.running?"Detected locally":"Available to open"})),[g]),qe=i.useMemo(()=>I==="cli"?be.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"CLI provider"})):I==="acp"?Ae.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"ACP provider"})):Be,[Ae,I,be,Be]),G=i.useMemo(()=>A.find(Z=>Z.id===j)||null,[A,j]),U=i.useMemo(()=>be.find(Z=>Z.type===R)||null,[be,R]),X=i.useMemo(()=>Bd(U==null?void 0:U.meshCoordinator,{meshId:(G==null?void 0:G.id)||"",workspace:(G==null?void 0:G.workspace)||""}),[U,G]),se=ne||X,W=i.useCallback(async Z=>{N(!0),C("");try{const $e=await c(Z);k($e),O(_=>{var Y;return $e.some(ye=>ye.id===_)?_:((Y=$e[0])==null?void 0:Y.id)||""}),B(Z)}catch($e){k([]),O(""),B(Z),C($e instanceof Error?$e.message:"Could not load meshes")}finally{N(!1)}},[c]);i.useEffect(()=>{var $e;if(!g)return;if(pt.current!==g.id){pt.current=g.id,h("workspace"),S(x||(($e=f[0])==null?void 0:$e.id)||"__home__"),T(""),k([]),O(""),B(null),C(""),E(La(g)),$(""),H(""),ce(""),Ne([]),we(!1),Se(""),ue(Nt()),pe(""),Ie(null);return}S(_=>{var Y;return _==="__custom__"||_==="__home__"||f.some(ye=>ye.id===_)?_:x||((Y=f[0])==null?void 0:Y.id)||"__home__"}),E(_=>_==="ide"&&Be.length>0||_==="cli"&&be.length>0||_==="acp"&&Ae.length>0?_:La(g))},[Ae.length,be.length,x,Be.length,g,f]),i.useEffect(()=>{!g||y!=="mesh"||P===g.id||L||W(g.id)},[W,P,L,g,y]),i.useEffect(()=>{y==="mesh"&&I!=="cli"&&be.length>0&&E("cli")},[I,be.length,y]),i.useEffect(()=>{var Z;I&&(qe.some($e=>$e.id===R)||$(((Z=qe[0])==null?void 0:Z.id)||""))},[I,qe,R]),i.useEffect(()=>{Ie(null)},[g==null?void 0:g.id,j,R,y]);const V=i.useCallback(async(Z,$e)=>{const _=F.current+1;return F.current=_,ge(!0),Se(""),m(Z,$e).then(Y=>{F.current===_&&Ne(Y)}).catch(Y=>{F.current===_&&(Ne([]),Se(Y instanceof Error?Y.message:"Could not load saved sessions"))}).finally(()=>{F.current===_&&(ge(!1),we(!0))})},[m]),te=i.useCallback((Z,$e)=>{ie(bo(Z,$e))},[]);i.useEffect(()=>{F.current+=1,ce(""),ue(Nt()),!g||!R||I==="ide"?ie([]):te(g.id,R),we(!1),Ne([]),Se(""),ge(!1)},[I,te,V,g,R]),i.useEffect(()=>{if(!ee)return;const Z=je.find($e=>$e.providerSessionId===ee);Z!=null&&Z.canResume||ce("")},[je,ee]);const re=M==="__custom__"?v.trim():M==="__home__"?"":((Wt=f.find(Z=>Z.id===M))==null?void 0:Wt.path)||"",ke=i.useMemo(()=>g?t.filter(Z=>Z.id!==g.id&&Z.daemonId===g.id).map(Z=>Z.workspace):[],[t,g]),Ee=i.useMemo(()=>((g==null?void 0:g.recentLaunches)||[]).map(Z=>Z.workspace),[g]),Oe=i.useCallback(Z=>{const $e=String(Z.workspace||"").trim();if(!$e)return;const _=f.find(Y=>rn(Y.path)===rn($e));if(_){S(_.id),T("");return}S("__custom__"),T($e)},[f]),Re=i.useCallback(Z=>{const $e=String(Z.workspace||"").trim();if(!$e)return{workspaceId:null,workspacePath:null};const _=f.find(Y=>rn(Y.path)===rn($e));return _?{workspaceId:_.id,workspacePath:null}:{workspaceId:null,workspacePath:$e}},[f]),Fe=i.useMemo(()=>je.find(Z=>Z.providerSessionId===ee)||null,[je,ee]),Ue=i.useMemo(()=>{var $e;if(I!=="cli"||!g||!R)return null;const Z=(($e=be.find(_=>_.type===R))==null?void 0:$e.displayName)||R;return{routeId:g.id,daemonId:g.id,providerSessionId:ee||void 0,transport:"pty",mode:"chat",agentName:Z,agentType:R,status:"idle",title:Z,messages:[],ideType:R,workspaceName:re,workspacePath:re,displayPrimary:Z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${g.id}:${R}`,machineName:_t(g,{fallbackId:g.id})}},[I,be,re,g,ee,R]),Le=i.useCallback(()=>{var $e;if(!g)return;S("__custom__"),_e(!0),tt("");const Z=Qn(g.platform,Jn(v.trim(),re,ke,Ee,g.defaultWorkspacePath,($e=f.find(_=>_.id===x))==null?void 0:$e.path,f.map(_=>_.path)));Xe(!0),n(g.id,Z).then(_=>{Me(_.path),T(_.path),We(_.directories)}).catch(_=>{tt(_ instanceof Error?_.message:"Could not load folder")}).finally(()=>Xe(!1))},[v,x,Ee,ke,n,re,g,f]),Qe=i.useCallback(Z=>{g&&(Xe(!0),tt(""),n(g.id,Z).then($e=>{Me($e.path),T($e.path),We($e.directories)}).catch($e=>{tt($e instanceof Error?$e.message:"Could not load folder")}).finally(()=>Xe(!1)))},[n,g]),et=i.useCallback(async()=>{if(!g||!re)return;mt(!0),pe("");const Z=await a(g.id,re);if(mt(!1),!Z.ok){pe(Z.error||"Could not save workspace");return}pe("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,re,g]),gt=i.useCallback(async()=>{if(!g)return;if(y==="mesh"){if(!j||!R)return;ve(!0),pe(""),Ie(null);const _=await d(g.id,j,R);if(ve(!1),!_.ok){if(_.code==="mesh_coordinator_manual_mcp_setup_required"&&_.manualSetup){Ie(_.manualSetup),pe("Manual MCP setup required before this provider can act as mesh coordinator.");return}pe(_.error||"Could not start mesh coordinator");return}r();return}if(!I||!R)return;ve(!0),pe("");const Z=z.trim()?z.trim().split(/\s+/).filter(Boolean):[],$e=I==="ide"?await o(g.id,R,{workspacePath:re||null}):await l(g.id,I,R,{workspaceId:M!=="__home__"&&M!=="__custom__"?M:null,workspacePath:M==="__custom__"&&re||null,resumeSessionId:I==="cli"&&ee?ee:null,cliArgs:Z});if(ve(!1),!$e.ok){pe($e.error||"Could not start session");return}I!=="ide"&&z.trim()&&(ou(g.id,R,z),te(g.id,R)),r()},[I,z,te,r,o,d,l,re,g,j,ee,R,M,y]),yt=y==="mesh"?"Start mesh coordinator":I?nd(I,I==="cli"&&!!ee):"Start",dt=y==="mesh"?"Starting coordinator…":I?ad(I,I==="cli"&&!!ee):"Starting…",ht=p.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(jt,{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:[s.jsx(yn,{title:"Machine",children:ht?s.jsx("select",{"aria-label":"Machine",value:g.id,onChange:Z=>w(Z.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:Q,children:p.map(Z=>s.jsx("option",{value:Z.id,children:_t(Z,{fallbackId:Z.id})},Z.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:p.map(Z=>{const $e=_t(Z,{fallbackId:Z.id}),_=g.id===Z.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${$e}`,"aria-pressed":_,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${_?"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:()=>w(Z.id),disabled:Q,title:$e,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${Z.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:$e})]},Z.id)})})}),s.jsxs(yn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:y==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Le,disabled:Q,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(Z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":y===Z.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${y===Z.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:()=>{h(Z.id),pe(""),Z.id==="mesh"&&g&&P!==g.id&&!L&&W(g.id)},disabled:Q,children:[s.jsx("div",{className:"text-sm font-semibold",children:Z.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:Z.desc})]},Z.id))}),y==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:M,onChange:Z=>{const $e=Z.target.value;S($e),$e==="__custom__"?Le():pe("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Q,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),f.map(Z=>s.jsxs("option",{value:Z.id,children:[Z.id===x?"⭐ ":"",Gn(Z.path,Z.label)||Z.path]},Z.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:M==="__home__"?"Launch without a workspace.":re||"Select a workspace folder."}),M==="__custom__"&&re&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Le,disabled:Q,children:[s.jsx(Ss,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:et,disabled:Q||ct,children:ct?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[L&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!L&&D&&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:D}),!L&&!D&&A.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."}),A.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:A.map(Z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":j===Z.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${j===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>O(Z.id),disabled:Q,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[Z.repoIdentity||"Repo mesh",typeof Z.nodesCount=="number"?` · ${Z.nodesCount} node${Z.nodesCount===1?"":"s"}`:""]}),Z.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",Z.workspace]})]},Z.id))}),G&&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(Ay,{workspaceMode:y,activeKind:I,cliEnabled:be.length>0,ideEnabled:Be.length>0,acpEnabled:Ae.length>0,busy:Q,onSelect:E}),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:I==="ide"?"Choose IDE":I==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[qe.map(Z=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${R===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(Z.id),disabled:Q,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Z.meta})]},Z.id)),qe.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."})]})]}),y==="mesh"&&se&&s.jsx(cu,{setup:se,providerName:(U==null?void 0:U.displayName)||(U==null?void 0:U.name)||R}),y!=="mesh"&&I!=="ide"&&s.jsxs(yn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:z,onChange:Z=>H(Z.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:Q}),me.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:me.map(Z=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>H(Z),disabled:Q,title:Z,children:Z},Z))})]}),y!=="mesh"&&I==="cli"&&s.jsx(lu,{busy:Q,savedSessionsLoading:q,savedSessionsError:xe,selectedSession:Fe,onRefresh:()=>{!g||!R||V(g.id,R)},onOpenHistory:()=>{!g||!R||(fe(!0),iu({hasLoadedInitialResults:he,isLoading:q})&&V(g.id,R))},onClearSelection:()=>ce("")}),le&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${le.includes("saved")||le.includes("requested")||le.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:le})]}),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:Q,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:gt,disabled:Q||(y==="mesh"?!j||!R||I!=="cli"||L:!I||!R||M==="__custom__"&&!re),children:[s.jsx(Mo,{size:14}),Q?dt:yt]})]})]})}),Ce&&s.jsx(ea,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:K,directories:Te,busy:Ge,error:Ye,onClose:()=>_e(!1),onNavigate:Qe,onConfirm:Z=>{T(Z),Me(Z),S("__custom__"),_e(!1)}}),J&&Ue&&s.jsx(qo,{activeConv:Ue,ides:[],isCreatingChat:!1,isRefreshingHistory:q,savedSessions:je,isSavedSessionsLoading:q,isResumingSavedSessionId:oe,savedHistoryFilters:ae,missingWorkspaceResumePath:re||null,onSavedHistoryFiltersChange:ue,onClose:()=>fe(!1),onNewChat:()=>{ce(""),fe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!g||!R||V(g.id,R)},onResumeSavedSession:Z=>{if(!g||!R||oe||!Z.canResume)return;const $e=Re(Z);ce(Z.providerSessionId),Oe(Z),de(Z.providerSessionId),fe(!1),ve(!0),pe(""),l(g.id,"cli",R,{workspaceId:$e.workspaceId,workspacePath:$e.workspacePath,resumeSessionId:Z.providerSessionId}).then(_=>{if(!_.ok){pe(_.error||"Could not resume session");return}r()}).finally(()=>{ve(!1),de(_=>_===Z.providerSessionId?null:_)})}})]}):null}function du(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 oi(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=du(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 ii(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function uu(e){var t;return!ii(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 nn(e){return[...new Set(e.filter(t=>!!t))]}function Ly(e){const t=e.nodes.find(l=>l.type==="defaultBranchNode")??null,r=(t==null?void 0:t.branch)??null,n=e.nodes.filter(l=>l.type!=="defaultBranchNode"&&l.type!=="submoduleNode"&&!l.isOrphan&&!!r&&l.branch===r),a=e.nodes.filter(l=>l.type!=="submoduleNode"&&!l.isOrphan),o=e.nodes.filter(l=>l.type!=="submoduleNode");return t||n.length>0?nn([t==null?void 0:t.id,...n.map(l=>l.id)]):a.length>0?nn(a.map(l=>l.id)):o.length>0?nn(o.map(l=>l.id)):nn(e.nodes.map(l=>l.id))}function mu(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 Ry(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${mu(e)}::${n}x${a}`}const Py={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"},Dy={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"},Ey={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"},$y={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 Zs(e){return e==="light"?{theme:e,isDark:!1,flowColorMode:"light",textPrimary:"text-slate-900",textSecondary:"text-slate-700",textMuted:"text-slate-500",graphShellClass:"relative w-full min-w-0 overflow-hidden rounded-2xl border border-slate-200 bg-[radial-gradient(circle_at_top,_rgba(14,165,233,0.16),_rgba(248,250,252,0.98)_42%,_rgba(255,255,255,1))]",graphStatChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-slate-700 shadow-sm",graphHintChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-[10px] text-slate-500 shadow-sm",graphControlsClass:"!bottom-4 !left-4 !shadow-md",graphBackgroundDotColor:"rgba(148, 163, 184, 0.34)",edgeLabelTextColor:"#334155",edgeLabelBackgroundColor:"rgba(255, 255, 255, 0.96)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.45)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[rgba(148,163,184,0.22)] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"flex h-[100dvh] w-full flex-col overflow-hidden bg-white md:h-[min(90vh,960px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-slate-200 md:bg-white/98 md:shadow-[0_28px_120px_rgba(148,163,184,0.28)]",dialogHeaderClass:"flex shrink-0 flex-col gap-3 border-b border-slate-200 bg-white/96 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-slate-900 md:text-xl",dialogKickerClass:"rounded-full border border-slate-300 bg-slate-50 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-600",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-500",dialogRefreshedChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1.5 text-xs text-slate-600",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-300 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",dialogBodyClass:"min-h-0 flex-1 overflow-y-auto bg-[linear-gradient(180deg,rgba(248,250,252,0.98),rgba(241,245,249,0.96))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-slate-300 bg-white/90 px-6 text-center text-sm text-slate-500",cardClass:"rounded-2xl border border-slate-200 bg-white/95 shadow-sm",cardHeaderClass:"border-b border-slate-200 px-4 py-3",cardTitleClass:"text-sm font-semibold text-slate-900",cardSubtitleClass:"mt-1 text-xs text-slate-500",rowClass:"flex items-start justify-between gap-3 border-b border-slate-200/80 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"text-slate-500",rowValueClass:"max-w-[65%] break-all text-right text-slate-800",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-slate-200 bg-white/95 p-4 shadow-md md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-slate-200 bg-white/95 p-4 text-xs text-slate-500 shadow-sm md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-900",panelCloseButtonClass:"text-xs text-slate-500 hover:text-slate-900",panelFieldRowClass:"flex justify-between gap-3 border-b border-slate-200/80 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-500",panelFieldValueClass:"break-all text-right font-medium text-slate-700",infoCalloutClass:"mt-1 rounded border border-sky-300 bg-sky-50 px-2 py-1.5 text-[10px] text-sky-700",badge:t=>Dy[t],actionButton:t=>$y[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative w-full min-w-0 overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",graphStatChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-slate-200",graphHintChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-[10px] text-slate-300",graphControlsClass:"!bottom-4 !left-4 !shadow-lg",graphBackgroundDotColor:"rgba(148, 163, 184, 0.22)",edgeLabelTextColor:"#cbd5e1",edgeLabelBackgroundColor:"rgba(2, 6, 23, 0.86)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.2)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[#030617]/[0.58] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"flex h-[100dvh] w-full flex-col overflow-hidden bg-slate-950 md:h-[min(90vh,960px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-white/10 md:bg-slate-950/96 md:shadow-[0_28px_120px_rgba(2,6,23,0.46)]",dialogHeaderClass:"flex shrink-0 flex-col gap-3 border-b border-white/10 bg-slate-950/92 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-white md:text-xl",dialogKickerClass:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-300",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-400",dialogRefreshedChipClass:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 bg-white/6 text-slate-300 transition hover:bg-white/10 hover:text-white",dialogBodyClass:"min-h-0 flex-1 overflow-y-auto bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-white/10 bg-white/[0.03] px-6 text-center text-sm text-slate-400",cardClass:"rounded-2xl border border-white/10 bg-white/[0.04]",cardHeaderClass:"border-b border-white/10 px-4 py-3",cardTitleClass:"text-sm font-semibold text-white",cardSubtitleClass:"mt-1 text-xs text-slate-400",rowClass:"flex items-start justify-between gap-3 border-b border-white/5 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"text-slate-400",rowValueClass:"max-w-[65%] break-all text-right text-slate-100",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-white/10 bg-white/[0.04] p-4 shadow-lg md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-white/10 bg-white/[0.04] p-4 text-xs text-slate-400 md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-100",panelCloseButtonClass:"text-xs text-slate-400 hover:text-slate-100",panelFieldRowClass:"flex justify-between gap-3 border-b border-white/6 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-400",panelFieldValueClass:"break-all text-right font-medium text-slate-200",infoCalloutClass:"mt-1 rounded bg-blue-500/10 border border-blue-500/20 px-2 py-1.5 text-[10px] text-blue-300",badge:t=>Py[t],actionButton:t=>Ey[t]}}const It={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,columnGap:540,edgeLabelBuffer:180,defaultToContentGap:136,worktreeStackGap:82,parentToSubmoduleGap:48,submoduleStackGap:36,submoduleIndentX:72,placeholderTopOffset:0};function an(e,t,r){const n=(e||"").trim();return n?Math.max(1,Math.min(r,Math.ceil(n.length/t))):0}function By(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 li(e){return e.type==="submoduleNode"?It.submoduleCardWidth:It.worktreeCardWidth}function pu(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=du(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 vn(e){const t=li(e),r=e.type==="submoduleNode"?24:30,n=Math.ceil(By(e)/(e.type==="submoduleNode"?2:3)),a=an(e.label,r,2),o=an(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,r,2),l=an(pu(e),r+4,3),c=oi(e),d=uu(e)?ii(e):null,m=an(d,Math.max(24,Math.floor(t/8)),4),u=52+a*18+o*14+(c?30:0)+n*24+Math.max(22,l*18)+(m>0?22+m*16:0),p=e.type==="submoduleNode"?It.minSubmoduleCardHeight:It.minWorktreeCardHeight;return Math.min(It.maxEstimatedCardHeight,Math.max(p,Math.ceil(u)))}function Ra(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)}function Oy(e){return e?Math.min(260,Math.max(72,e.length*7+26)):0}function Fy(e){const t=e.edges.reduce((r,n)=>Math.max(r,Oy(n.label)),0);return Math.max(It.columnGap,It.worktreeCardWidth+t+It.edgeLabelBuffer)}function on(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 ln(e,t,r){return{id:e.id,x:t,y:r,width:li(e),height:vn(e)}}function Hy(e,t){return{id:`${e.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:t.repoIdentity,branch:e.branch,upstream:null,upstreamStatus:null,machineLabel:null,health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],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 Wy(e){const t=[...e.nodes].sort(Ra),r=t.find(x=>x.type==="defaultBranchNode")??null,n=new Map;for(const x of t){if(x.type!=="submoduleNode"||!x.parentNodeId)continue;const y=n.get(x.parentNodeId)??[];y.push(x),n.set(x.parentNodeId,y)}const a=t.filter(x=>x.id!==(r==null?void 0:r.id)&&x.type!=="submoduleNode"),o=new Map,l=[];for(const x of a){if(x.isOrphan||!x.branch){l.push(x);continue}const y=o.get(x.branch)??[];y.push(x),o.set(x.branch,y)}const c=[...o.entries()].sort(([x],[y])=>r!=null&&r.branch&&x===r.branch&&y!==r.branch?-1:r!=null&&r.branch&&y===r.branch&&x!==r.branch?1:x.localeCompare(y));l.length>0&&c.push(["__orphans__",[...l].sort(Ra)]),c.length===0&&c.push(["__nodes__",[]]);const d=[],m=[],u=c.length,p=Fy(e),b=Math.max(1,u-1)*p,w=r?0:96,g=r?vn(r):0,f=r?w+g+It.defaultToContentGap:0;if(r){const x=b/2;d.push(on(r,x,w)),m.push(ln(r,x,w))}return c.forEach(([x,y],h)=>{const M=h*p,S=y.length>0?y:a.length>0?a:[];let v=f;if(S.forEach(T=>{const A=vn(T);d.push(on(T,M,v)),m.push(ln(T,M,v));const k=[...n.get(T.id)??[]].sort(Ra);if(k.length>0){let j=v+A+It.parentToSubmoduleGap;k.forEach(O=>{const L=M+It.submoduleIndentX,N=vn(O);d.push(on(O,L,j)),m.push(ln(O,L,j)),j+=N+It.submoduleStackGap}),v=j+It.worktreeStackGap-It.submoduleStackGap;return}v+=A+It.worktreeStackGap}),x==="__nodes__"&&a.length===0&&r){const T=Hy(r,e),A=f+It.placeholderTopOffset;d.push(on(T,M,A,!1)),m.push(ln(T,M,A))}}),{nodes:d,bounds:m,columnGap:p}}const fu=i.createContext(Zs("dark"));function Ky(e,t,r){const n=t?"border-cyan-400/70 shadow-[0_0_0_1px_rgba(34,211,238,0.35),0_24px_60px_rgba(8,145,178,0.18)]":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)]",a=oi(e);if((a==null?void 0:a.tone)==="danger")return`${n} ${r?"bg-rose-500/12":"bg-rose-50/95"}`;if((a==null?void 0:a.tone)==="warn")return`${n} ${r?"bg-amber-500/10":"bg-amber-50/95"}`;if((a==null?void 0:a.tone)==="info")return`${n} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;switch(e.health){case"online":return`${n} ${r?"bg-emerald-500/8":"bg-emerald-50/95"}`;case"dirty":return`${n} ${r?"bg-amber-500/8":"bg-amber-50/95"}`;case"degraded":return`${n} ${r?"bg-rose-500/10":"bg-rose-50/95"}`;case"wrong_branch":return`${n} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;case"offline":return`${n} ${r?"bg-slate-500/12":"bg-slate-100/95"}`;default:return`${n} ${r?"bg-slate-950/78":"bg-white/96"}`}}function Vt(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 Uy(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 zy(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 Gy(e){return e.replace(/_/g," ")}function Vy({data:e,selected:t}){const r=i.useContext(fu),n=e.graphNode,a=n.type==="defaultBranchNode",o=n.type==="submoduleNode",l=uu(n),c=a?"default branch anchor":o?n.submodulePath||"submodule checkout":n.machineLabel||n.workspace,d=n.submoduleCommit?n.submoduleCommit.slice(0,7):null,m=oi(n),u=pu(n),p=ii(n);return s.jsxs("div",{className:`${o?"w-[228px]":"w-[256px]"} rounded-2xl border px-4 py-3.5 backdrop-blur-sm transition-all ${Ky(n,t,r.isDark)}`,style:{width:li(n)},children:[s.jsx(Ni,{type:"target",position:Ci.Top,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:n.label}),s.jsx("div",{className:`truncate text-[11px] ${r.textMuted}`,children:c})]}),s.jsx("span",{className:"mt-0.5 h-2.5 w-2.5 shrink-0 rounded-full",style:{backgroundColor:zy(n.health)},"aria-hidden":!0})]}),m&&s.jsx("div",{className:`mt-3 inline-flex max-w-full items-center rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] ${Uy(m.tone,r.isDark)}`,children:s.jsx("span",{className:"truncate",children:m.label})}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-1.5 text-[10px]",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${Vt("health",r.isDark)}`,children:Gy(n.health)}),o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("submodule",r.isDark)}`,children:"submodule"}),n.branch&&!o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("meta",r.isDark)}`,children:n.branch}),d&&o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("meta",r.isDark)}`,children:d}),n.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("dirty",r.isDark)}`,children:o?"local changes":`${n.dirtyFiles} dirty`}),n.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("conflict",r.isDark)}`,children:"out of sync"}),n.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("conflict",r.isDark)}`,children:"conflicts"}),!o&&n.upstream&&n.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("orphan",r.isDark)}`,children:"upstream unverified"}),n.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("orphan",r.isDark)}`,children:"needs follow-up"})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,children:u}),l&&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"}`,children:p}),s.jsx(Ni,{type:"source",position:Ci.Bottom,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const qy={meshNode:Vy};function Yy(e,t=Zs("dark")){const n=Wy(e).nodes.map(o=>({id:o.id,type:o.type,position:o.position,data:{graphNode:o.graphNode},selected:o.selected,draggable:o.draggable,selectable:o.selectable})),a=e.edges.map(o=>({id:o.id,source:o.source,target:o.target,label:o.label,type:o.type==="worktreeLink"||o.type==="submoduleLink"?"smoothstep":"bezier",animated:o.type==="orphanLink",markerEnd:{type:nm.ArrowClosed,width:o.type==="submoduleLink"?16:18,height:o.type==="submoduleLink"?16:18,color:Rl(o)},style:{stroke:Rl(o),strokeWidth:o.type==="orphanLink"?2.25:o.type==="submoduleLink"?1.7:o.type==="worktreeLink"?1.8:2,strokeDasharray:o.type==="orphanLink"?"5 4":o.type==="submoduleLink"?"4 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:n,edges:a}}function Rl(e){switch(e.type){case"parentBranch":return"#38bdf8";case"worktreeLink":return"#a78bfa";case"sessionLink":return"#34d399";case"orphanLink":return"#f97316";case"submoduleLink":return"#c084fc";default:return"#64748b"}}function Xy({data:e,viewportKey:t}){const r=am(),n=om(),a=i.useRef(null),o=i.useMemo(()=>mu(e),[e]),l=i.useMemo(()=>Ly(e),[e]);return i.useEffect(()=>{if(!r||e.nodes.length===0||a.current===t)return;let c=!1;const d=requestAnimationFrame(()=>{if(c)return;const m=l.length>0&&l.length<e.nodes.length;n.fitView({nodes:m?l.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,l,o,r,n,t]),null}function Jy({data:e,selectedNodeId:t=null,onNodeClick:r}){const{theme:n}=Qs(),a=i.useMemo(()=>Zs(n),[n]),o=i.useMemo(()=>Yy(e,a),[e,a]),l=i.useRef(null),[c,d]=i.useState({width:0,height:0}),m=i.useMemo(()=>Ry(e,c.width,c.height),[e,c.height,c.width]),u=i.useMemo(()=>o.nodes.map(p=>({...p,selected:p.id===t})),[o.nodes,t]);return i.useEffect(()=>{const p=l.current;if(!p)return;const b=()=>{const g=Math.max(0,Math.round(p.clientWidth)),f=Math.max(0,Math.round(p.clientHeight));d(x=>x.width===g&&x.height===f?x:{width:g,height:f})};b();const w=typeof ResizeObserver=="function"?new ResizeObserver(()=>b()):null;return w==null||w.observe(p),window.addEventListener("resize",b),()=>{w==null||w.disconnect(),window.removeEventListener("resize",b)}},[]),s.jsx(fu.Provider,{value:a,children:s.jsxs("div",{ref:l,className:a.graphShellClass,children:[s.jsxs("div",{className:`absolute inset-x-3 top-3 z-10 flex flex-wrap items-center justify-between gap-2 text-[11px] ${a.textSecondary}`,children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs("span",{className:a.graphStatChipClass,children:[e.stats.totalNodes," node",e.stats.totalNodes===1?"":"s"]}),s.jsxs("span",{className:a.graphStatChipClass,children:[e.stats.totalActiveSessions," active session",e.stats.totalActiveSessions===1?"":"s"]}),e.stats.orphanNodes>0&&s.jsxs("span",{className:a.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"]})]}),s.jsx("div",{className:a.graphHintChipClass,children:"Focused on the main path first · drag or scroll to pan"})]}),s.jsx("div",{className:"h-[460px] w-full min-w-0 min-h-[460px] sm:h-[560px] xl:h-[680px]",children:s.jsxs(em,{nodes:u,edges:o.edges,nodeTypes:qy,minZoom:.25,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(p,b)=>r==null?void 0:r(b.data.graphNode),className:"h-full w-full",colorMode:a.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(Xy,{data:e,viewportKey:m}),s.jsx(tm,{className:a.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),s.jsx(sm,{variant:rm.Dots,gap:18,size:1.2,color:a.graphBackgroundDotColor})]})})]})})}function bt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function De(...e){for(const t of e){if(typeof t!="string")continue;const r=t.trim();if(r)return r}}function Rt(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function Et(...e){for(const t of e)if(typeof t=="boolean")return t}function Pa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function Qy(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 Zy(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=bt(n),o=De(a.path),l=De(a.commit),c=De(a.repoPath,a.repo_root)??Qy(t,o);return!o||!l||!c?null:{path:o,commit:l,repoPath:c,dirty:Et(a.dirty)??!1,outOfSync:Et(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:Rt(a.lastCheckedAt,a.last_checked_at)??Date.now(),...De(a.error)?{error:De(a.error)}:{}}}).filter(n=>n!==null);return r.length>0?r:void 0}function e0(e){return Et(e.isGitRepo)!==void 0||!!De(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||Rt(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 wn(e,t,r){const n=Et(e.isGitRepo);if(!Object.keys(e).length||!e0(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(b=>typeof b=="string"):[],l=Rt(e.conflicts)??o.length,c=Et(e.hasConflicts)??l>0,d=De(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,m=Zy(e.submodules,d),u=De(e.upstreamStatus,e.upstream_status),p=De(e.error);return{workspace:De(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:a,branch:De(e.branch)??null,headCommit:De(e.headCommit)??null,headMessage:De(e.headMessage)??null,upstream:De(e.upstream)??null,upstreamStatus:u??"unchecked",ahead:Rt(e.ahead)??0,behind:Rt(e.behind)??0,staged:Rt(e.staged)??0,modified:Rt(e.modified)??0,untracked:Rt(e.untracked)??0,deleted:Rt(e.deleted)??0,renamed:Rt(e.renamed)??0,hasConflicts:c,conflictFiles:o,stashCount:Rt(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??Rt(e.lastCheckedAt,e.last_checked_at)??Date.now(),...m?{submodules:m}:{},...p?{error:p}:{}}}function t0(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),e.upstreamStatus&&e.upstreamStatus!=="unchecked"&&(t+=5),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 s0(e){const t=bt(e.lastGit??e.last_git),r=bt(t.result),n=bt(t.status),a=bt(r.status),o=bt(e.lastProbe??e.last_probe),l=bt(o.git),c=bt(l.result),d=bt(l.status),m=bt(c.status);let u=null;for(const p of[n,a,d,m]){const b=wn(p,e,{lastCheckedAt:Date.now()});if(!b)continue;const w=t0(b);(!u||w>u.score)&&(u={git:b,score:w})}return u==null?void 0:u.git}function r0(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 n0(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 Fn(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=r0(e);return t.outOfSync?"degraded":t.dirty||n0(e)?"dirty":"online"}function a0(e,t){const r=t?Fn(t):void 0;return!e||e==="unknown"?r:e}function o0(e){const t=Array.isArray(e.activeSessionDetails)?e.activeSessionDetails:Array.isArray(e.active_session_details)?e.active_session_details:null;if(t){const a=t.map(o=>{const l=bt(o),c=De(l.sessionId,l.session_id,l.id);return c?{sessionId:c,...De(l.providerType,l.provider)?{providerType:De(l.providerType,l.provider)}:{},...De(l.state,l.status)?{state:De(l.state,l.status)}:{},...De(l.lifecycle)?{lifecycle:De(l.lifecycle)}:{},...De(l.surfaceKind,l.surface_kind)?{surfaceKind:De(l.surfaceKind,l.surface_kind)}:{},...De(l.recoveryState,l.recovery_state)?{recoveryState:De(l.recoveryState,l.recovery_state)}:{},...De(l.workspace)?{workspace:De(l.workspace)}:{},...De(l.title)?{title:De(l.title)}:{},...De(l.lastActivityAt,l.last_activity_at)?{lastActivityAt:De(l.lastActivityAt,l.last_activity_at)}:{},...Et(l.isCached,l.is_cached)!==void 0?{isCached:Et(l.isCached,l.is_cached)}:{}}:null}).filter(o=>o!==null);if(a.length>0)return a}const r=bt(e.activeSession??e.active_session),n=De(r.id,r.sessionId,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id);if(n)return[{sessionId:n,...De(r.providerType,r.provider)?{providerType:De(r.providerType,r.provider)}:{},...De(r.state,r.status)?{state:De(r.state,r.status)}:{}}]}function i0(e){const t=bt(e.connection);return Object.keys(t).length>0?t:void 0}function l0(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 ci(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 Pl(e){var n,a,o,l,c,d;let t=0;const r=e.git;return ci(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),r!=null&&r.upstreamStatus&&r.upstreamStatus!=="unchecked"&&(t+=6),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"||((l=e.connection)==null?void 0:l.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 c0(e,t){var w,g,f,x;const r=Pl(e),a=Pl(t)>r?t:e,o=a===t?e:t,l=a.git??o.git,c=(((w=a.providers)==null?void 0:w.length)??0)>0?a.providers:o.providers,d=(((g=a.activeSessions)==null?void 0:g.length)??0)>0?a.activeSessions:o.activeSessions,m=(((f=a.activeSessionDetails)==null?void 0:f.length)??0)>0?a.activeSessionDetails:o.activeSessionDetails,u=(((x=a.providerPriority)==null?void 0:x.length)??0)>0?a.providerPriority:o.providerPriority,p=a.connection??o.connection,b={...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:l&&(!a.health||a.health==="unknown")?Fn(l):a.health,providers:c??[],activeSessions:d??[],...m&&m.length>0?{activeSessionDetails:m}:{},...u&&u.length>0?{providerPriority:u}:{},...p?{connection:p}:{},...l?{git:l}:{}};return l&&(delete b.gitProbePending,delete b.error),b}function d0(e){const t=bt(e),r=De(t.nodeId,t.id);if(!r)return null;const n=bt(t.cachedStatus),a=s0(t),o=a?void 0:wn(bt(t.git),t)??wn(t,t),l=a??o,c=l?void 0:wn(bt(n.git),t),d=l??c,m=De(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),u=De(t.health),p=a?Fn(d):a0(u,l)||(d?Fn(d):void 0)||De(n.health)||m||De(t.status)||"unknown",w=(a?void 0:De(t.error))??(l?void 0:De(n.error)),g=o0(t),f=Pa(t.activeSessions),x=(g==null?void 0:g.map(k=>k.sessionId))??[],y=Pa(t.providerPriority),h=Et(t.gitProbePending,t.git_probe_pending),M=l?void 0:h,S=i0(t),v=bt(t.branchConvergence??t.branch_convergence),T=S==null?void 0:S.state,A=a&&(!(S!=null&&S.reported)||T==="unknown")?l0(S):S;return{nodeId:r,machineLabel:De(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:De(t.workspace,d==null?void 0:d.workspace)||"",...De(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:De(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},...De(t.daemonId,t.daemon_id)?{daemonId:De(t.daemonId,t.daemon_id)}:{},...De(t.machineId,t.machine_id)?{machineId:De(t.machineId,t.machine_id)}:{},...m?{machineStatus:m}:{},...Et(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Et(t.isLocalWorktree,t.is_local_worktree)}:{},...De(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:De(t.worktreeBranch,t.worktree_branch)}:{},health:p,...d?{git:d}:{},...M!==void 0?{gitProbePending:M}:{},providers:Pa(t.providers),activeSessions:f.length>0?f:x,...g&&g.length>0?{activeSessionDetails:g}:{},...y.length>0?{providerPriority:y}:{},...Et(t.launchReady)!==void 0?{launchReady:Et(t.launchReady)}:a?{launchReady:!0}:{},...De(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:De(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},...De(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:De(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...A?{connection:A}:{},...Object.keys(v).length>0?{branchConvergence:v}:{},...w?{error:w}:{}}}function hu(e){const t=new Map,r=[];for(const n of e){const a=t.get(n.nodeId);if(!a){t.set(n.nodeId,n),r.push(n);continue}const o=c0(a,n);t.set(n.nodeId,o);const l=r.findIndex(c=>c.nodeId===n.nodeId);l>=0&&(r[l]=o)}return r}function xu(e){return{...e,nodes:hu(e.nodes??[])}}function u0(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:ci(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 m0(e){const t=De(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(d=>d0(d)).filter(d=>d!==null):null;if(!t||!n)return null;const a=hu(n),o=De(e.meshName,e.mesh_name,e.name),l=De(e.repoIdentity,e.repo_identity),c=De(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!o||!l||!c?null:{...e,meshId:t,meshName:o,repoIdentity:l,refreshedAt:c,nodes:a}}function p0(e){var o;let t=0;const r=bt(e.sourceOfTruth),n=bt(r.directPeerTruth);De(r.currentStatus)==="live_git_and_session_probes"&&(t+=100),r.coordinatorOwnsLiveTruth===!0&&(t+=25),n.satisfied===!0&&(t+=15);for(const l of e.nodes){const c=l.git;if(!c){l.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),c.upstreamStatus&&c.upstreamStatus!=="unchecked"&&(t+=2),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 bu(e){const t=(e==null?void 0:e.result)??e,r=[e==null?void 0:e.status,t==null?void 0:t.status,t,e];let n=null;for(const a of r){const o=m0(bt(a));if(!o)continue;const l=p0(o);(!n||l>n.score)&&(n={status:o,score:l})}return(n==null?void 0:n.status)??null}const f0=5*60*1e3;function h0(e){return ci(e)}function di(e){var t;return h0(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function x0(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function ui(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function mi(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function Tr(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function b0(e){return Tr(e)?"degraded":mi(e)?"dirty":"online"}function g0(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function Dl(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 Da(e){return e.length===0?"unknown":e.reduce((t,r)=>Dl(r)>Dl(t)?r:t)}function y0(e){var o,l,c,d,m;const t=new Map,r=new Map;for(const u of e){const p=(l=(o=u.git)==null?void 0:o.branch)==null?void 0:l.trim();p&&(r.set(p,(r.get(p)??0)+1),(c=u.git)!=null&&c.upstream&&t.set(p,(t.get(p)??0)+1))}const n=[...t.entries()].sort((u,p)=>{if(p[1]!==u[1])return p[1]-u[1];const b=["main","master","develop","dev"],w=b.indexOf(u[0]),g=b.indexOf(p[0]);return w!==-1||g!==-1?w===-1?1:g===-1?-1:w-g:u[0].localeCompare(p[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((m=[...r.entries()].sort((u,p)=>p[1]-u[1])[0])==null?void 0:m[0])??null}function v0(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 El(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 w0(e){return e.reduce((t,r)=>El(r.status)>El(t.status)?r:t)}function j0(e){if(di(e))return null;const t=e.branchConvergence;if(!t||typeof t!="object")return null;const r=t.status;if(!r||!["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"].includes(r))return null;const n=e.git,a=ui(n)||mi(n),o=!!(n!=null&&n.hasConflicts)||Tr(n),l=(n==null?void 0:n.ahead)??0,c=(n==null?void 0:n.behind)??0,d=(n==null?void 0:n.branch)??null,m=(n==null?void 0:n.upstream)??null,u=(n==null?void 0:n.upstreamStatus)??null,p=t.defaultBranch??null,b=(f,x)=>typeof f=="number"&&f!==x,w=(f,x)=>typeof f=="string"&&x!==null&&f!==x;return!!n&&(w(t.branch,d)||w(t.upstream,m)||w(t.upstreamStatus,u)||b(t.ahead,l)||b(t.behind,c)||typeof t.dirty=="boolean"&&t.dirty!==a||typeof t.hasConflicts=="boolean"&&t.hasConflicts!==o||r!=="merged_to_main"&&(n==null?void 0:n.isGitRepo)===!0&&d!==null&&p!==null&&d===p&&l===0&&c===0&&!a&&!o&&(!m||!u||u==="fresh"))?null:{status:r,needsConvergence:t.needsConvergence??r!=="merged_to_main",reason:t.reason??"provided_by_coordinator",nextStep:t.nextStep??null,branch:t.branch??d,defaultBranch:p,upstream:t.upstream??m,upstreamStatus:t.upstreamStatus??u,ahead:t.ahead??l,behind:t.behind??c,dirty:t.dirty??a,hasConflicts:t.hasConflicts??o}}function k0(e,t){const r=j0(e);if(r)return{...r,defaultBranch:r.defaultBranch??t};if(!t||di(e))return null;const n=e.git,a=(n==null?void 0:n.branch)??null,o=(n==null?void 0:n.upstream)??null,l=(n==null?void 0:n.upstreamStatus)??null,c=(n==null?void 0:n.ahead)??0,d=(n==null?void 0:n.behind)??0,m=ui(n)||mi(n),u=!!(n!=null&&n.hasConflicts)||Tr(n),p={branch:a,defaultBranch:t,upstream:o,upstreamStatus:l,ahead:c,behind:d,dirty:m,hasConflicts:u};return(n==null?void 0:n.isGitRepo)!==!0?{...p,status:"blocked_review",needsConvergence:!0,reason:"git_status_unavailable",nextStep:`Resolve git status for '${e.machineLabel||e.nodeId}' before declaring the mesh converged.`}:a?u||m?{...p,status:"not_mergeable",needsConvergence:!0,reason:n!=null&&n.hasConflicts?"conflicts_present":Tr(n)?"submodule_out_of_sync":"dirty_workspace",nextStep:`Commit, checkpoint, or resolve '${a}' before any convergence step into ${t}.`}:o&&l&&l!=="fresh"?{...p,status:"blocked_review",needsConvergence:!0,reason:"upstream_unverified",nextStep:`Refresh '${a}' against ${o} before claiming the mesh is converged.`}:a===t?c>0||d>0?{...p,status:"blocked_review",needsConvergence:!0,reason:"default_branch_not_even_with_upstream",nextStep:`Bring ${t} even with ${o??"its upstream"} before declaring convergence complete.`}:{...p,status:"merged_to_main",needsConvergence:!1,reason:"clean_default_branch",nextStep:null}:e.isLocalWorktree?{...p,status:"cleanup_candidate",needsConvergence:!0,reason:"clean_non_default_worktree_branch",nextStep:`Run refine / cleanup for '${a}' or explicitly classify the worktree before ending the task.`}:!o||c>0||d>0?{...p,status:"blocked_review",needsConvergence:!0,reason:o?"feature_branch_not_even_with_upstream":"feature_branch_missing_upstream",nextStep:`Push or reconcile '${a}', then merge it into ${t} or mark it blocked with a reason.`}:{...p,status:"pushed_feature_branch_needs_merge",needsConvergence:!0,reason:"clean_non_default_branch",nextStep:`Review and merge '${a}' into ${t}; do not treat it as fully complete while it remains off ${t}.`}:{...p,status:"blocked_review",needsConvergence:!0,reason:"branch_unknown",nextStep:`Inspect '${e.machineLabel||e.nodeId}' and confirm which branch should converge into ${t}.`}}function S0(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function N0(e){var d,m,u;const{nodeStatus:t,expectedSubmodulePaths:r,refreshedAtMs:n}=e,a=[],o=t.machineLabel||t.nodeId,l=t.git;if(!l){if(di(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const p=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(p?`${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((l.submodules??[]).map(p=>p.path));if(r.size>0){const p=[...r].filter(b=>!c.has(b));p.length>0&&a.push(`${o} is missing submodule visibility for ${p.join(", ")} even though another peer reported it.`)}return((u=t.connection)==null?void 0:u.state)!=="self"&&n!==null&&typeof l.lastCheckedAt=="number"&&n-l.lastCheckedAt>f0&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(p=>p.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(p=>p.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function C0(e){var L;const t=xu(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??y0(t.nodes),a=x0(t.refreshedAt),o=new Set(t.nodes.flatMap(N=>{var P;return(((P=N.git)==null?void 0:P.submodules)??[]).map(B=>B.path)})),l=[],c=[],d=[],m=new Map;for(const N of t.nodes){const P=N.git,B=(P==null?void 0:P.branch)??null,D=b0(P),C=ui(P)||D==="dirty",I=v0(N,n),E=k0(N,n),R=N0({nodeStatus:N,expectedSubmodulePaths:o,refreshedAtMs:a}),$={id:N.nodeId,type:I.length>0?"orphanNode":"worktreeNode",label:N.machineLabel||N.nodeId.slice(0,8),workspace:N.workspace,branch:B,upstream:(P==null?void 0:P.upstream)??null,upstreamStatus:(P==null?void 0:P.upstreamStatus)??null,machineLabel:N.machineLabel||null,health:Da([N.health,D]),ahead:(P==null?void 0:P.ahead)??0,behind:(P==null?void 0:P.behind)??0,dirty:C,dirtyFiles:g0(P),hasConflicts:(P==null?void 0:P.hasConflicts)??!1,activeSessionCount:((L=N.activeSessions)==null?void 0:L.length)??0,activeSessions:N.activeSessions??[],providers:N.providers??[],isOrphan:I.length>0,orphanReasons:I,error:N.error,nextStepHint:R.snapshotWarnings[0]??I[0]??(E==null?void 0:E.nextStep)??void 0,parentNodeId:null,submodulePath:null,submoduleCommit:(P==null?void 0:P.headCommit)??null,outOfSync:Tr(P),snapshotCompleteness:R.snapshotCompleteness,snapshotWarnings:R.snapshotWarnings,branchConvergence:E,source:N};if(l.push($),B){const z=m.get(B)??[];z.push($.id),m.set(B,z)}for(const z of(P==null?void 0:P.submodules)??[]){const H=`${$.id}::submodule::${z.path}`,me=z.path.split("/").filter(Boolean).pop()||z.path;l.push({id:H,type:"submoduleNode",label:me,workspace:z.repoPath,branch:null,upstream:null,upstreamStatus:null,machineLabel:$.machineLabel,health:S0(z),ahead:0,behind:0,dirty:z.dirty,dirtyFiles:z.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],error:z.error,nextStepHint:z.error||(z.outOfSync?`${z.path} is out of sync with the parent checkout`:z.dirty?`${z.path} has local changes`:`${z.path} is in sync with the parent checkout`),parentNodeId:$.id,submodulePath:z.path,submoduleCommit:z.commit,outOfSync:z.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:$.id,parentWorkspace:N.workspace,submodule:z}}),c.push({id:`${$.id}--${H}`,source:$.id,target:H,type:"submoduleLink",label:z.outOfSync?"submodule out of sync":"submodule"})}}const u=n?`__branch_${n}`:null;if(u&&n){const P=(m.get(n)??[]).map(E=>l.find(R=>R.id===E)).filter(Boolean),B=P.map(E=>E.branchConvergence).filter(Boolean),D=B.length>0?w0(B):null,C=B.filter(E=>E.needsConvergence).length,I={id:u,type:"defaultBranchNode",label:n,workspace:t.repoIdentity,branch:n,upstream:null,upstreamStatus:null,machineLabel:"default branch",health:Da(P.map(E=>E.health)),ahead:0,behind:0,dirty:P.some(E=>E.dirty),dirtyFiles:P.reduce((E,R)=>E+R.dirtyFiles,0),hasConflicts:P.some(E=>E.hasConflicts),activeSessionCount:P.reduce((E,R)=>E+R.activeSessionCount,0),activeSessions:P.flatMap(E=>E.activeSessions),providers:[...new Set(P.flatMap(E=>E.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:C>0?`${C} workspace(s) on ${n} still need follow-up`:P.length>0?`${P.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:D,source:{nodeId:u,machineLabel:n,workspace:t.repoIdentity,health:Da(P.map(E=>E.health)),providers:[],activeSessions:[]}};l.push(I);for(const E of l)if(!(E.id===u||E.type==="submoduleNode")){if(E.branch===n){c.push({id:`${u}--${E.id}`,source:u,target:E.id,type:"parentBranch",label:"checked out"});continue}if(E.branch){c.push({id:`${u}--${E.id}`,source:u,target:E.id,type:E.isOrphan?"orphanLink":"parentBranch",label:E.branch});continue}E.isOrphan&&c.push({id:`${u}--${E.id}`,source:u,target:E.id,type:"orphanLink",label:"detached"})}}for(const[N,P]of m){if(P.length<2)continue;const B=P.map(D=>l.find(C=>C.id===D)).filter(Boolean);B.sort((D,C)=>D.label.localeCompare(C.label));for(let D=1;D<B.length;D+=1)c.push({id:`wt_${B[D-1].id}--${B[D].id}`,source:B[D-1].id,target:B[D].id,type:"worktreeLink",label:D===1?`${N} peers`:void 0})}const p=l.filter(N=>N.type!=="defaultBranchNode"),b=p.filter(N=>N.isOrphan).length,w=p.filter(N=>N.hasConflicts).length,g=p.filter(N=>N.health==="offline").length,f=p.filter(N=>N.type==="submoduleNode"&&N.outOfSync).length,x=p.filter(N=>{var P;return N.type!=="submoduleNode"&&((P=N.branchConvergence)==null?void 0:P.needsConvergence)}).length,y=p.filter(N=>{var P;return((P=N.branchConvergence)==null?void 0:P.status)==="blocked_review"}).length,h=p.filter(N=>{var P;return((P=N.branchConvergence)==null?void 0:P.status)==="pushed_feature_branch_needs_merge"}).length,M=p.filter(N=>{var P;return((P=N.branchConvergence)==null?void 0:P.status)==="cleanup_candidate"}).length,S=p.filter(N=>{var P;return((P=N.branchConvergence)==null?void 0:P.status)==="not_mergeable"}).length,v=p.filter(N=>N.snapshotWarnings.length>0).length,T=p.filter(N=>N.snapshotCompleteness==="pending_git").length,A=p.filter(N=>N.snapshotCompleteness==="missing_git").length,k=p.filter(N=>N.snapshotCompleteness==="missing_submodule_report").length,j=p.filter(N=>N.snapshotCompleteness==="stale").length,O=[T>0?`${T} node(s) are still waiting for a live peer git snapshot`:null,A>0?`${A} node(s) have no visible peer git snapshot`:null,k>0?`${k} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,j>0?`${j} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return x>0&&d.push(`${x} workspace(s) still need follow-up before the mesh is converged`),b>0&&d.push(`${b} workspace(s) need attention before safe coordination`),y>0&&d.push(`${y} workspace(s) are blocked on branch convergence or upstream sync`),h>0&&d.push(`${h} clean feature branch workspace(s) still need merge follow-up`),M>0&&d.push(`${M} worktree workspace(s) are ready for refine / cleanup`),S>0&&d.push(`${S} workspace(s) have local changes or conflicts blocking convergence`),w>0&&d.push(`${w} workspace(s) report merge conflicts`),g>0&&d.push(`${g} node(s) are currently offline`),f>0&&d.push(`${f} submodule(s) are out of sync with their parent checkout`),d.push(...O),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:l,edges:c,stats:{totalNodes:p.length,onlineNodes:p.filter(N=>N.health==="online").length,dirtyNodes:p.filter(N=>N.dirty).length,orphanNodes:b,errorNodes:p.filter(N=>!!N.error||N.outOfSync).length,offlineNodes:g,followUpNodes:x,blockedReviewNodes:y,mergeReadyNodes:h,cleanupCandidateNodes:M,notMergeableNodes:S,incompleteSnapshotNodes:v,missingGitSnapshotNodes:A,missingSubmoduleSnapshotNodes:k,staleGitSnapshotNodes:j,totalActiveSessions:p.reduce((N,P)=>N+P.activeSessionCount,0)},warnings:d,snapshotWarnings:O}}const I0={recentFailures:0},pi=i.createContext(Zs("dark"));function nt({label:e,tone:t="default"}){const r=i.useContext(pi);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 ss({label:e,value:t}){const r=i.useContext(pi);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 M0(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 T0(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 A0(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 _0(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 L0(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 $l(e){return e?e.slice(0,7):null}function R0(e,t){var o,l,c;const r=$l((o=e==null?void 0:e.git)==null?void 0:o.headCommit),n=((c=(l=e==null?void 0:e.git)==null?void 0:l.headMessage)==null?void 0:c.trim())||"";if(r||n)return[r,n].filter(Boolean).join(" · ");const a=t[0];return a?[$l(a.commit),a.message].filter(Boolean).join(" · "):null}function P0(e,t){const r=R0(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function D0(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 E0(e){var r,n,a,o,l,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)||((l=e.selectedNodeStatus)==null?void 0:l.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 $0(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":_0(e.connection)}function B0(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 O0(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function gu({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null}){var I,E,R,$,z;const{theme:a}=Qs(),o=i.useMemo(()=>Zs(a),[a]),l=i.useMemo(()=>xu(e),[e]),c=i.useMemo(()=>C0(l),[l]),[d,m]=i.useState(null),[u,p]=i.useState(null),[b,w]=i.useState({}),g=i.useMemo(()=>new Map(l.nodes.map(H=>[H.nodeId,H])),[l.nodes]),f=i.useMemo(()=>new Map(c.nodes.map(H=>[H.id,H])),[c.nodes]),x=((I=l.queue)==null?void 0:I.summary)??null,y=((E=l.ledger)==null?void 0:E.summary)??I0,h=i.useMemo(()=>L0(l),[l]),M=i.useMemo(()=>{const H=new Map;for(const me of h){const ie=me.session.state||me.session.lifecycle||"unknown";H.set(ie,(H.get(ie)??0)+1)}return[...H.entries()].sort((me,ie)=>ie[1]-me[1])},[h]);i.useEffect(()=>{d&&(f.has(d)||(m(null),p(H=>!H||"nodeId"in H&&H.nodeId===d?null:H)))},[f,d]);const S=d?g.get(d)??null:null,v=O0(c,d);i.useEffect(()=>{var H,me,ie;if(d)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:l.meshId,selectedNodeId:d,canonicalNode:u0(S),graphNode:v?{id:v.id,branch:v.branch,upstream:v.upstream,headCommit:v.submoduleCommit,submoduleCount:((me=(H=S==null?void 0:S.git)==null?void 0:H.submodules)==null?void 0:me.length)??0,snapshotCompleteness:v.snapshotCompleteness,snapshotWarnings:v.snapshotWarnings,branchConvergence:((ie=v.branchConvergence)==null?void 0:ie.status)??null}:null})}catch{}},[l.meshId,v,d,S]);const T=(u==null?void 0:u.kind)==="session"?h.find(H=>H.nodeId===u.nodeId&&H.session.sessionId===u.sessionId)??null:null,A=i.useMemo(()=>h.filter(H=>H.nodeId===d),[d,h]),k=E0({coordinatorDaemonId:r,selectedNodeStatus:S,selectedSessionEntry:T}),j=(k==null?void 0:k.workspace)??null,O=j?b[j]??null:null,L=P0(S,(O==null?void 0:O.entries)??[]),N=i.useCallback(()=>{m(null),p(null)},[]);i.useEffect(()=>{if(!v)return;const H=me=>{me.key==="Escape"&&N()};return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[N,v]),i.useEffect(()=>{if(!k||!n)return;const{daemonId:H,workspace:me}=k,ie=b[me];if(ie!=null&&ie.loading||ie&&(ie.entries.length>0||ie.error))return;let ee=!1;return w(ce=>{var je;return{...ce,[me]:{loading:!0,error:null,entries:((je=ce[me])==null?void 0:je.entries)??[]}}}),n(H,"git_log",{workspace:me,limit:5}).then(ce=>{ee||w(je=>({...je,[me]:{loading:!1,error:null,entries:D0(ce)}}))}).catch(ce=>{ee||w(je=>({...je,[me]:{loading:!1,error:ce instanceof Error?ce.message:"git_log failed",entries:[]}}))}),()=>{ee=!0}},[b,k,n]);const P=[...c.warnings??[],...l.nodes.filter(H=>H.machineStatus&&H.machineStatus!=="online").map(H=>`${H.machineLabel}: ${H.machineStatus}`)],B=c.stats.incompleteSnapshotNodes>0,D=c.stats.followUpNodes>0?`${c.stats.followUpNodes} need follow-up`:B?"mesh visibility incomplete":"mesh converged",C=c.stats.followUpNodes>0?"danger":B?"warn":"good";return s.jsx(pi.Provider,{value:o,children:s.jsx("div",{className:"flex min-h-0 flex-col gap-4",children:s.jsx("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-4",children:s.jsxs("div",{className:`${o.cardClass} relative min-h-0 flex-1 rounded-[28px] p-3 sm:p-4`,style:{minHeight:420},children:[s.jsxs("div",{className:`absolute inset-x-4 top-4 z-30 flex max-h-[42dvh] flex-wrap items-start justify-between gap-3 overflow-y-auto rounded-2xl px-3.5 py-3 backdrop-blur-xl sm:static sm:mb-3 sm:max-h-none sm:overflow-visible sm:backdrop-blur-none ${o.isDark?"border border-white/10 bg-slate-950/85 sm:bg-slate-950/45":"border border-slate-200 bg-white/95 shadow-lg shadow-slate-900/10 sm:bg-white/95 sm:shadow-sm"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-wrap gap-2 text-xs ${o.textSecondary}`,children:[s.jsx(nt,{label:D,tone:C}),c.stats.blockedReviewNodes>0&&s.jsx(nt,{label:`${c.stats.blockedReviewNodes} blocked review`,tone:"danger"}),c.stats.notMergeableNodes>0&&s.jsx(nt,{label:`${c.stats.notMergeableNodes} not mergeable`,tone:"danger"}),c.stats.mergeReadyNodes>0&&s.jsx(nt,{label:`${c.stats.mergeReadyNodes} need merge`,tone:"warn"}),c.stats.cleanupCandidateNodes>0&&s.jsx(nt,{label:`${c.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),c.stats.offlineNodes>0&&s.jsx(nt,{label:`${c.stats.offlineNodes} offline`,tone:"danger"}),c.stats.incompleteSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),c.stats.missingGitSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),c.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),c.stats.staleGitSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((x==null?void 0:x.active)??0)>0&&s.jsx(nt,{label:`${(x==null?void 0:x.active)??0} active queue`,tone:"info"}),s.jsx(nt,{label:`${c.stats.totalNodes} nodes`,tone:"default"}),c.stats.totalActiveSessions>0&&s.jsx(nt,{label:`${c.stats.totalActiveSessions} active sessions`,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(nt,{label:`${c.stats.dirtyNodes} dirty`,tone:c.stats.dirtyNodes>0?"warn":"good"}),s.jsx(nt,{label:`${c.stats.orphanNodes} orphan`,tone:c.stats.orphanNodes>0?"warn":"good"}),s.jsx(nt,{label:`${y.recentFailures} recent failures`,tone:y.recentFailures>0?"danger":"good"}),M.length===0?s.jsx(nt,{label:"no session metadata"}):M.slice(0,2).map(([H,me])=>s.jsx(nt,{label:`${me} ${H}`,tone:T0(H)},H))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(nt,{label:"Anchor = default branch",tone:"info"}),s.jsx(nt,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(nt,{label:"Submodule link = child checkout",tone:"warn"})]}),P.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:P.map(H=>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:H},H))}),s.jsx("div",{className:`text-xs ${o.textMuted}`,children:"Click a node only when you want drill-down details. The graph itself now carries the convergence state."})]})]})]}),c.nodes.length>0?s.jsx(Jy,{data:c,selectedNodeId:d,onNodeClick:H=>{if((u==null?void 0:u.kind)==="node"&&d===H.id){m(null),p(null);return}m(H.id),p({kind:"node",nodeId:H.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}),v&&(u==null?void 0:u.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:N,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:H=>H.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:v.label}),s.jsx("div",{className:`mt-1 font-mono text-[11px] ${o.textMuted}`,children:v.id.slice(0,16)})]}),s.jsx("button",{type:"button",onClick:N,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(nt,{label:(S==null?void 0:S.health)??v.health,tone:M0((S==null?void 0:S.health)??v.health)}),v.branch&&s.jsx(nt,{label:v.branch,tone:"default"}),v.ahead>0&&s.jsx(nt,{label:`ahead ${v.ahead}`,tone:"warn"}),v.behind>0&&s.jsx(nt,{label:`behind ${v.behind}`,tone:"warn"}),v.dirtyFiles>0&&s.jsx(nt,{label:`${v.dirtyFiles} dirty`,tone:"warn"}),(S==null?void 0:S.connection)&&s.jsx(nt,{label:$0(S),tone:A0(S.connection)}),A.length>0&&s.jsx(nt,{label:`${A.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[s.jsx(ss,{label:"Workspace",value:(S==null?void 0:S.workspace)??v.workspace}),s.jsx(ss,{label:"Branch",value:v.branch??"unknown"}),s.jsx(ss,{label:"HEAD",value:L??(S!=null&&S.gitProbePending?"Pending live git probe":"not reported")}),s.jsx(ss,{label:"Upstream",value:v.upstream??"none"}),s.jsx(ss,{label:"Dirty/ahead/behind",value:`${v.dirtyFiles} dirty · ↑${v.ahead}/↓${v.behind}`}),s.jsx(ss,{label:"Source",value:String(((R=S==null?void 0:S.connection)==null?void 0:R.source)??B0(v))}),s.jsx(ss,{label:"Transport",value:(($=S==null?void 0:S.connection)==null?void 0:$.transport)??"unknown"}),s.jsx(ss,{label:"Sessions",value:A.length>0?A.map(H=>H.session.state||H.session.lifecycle||"unknown").join(", "):"none active"})]}),v.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:v.snapshotWarnings[0]})]}),((z=v.branchConvergence)==null?void 0:z.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:v.branchConvergence.nextStep})]})]})})]})})})})}function F0({activeConv:e,sendDaemonCommand:t,onClose:r}){var v;const n=typeof((v=e.settings)==null?void 0:v.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null,a=e.daemonId??null,o=$d(),{theme:l}=Qs(),c=i.useMemo(()=>Zs(l),[l]),[d,m]=i.useState(null),[u,p]=i.useState(!1),[b,w]=i.useState(null),[g,f]=i.useState(null),x=i.useRef(!1);i.useEffect(()=>{x.current=d!==null},[d]);const y=i.useCallback(async(T=!1)=>{if(!a||!n){w("This coordinator does not expose a live mesh id."),m(null);return}p(!x.current),w(null);try{const A=o!=null&&o.loadMeshStatus?await o.loadMeshStatus(a,n,{refresh:T}):await t(a,"mesh_status",{meshId:n,refresh:T}),k=bu(A);if(!k){w("mesh_status returned an unexpected payload.");return}m(k),f(k.refreshedAt||new Date().toISOString())}catch(A){w(A instanceof Error?A.message:"Failed to load live mesh status")}finally{p(!1)}},[a,n,o,t]);i.useEffect(()=>{y(!1)},[y]),i.useEffect(()=>{const T=A=>{A.key==="Escape"&&r()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[r]);const h=(d==null?void 0:d.meshName)||n||"Repo Mesh",M=g?new Date(g).toLocaleTimeString():null,S=i.useMemo(()=>u?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[u]);return s.jsx("div",{className:c.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:c.dialogShellClass,onClick:T=>T.stopPropagation(),children:[s.jsxs("div",{className:c.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(ns,{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:c.dialogTitleClass,children:h}),s.jsx("span",{className:c.dialogKickerClass,children:"Mesh observability"})]}),s.jsxs("p",{className:c.dialogSubtitleClass,children:[ut(e),e.workspaceName?` · ${e.workspaceName}`:"",d!=null&&d.repoIdentity?` · ${d.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[M&&s.jsxs("span",{className:c.dialogRefreshedChipClass,children:["Refreshed ",M]}),s.jsx("button",{type:"button",onClick:()=>{y(!0)},disabled:u,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:u?"Refreshing…":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:c.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:s.jsx(jt,{size:16})})]})]}),b&&s.jsx("div",{className:c.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:b}),s.jsx("div",{className:c.dialogBodyClass,children:d?s.jsx(gu,{status:d,emptyMessage:S,daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:c.dialogEmptyClass,children:S})})]})})}function H0(e,t){const{sendCommand:r}=kt(),[n,a]=i.useState(null),[o,l]=i.useState(!1);i.useEffect(()=>{if(!e||!t){a(null);return}l(!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(()=>l(!1))},[e,t,r]);const c=W0(n);return{remoteUrl:n,githubUrl:c,loading:o}}function W0(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 yu=5e3;function K0(e){return`git:${e}`}function U0({workspace:e,includeDiffSummary:t=!1,intervalMs:r=yu}){return{type:"subscribe",topic:"workspace.git",key:K0(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function fi(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Ms(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 z0(e){const t=fi(e);return(t==null?void 0:t.success)===!1?{status:null,error:Ms(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Ms(t,"Git status response did not include status")}}function G0(e){const t=fi(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Ms(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Ms(t,"Git diff summary response did not include diffSummary")}}function Ea(e){return e===void 0||typeof e=="boolean"}function V0(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Ea(t.binary)&&Ea(t.truncated)&&Ea(t.staged)}function q0(e){const t=fi(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Ms(t,"Git file diff request failed")}:V0(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Ms(t,"Git file diff response did not include a valid diff object")}}function Y0({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=yu}){const{sendCommand:o,sendData:l}=kt(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[m,u]=i.useState(null),[p,b]=i.useState(null),[w,g]=i.useState(!1),[f,x]=i.useState(null),y=i.useCallback(async()=>{if(!(!d||!e||!c)){g(!0),x(null);try{const M=z0(await o(e,"git_status",{workspace:c}));if(M.error){u(null),b(null),x(M.error);return}if(u(M.status),!n){b(null);return}const S=G0(await o(e,"git_diff_summary",{workspace:c}));if(S.error){b(null),x(S.error);return}b(S.diffSummary)}catch(M){x(Ms(M,"Git status request failed"))}finally{g(!1)}}},[d,e,n,o,c]),h=i.useMemo(()=>c?U0({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return i.useEffect(()=>{if(!d||!e||!c||!h){u(null),b(null),g(!1),x(null);return}const M=l?Jt.subscribe({sendData:l},e,h,S=>{var v,T;S.workspace===c&&(u(S.status),b(S.diffSummary??null),x(((v=S.status)==null?void 0:v.error)||((T=S.diffSummary)==null?void 0:T.error)||null),g(!1))},{retryIntervalMs:1e3}):null;return y(),()=>{M==null||M()}},[d,e,y,h,l,c]),{status:m,diffSummary:p,loading:w,error:f,refresh:y}}const X0={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},J0={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 Bl(e){return e.split("/").pop()??e}function Q0(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function Z0({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 l=n===o.path,c=X0[o.status]??"?",d=J0[o.status]??"text-zinc-400",m=Q0(o.path),u=Bl(o.path),p=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 ${l?"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:["← ",Bl(o.oldPath)]}),p]}),!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 ev(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 tv({diff:e,binary:t,truncated:r,loading:n,error:a,className:o=""}){const l=i.useRef(null);if(i.useEffect(()=>{l.current&&(l.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(`
65
65
  `);return s.jsxs("div",{ref:l,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((d,m)=>ev(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 sv(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(`
66
66
  `)}function vu({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=kt(),{status:a,diffSummary:o,loading:l,error:c,refresh:d}=Y0({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=i.useState(null),[p,b]=i.useState(null),[w,g]=i.useState(""),[f,x]=i.useState(!1),[y,h]=i.useState(!1),[M,S]=i.useState(null),[v,T]=i.useState(null),{githubUrl:A}=H0(e,t),k=i.useCallback(async B=>{if(!((m==null?void 0:m.path)===B.path&&!m.loading)){u({path:B.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const D=await n(e,"git_diff_file",{workspace:t,path:B.path,staged:B.staged}),C=q0(D);if(C.error||!C.diff){u({path:B.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C.error??"Failed to load diff"});return}u({path:B.path,diff:C.diff.diff,binary:C.diff.binary??!1,truncated:C.diff.truncated??!1,loading:!1,error:null})}catch(D){const C=D instanceof Error?D.message:"Failed to load diff";u({path:B.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C})}}},[e,n,m,t]),j=i.useCallback(B=>{g(""),x(!1),S(null),T(null),b(B)},[]),O=i.useCallback(()=>{b(null),S(null),h(!1)},[]),L=i.useCallback(async()=>{var B,D,C;if(p){h(!0),S(null);try{let I;p==="checkpoint"?I=await n(e,"git_checkpoint",{workspace:t,message:w,includeUntracked:f}):p==="stash"?I=await n(e,"git_stash_push",{workspace:t,message:w,includeUntracked:f}):p==="stash_pop"?I=await n(e,"git_stash_pop",{workspace:t}):p==="checkout_files"&&m&&(I=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const E=(I==null?void 0:I.result)??I;if((E==null?void 0:E.success)===!1||E!=null&&E.error){S((E==null?void 0:E.error)??"Action failed"),h(!1);return}p==="checkpoint"?T(`Checkpoint created: ${((D=(B=E==null?void 0:E.checkpoint)==null?void 0:B.commit)==null?void 0:D.slice(0,7))??"done"}`):p==="stash"?T(`Stashed as ${((C=E==null?void 0:E.stash)==null?void 0:C.stashRef)??"stash@{0}"}`):p==="stash_pop"?T("Stash restored"):(T("File reverted"),u(null)),b(null),await d()}catch(I){S(I instanceof Error?I.message:"Action failed")}finally{h(!1)}}},[p,n,e,t,w,f,m,d]),N=!!(a!=null&&a.hasConflicts),P=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:B=>{B.target===B.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}),A&&s.jsx("a",{href:`${A}/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:l,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(jt,{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"}),P===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:[l&&!o&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),o&&s.jsx(Z0,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:k}),!l&&!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(tv,{diff:m.diff,binary:m.binary,truncated:m.truncated,loading:m.loading,error:m.error,className:"h-full"}):s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),v&&s.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-emerald-500/10 px-4 py-2 text-xs text-emerald-400 flex items-center justify-between",children:[s.jsx("span",{children:v}),s.jsx("button",{onClick:()=>T(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:()=>j("checkpoint"),disabled:N,title:N?"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:()=>j("stash"),disabled:N,title:N?"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:()=>j("stash_pop"),disabled:N||!(a!=null&&a.stashCount),title:N?"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:()=>j("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 B=sv((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(B),T("Copied to clipboard"),setTimeout(()=>T(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),p&&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:[p==="checkpoint"&&"Create checkpoint commit",p==="stash"&&"Stash changes",p==="stash_pop"&&"Restore latest stash?",p==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(p==="checkpoint"||p==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:w,onChange:B=>g(B.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:f,onChange:B=>x(B.target.checked)}),"Include untracked files"]})]}),M&&s.jsx("p",{className:"text-xs text-red-400",children:M}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:O,disabled:y,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:L,disabled:y||(p==="checkpoint"||p==="stash")&&!w.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:y?"Working…":"Confirm"})]})]})})]})})}function rv({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=i.useState(!1),[o,l]=i.useState(!1),[c,d]=i.useState(!1),[m,u]=i.useState(!1),[p,b]=i.useState(!1),[w,g]=i.useState("quickstart"),[f,x]=i.useState("workspace"),y=i.useMemo(()=>!t&&!e,[t,e]),h=i.useCallback(k=>{a(k),k&&l(!1)},[]),M=i.useCallback(k=>{l(k),k&&a(!1)},[]),S=i.useCallback(()=>{g(r===0?"quickstart":"shortcuts"),x("workspace"),d(!0),a(!1),l(!1)},[r]),v=i.useCallback(()=>{d(!1)},[]),T=i.useCallback(()=>{u(!0)},[]),A=i.useCallback(()=>{u(!1)},[]);return i.useEffect(()=>{if(!y){b(!1);return}b(!0);const k=window.setTimeout(()=>{b(!1)},1e4);return()=>window.clearTimeout(k)},[y]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:m,guideNudgeVisible:p,guideTab:w,shortcutSection:f,isDesktopDashboard:y,setGuideTab:g,setShortcutSection:x,handleInboxOpenChange:h,handleHiddenOpenChange:M,handleOpenShortcutHelp:S,closeShortcutHelp:v,openNewSession:T,closeNewSession:A}}function nv(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 av(e){return e instanceof Error?e.message:String(e||"")}function ov(e){const t=av(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function iv({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:l,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:p,ides:b,actionLogs:w,sendDaemonCommand:g,setActionLogs:f,setCliViewModeOverrides:x,isStandalone:y,initialDataLoaded:h,userName:M,requestedMobileTabKey:S,onRequestedMobileTabConsumed:v,requestedMachineId:T,onRequestedMachineConsumed:A,requestedMobileSection:k,onRequestedMobileSectionConsumed:j,containerRef:O,isSplitMode:L,numGroups:N,groupSizes:P,groupedConvs:B,clearedTabs:D,focusedGroup:C,focusGroup:I,moveTabToGroup:E,splitTabRelative:R,closeGroup:$,handleResizeStart:z,groupActiveTabIds:H,setGroupActiveTab:me,groupTabOrders:ie,setGroupTabOrder:ee,toggleHiddenTab:ce,visibleConversations:je,requestedDesktopTabKey:Ne,onRequestedDesktopTabConsumed:q,onDesktopActiveTabChange:ge,onRequestScrollToBottom:he,onHideConversation:we,onShowHiddenConversation:xe,onShowAllHiddenConversations:Se,scrollToBottomRequest:J,machineEntries:fe,layoutProfile:ae,onBrowseMachineDirectory:ue,onSaveMachineWorkspace:oe,onLaunchMachineIde:de,onLaunchMachineProvider:Q,onListMachineMeshes:ve,onLaunchMeshCoordinator:le,onListMachineSavedSessions:pe,notifications:ne,notificationUnreadCount:Ie,liveSessionInboxState:Ce,onMarkNotificationRead:_e,onMarkNotificationUnread:K,onDeleteNotification:Me}){const Te=St.useRef(null),{inboxOpen:We,hiddenOpen:Ge,shortcutHelpOpen:Xe,newSessionOpen:Ye,guideNudgeVisible:tt,guideTab:ct,shortcutSection:mt,isDesktopDashboard:pt,setGuideTab:F,setShortcutSection:be,handleInboxOpenChange:Ae,handleHiddenOpenChange:Be,handleOpenShortcutHelp:qe,closeShortcutHelp:G,openNewSession:U,closeNewSession:X}=rv({isMobile:t,showMobileChatMode:e,visibleConversationCount:je.length}),[se,W]=St.useState(null),[V,te]=St.useState(null),re=St.useCallback((_,Y)=>{W({daemonId:_,workspace:Y})},[]),ke=St.useCallback(_=>{te(_)},[]),Ee=St.useCallback(_=>{var Y;Nr.flushSync(()=>{xe(_)}),(Y=Te.current)==null||Y.restoreHiddenTabToSavedLocation(_.tabKey)},[xe]),Oe=St.useCallback(_=>{var ye;const Y=u.find(He=>ao(He,_))||p.find(He=>ao(He,_));Y&&(p.some(He=>He.tabKey===Y.tabKey)&&Ee(Y),ge(Y.tabKey),(ye=Te.current)==null||ye.activateConversationTab(Y.tabKey),he(Y.tabKey,"notification-open")),_e(_.id),Ae(!1)},[Ee,p,u,ge,_e,he]),Re=St.useCallback(()=>{var Y;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Y=Te.current)==null||Y.resetAllPanelsToMain(),Be(!1))},[Be]),Fe=St.useCallback(async _=>{var Ke;if(!r)return;const Y=(Ke=r.modalButtons)==null?void 0:Ke[_];if(!Y)return;const ye=Us(r);if(!ye)return;const He=Y.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Pe=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(He);try{await g(ye,"resolve_action",{button:Y,action:Pe?"approve":"reject",buttonIndex:_,...hs(r)})}catch(rt){ov(rt)||console.error("[Shortcut approval] Failed:",rt)}},[r,g]),{isMac:Ue,actionDefinitions:Le,actionShortcuts:Qe,shortcutListening:et,shortcutListeningDraft:gt,setShortcutListening:yt,setShortcutListeningDraft:dt,saveShortcuts:ht}=my({enabled:pt&&!Xe,onTrigger:_=>{var Y,ye,He,Pe,Ke,rt,Tt,xt,es,$r,Br,Or,Fr,Hr,Wr,Kr;if(_==="openShortcutHelp"){qe();return}if(_==="openNewSession"){U();return}if(_==="hideCurrentTab"){r&&we(r);return}if(_==="toggleHiddenTabs"){Be(!Ge);return}if(_==="openHistoryForActiveTab"){r&&!st(r)&&o(r);return}if(_==="openRemoteForActiveTab"){r&&!at(r)&&!st(r)&&l(r);return}if(_==="splitActiveTabRight"){(Y=Te.current)==null||Y.splitActiveTabRight();return}if(_==="splitActiveTabDown"){(ye=Te.current)==null||ye.splitActiveTabDown();return}if(_==="floatActiveTab"){(He=Te.current)==null||He.floatActiveTab();return}if(_==="popoutActiveTab"){(Pe=Te.current)==null||Pe.popoutActiveTab();return}if(_==="dockActiveTab"){(Ke=Te.current)==null||Ke.dockActiveTab();return}if(_==="focusLeftPane"){(rt=Te.current)==null||rt.focusLeftPane();return}if(_==="focusRightPane"){(Tt=Te.current)==null||Tt.focusRightPane();return}if(_==="focusUpPane"){(xt=Te.current)==null||xt.focusUpPane();return}if(_==="focusDownPane"){(es=Te.current)==null||es.focusDownPane();return}if(_==="moveActiveTabToLeftPane"){($r=Te.current)==null||$r.moveActiveTabToLeftPane();return}if(_==="moveActiveTabToRightPane"){(Br=Te.current)==null||Br.moveActiveTabToRightPane();return}if(_==="moveActiveTabToUpPane"){(Or=Te.current)==null||Or.moveActiveTabToUpPane();return}if(_==="moveActiveTabToDownPane"){(Fr=Te.current)==null||Fr.moveActiveTabToDownPane();return}if(_==="triggerPrimaryApprovalAction"){Fe(0);return}if(_==="triggerSecondaryApprovalAction"){Fe(1);return}if(_==="triggerTertiaryApprovalAction"){Fe(2);return}if(_==="setActiveTabShortcut"){(Hr=Te.current)==null||Hr.setShortcutForActiveTab();return}if(_==="selectPreviousGroupTab"){(Wr=Te.current)==null||Wr.activatePreviousTabInGroup();return}if(_==="selectNextGroupTab"){(Kr=Te.current)==null||Kr.activateNextTabInGroup();return}!r||!at(r)||st(r)||_==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),Ve=St.useCallback(()=>{G(),yt(null),dt([])},[G,yt,dt]),Wt=St.useMemo(()=>mt==="all"?Le:Le.filter(_=>nv(_)===mt),[Le,mt]),Z=St.useCallback(()=>{const _=Object.fromEntries(Le.map(Y=>[Y.id,""]));ht(_)},[Le,ht]),$e=St.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const _=Object.fromEntries(Le.map(Y=>[Y.id,Y.defaultShortcut]));ht(_)},[Le,ht]);return St.useEffect(()=>{const _=Y=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Y.metaKey&&Y.key.toLowerCase()==="w":Y.ctrlKey&&Y.key.toLowerCase()==="w")&&(Y.preventDefault(),r&&we&&we(r))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[r,we]),St.useEffect(()=>{if(!Xe||et)return;const _=Y=>{Y.key==="Escape"&&(Y.preventDefault(),Ve())};return window.addEventListener("keydown",_,!0),()=>window.removeEventListener("keydown",_,!0)},[Ve,Xe,et]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(dx,{activeConv:r,wsStatus:n,isConnected:a,conversations:je,hiddenConversations:p,onOpenHistory:o,onHideConversation:we,onShowConversation:Ee,onShowAllHidden:Se,onResetPanelsToMain:Re,notifications:ne,notificationUnreadCount:Ie,onOpenNotification:Oe,onMarkNotificationRead:_e,onMarkNotificationUnread:K,onDeleteNotification:Me,inboxOpen:We,onInboxOpenChange:Ae,hiddenOpen:Ge,onHiddenOpenChange:Be,onOpenNewSession:t?void 0:U,onOpenDashboardGuide:qe,guideNudgeVisible:tt,actionShortcuts:Qe,onOpenRemote:()=>{!r||at(r)||st(r)||l(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:re,onOpenMeshGraph:ke}),e?s.jsx(ey,{conversations:u,hiddenConversations:p,ides:b,actionLogs:w,sendDaemonCommand:g,setActionLogs:f,setCliViewModeOverrides:x,isStandalone:y,userName:M,requestedActiveTabKey:S,onRequestedActiveTabConsumed:v,requestedMachineId:T,onRequestedMachineConsumed:A,requestedMobileSection:k,onRequestedMobileSectionConsumed:j,onOpenHistory:o,onOpenRemote:l,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Se,onHideConversation:we,onOpenMeshGraph:ke,onOpenNewSession:U,liveSessionInboxState:Ce}):t?s.jsx(ly,{containerRef:O,isSplitMode:L,numGroups:N,groupSizes:P,groupedConvs:B,clearedTabs:D,ides:b,actionLogs:w,sendDaemonCommand:g,setActionLogs:f,isStandalone:y,hasRegisteredMachines:fe.length>0,userName:M,focusedGroup:C,focusGroup:I,moveTabToGroup:E,splitTabRelative:R,closeGroup:$,handleResizeStart:z,groupActiveTabIds:H,setGroupActiveTab:me,groupTabOrders:ie,setGroupTabOrder:ee,toggleHiddenTab:ce,onOpenNewSession:U,allowTabShortcuts:!1,liveSessionInboxState:Ce}):s.jsx(Cy,{visibleConversations:je,clearedTabs:D,ides:b,actionLogs:w,sendDaemonCommand:g,setActionLogs:f,isStandalone:y,hasRegisteredMachines:fe.length>0,initialDataLoaded:h,userName:M,toggleHiddenTab:ce,actionShortcuts:Qe,registerActionHandlers:_=>{Te.current=_},onActiveTabChange:ge,requestedActiveTabKey:Ne,onRequestedActiveTabConsumed:q,onRequestScrollToBottom:he,scrollToBottomRequest:J,onOpenNewSession:U,liveSessionInboxState:Ce,layoutProfile:ae}),Ye&&s.jsx(_y,{machines:fe,ides:b,onClose:X,onBrowseDirectory:ue,onSaveWorkspace:oe,onLaunchIde:de,onLaunchProvider:Q,onListMeshes:ve,onLaunchMeshCoordinator:le,onListSavedSessions:pe}),V&&s.jsx(F0,{activeConv:V,sendDaemonCommand:g,onClose:()=>te(null)}),se&&s.jsx(vu,{daemonId:se.daemonId,workspace:se.workspace,onClose:()=>W(null)}),Xe&&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:Ve,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:_=>_.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:Ve,"aria-label":"Close dashboard guide",children:s.jsx(jt,{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(_=>s.jsx("button",{type:"button",className:`btn btn-sm ${ct===_.id?"btn-primary":"btn-secondary"}`,onClick:()=>F(_.id),children:_.label},_.id))}),ct==="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 ",Ue?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),ct==="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."]})]})]})]}),ct==="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(_=>s.jsx("button",{type:"button",className:`btn btn-sm ${mt===_.id?"btn-primary":"btn-secondary"}`,onClick:()=>be(_.id),children:_.label},_.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Z,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:Wt.map(_=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${et===_.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:_.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:_.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:_.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:et===_.id?gt.length>0?`${gt.join(" ")} ...`:"Listening...":Qe[_.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{yt(_.id),dt([])},children:et===_.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Y={...Qe};Y[_.id]="",ht(Y)},children:"Disable"})]})]})},_.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Ue?"⌘⇧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 $a=[{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 lv({onClose:e}){const[t,r]=i.useState(0),n=$a[t],a=t===$a.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(jt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:$a.map((o,l)=>s.jsx("div",{style:{width:l===t?24:8,height:8,borderRadius:4,background:l===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},l))}),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:`
67
67
  @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }