@adhdev/daemon-standalone 0.9.82-rc.30 → 0.9.82-rc.31

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,38 +61,38 @@ 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
- `,Y.style.top="52px",Y.style.height="calc(100% - 52px)";const $e=Ae.querySelector("[data-adhdev-popout-focus]");$e&&($e.onclick=()=>{window.focus()});const Fe=Ae.querySelector("[data-adhdev-popout-dock]");Fe&&(Fe.disabled=!se,Fe.style.opacity=se?"1":"0.5",Fe.style.cursor=se?"pointer":"default",Fe.onclick=()=>{var Me;se&&ve(se),(Me=K.defaultView)==null||Me.focus()})}},[G,ve]),ie=i.useCallback(U=>{var ae;const V=N.current,Z=V==null?void 0:V.getPanel(U);if(!(!V||!Z)){Z.group.model.openPanel(Z),Z.api.setActive(),he(U,"dockview-shortcut");try{const K=Z.group.model.location;K.type==="popout"?K.getWindow().focus():_a((ae=Z.group.element)==null?void 0:ae.ownerDocument)}catch{}}},[he]),pe=i.useCallback(U=>{const V=N.current,Z=V==null?void 0:V.activePanel,ae=(V==null?void 0:V.activeGroup)||(Z==null?void 0:Z.group);if(!V||!Z||!ae)return;const K=ae.panels||[];if(K.length<=1)return;const Y=K.findIndex(ke=>ke.id===Z.id);if(Y<0)return;const se=(Y+U+K.length)%K.length,oe=K[se];oe&&(oe.group.model.openPanel(oe),oe.api.setActive(),Bt(oe.id)||he(oe.id,"dockview-shortcut"))},[he]),le=i.useCallback(U=>{var $e;const V=N.current,Z=(V==null?void 0:V.activeGroup)||(($e=V==null?void 0:V.activePanel)==null?void 0:$e.group);if(!V||!Z)return;const ae=V.groups||[],K=ae.find(Fe=>Fe.id===Z.id);if(!K)return;const Y=K.element.getBoundingClientRect(),se=Y.left+Y.width/2,oe=Y.top+Y.height/2,ke=(Fe,Me,Qe,et)=>Math.max(0,Math.min(Me,et)-Math.max(Fe,Qe)),Pe=Fe=>{const Me=Fe.element.getBoundingClientRect(),Qe=Me.left+Me.width/2,et=Me.top+Me.height/2;let bt=0,gt=0,dt=0,ht=!1;if(U==="left"?(ht=Qe<se,bt=Math.max(0,Y.left-Me.right),gt=Math.abs(et-oe),dt=ke(Y.top,Y.bottom,Me.top,Me.bottom)):U==="right"?(ht=Qe>se,bt=Math.max(0,Me.left-Y.right),gt=Math.abs(et-oe),dt=ke(Y.top,Y.bottom,Me.top,Me.bottom)):U==="above"?(ht=et<oe,bt=Math.max(0,Y.top-Me.bottom),gt=Math.abs(Qe-se),dt=ke(Y.left,Y.right,Me.left,Me.right)):(ht=et>oe,bt=Math.max(0,Me.top-Y.bottom),gt=Math.abs(Qe-se),dt=ke(Y.left,Y.right,Me.left,Me.right)),!ht)return Number.POSITIVE_INFINITY;const Ue=dt>0?0:120;return bt*3+gt+Ue};let Ee=null,Ae=Number.POSITIVE_INFINITY;for(const Fe of ae){if(Fe.id===K.id)continue;const Me=Pe(Fe);Number.isFinite(Me)&&(Me>=Ae||(Ae=Me,Ee=Fe))}return Ee||void 0},[]),B=i.useCallback(U=>{var ae;const V=le(U);if(!V)return;const Z=V.activePanel||V.panels[0];Z&&(V.model.openPanel(Z),Z.api.setActive(),Bt(Z.id)||he(Z.id,"dockview-focus"),_a((ae=V.element)==null?void 0:ae.ownerDocument))},[le,he]),z=i.useCallback((U,V)=>{const Z=N.current,ae=Z==null?void 0:Z.activePanel,K=(Z==null?void 0:Z.activeGroup)||(ae==null?void 0:ae.group);if(!Z||!ae||!K)return;let Y=le(U);!Y&&(V!=null&&V.createGroupIfMissing)&&(Y=Z.addGroup({referenceGroup:K,direction:U})),Y&&(ae.api.moveTo({group:Y,position:"center"}),ae.group.model.openPanel(ae),ae.api.setActive(),Bt(ae.id)||he(ae.id,V!=null&&V.createGroupIfMissing?"dockview-split":"dockview-move"))},[le,he]),{isMac:de,tabShortcuts:re,shortcutListening:R,setShortcutListening:q,saveShortcuts:ce}=nu({sortedTabKeys:e.map(U=>U.tabKey),onFocus:ye,onSelectTab:ie}),Ne=i.useCallback(()=>{var Z;const U=N.current;if(!U)return;const V=U.activePanel;if(V){if(Bt(V.id)){const ae=((Z=V.params)==null?void 0:Z.routeId)||V.id.slice(7),K=Wt(e,ae);K!=null&&K.tabKey&&q(K.tabKey);return}G.has(V.id)&&q(V.id)}},[G,ie,q,e]),je=i.useCallback(U=>{const V=[];return U.metaKey&&V.push(de?"⌘":"Meta"),U.ctrlKey&&V.push("Ctrl"),U.altKey&&V.push(de?"⌥":"Alt"),U.shiftKey&&U.key.length!==1&&V.push(de?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(U.key)?null:(V.push(lu(U.key)),V.join("+"))},[de]),O=i.useCallback(U=>{var V,Z;switch(U){case"splitActiveTabRight":z("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":z("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const ae=be();ae&&fe(ae);return}case"popoutActiveTab":{const ae=be();ae&&Se(ae);return}case"dockActiveTab":{const ae=be();if(!ae)return;X(ae)?ve(ae):we(ae)&&Ce(ae);return}case"focusLeftPane":B("left");return;case"focusRightPane":B("right");return;case"focusUpPane":B("above");return;case"focusDownPane":B("below");return;case"moveActiveTabToLeftPane":z("left");return;case"moveActiveTabToRightPane":z("right");return;case"moveActiveTabToUpPane":z("above");return;case"moveActiveTabToDownPane":z("below");return;case"selectPreviousGroupTab":pe(-1);return;case"selectNextGroupTab":pe(1);return;case"setActiveTabShortcut":Ne();return;case"hideCurrentTab":{const ae=(Z=(V=N.current)==null?void 0:V.activePanel)==null?void 0:Z.id;ae&&!Bt(ae)&&xe(ae);return}default:return}},[pe,Ce,B,fe,be,xe,we,X,ve,z,Se,Ne]);i.useEffect(()=>{if(!C)return;const U=C.sourceDocument,V=U.defaultView??window,Z=ae=>{const K=U.querySelector("[data-dockview-tab-context-menu]");K&&K.contains(ae.target)||y(null)};return V.addEventListener("mousedown",Z,!0),V!==window&&window.addEventListener("mousedown",()=>y(null),!0),()=>{V.removeEventListener("mousedown",Z,!0),V!==window&&window.removeEventListener("mousedown",()=>y(null),!0)}},[C]);const Ie=i.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:G,hasDetachedConversationPanels:J,ides:r,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:b,liveSessionInboxState:I,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:xe,userName:m,scrollToBottomRequest:T,tabShortcuts:re,openTabContextMenu:({x:U,y:V,tabKey:Z,sourceDocument:ae})=>y({x:U,y:V,tabKey:Z,sourceDocument:ae??document}),popoutTab:Se,moveTabBackToMain:ve,isTabInPopout:X,floatTab:fe,isTabFloating:we}),[n,t,G,J,r,l,c,b,I,a,o,xe,m,T,re,Se,ve,X,fe,we]),Le=C?Ty({isTabInPopout:X(C.tabKey),isTabFloating:we(C.tabKey),tabShortcut:re[C.tabKey],actionShortcuts:h}):[],He=i.useCallback(U=>{var ae;const V=N.current;if((((ae=V==null?void 0:V.activePanel)==null?void 0:ae.id)??null)===U.id){U.group.model.openPanel(U);return}U.group.model.openPanel(U),U.api.setActive()},[]),ze=i.useCallback((U,V="requested-tab")=>{if(!U)return!1;const Z=N.current;if(!Z)return!1;const ae=Z.getPanel(U);return ae?(He(ae),he(U,V),f==null||f(),!0):!1},[He,f,he]),Xe=i.useCallback(()=>{if(W.current)return!1;const U=ze(H.current,"stored-layout-restore");return U&&(W.current=!0),U},[ze]),Je=i.useCallback(()=>{var V;const U=N.current;U&&ag(k,{activeTabId:((V=U.activePanel)==null?void 0:V.id)??null,layout:U.toJSON()})},[k]),rt=i.useCallback(()=>{ig(k,E.current)},[k]),pt=i.useCallback(U=>{var ae,K,Y,se;const V=N.current;if(!V)return{kind:"grid"};const Z=V.toJSON();for(const oe of Z.floatingGroups||[])if((K=(ae=oe.data)==null?void 0:ae.views)!=null&&K.includes(U)&&oe.position)return{kind:"floating",position:oe.position};for(const oe of Z.popoutGroups||[])if((se=(Y=oe.data)==null?void 0:Y.views)!=null&&se.includes(U))return{kind:"popout",position:oe.position,popoutUrl:oe.url};return{kind:"grid"}},[]),xt=i.useCallback(U=>{const V=N.current;if(!V)return;const Z=V.getPanel(U),ae=E.current[U];if(!Z||!ae||ae.kind==="grid")return;if(Z.group.model.location.type===ae.kind){delete E.current[U],rt();return}if(ae.kind==="floating"){V.addFloatingGroup(Z,{x:ae.position.left??24,y:ae.position.top??24,width:ae.position.width,height:ae.position.height}),delete E.current[U],rt();return}delete E.current[U],rt()},[rt]);i.useEffect(()=>(x==null||x({setShortcutForActiveTab:Ne,restoreHiddenTabToSavedLocation:xt,activateConversationTab:ie,resetAllPanelsToMain:ee,activatePreviousTabInGroup:()=>pe(-1),activateNextTabInGroup:()=>pe(1),floatActiveTab:()=>{const U=be();U&&fe(U)},popoutActiveTab:()=>{const U=be();U&&Se(U)},dockActiveTab:()=>{const U=be();U&&(X(U)?ve(U):we(U)&&Ce(U))},splitActiveTabRight:()=>z("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>z("below",{createGroupIfMissing:!0}),focusLeftPane:()=>B("left"),focusRightPane:()=>B("right"),focusUpPane:()=>B("above"),focusDownPane:()=>B("below"),moveActiveTabToLeftPane:()=>z("left"),moveActiveTabToRightPane:()=>z("right"),moveActiveTabToUpPane:()=>z("above"),moveActiveTabToDownPane:()=>z("below")}),()=>x==null?void 0:x(null)),[pe,Ce,fe,B,be,we,X,z,ve,Se,x,ee,xt,ie,Ne]),i.useEffect(()=>()=>{var U;(U=D.current)==null||U.call(D),D.current=null},[]);const vt=i.useCallback(U=>{var Z,ae;N.current=U.api,(Z=D.current)==null||Z.call(D),D.current=null;const V=ng(k);if(H.current=(V==null?void 0:V.activeTabId)??null,V!=null&&V.layout&&U.api.fromJSON(V.layout,{reuseExistingPanels:!1}),j.current=kl({hasStoredLayout:!!(V!=null&&V.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),j.current||(Ml(U.api,e),Al(U.api,e,v)),U.api.totalPanels===0&&e.length>0){const K=Ey(U.api,e,g);if(K){const Y=U.api.getPanel(K);Y&&He(Y)}}else!j.current&&!ze(g)&&Xe();if(M.current=!0,U.api.onDidActivePanelChange(K=>{var se;if(H.current=(K==null?void 0:K.id)??null,W.current=!0,me(),K&&Bt(K.id)){const oe=((se=K.params)==null?void 0:se.routeId)||K.id.slice(7),ke=Wt(e,oe);S((ke==null?void 0:ke.tabKey)??null),Je();return}if(S((K==null?void 0:K.id)??null),Je(),!K)return;const Y=G.get(K.id);(Y==null?void 0:Y.streamSource)==="agent-stream"&&Y.agentType&&_(Y.routeId,Gc(),{agentType:Y.agentType,...Y.sessionId&&{targetSessionId:Y.sessionId}}).catch(()=>{})}),U.api.onDidLayoutChange(()=>{Je(),me(),P(K=>K+1)}),Ly()){const K=Ae=>({clientX:Ae.clientX,clientY:Ae.clientY}),Y=Ae=>{const $e=Ae==null?void 0:Ae.getBoundingClientRect();return $e?{left:$e.left,right:$e.right,top:$e.top,bottom:$e.bottom}:null},se=Ae=>{var Fe;const $e=(Fe=w.current)==null?void 0:Fe.getBoundingClientRect();return $e?Ae.clientX<$e.left||Ae.clientX>$e.right||Ae.clientY<$e.top||Ae.clientY>$e.bottom:!1},oe=_y({detachDelayMs:du,onDetach:({panelId:Ae,clientX:$e,clientY:Fe})=>{var dt,ht;const Me=U.api.getPanel(Ae);if(!Me)return;try{if(Me.group.model.location.type!=="grid")return}catch{return}const Qe=(dt=w.current)==null?void 0:dt.getBoundingClientRect(),et=(ht=Me.group.element)==null?void 0:ht.getBoundingClientRect(),bt=Math.round(Math.min(Math.max((et==null?void 0:et.width)??600,360),720)),gt=Math.round(Math.min(Math.max((et==null?void 0:et.height)??500,260),640));U.api.addFloatingGroup(Me,{x:Qe?Math.max(0,$e-Qe.left-32):void 0,y:Qe?Math.max(0,Fe-Qe.top-18):void 0,width:bt,height:gt}),Me.api.setActive(),Je(),me(),P(Ue=>Ue+1)}}),ke=[U.api.onWillDragPanel(Ae=>{if(!(Ae.nativeEvent.defaultPrevented||Ae.nativeEvent.shiftKey)){try{if(Ae.panel.group.model.location.type!=="grid")return}catch{return}oe.startDrag({panelId:Ae.panel.id,selfPanelBounds:Y(Ae.panel.group.element),...K(Ae.nativeEvent)})}}),U.api.onWillShowOverlay(Ae=>{if(oe.hasDetached()){Ae.preventDefault();return}oe.markDockTarget(K(Ae.nativeEvent))}),U.api.onWillDrop(Ae=>{if(oe.hasDetached()){Ae.preventDefault(),oe.endDrag();return}oe.markDockTarget(K(Ae.nativeEvent))}),U.api.onDidDrop(()=>oe.endDrag()),U.api.onUnhandledDragOverEvent(Ae=>{oe.isDragging()&&oe.markSelfPanel(K(Ae.nativeEvent))})],Pe=Ae=>{if(!oe.isDragging())return;const $e=K(Ae);se($e)&&oe.markNonSelfPanel($e)},Ee=()=>oe.endDrag();window.addEventListener("dragover",Pe,!0),window.addEventListener("drop",Ee,!0),window.addEventListener("dragend",Ee,!0),D.current=()=>{oe.dispose();for(const Ae of ke)Ae.dispose();window.removeEventListener("dragover",Pe,!0),window.removeEventListener("drop",Ee,!0),window.removeEventListener("dragend",Ee,!0)}}U.api.onDidAddGroup(K=>{requestAnimationFrame(()=>{var Y,se;try{const oe=(Y=K.element)==null?void 0:Y.ownerDocument;if(!oe||oe===document)return;(se=oe.getElementById("dv-popout-window"))==null||se.classList.add("adhdev-dockview");const ke=document.documentElement.getAttribute("data-theme");ke&&oe.documentElement.setAttribute("data-theme",ke),oe.body.className=document.body.className;const Pe=document.documentElement.getAttribute("style");Pe&&oe.documentElement.setAttribute("style",Pe)}catch{}me(),P(oe=>oe+1)})}),S(((ae=U.api.activePanel)==null?void 0:ae.id)??null)},[He,ze,G,r,d,k,S,Je,g,v,_,me,e]);i.useLayoutEffect(()=>{const U=N.current;if(!U||!M.current||j.current&&kl({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;j.current&&(j.current=!1);const V=$.current,Z=new Set(V),ae=e.map(Ee=>Ee.tabKey),K=new Set(ae),Y=My({previousVisibleConversationCount:V.length,visibleConversationCount:e.length,ides:r});let se=!1;for(const Ee of V)K.has(Ee)||Y||(E.current[Ee]=pt(Ee),se=!0);se&&rt(),Y||(Ml(U,e),Al(U,e,v));const oe=ae.filter(Ee=>!Z.has(Ee));let ke=!1;for(const Ee of oe){const Ae=U.getPanel(Ee),$e=E.current[Ee];if(!Ae||!$e||$e.kind==="grid")continue;if(Ae.group.model.location.type===$e.kind){delete E.current[Ee],ke=!0;continue}if($e.kind==="floating"){U.addFloatingGroup(Ae,{x:$e.position.left??24,y:$e.position.top??24,width:$e.position.width,height:$e.position.height}),delete E.current[Ee],ke=!0;continue}}if(ke&&rt(),$.current=ae,g&&ze(g))return;!U.activePanel&&U.panels[0]&&He(U.panels[0]),!!(U.activePanel&&U.getPanel(U.activePanel.id))||Xe()},[He,ze,Xe,r,d,rt,pt,g,v,e]),i.useEffect(()=>{M.current&&ze(g)},[ze,g]),i.useEffect(()=>{const U=Z=>{const ae=Z.target;if(!ae)return;const K=ae.querySelector("[data-tab-key]")||ae.closest("[data-tab-key]");if(K){const Y=K.getAttribute("data-tab-key");if(Y&&Z.dataTransfer){const se=ae.closest(".dv-tab")||K.closest(".dv-tab")||K;Z.dataTransfer.effectAllowed="move",Z.dataTransfer.setData("text/tab-key",Y),se instanceof HTMLElement&&Z.dataTransfer.setDragImage(se,Math.max(12,Math.round(se.clientWidth/2)),Math.max(10,Math.round(se.clientHeight/2)))}}};window.addEventListener("dragstart",U);const V=Tl(N.current);for(const Z of V)Z.addEventListener("dragstart",U);return()=>{window.removeEventListener("dragstart",U);for(const Z of V)Z.removeEventListener("dragstart",U)}},[F]),i.useEffect(()=>{var V;const U=(V=w.current)==null?void 0:V.querySelector(".adhdev-dockview");U instanceof HTMLElement&&La(U,A),ue(),me()},[me,ue,A]),i.useEffect(()=>{me()},[me]),i.useEffect(()=>{const U=V=>{if(V.defaultPrevented||R)return;const Z=je(V);if(!Z)return;const ae=V.metaKey||V.ctrlKey||V.altKey;wo(V.target)&&!ae||On(de).setActiveTabShortcut!==Z||(V.preventDefault(),V.stopPropagation(),Ne())};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[je,de,R,Ne]),i.useEffect(()=>{const U=w.current;if(!U)return;const V=Z=>{var oe,ke;if(!Z.isTrusted)return;const ae=(ke=(oe=Z.target)==null?void 0:oe.closest)==null?void 0:ke.call(oe,".dv-scrollable");if(!ae)return;Z.preventDefault(),Z.stopPropagation();const K=Math.abs(Z.deltaX),Y=Math.abs(Z.deltaY),se=K>Y?Z.deltaX:Z.deltaY;ae.dispatchEvent(new WheelEvent("wheel",{deltaY:se,deltaMode:Z.deltaMode,bubbles:!1,cancelable:!0}))};return U.addEventListener("wheel",V,{passive:!1,capture:!0}),()=>U.removeEventListener("wheel",V,{capture:!0})},[]),i.useEffect(()=>{const U=Tl(N.current);if(U.length===0)return;const V=U.map(Z=>{let ae=[],K=null;const Y=()=>{K!=null&&Z.clearTimeout(K),K=null,ae=[]},se=()=>{K!=null&&Z.clearTimeout(K),K=Z.setTimeout(()=>{K=null,ae=[]},1200)},oe=Pe=>{if(!Pe.ctrlKey&&!Pe.metaKey&&!Pe.altKey)return;const Ee=je(Pe);if(!Ee)return;const Ae=ru();for(const[$e,Fe]of Object.entries(Ae))if(e.some(Me=>Me.tabKey===$e)&&Fe===Ee){Pe.preventDefault(),ie($e);return}},ke=Pe=>{if(Pe.defaultPrevented||R)return;const Ee=je(Pe);if(!Ee)return;const Ae=Pe.metaKey||Pe.ctrlKey||Pe.altKey;if(wo(Pe.target))return;const $e=On(de),Fe=Object.entries($e).filter(([Ue,Kt])=>!!Kt&&(Ue==="splitActiveTabRight"||Ue==="splitActiveTabDown"||Ue==="floatActiveTab"||Ue==="popoutActiveTab"||Ue==="dockActiveTab"||Ue==="focusLeftPane"||Ue==="focusRightPane"||Ue==="focusUpPane"||Ue==="focusDownPane"||Ue==="moveActiveTabToLeftPane"||Ue==="moveActiveTabToRightPane"||Ue==="moveActiveTabToUpPane"||Ue==="moveActiveTabToDownPane"||Ue==="selectPreviousGroupTab"||Ue==="selectNextGroupTab"||Ue==="setActiveTabShortcut"||Ue==="hideCurrentTab")),Me=Ae?[Ee]:[...ae.slice(-1),Ee].slice(-2),Qe=Me.join(" "),et=Me[Me.length-1],bt=Fe.find(([,Ue])=>Ue===Qe);if(bt){Pe.preventDefault(),Y(),O(bt[0]);return}if(Fe.some(([,Ue])=>Ue.startsWith(`${Qe} `))){Pe.preventDefault(),ae=Me,se();return}const dt=Fe.find(([,Ue])=>Ue===et);if(dt){Pe.preventDefault(),Y(),O(dt[0]);return}if(Fe.some(([,Ue])=>Ue.startsWith(`${et} `))){Pe.preventDefault(),ae=[et],se();return}Y()};return Z.addEventListener("keydown",oe),Z.addEventListener("keydown",ke),()=>{Y(),Z.removeEventListener("keydown",oe),Z.removeEventListener("keydown",ke)}});return()=>{for(const Z of V)Z()}},[je,de,F,ie,R,O,e]);const Te=A==="light"?eo:to,Ve=((ot=(Ge=(tt=N.current)==null?void 0:tt.activePanel)==null?void 0:Ge.group.element)==null?void 0:ot.ownerDocument)??document;return s.jsxs(uu.Provider,{value:Ie,children:[s.jsx("div",{ref:w,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(pm,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:$y,remote:By},defaultTabComponent:Fy,watermarkComponent:Oy,onReady:vt,singleTabMode:"default",tabAnimation:"smooth",theme:Te,popoutUrl:"/popout.html"})}),C&&Tr.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:Le.map(U=>{if(U.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},U.id);let V=s.jsx(xp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{};switch(U.id){case"dockInWindow":case"dockBackToGrid":V=s.jsx(gp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{Ce(C.tabKey),y(null)};break;case"moveBackToMain":V=s.jsx(fp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{ve(C.tabKey),y(null)};break;case"floatAsPanel":V=s.jsx(bp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{fe(C.tabKey),y(null)};break;case"openInNewWindow":V=s.jsx(hp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{Se(C.tabKey),y(null)};break;case"setShortcut":Z=ae=>{ae.stopPropagation(),q(C.tabKey),y(null)};break;case"removeShortcut":V=s.jsx(wt,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{const ae={...re};delete ae[C.tabKey],ce(ae),y(null)};break;case"hideTab":V=s.jsx(Lo,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{xe(C.tabKey),y(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${U.tone==="muted"?"text-text-muted":""}`,onMouseDown:Py,onClick:Z,children:[V,s.jsx("span",{className:"flex-1 min-w-0",children:U.label}),U.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:U.shortcut}):null]},U.id)})}),C.sourceDocument.body),R&&Tr.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:()=>q(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:U=>U.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",de?"⌘+1":"Ctrl+1",", ",de?"⌥+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"})]})}),Ve.body)]})}const mu="adhdev-recent-launch-args-v1",Ky=8;function pu(e){return String(e||"").trim().replace(/\s+/g," ")}function di(e,t){return`${e.trim()}::${t.trim()}`}function ui(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(mu)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function hu(e){if(!(typeof window>"u"))try{window.localStorage.setItem(mu,JSON.stringify(e))}catch{}}function jo(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=ui().byKey[di(r,n)])==null?void 0:o.items)||[]}function fu(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=pu(r);if(!n||!a||!o)return;const l=ui(),c=di(n,a),d=((u=l.byKey[c])==null?void 0:u.items)||[],m=[o,...d.filter(h=>h!==o)].slice(0,Ky);l.byKey[c]={items:m},hu(l)}function Hy(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=pu(r);if(!n||!a||!o)return;const l=ui(),c=di(n,a),m=(((u=l.byKey[c])==null?void 0:u.items)||[]).filter(h=>h!==o);m.length>0?l.byKey[c]={items:m}:delete l.byKey[c],hu(l)}function xu(e){return!e.hasLoadedInitialResults&&!e.isLoading}function wn({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 Uy({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 bu({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:l,onOpenHistory:c,onClearSelection:d}){const m=o?eu(o):null,u=Uy({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(wn,{title:"Saved history",description:Jo(),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:_x()})]}),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 gu({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 zy({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 Ra(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>Ts(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>Ts(a,"acp"))?"acp":null}function on(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Vy({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:l,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Ue,Kt;const u=Er(),h=i.useMemo(()=>[...e].sort(Fo),[e]),[x,S]=i.useState(((Ue=h[0])==null?void 0:Ue.id)||""),b=i.useMemo(()=>h.find(te=>te.id===x)||h[0],[x,h]),p=i.useMemo(()=>((b==null?void 0:b.workspaces)||[]).map(te=>({id:te.id,path:te.path,label:te.label})),[b]),g=(b==null?void 0:b.defaultWorkspaceId)||null,[v,f]=i.useState("workspace"),[T,I]=i.useState(""),[k,A]=i.useState(""),[_,N]=i.useState([]),[w,D]=i.useState(""),[M,j]=i.useState(!1),[W,H]=i.useState(null),[$,C]=i.useState(""),[y,F]=i.useState(Ra(h[0])),[P,E]=i.useState(""),[G,J]=i.useState(""),[ye,he]=i.useState([]),[ne,ue]=i.useState(""),[Se,ve]=i.useState([]),[X,xe]=i.useState(!1),[fe,we]=i.useState(!1),[be,Ce]=i.useState(""),[ee,me]=i.useState(!1),[ie,pe]=i.useState(()=>Ct()),[le,B]=i.useState(null),[z,de]=i.useState(!1),[re,R]=i.useState(""),[q,ce]=i.useState(null),[Ne,je]=i.useState(!1),[O,Ie]=i.useState(""),[Le,He]=i.useState([]),[ze,Xe]=i.useState(!1),[Je,rt]=i.useState(""),[pt,xt]=i.useState(!1),vt=i.useRef(null),Te=i.useRef(0);i.useEffect(()=>{var te;!x&&((te=h[0])!=null&&te.id)&&S(h[0].id)},[x,h]),i.useEffect(()=>{!b||!(!b.workspaces||!b.availableProviders||!b.detectedIdes||!b.recentLaunches)||u(b.id,{minFreshMs:3e4}).catch(()=>{})},[u,b]);const Ve=i.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(te=>Ts(te,"cli")),[b]),tt=i.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(te=>Ts(te,"acp")),[b]),Ge=i.useMemo(()=>((b==null?void 0:b.detectedIdes)||[]).map(te=>({id:te.type,label:te.name||te.type,meta:te.running?"Detected locally":"Available to open"})),[b]),ot=i.useMemo(()=>y==="cli"?Ve.map(te=>({id:te.type,label:te.displayName||te.type,meta:"CLI provider"})):y==="acp"?tt.map(te=>({id:te.type,label:te.displayName||te.type,meta:"ACP provider"})):Ge,[tt,y,Ve,Ge]),U=i.useMemo(()=>_.find(te=>te.id===w)||null,[_,w]),V=i.useMemo(()=>Ve.find(te=>te.type===P)||null,[Ve,P]),Z=i.useMemo(()=>Gd(V==null?void 0:V.meshCoordinator,{meshId:(U==null?void 0:U.id)||"",workspace:(U==null?void 0:U.workspace)||""}),[V,U]),ae=q||Z,K=i.useCallback(async te=>{j(!0),C("");try{const De=await c(te);N(De),D(L=>{var Q;return De.some(ge=>ge.id===L)?L:((Q=De[0])==null?void 0:Q.id)||""}),H(te)}catch(De){N([]),D(""),H(te),C(De instanceof Error?De.message:"Could not load meshes")}finally{j(!1)}},[c]);i.useEffect(()=>{var De;if(!b)return;if(vt.current!==b.id){vt.current=b.id,f("workspace"),I(g||((De=p[0])==null?void 0:De.id)||"__home__"),A(""),N([]),D(""),H(null),C(""),F(Ra(b)),E(""),J(""),ue(""),ve([]),we(!1),Ce(""),pe(Ct()),R(""),ce(null);return}I(L=>{var Q;return L==="__custom__"||L==="__home__"||p.some(ge=>ge.id===L)?L:g||((Q=p[0])==null?void 0:Q.id)||"__home__"}),F(L=>L==="ide"&&Ge.length>0||L==="cli"&&Ve.length>0||L==="acp"&&tt.length>0?L:Ra(b))},[tt.length,Ve.length,g,Ge.length,b,p]),i.useEffect(()=>{!b||v!=="mesh"||W===b.id||M||K(b.id)},[K,W,M,b,v]),i.useEffect(()=>{v==="mesh"&&y!=="cli"&&Ve.length>0&&F("cli")},[y,Ve.length,v]),i.useEffect(()=>{var te;y&&(ot.some(De=>De.id===P)||E(((te=ot[0])==null?void 0:te.id)||""))},[y,ot,P]),i.useEffect(()=>{ce(null)},[b==null?void 0:b.id,w,P,v]);const Y=i.useCallback(async(te,De)=>{const L=Te.current+1;return Te.current=L,xe(!0),Ce(""),m(te,De).then(Q=>{Te.current===L&&ve(Q)}).catch(Q=>{Te.current===L&&(ve([]),Ce(Q instanceof Error?Q.message:"Could not load saved sessions"))}).finally(()=>{Te.current===L&&(xe(!1),we(!0))})},[m]),se=i.useCallback((te,De)=>{he(jo(te,De))},[]);i.useEffect(()=>{Te.current+=1,ue(""),pe(Ct()),!b||!P||y==="ide"?he([]):se(b.id,P),we(!1),ve([]),Ce(""),xe(!1)},[y,se,Y,b,P]),i.useEffect(()=>{if(!ne)return;const te=Se.find(De=>De.providerSessionId===ne);te!=null&&te.canResume||ue("")},[Se,ne]);const oe=T==="__custom__"?k.trim():T==="__home__"?"":((Kt=p.find(te=>te.id===T))==null?void 0:Kt.path)||"",ke=i.useMemo(()=>b?t.filter(te=>te.id!==b.id&&te.daemonId===b.id).map(te=>te.workspace):[],[t,b]),Pe=i.useMemo(()=>((b==null?void 0:b.recentLaunches)||[]).map(te=>te.workspace),[b]),Ee=i.useCallback(te=>{const De=String(te.workspace||"").trim();if(!De)return;const L=p.find(Q=>on(Q.path)===on(De));if(L){I(L.id),A("");return}I("__custom__"),A(De)},[p]),Ae=i.useCallback(te=>{const De=String(te.workspace||"").trim();if(!De)return{workspaceId:null,workspacePath:null};const L=p.find(Q=>on(Q.path)===on(De));return L?{workspaceId:L.id,workspacePath:null}:{workspaceId:null,workspacePath:De}},[p]),$e=i.useMemo(()=>Se.find(te=>te.providerSessionId===ne)||null,[Se,ne]),Fe=i.useMemo(()=>{var De;if(y!=="cli"||!b||!P)return null;const te=((De=Ve.find(L=>L.type===P))==null?void 0:De.displayName)||P;return{routeId:b.id,daemonId:b.id,providerSessionId:ne||void 0,transport:"pty",mode:"chat",agentName:te,agentType:P,status:"idle",title:te,messages:[],ideType:P,workspaceName:oe,workspacePath:oe,displayPrimary:te,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${b.id}:${P}`,machineName:At(b,{fallbackId:b.id})}},[y,Ve,oe,b,ne,P]),Me=i.useCallback(()=>{var De;if(!b)return;I("__custom__"),je(!0),rt("");const te=Qn(b.platform,Jn(k.trim(),oe,ke,Pe,b.defaultWorkspacePath,(De=p.find(L=>L.id===g))==null?void 0:De.path,p.map(L=>L.path)));Xe(!0),n(b.id,te).then(L=>{Ie(L.path),A(L.path),He(L.directories)}).catch(L=>{rt(L instanceof Error?L.message:"Could not load folder")}).finally(()=>Xe(!1))},[k,g,Pe,ke,n,oe,b,p]),Qe=i.useCallback(te=>{b&&(Xe(!0),rt(""),n(b.id,te).then(De=>{Ie(De.path),A(De.path),He(De.directories)}).catch(De=>{rt(De instanceof Error?De.message:"Could not load folder")}).finally(()=>Xe(!1)))},[n,b]),et=i.useCallback(async()=>{if(!b||!oe)return;xt(!0),R("");const te=await a(b.id,oe);if(xt(!1),!te.ok){R(te.error||"Could not save workspace");return}R("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,oe,b]),bt=i.useCallback(async()=>{if(!b)return;if(v==="mesh"){if(!w||!P)return;de(!0),R(""),ce(null);const L=await d(b.id,w,P);if(de(!1),!L.ok){if(L.code==="mesh_coordinator_manual_mcp_setup_required"&&L.manualSetup){ce(L.manualSetup),R("Manual MCP setup required before this provider can act as mesh coordinator.");return}R(L.error||"Could not start mesh coordinator");return}r();return}if(!y||!P)return;de(!0),R("");const te=G.trim()?G.trim().split(/\s+/).filter(Boolean):[],De=y==="ide"?await o(b.id,P,{workspacePath:oe||null}):await l(b.id,y,P,{workspaceId:T!=="__home__"&&T!=="__custom__"?T:null,workspacePath:T==="__custom__"&&oe||null,resumeSessionId:y==="cli"&&ne?ne:null,cliArgs:te});if(de(!1),!De.ok){R(De.error||"Could not start session");return}y!=="ide"&&G.trim()&&(fu(b.id,P,G),se(b.id,P)),r()},[y,G,se,r,o,d,l,oe,b,w,ne,P,T,v]),gt=v==="mesh"?"Start mesh coordinator":y?pd(y,y==="cli"&&!!ne):"Start",dt=v==="mesh"?"Starting coordinator…":y?hd(y,y==="cli"&&!!ne):"Starting…",ht=h.length>5;return b?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(wt,{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(wn,{title:"Machine",children:ht?s.jsx("select",{"aria-label":"Machine",value:b.id,onChange:te=>S(te.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:z,children:h.map(te=>s.jsx("option",{value:te.id,children:At(te,{fallbackId:te.id})},te.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:h.map(te=>{const De=At(te,{fallbackId:te.id}),L=b.id===te.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${De}`,"aria-pressed":L,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${L?"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:()=>S(te.id),disabled:z,title:De,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${te.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:De})]},te.id)})})}),s.jsxs(wn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:v==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Me,disabled:z,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(te=>s.jsxs("button",{type:"button",role:"radio","aria-checked":v===te.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${v===te.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{f(te.id),R(""),te.id==="mesh"&&b&&W!==b.id&&!M&&K(b.id)},disabled:z,children:[s.jsx("div",{className:"text-sm font-semibold",children:te.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:te.desc})]},te.id))}),v==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:T,onChange:te=>{const De=te.target.value;I(De),De==="__custom__"?Me():R("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:z,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),p.map(te=>s.jsxs("option",{value:te.id,children:[te.id===g?"⭐ ":"",Vn(te.path,te.label)||te.path]},te.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:T==="__home__"?"Launch without a workspace.":oe||"Select a workspace folder."}),T==="__custom__"&&oe&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Me,disabled:z,children:[s.jsx(Ns,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:et,disabled:z||pt,children:pt?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[M&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!M&&$&&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:$}),!M&&!$&&_.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."}),_.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:_.map(te=>s.jsxs("button",{type:"button",role:"radio","aria-checked":w===te.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${w===te.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>D(te.id),disabled:z,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:te.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[te.repoIdentity||"Repo mesh",typeof te.nodesCount=="number"?` · ${te.nodesCount} node${te.nodesCount===1?"":"s"}`:""]}),te.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",te.workspace]})]},te.id))}),U&&s.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),s.jsx(zy,{workspaceMode:v,activeKind:y,cliEnabled:Ve.length>0,ideEnabled:Ge.length>0,acpEnabled:tt.length>0,busy:z,onSelect:F}),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:y==="ide"?"Choose IDE":y==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[ot.map(te=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${P===te.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>E(te.id),disabled:z,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:te.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:te.meta})]},te.id)),ot.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."})]})]}),v==="mesh"&&ae&&s.jsx(gu,{setup:ae,providerName:(V==null?void 0:V.displayName)||(V==null?void 0:V.name)||P}),v!=="mesh"&&y!=="ide"&&s.jsxs(wn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:G,onChange:te=>J(te.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:z}),ye.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:ye.map(te=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>J(te),disabled:z,title:te,children:te},te))})]}),v!=="mesh"&&y==="cli"&&s.jsx(bu,{busy:z,savedSessionsLoading:X,savedSessionsError:be,selectedSession:$e,onRefresh:()=>{!b||!P||Y(b.id,P)},onOpenHistory:()=>{!b||!P||(me(!0),xu({hasLoadedInitialResults:fe,isLoading:X})&&Y(b.id,P))},onClearSelection:()=>ue("")}),re&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${re.includes("saved")||re.includes("requested")||re.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:re})]}),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:z,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:bt,disabled:z||(v==="mesh"?!w||!P||y!=="cli"||M:!y||!P||T==="__custom__"&&!oe),children:[s.jsx(Po,{size:14}),z?dt:gt]})]})]})}),Ne&&s.jsx(ea,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:O,directories:Le,busy:ze,error:Je,onClose:()=>je(!1),onNavigate:Qe,onConfirm:te=>{A(te),Ie(te),I("__custom__"),je(!1)}}),ee&&Fe&&s.jsx(ei,{activeConv:Fe,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:Se,isSavedSessionsLoading:X,isResumingSavedSessionId:le,savedHistoryFilters:ie,missingWorkspaceResumePath:oe||null,onSavedHistoryFiltersChange:pe,onClose:()=>me(!1),onNewChat:()=>{ue(""),me(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!b||!P||Y(b.id,P)},onResumeSavedSession:te=>{if(!b||!P||le||!te.canResume)return;const De=Ae(te);ue(te.providerSessionId),Ee(te),B(te.providerSessionId),me(!1),de(!0),R(""),l(b.id,"cli",P,{workspaceId:De.workspaceId,workspacePath:De.workspacePath,resumeSessionId:te.providerSessionId}).then(L=>{if(!L.ok){R(L.error||"Could not resume session");return}r()}).finally(()=>{de(!1),B(L=>L===te.providerSessionId?null:L)})}})]}):null}const Gy=5*60*1e3;function yu(e){var t,r;return((t=e.git)==null?void 0:t.isGitRepo)===!0?!1:!!(e.gitProbePending||((r=e.connection)==null?void 0:r.state)==="connecting")}function qy(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function vu(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function wu(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function Fn(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function Yy(e){return Fn(e)?"degraded":wu(e)?"dirty":"online"}function Xy(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function _l(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 Pa(e){return e.length===0?"unknown":e.reduce((t,r)=>_l(r)>_l(t)?r:t)}function Jy(e){var o,l,c,d,m;const t=new Map,r=new Map;for(const u of e){const h=(l=(o=u.git)==null?void 0:o.branch)==null?void 0:l.trim();h&&(r.set(h,(r.get(h)??0)+1),(c=u.git)!=null&&c.upstream&&t.set(h,(t.get(h)??0)+1))}const n=[...t.entries()].sort((u,h)=>{if(h[1]!==u[1])return h[1]-u[1];const x=["main","master","develop","dev"],S=x.indexOf(u[0]),b=x.indexOf(h[0]);return S!==-1||b!==-1?S===-1?1:b===-1?-1:S-b:u[0].localeCompare(h[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((m=[...r.entries()].sort((u,h)=>h[1]-u[1])[0])==null?void 0:m[0])??null}function Qy(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 Ll(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 Zy(e){return e.reduce((t,r)=>Ll(r.status)>Ll(t.status)?r:t)}function e0(e,t){if(!t||yu(e))return null;const r=e.git,n=(r==null?void 0:r.branch)??null,a=(r==null?void 0:r.upstream)??null,o=(r==null?void 0:r.upstreamStatus)??null,l=(r==null?void 0:r.ahead)??0,c=(r==null?void 0:r.behind)??0,d=vu(r)||wu(r),m=!!(r!=null&&r.hasConflicts)||Fn(r),u={branch:n,defaultBranch:t,upstream:a,upstreamStatus:o,ahead:l,behind:c,dirty:d,hasConflicts:m};return(r==null?void 0:r.isGitRepo)!==!0?{...u,status:"blocked_review",needsConvergence:!0,reason:"git_status_unavailable",nextStep:`Resolve git status for '${e.machineLabel||e.nodeId}' before declaring the mesh converged.`}:n?m||d?{...u,status:"not_mergeable",needsConvergence:!0,reason:r!=null&&r.hasConflicts?"conflicts_present":Fn(r)?"submodule_out_of_sync":"dirty_workspace",nextStep:`Commit, checkpoint, or resolve '${n}' before any convergence step into ${t}.`}:a&&o&&o!=="fresh"?{...u,status:"blocked_review",needsConvergence:!0,reason:"upstream_unverified",nextStep:`Refresh '${n}' against ${a} before claiming the mesh is converged.`}:n===t?l>0||c>0?{...u,status:"blocked_review",needsConvergence:!0,reason:"default_branch_not_even_with_upstream",nextStep:`Bring ${t} even with ${a??"its upstream"} before declaring convergence complete.`}:{...u,status:"merged_to_main",needsConvergence:!1,reason:"clean_default_branch",nextStep:null}:e.isLocalWorktree?{...u,status:"cleanup_candidate",needsConvergence:!0,reason:"clean_non_default_worktree_branch",nextStep:`Run refine / cleanup for '${n}' or explicitly classify the worktree before ending the task.`}:!a||l>0||c>0?{...u,status:"blocked_review",needsConvergence:!0,reason:a?"feature_branch_not_even_with_upstream":"feature_branch_missing_upstream",nextStep:`Push or reconcile '${n}', then merge it into ${t} or mark it blocked with a reason.`}:{...u,status:"pushed_feature_branch_needs_merge",needsConvergence:!0,reason:"clean_non_default_branch",nextStep:`Review and merge '${n}' into ${t}; do not treat it as fully complete while it remains off ${t}.`}:{...u,status:"blocked_review",needsConvergence:!0,reason:"branch_unknown",nextStep:`Inspect '${e.machineLabel||e.nodeId}' and confirm which branch should converge into ${t}.`}}function t0(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function s0(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(yu(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const h=t.health==="online"||t.machineStatus==="online"||((d=t.connection)==null?void 0:d.state)==="connected"||((m=t.connection)==null?void 0:m.state)==="self";return a.push(h?`${o} is online but no peer git snapshot is visible yet.`:`${o} has no peer git snapshot visible yet.`),{snapshotCompleteness:"missing_git",snapshotWarnings:a}}const c=new Set((l.submodules??[]).map(h=>h.path));if(r.size>0){const h=[...r].filter(x=>!c.has(x));h.length>0&&a.push(`${o} is missing submodule visibility for ${h.join(", ")} even though another peer reported it.`)}return((u=t.connection)==null?void 0:u.state)!=="self"&&n!==null&&typeof l.lastCheckedAt=="number"&&n-l.lastCheckedAt>Gy&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(h=>h.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(h=>h.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function ju(e){var D;const r=(typeof e.defaultBranch=="string"&&e.defaultBranch.trim().length>0?e.defaultBranch.trim():null)??Jy(e.nodes),n=qy(e.refreshedAt),a=new Set(e.nodes.flatMap(M=>{var j;return(((j=M.git)==null?void 0:j.submodules)??[]).map(W=>W.path)})),o=[],l=[],c=[],d=new Map;for(const M of e.nodes){const j=M.git,W=(j==null?void 0:j.branch)??null,H=Yy(j),$=vu(j)||H==="dirty",C=Qy(M,r),y=e0(M,r),F=s0({nodeStatus:M,expectedSubmodulePaths:a,refreshedAtMs:n}),P={id:M.nodeId,type:C.length>0?"orphanNode":"worktreeNode",label:M.machineLabel||M.nodeId.slice(0,8),workspace:M.workspace,branch:W,upstream:(j==null?void 0:j.upstream)??null,upstreamStatus:(j==null?void 0:j.upstreamStatus)??null,machineLabel:M.machineLabel||null,health:Pa([M.health,H]),ahead:(j==null?void 0:j.ahead)??0,behind:(j==null?void 0:j.behind)??0,dirty:$,dirtyFiles:Xy(j),hasConflicts:(j==null?void 0:j.hasConflicts)??!1,activeSessionCount:((D=M.activeSessions)==null?void 0:D.length)??0,activeSessions:M.activeSessions??[],providers:M.providers??[],isOrphan:C.length>0,orphanReasons:C,error:M.error,nextStepHint:F.snapshotWarnings[0]??C[0]??(y==null?void 0:y.nextStep)??void 0,parentNodeId:null,submodulePath:null,submoduleCommit:(j==null?void 0:j.headCommit)??null,outOfSync:Fn(j),snapshotCompleteness:F.snapshotCompleteness,snapshotWarnings:F.snapshotWarnings,branchConvergence:y,source:M};if(o.push(P),W){const E=d.get(W)??[];E.push(P.id),d.set(W,E)}for(const E of(j==null?void 0:j.submodules)??[]){const G=`${P.id}::submodule::${E.path}`,J=E.path.split("/").filter(Boolean).pop()||E.path;o.push({id:G,type:"submoduleNode",label:J,workspace:E.repoPath,branch:null,upstream:null,upstreamStatus:null,machineLabel:P.machineLabel,health:t0(E),ahead:0,behind:0,dirty:E.dirty,dirtyFiles:E.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],error:E.error,nextStepHint:E.error||(E.outOfSync?`${E.path} is out of sync with the parent checkout`:E.dirty?`${E.path} has local changes`:`${E.path} is in sync with the parent checkout`),parentNodeId:P.id,submodulePath:E.path,submoduleCommit:E.commit,outOfSync:E.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:P.id,parentWorkspace:M.workspace,submodule:E}}),l.push({id:`${P.id}--${G}`,source:P.id,target:G,type:"submoduleLink",label:E.outOfSync?"submodule out of sync":"submodule"})}}const m=r?`__branch_${r}`:null;if(m&&r){const j=(d.get(r)??[]).map(y=>o.find(F=>F.id===y)).filter(Boolean),W=j.map(y=>y.branchConvergence).filter(Boolean),H=W.length>0?Zy(W):null,$=W.filter(y=>y.needsConvergence).length,C={id:m,type:"defaultBranchNode",label:r,workspace:e.repoIdentity,branch:r,upstream:null,upstreamStatus:null,machineLabel:"default branch",health:Pa(j.map(y=>y.health)),ahead:0,behind:0,dirty:j.some(y=>y.dirty),dirtyFiles:j.reduce((y,F)=>y+F.dirtyFiles,0),hasConflicts:j.some(y=>y.hasConflicts),activeSessionCount:j.reduce((y,F)=>y+F.activeSessionCount,0),activeSessions:j.flatMap(y=>y.activeSessions),providers:[...new Set(j.flatMap(y=>y.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:$>0?`${$} workspace(s) on ${r} still need follow-up`:j.length>0?`${j.length} workspace(s) currently on ${r}`:"No workspaces currently checked out to the default branch",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:H,source:{nodeId:m,machineLabel:r,workspace:e.repoIdentity,health:Pa(j.map(y=>y.health)),providers:[],activeSessions:[]}};o.push(C);for(const y of o)if(!(y.id===m||y.type==="submoduleNode")){if(y.branch===r){l.push({id:`${m}--${y.id}`,source:m,target:y.id,type:"parentBranch",label:"checked out"});continue}if(y.branch){l.push({id:`${m}--${y.id}`,source:m,target:y.id,type:y.isOrphan?"orphanLink":"parentBranch",label:y.branch});continue}y.isOrphan&&l.push({id:`${m}--${y.id}`,source:m,target:y.id,type:"orphanLink",label:"detached"})}}for(const[M,j]of d){if(j.length<2)continue;const W=j.map(H=>o.find($=>$.id===H)).filter(Boolean);W.sort((H,$)=>H.label.localeCompare($.label));for(let H=1;H<W.length;H+=1)l.push({id:`wt_${W[H-1].id}--${W[H].id}`,source:W[H-1].id,target:W[H].id,type:"worktreeLink",label:H===1?`${M} peers`:void 0})}const u=o.filter(M=>M.type!=="defaultBranchNode"),h=u.filter(M=>M.isOrphan).length,x=u.filter(M=>M.hasConflicts).length,S=u.filter(M=>M.health==="offline").length,b=u.filter(M=>M.type==="submoduleNode"&&M.outOfSync).length,p=u.filter(M=>{var j;return M.type!=="submoduleNode"&&((j=M.branchConvergence)==null?void 0:j.needsConvergence)}).length,g=u.filter(M=>{var j;return((j=M.branchConvergence)==null?void 0:j.status)==="blocked_review"}).length,v=u.filter(M=>{var j;return((j=M.branchConvergence)==null?void 0:j.status)==="pushed_feature_branch_needs_merge"}).length,f=u.filter(M=>{var j;return((j=M.branchConvergence)==null?void 0:j.status)==="cleanup_candidate"}).length,T=u.filter(M=>{var j;return((j=M.branchConvergence)==null?void 0:j.status)==="not_mergeable"}).length,I=u.filter(M=>M.snapshotWarnings.length>0).length,k=u.filter(M=>M.snapshotCompleteness==="pending_git").length,A=u.filter(M=>M.snapshotCompleteness==="missing_git").length,_=u.filter(M=>M.snapshotCompleteness==="missing_submodule_report").length,N=u.filter(M=>M.snapshotCompleteness==="stale").length,w=[k>0?`${k} node(s) are still waiting for a live peer git snapshot`:null,A>0?`${A} node(s) have no visible peer git snapshot`:null,_>0?`${_} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,N>0?`${N} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return p>0&&c.push(`${p} workspace(s) still need follow-up before the mesh is converged`),h>0&&c.push(`${h} workspace(s) need attention before safe coordination`),g>0&&c.push(`${g} workspace(s) are blocked on branch convergence or upstream sync`),v>0&&c.push(`${v} clean feature branch workspace(s) still need merge follow-up`),f>0&&c.push(`${f} worktree workspace(s) are ready for refine / cleanup`),T>0&&c.push(`${T} workspace(s) have local changes or conflicts blocking convergence`),x>0&&c.push(`${x} workspace(s) report merge conflicts`),S>0&&c.push(`${S} node(s) are currently offline`),b>0&&c.push(`${b} submodule(s) are out of sync with their parent checkout`),c.push(...w),r||c.push("Could not infer a default branch from live mesh status"),{meshId:e.meshId,meshName:e.meshName,repoIdentity:e.repoIdentity,refreshedAt:e.refreshedAt,nodes:o,edges:l,stats:{totalNodes:u.length,onlineNodes:u.filter(M=>M.health==="online").length,dirtyNodes:u.filter(M=>M.dirty).length,orphanNodes:h,errorNodes:u.filter(M=>!!M.error||M.outOfSync).length,offlineNodes:S,followUpNodes:p,blockedReviewNodes:g,mergeReadyNodes:v,cleanupCandidateNodes:f,notMergeableNodes:T,incompleteSnapshotNodes:I,missingGitSnapshotNodes:A,missingSubmoduleSnapshotNodes:_,staleGitSnapshotNodes:N,totalActiveSessions:u.reduce((M,j)=>M+j.activeSessionCount,0)},warnings:c,snapshotWarnings:w}}function ku(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 Su(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=ku(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 Nu(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function r0(e){var t;return!Nu(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 ln(e){return[...new Set(e.filter(t=>!!t))]}function Cu(e){return e.nodes.filter(t=>t.type!=="submoduleNode")}function n0(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=Cu(e);return t||n.length>0?ln([t==null?void 0:t.id,...n.map(l=>l.id)]):a.length>0?ln(a.map(l=>l.id)):o.length>0?ln(o.map(l=>l.id)):ln(e.nodes.map(l=>l.id))}function a0(e){const t=Cu(e),r=new Set(t.map(o=>o.branch).filter(o=>!!o)).size,n=e.nodes.filter(o=>o.type==="submoduleNode").length,a=t.filter(o=>o.isOrphan).length;return t.length>=6||r>=3||n>=3||a>0}function Iu(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 o0(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${Iu(e)}::${n}x${a}`}const i0={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"},l0={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"},c0={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"},d0={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 tr(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",graphMiniMapClass:"!bottom-4 !right-4 !bg-white/95 !border !border-slate-200 !rounded-xl !shadow-md",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=>l0[t],actionButton:t=>d0[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",graphMiniMapClass:"!bottom-4 !right-4 !bg-slate-950/85 !border !border-white/10 !rounded-xl",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=>i0[t],actionButton:t=>c0[t]}}const Rl=390,Pl=192,Dl=120,u0=36,El=148,m0=24,Tu=i.createContext(tr("dark"));function p0(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=Su(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 qt(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 h0(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 Mu(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 f0(e){return e.replace(/_/g," ")}function x0(e){return!e.upstream||e.upstreamStatus==="fresh"}function b0(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),!x0(e))t.push("upstream unverified");else{const n=ku(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 g0({data:e,selected:t}){const r=i.useContext(Tu),n=e.graphNode,a=n.type==="defaultBranchNode",o=n.type==="submoduleNode",l=r0(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=Su(n),u=b0(n),h=Nu(n);return s.jsxs("div",{className:`${o?"w-[204px]":"w-[220px]"} rounded-2xl border px-3.5 py-3 backdrop-blur-sm transition-all ${p0(n,t,r.isDark)}`,children:[s.jsx(ki,{type:"target",position:Si.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:Mu(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] ${h0(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 ${qt("health",r.isDark)}`,children:f0(n.health)}),o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("submodule",r.isDark)}`,children:"submodule"}),n.branch&&!o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("meta",r.isDark)}`,children:n.branch}),d&&o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("meta",r.isDark)}`,children:d}),n.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("dirty",r.isDark)}`,children:o?"local changes":`${n.dirtyFiles} dirty`}),n.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("conflict",r.isDark)}`,children:"out of sync"}),n.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("conflict",r.isDark)}`,children:"conflicts"}),!o&&n.upstream&&n.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("orphan",r.isDark)}`,children:"upstream unverified"}),n.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("orphan",r.isDark)}`,children:"needs follow-up"})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,children:u}),l&&h&&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:h}),s.jsx(ki,{type:"source",position:Si.Bottom,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const y0={meshNode:g0};function Da(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 v0(e,t=tr("dark")){const r=[...e.nodes].sort(Da),n=r.find(p=>p.type==="defaultBranchNode")??null,a=new Map;for(const p of r){if(p.type!=="submoduleNode"||!p.parentNodeId)continue;const g=a.get(p.parentNodeId)??[];g.push(p),a.set(p.parentNodeId,g)}const o=r.filter(p=>p.id!==(n==null?void 0:n.id)&&p.type!=="submoduleNode"),l=new Map,c=[];for(const p of o){if(p.isOrphan||!p.branch){c.push(p);continue}const g=p.branch,v=l.get(g)??[];v.push(p),l.set(g,v)}const d=[...l.entries()].sort(([p],[g])=>n!=null&&n.branch&&p===n.branch&&g!==n.branch?-1:n!=null&&n.branch&&g===n.branch&&p!==n.branch?1:p.localeCompare(g));c.length>0&&d.push(["__orphans__",[...c].sort(Da)]),d.length===0&&d.push(["__nodes__",[]]);const m=[],u=d.length,h=Math.max(1,u-1)*Rl,x=n?0:80,S=n?Pl:0;n&&m.push({id:n.id,type:"meshNode",position:{x:h/2,y:x},data:{graphNode:n},selected:!1,draggable:!1,selectable:!0}),d.forEach(([p,g],v)=>{const f=v*Rl,T=g.length>0?g:o.length>0?o:[];let I=S;T.forEach(k=>{m.push({id:k.id,type:"meshNode",position:{x:f,y:I},data:{graphNode:k},selected:!1,draggable:!1,selectable:!0});const A=[...a.get(k.id)??[]].sort(Da);if(A.length>0){A.forEach((_,N)=>{m.push({id:_.id,type:"meshNode",position:{x:f+u0,y:I+El+N*Dl},data:{graphNode:_},selected:!1,draggable:!1,selectable:!0})}),I+=El+A.length*Dl+m0;return}I+=Pl}),p==="__nodes__"&&o.length===0&&n&&m.push({id:`${n.id}__placeholder`,type:"meshNode",position:{x:f,y:S},data:{graphNode:{id:`${n.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:e.repoIdentity,branch:n.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:`${n.id}__placeholder`,machineLabel:"",workspace:e.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}},selected:!1,draggable:!1,selectable:!1})});const b=e.edges.map(p=>({id:p.id,source:p.source,target:p.target,label:p.label,type:p.type==="worktreeLink"||p.type==="submoduleLink"?"smoothstep":"bezier",animated:p.type==="orphanLink",markerEnd:{type:ym.ArrowClosed,width:p.type==="submoduleLink"?16:18,height:p.type==="submoduleLink"?16:18,color:$l(p)},style:{stroke:$l(p),strokeWidth:p.type==="orphanLink"?2.25:p.type==="submoduleLink"?1.7:p.type==="worktreeLink"?1.8:2,strokeDasharray:p.type==="orphanLink"?"5 4":p.type==="submoduleLink"?"4 3":void 0},labelStyle:{fill:t.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:t.edgeLabelBackgroundColor,fillOpacity:1,stroke:t.edgeLabelBorderColor},labelBgPadding:[5,3],labelBgBorderRadius:6}));return{nodes:m,edges:b}}function $l(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 w0({data:e,viewportKey:t}){const r=vm(),n=wm(),a=i.useRef(null),o=i.useMemo(()=>Iu(e),[e]),l=i.useMemo(()=>n0(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?.2:.16,maxZoom:m?1.04:.96,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(d)}},[e.nodes.length,l,o,r,n,t]),null}function j0({data:e,selectedNodeId:t=null,onNodeClick:r}){const{theme:n}=er(),a=i.useMemo(()=>tr(n),[n]),o=i.useMemo(()=>v0(e,a),[e,a]),l=i.useMemo(()=>a0(e),[e]),c=i.useRef(null),[d,m]=i.useState({width:0,height:0}),u=i.useMemo(()=>o0(e,d.width,d.height),[e,d.height,d.width]),h=i.useMemo(()=>o.nodes.map(x=>({...x,selected:x.id===t})),[o.nodes,t]);return i.useEffect(()=>{const x=c.current;if(!x)return;const S=()=>{const p=Math.max(0,Math.round(x.clientWidth)),g=Math.max(0,Math.round(x.clientHeight));m(v=>v.width===p&&v.height===g?v:{width:p,height:g})};S();const b=typeof ResizeObserver=="function"?new ResizeObserver(()=>S()):null;return b==null||b.observe(x),window.addEventListener("resize",S),()=>{b==null||b.disconnect(),window.removeEventListener("resize",S)}},[]),s.jsx(Tu.Provider,{value:a,children:s.jsxs("div",{ref:c,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-[420px] w-full min-w-0 min-h-[420px] sm:h-[520px] xl:h-[640px]",children:s.jsxs(hm,{nodes:h,edges:o.edges,nodeTypes:y0,minZoom:.25,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!1,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(x,S)=>r==null?void 0:r(S.data.graphNode),className:"h-full w-full",colorMode:a.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(w0,{data:e,viewportKey:u}),l&&s.jsx(fm,{className:a.graphMiniMapClass,nodeColor:x=>Mu(x.data.graphNode.health)}),s.jsx(xm,{className:a.graphControlsClass,showInteractive:!1}),s.jsx(bm,{variant:gm.Dots,gap:18,size:1.2,color:a.graphBackgroundDotColor})]})})]})})}const Bl=new Set(["pending","assigned"]),k0={pending:0,assigned:0},S0={recentFailures:0},Or=i.createContext(tr("dark"));function Ke({label:e,tone:t="default"}){const r=i.useContext(Or);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 hr({title:e,subtitle:t,children:r,className:n=""}){const a=i.useContext(Or);return s.jsxs("section",{className:`${a.cardClass} ${n}`,children:[s.jsxs("div",{className:a.cardHeaderClass,children:[s.jsx("div",{className:a.cardTitleClass,children:e}),t&&s.jsx("div",{className:a.cardSubtitleClass,children:t})]}),s.jsx("div",{className:"px-4 py-3",children:r})]})}function qe({label:e,value:t}){const r=i.useContext(Or);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 Ht({label:e,onClick:t,tone:r="default"}){const n=i.useContext(Or);return s.jsx("button",{type:"button",onClick:t,className:`rounded-full border px-2.5 py-1 text-[11px] transition ${n.actionButton(r)}`,children:e})}function ps(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function Rs(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleString()}function Ea(e){switch(e){case"completed":return"good";case"failed":case"cancelled":return"danger";case"assigned":return"info";case"pending":return"warn";default:return"default"}}function Ol(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 cn(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 Fl(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 Au(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 $a(e){return e===!0?"yes":e===!1?"no":"unknown"}function Wl(e,t){if(!t)return null;const r=new URLSearchParams;return e&&r.set("daemonId",e),r.set("targetSessionId",t),`/dashboard?${r.toString()}`}function Kl(e){if(e.gitProbePending)return"Git probe pending";const t=e.git;if(!t)return"No git probe";const r=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),n=[];t.branch&&n.push(t.branch),t.upstream&&t.upstreamStatus!=="fresh"&&n.push("upstream unverified"),t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&n.push(`↑${t.ahead??0}/↓${t.behind??0}`),r>0&&n.push(`${r} dirty`);const a=(t.submodules??[]).filter(l=>l.dirty),o=(t.submodules??[]).filter(l=>l.outOfSync||l.error);return a.length>0&&n.push(`${a.length} submodule dirty`),o.length>0&&n.push(`${o.length} submodule drift`),t.hasConflicts&&n.push("conflicts"),n.join(" · ")||"Clean"}function N0(e){switch(e){case"merged_to_main":return"merged to default branch";case"pushed_feature_branch_needs_merge":return"feature branch still needs merge";case"cleanup_candidate":return"worktree still needs refine / cleanup";case"blocked_review":return"review blocked before convergence";case"not_mergeable":return"not mergeable yet";default:return null}}function C0(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 Ba(e){const t=e.assignedNodeId||e.targetNodeId||"unbound",r=e.assignedSessionId||e.targetSessionId||"no session";return`${t} · ${r}`}function dn(e){return e.assignedNodeId||e.targetNodeId||null}function Oa(e){var t;return e.assignedSessionId||e.targetSessionId||((t=e.autoLaunch)==null?void 0:t.sessionId)||null}function Cr(e){return e?e.slice(0,7):null}function I0(e,t){var o,l,c;const r=Cr((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?[Cr(a.commit),a.message].filter(Boolean).join(" · "):null}function T0(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 M0(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 A0(e){return(e.providers??[]).length>0?e.providers.join(", "):((e.providerPriority??[]).length>0,"not reported yet")}function Hl(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":Au(e.connection)}function Ul(e,t){return ps(e)??e??(t?"pending live refresh":"not reported")}function _u({graph:e,status:t,emptyMessage:r="No live mesh graph is available for this coordinator yet.",daemonId:n=null,sendDaemonCommand:a=null}){var Se,ve,X,xe,fe,we,be,Ce,ee,me,ie,pe,le,B,z,de,re;const{theme:o}=er(),l=i.useMemo(()=>tr(o),[o]),c=As(),[d,m]=i.useState(null),[u,h]=i.useState(null),[x,S]=i.useState("active"),[b,p]=i.useState({}),g=i.useMemo(()=>new Map(t.nodes.map(R=>[R.nodeId,R])),[t.nodes]),v=i.useMemo(()=>new Map(e.nodes.map(R=>[R.id,R])),[e.nodes]),f=((Se=t.queue)==null?void 0:Se.tasks)??[],T=((ve=t.queue)==null?void 0:ve.summary)??null,I=(T==null?void 0:T.activeCounts)??k0,k=((X=t.ledger)==null?void 0:X.summary)??S0,A=i.useMemo(()=>C0(t),[t]),_=i.useMemo(()=>{const R=new Map;for(const q of A){const ce=q.session.state||q.session.lifecycle||"unknown";R.set(ce,(R.get(ce)??0)+1)}return[...R.entries()].sort((q,ce)=>ce[1]-q[1])},[A]),N=i.useMemo(()=>x==="all"?f:x==="active"?f.filter(R=>Bl.has(R.status)):f.filter(R=>!Bl.has(R.status)),[x,f]);i.useEffect(()=>{d&&(v.has(d)||(m(null),h(R=>!R||"nodeId"in R&&R.nodeId===d?null:R)))},[v,d]);const w=d?v.get(d)??null:null,D=d?g.get(d)??null:null,M=(u==null?void 0:u.kind)==="queue"?f.find(R=>R.id===u.taskId)??null:null,j=(u==null?void 0:u.kind)==="session"?A.find(R=>R.nodeId===u.nodeId&&R.session.sessionId===u.sessionId)??null:null,W=i.useMemo(()=>A.filter(R=>R.nodeId===d),[d,A]),H=i.useMemo(()=>f.filter(R=>dn(R)===d),[f,d]),$=M0({coordinatorDaemonId:n,selectedNodeStatus:D,selectedSessionEntry:j}),C=($==null?void 0:$.workspace)??null,y=C?b[C]??null:null,F=D!=null&&D.gitProbePending&&!((xe=y==null?void 0:y.entries)!=null&&xe.length)?"Pending live git probe":I0(D,(y==null?void 0:y.entries)??[]),P=i.useCallback(R=>{R&&c(Zt(R),{state:{openRemoteForTabKey:R}})},[c]),E=i.useCallback((R,q)=>{m(R),h({kind:"session",nodeId:R,sessionId:q})},[]),G=i.useCallback(R=>{m(R),h({kind:"node",nodeId:R})},[]);i.useEffect(()=>{if(!$||!a)return;const{daemonId:R,workspace:q}=$,ce=b[q];if(ce!=null&&ce.loading||ce&&(ce.entries.length>0||ce.error))return;let Ne=!1;return p(je=>{var O;return{...je,[q]:{loading:!0,error:null,entries:((O=je[q])==null?void 0:O.entries)??[]}}}),a(R,"git_log",{workspace:q,limit:5}).then(je=>{Ne||p(O=>({...O,[q]:{loading:!1,error:null,entries:T0(je)}}))}).catch(je=>{Ne||p(O=>({...O,[q]:{loading:!1,error:je instanceof Error?je.message:"git_log failed",entries:[]}}))}),()=>{Ne=!0}},[b,$,a]);const J=[...e.warnings??[],...t.nodes.filter(R=>R.machineStatus&&R.machineStatus!=="online").map(R=>`${R.machineLabel}: ${R.machineStatus}`)],ye=e.stats.incompleteSnapshotNodes>0,he=e.stats.followUpNodes>0?`${e.stats.followUpNodes} need follow-up`:ye?"mesh visibility incomplete":"mesh converged",ne=e.stats.followUpNodes>0?"danger":ye?"warn":"good",ue=!!(M||j||w);return s.jsx(Or.Provider,{value:l,children:s.jsxs("div",{className:"flex min-h-0 flex-col gap-4 xl:flex-row",children:[s.jsx("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-4",children:s.jsxs("div",{className:`${l.cardClass} min-h-0 flex-1 rounded-[28px] p-3 sm:p-4`,style:{minHeight:420},children:[s.jsxs("div",{className:`mb-3 flex flex-wrap items-start justify-between gap-3 rounded-2xl px-3.5 py-3 ${l.isDark?"border border-white/10 bg-slate-950/45":"border border-slate-200 bg-white/95 shadow-sm"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-wrap gap-2 text-xs ${l.textSecondary}`,children:[s.jsx(Ke,{label:he,tone:ne}),e.stats.blockedReviewNodes>0&&s.jsx(Ke,{label:`${e.stats.blockedReviewNodes} blocked review`,tone:"danger"}),e.stats.notMergeableNodes>0&&s.jsx(Ke,{label:`${e.stats.notMergeableNodes} not mergeable`,tone:"danger"}),e.stats.mergeReadyNodes>0&&s.jsx(Ke,{label:`${e.stats.mergeReadyNodes} need merge`,tone:"warn"}),e.stats.cleanupCandidateNodes>0&&s.jsx(Ke,{label:`${e.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),e.stats.offlineNodes>0&&s.jsx(Ke,{label:`${e.stats.offlineNodes} offline`,tone:"danger"}),e.stats.incompleteSnapshotNodes>0&&s.jsx(Ke,{label:`${e.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),e.stats.missingGitSnapshotNodes>0&&s.jsx(Ke,{label:`${e.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),e.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Ke,{label:`${e.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),e.stats.staleGitSnapshotNodes>0&&s.jsx(Ke,{label:`${e.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((T==null?void 0:T.active)??0)>0&&s.jsx(Ke,{label:`${(T==null?void 0:T.active)??0} active queue`,tone:"info"}),s.jsx(Ke,{label:`${e.stats.totalNodes} nodes`,tone:"default"}),e.stats.totalActiveSessions>0&&s.jsx(Ke,{label:`${e.stats.totalActiveSessions} active sessions`,tone:"info"})]}),s.jsxs("details",{className:`max-w-full rounded-xl px-3 py-2 text-xs ${l.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 ${l.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(Ke,{label:`${e.stats.dirtyNodes} dirty`,tone:e.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Ke,{label:`${e.stats.orphanNodes} orphan`,tone:e.stats.orphanNodes>0?"warn":"good"}),s.jsx(Ke,{label:`${k.recentFailures} recent failures`,tone:k.recentFailures>0?"danger":"good"}),_.length===0?s.jsx(Ke,{label:"no session metadata"}):_.slice(0,2).map(([R,q])=>s.jsx(Ke,{label:`${q} ${R}`,tone:cn(R)},R))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ke,{label:"Anchor = default branch",tone:"info"}),s.jsx(Ke,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Ke,{label:"Submodule link = child checkout",tone:"warn"})]}),J.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:J.map(R=>s.jsx("span",{className:l.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:R},R))}),s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"Click a node only when you want drill-down details. The graph itself now carries the convergence state."})]})]})]}),e.nodes.length>0?s.jsx(j0,{data:e,selectedNodeId:d,onNodeClick:R=>{if((u==null?void 0:u.kind)==="node"&&d===R.id){m(null),h(null);return}m(R.id),h({kind:"node",nodeId:R.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:r})]})}),ue&&s.jsxs("div",{className:"flex w-full shrink-0 flex-col gap-4 xl:w-[420px]",children:[s.jsx(hr,{title:"Selected detail",subtitle:"Node, session, or queue item drill-down.",children:s.jsx("div",{className:"flex flex-col gap-3",children:(u==null?void 0:u.kind)==="queue"&&M?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(Ke,{label:M.status,tone:Ea(M.status)}),s.jsx(Ke,{label:M.id.slice(0,8),tone:"default"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[dn(M)&&s.jsx(Ht,{label:"View node",onClick:()=>G(dn(M)||"")}),(()=>{const R=Oa(M);if(!R)return null;const q=A.find(ce=>ce.session.sessionId===R)??null;return s.jsxs(s.Fragment,{children:[q&&s.jsx(Ht,{label:"View session",onClick:()=>E(q.nodeId,q.session.sessionId)}),s.jsx(Ht,{label:"Open chat",tone:"info",onClick:()=>P(R)})]})})()]}),s.jsx(qe,{label:"Message",value:M.message}),s.jsx(qe,{label:"Routing",value:Ba(M)}),s.jsx(qe,{label:"Created",value:ps(M.createdAt)??"unknown"}),s.jsx(qe,{label:"Updated",value:ps(M.updatedAt)??"unknown"}),s.jsx(qe,{label:"Requeues",value:M.requeueCount??0}),s.jsx(qe,{label:"Auto-launch",value:M.autoLaunch?`${M.autoLaunch.status}${M.autoLaunch.providerType?` · ${M.autoLaunch.providerType}`:""}`:"none"}),(()=>{var Ne,je,O;const R=M.assignedSessionId||M.targetSessionId||((Ne=M.autoLaunch)==null?void 0:Ne.sessionId)||null,q=M.assignedNodeId||M.targetNodeId||((je=M.autoLaunch)==null?void 0:je.nodeId)||null,ce=Wl(q?(O=g.get(q))==null?void 0:O.daemonId:null,R);return ce?s.jsx("a",{href:ce,className:l.isDark?"inline-flex w-fit items-center rounded-full border border-sky-400/30 bg-sky-500/10 px-3 py-1 text-xs font-medium text-sky-100 transition hover:bg-sky-500/20":"inline-flex w-fit items-center rounded-full border border-sky-300 bg-sky-50 px-3 py-1 text-xs font-medium text-sky-700 transition hover:bg-sky-100",children:"Open linked dashboard chat"}):null})(),M.cancelReason&&s.jsx(qe,{label:"Cancel reason",value:M.cancelReason}),M.requeueReason&&s.jsx(qe,{label:"Requeue reason",value:M.requeueReason})]}):(u==null?void 0:u.kind)==="session"&&j?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(Ke,{label:j.session.state||j.session.lifecycle||"unknown",tone:cn(j.session.state||j.session.lifecycle)}),j.session.providerType&&s.jsx(Ke,{label:j.session.providerType,tone:"info"}),j.session.isCached&&s.jsx(Ke,{label:"cached",tone:"default"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ht,{label:"View node",onClick:()=>G(j.nodeId)}),s.jsx(Ht,{label:"Open chat",tone:"info",onClick:()=>P(j.session.sessionId)})]}),s.jsx(qe,{label:"Session id",value:j.session.sessionId}),s.jsx(qe,{label:"Node",value:j.machineLabel}),s.jsx(qe,{label:"Workspace",value:j.workspace}),s.jsx(qe,{label:"Branch",value:j.branch??"unknown"}),s.jsx(qe,{label:"Node health",value:j.nodeHealth}),s.jsx(qe,{label:"Lifecycle",value:j.session.lifecycle??"unknown"}),j.session.surfaceKind&&s.jsx(qe,{label:"Surface",value:j.session.surfaceKind}),j.session.recoveryState&&s.jsx(qe,{label:"Recovery",value:j.session.recoveryState}),j.session.lastActivityAt&&s.jsx(qe,{label:"Last activity",value:ps(j.session.lastActivityAt)??j.session.lastActivityAt}),(()=>{var q;const R=Wl((q=g.get(j.nodeId))==null?void 0:q.daemonId,j.session.sessionId);return R?s.jsx("a",{href:R,className:l.isDark?"inline-flex w-fit items-center rounded-full border border-sky-400/30 bg-sky-500/10 px-3 py-1 text-xs font-medium text-sky-100 transition hover:bg-sky-500/20":"inline-flex w-fit items-center rounded-full border border-sky-300 bg-sky-50 px-3 py-1 text-xs font-medium text-sky-700 transition hover:bg-sky-100",children:"Open dashboard chat"}):null})(),s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-slate-950/40 p-3":"rounded-xl border border-slate-200 bg-slate-50 p-3",children:[s.jsx("div",{className:`mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Git context"}),s.jsxs("div",{className:`flex flex-col gap-2 text-xs ${l.textSecondary}`,children:[s.jsx("div",{children:F||"HEAD subject not present in cached mesh_status."}),(y==null?void 0:y.loading)&&s.jsx("div",{className:"text-slate-500",children:"Loading recent commits…"}),(y==null?void 0:y.error)&&s.jsxs("div",{className:"text-amber-200",children:["Recent history unavailable: ",y.error]}),((y==null?void 0:y.entries)??[]).slice(0,5).map(R=>s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-2.5 py-2":"rounded-lg border border-slate-200 bg-white px-2.5 py-2",children:[s.jsxs("div",{className:`font-medium ${l.textPrimary}`,children:[Cr(R.commit)," · ",R.message]}),s.jsxs("div",{className:"mt-1 text-[11px] text-slate-500",children:[R.authorName||"unknown author",Rs(R.committedAt)?` · ${Rs(R.committedAt)}`:""]})]},R.commit))]})]})]}):w?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-slate-950/40 p-3":"rounded-xl border border-slate-200 bg-slate-50 p-3",children:[s.jsxs("div",{className:"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 ${l.textPrimary}`,children:w.label}),s.jsx("div",{className:`mt-1 break-all text-xs ${l.textMuted}`,children:(D==null?void 0:D.workspace)??w.workspace})]}),s.jsx("button",{type:"button",onClick:()=>{m(null),h(null)},className:l.isDark?"rounded-full border border-white/10 bg-white/[0.03] px-2 py-1 text-xs text-slate-300 transition hover:bg-white/[0.06] hover:text-white":"rounded-full border border-slate-200 bg-white px-2 py-1 text-xs text-slate-600 transition hover:bg-slate-50 hover:text-slate-900",children:"Close"})]}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[w.branch&&s.jsx(Ke,{label:w.branch,tone:"default"}),((fe=w.branchConvergence)==null?void 0:fe.status)&&s.jsx(Ke,{label:w.branchConvergence.status,tone:w.branchConvergence.needsConvergence?"warn":"good"}),w.snapshotWarnings.length>0&&s.jsx(Ke,{label:`snapshot ${w.snapshotCompleteness}`,tone:"warn"})]}),s.jsxs("div",{className:"mt-3 flex flex-col gap-0.5",children:[s.jsx(qe,{label:"Graph branch",value:w.branch??"unknown"}),s.jsx(qe,{label:"Graph upstream",value:w.upstream??"none"}),s.jsx(qe,{label:"Convergence",value:N0((we=w.branchConvergence)==null?void 0:we.status)??"not classified"})]}),w.snapshotWarnings.length>0&&s.jsxs("div",{className:l.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:"Peer snapshot warning"}),s.jsx("div",{className:"mt-1",children:w.snapshotWarnings[0]})]}),((be=w.branchConvergence)==null?void 0:be.nextStep)&&s.jsxs("div",{className:l.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:"Convergence follow-up"}),s.jsx("div",{className:"mt-1",children:w.branchConvergence.nextStep})]})]}),D&&s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-slate-950/40 p-3":"rounded-xl border border-slate-200 bg-slate-50 p-3",children:[s.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[s.jsx(Ke,{label:D.health,tone:Ol(D.health)}),D.machineStatus&&s.jsx(Ke,{label:D.machineStatus,tone:D.machineStatus==="online"?"good":"warn"}),s.jsx(Ke,{label:`launchReady ${$a(D.launchReady)}`,tone:D.launchReady?"good":"warn"}),s.jsx(Ke,{label:Hl(D),tone:Fl(D.connection)}),D.worktreeBranch&&s.jsx(Ke,{label:D.worktreeBranch,tone:"info"})]}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsx(qe,{label:"Repo root",value:D.repoRoot??D.workspace}),s.jsx(qe,{label:"Provider(s)",value:A0(D)}),s.jsx(qe,{label:"Provider priority",value:(D.providerPriority??[]).join(", ")||"not configured"}),s.jsx(qe,{label:"Drift",value:Kl(D)}),s.jsx(qe,{label:"HEAD",value:F??(D.gitProbePending?"Pending live git probe":"Not available")}),s.jsx(qe,{label:"Daemon",value:D.daemonId??"unknown"}),s.jsx(qe,{label:"Machine",value:D.machineId??D.machineLabel}),s.jsx(qe,{label:"Launch ready",value:$a(D.launchReady)}),s.jsx(qe,{label:"Mesh connection",value:Hl(D)}),s.jsx(qe,{label:"Transport",value:((Ce=D.connection)==null?void 0:Ce.transport)??"unknown"}),s.jsx(qe,{label:"Connection source",value:((ee=D.connection)==null?void 0:ee.source)??"unknown"}),s.jsx(qe,{label:"Last seen",value:Ul(D.lastSeenAt,!!D.gitProbePending)}),s.jsx(qe,{label:"Updated",value:Ul(D.updatedAt,!!D.gitProbePending)}),((me=D.connection)==null?void 0:me.lastConnectedAt)&&s.jsx(qe,{label:"Last connected",value:ps(D.connection.lastConnectedAt)??D.connection.lastConnectedAt}),((ie=D.connection)==null?void 0:ie.lastCommandAt)&&s.jsx(qe,{label:"Last mesh command",value:ps(D.connection.lastCommandAt)??D.connection.lastCommandAt}),((pe=D.connection)==null?void 0:pe.reason)&&s.jsx(qe,{label:"Connection reason",value:D.connection.reason}),s.jsx(qe,{label:"Sessions",value:D.activeSessions.length}),D.error&&s.jsx(qe,{label:"Error",value:D.error})]}),W.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Active sessions"}),s.jsx("div",{className:"flex flex-col gap-2",children:W.map(R=>{const q=R.session.state||R.session.lifecycle||"unknown";return s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",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:`truncate font-medium ${l.textPrimary}`,children:R.session.title||R.session.sessionId}),s.jsxs("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:[R.session.providerType||"unknown provider"," · ",q]})]}),s.jsx(Ke,{label:q,tone:cn(q)})]}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[s.jsx(Ht,{label:"View session",onClick:()=>E(R.nodeId,R.session.sessionId)}),s.jsx(Ht,{label:"Open chat",tone:"info",onClick:()=>P(R.session.sessionId)})]})]},`${R.nodeId}:${R.session.sessionId}`)})})]}),H.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Related queue items"}),s.jsx("div",{className:"flex flex-col gap-2",children:H.map(R=>{const q=Oa(R),ce=q?A.find(Ne=>Ne.session.sessionId===q)??null:null;return s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",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:`truncate font-medium ${l.textPrimary}`,children:R.message}),s.jsx("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:Ba(R)})]}),s.jsx(Ke,{label:R.status,tone:Ea(R.status)})]}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[s.jsx(Ht,{label:"View queue detail",onClick:()=>h({kind:"queue",taskId:R.id})}),ce&&s.jsx(Ht,{label:"View session",onClick:()=>E(ce.nodeId,ce.session.sessionId)}),q&&s.jsx(Ht,{label:"Open chat",tone:"info",onClick:()=>P(q)})]})]},R.id)})})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Recent commits"}),s.jsxs("div",{className:"flex flex-col gap-2",children:[(y==null?void 0:y.loading)&&s.jsx("div",{className:(l.isDark,"text-xs text-slate-500"),children:"Loading recent commits…"}),(y==null?void 0:y.error)&&s.jsxs("div",{className:"text-xs text-amber-200",children:["Recent history unavailable: ",y.error]}),!(y!=null&&y.loading)&&!(y!=null&&y.error)&&((y==null?void 0:y.entries)??[]).length===0&&s.jsx("div",{className:(l.isDark,"text-xs text-slate-500"),children:"Recent commit history not available from the current mesh snapshot yet."}),((y==null?void 0:y.entries)??[]).slice(0,5).map(R=>s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",children:[s.jsxs("div",{className:`font-medium ${l.textPrimary}`,children:[Cr(R.commit)," · ",R.message]}),s.jsxs("div",{className:"mt-1 text-[11px] text-slate-500",children:[R.authorName||"unknown author",Rs(R.committedAt)?` · ${Rs(R.committedAt)}`:""]})]},R.commit))]})]}),(((B=(le=D.git)==null?void 0:le.submodules)==null?void 0:B.length)??0)>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Submodules"}),s.jsx("div",{className:"flex flex-col gap-2",children:(((z=D.git)==null?void 0:z.submodules)??[]).map(R=>s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"font-medium",children:R.path}),R.dirty&&s.jsx(Ke,{label:"dirty",tone:"warn"}),(R.outOfSync||R.error)&&s.jsx(Ke,{label:"drift",tone:"danger"})]}),s.jsx("div",{className:"mt-1 break-all text-[11px] text-slate-400",children:R.repoPath}),s.jsx("div",{className:"mt-1 text-[11px] text-slate-500",children:"Select the submodule node in the graph for its own HEAD and recent history."}),R.error&&s.jsx("div",{className:"mt-1 text-[11px] text-rose-200",children:R.error})]},`${D.nodeId}:${R.path}`))})]})]}),!D&&s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-slate-950/40 p-3":"rounded-xl border border-slate-200 bg-slate-50 p-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Git context"}),s.jsx("div",{className:"text-xs text-slate-300",children:F??"No daemon-owned node status is attached to this graph node."}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Recent commits"}),s.jsxs("div",{className:"flex flex-col gap-2",children:[(y==null?void 0:y.loading)&&s.jsx("div",{className:(l.isDark,"text-xs text-slate-500"),children:"Loading recent commits…"}),(y==null?void 0:y.error)&&s.jsxs("div",{className:"text-xs text-amber-200",children:["Recent history unavailable: ",y.error]}),!(y!=null&&y.loading)&&!(y!=null&&y.error)&&((y==null?void 0:y.entries)??[]).length===0&&s.jsx("div",{className:(l.isDark,"text-xs text-slate-500"),children:"Recent commit history not available for this detached graph node yet."}),((y==null?void 0:y.entries)??[]).slice(0,5).map(R=>s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",children:[s.jsxs("div",{className:`font-medium ${l.textPrimary}`,children:[Cr(R.commit)," · ",R.message]}),s.jsxs("div",{className:"mt-1 text-[11px] text-slate-500",children:[R.authorName||"unknown author",Rs(R.committedAt)?` · ${Rs(R.committedAt)}`:""]})]},R.commit))]})]})]})]}):s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"Select a node, session, or queue item."})})}),s.jsxs(hr,{title:"Queue",subtitle:"Active work plus recent history from mesh_status.",children:[s.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:["active","history","all"].map(R=>s.jsx("button",{type:"button",onClick:()=>S(R),className:`rounded-full border px-3 py-1 text-xs transition ${x===R?l.isDark?"border-sky-400/30 bg-sky-500/10 text-sky-100":"border-sky-300 bg-sky-50 text-sky-700":l.isDark?"border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.06]":"border-slate-200 bg-white text-slate-600 hover:bg-slate-50"}`,children:R},R))}),s.jsxs("div",{className:"mb-3 grid grid-cols-2 gap-2 text-xs sm:grid-cols-4 xl:grid-cols-2",children:[s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-600",children:["Active ",s.jsx("span",{className:`ml-1 ${l.textPrimary}`,children:(T==null?void 0:T.active)??0})]}),s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-600",children:["Pending ",s.jsx("span",{className:`ml-1 ${l.textPrimary}`,children:I.pending})]}),s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-600",children:["Assigned ",s.jsx("span",{className:`ml-1 ${l.textPrimary}`,children:I.assigned})]}),s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-600",children:["History ",s.jsx("span",{className:`ml-1 ${l.textPrimary}`,children:(T==null?void 0:T.historical)??0})]})]}),s.jsx("div",{className:"max-h-[24vh] overflow-y-auto pr-1",children:N.length===0?s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"No queue items for this filter."}):s.jsx("div",{className:"flex flex-col gap-2",children:N.map(R=>{const q=Oa(R),ce=q?A.find(je=>je.session.sessionId===q)??null:null,Ne=dn(R);return s.jsxs("button",{type:"button",onClick:()=>h({kind:"queue",taskId:R.id}),className:`rounded-xl border px-3 py-2 text-left transition ${(u==null?void 0:u.kind)==="queue"&&u.taskId===R.id?l.isDark?"border-sky-400/30 bg-sky-500/10":"border-sky-300 bg-sky-50":l.isDark?"border-white/10 bg-white/[0.03] hover:bg-white/[0.06]":"border-slate-200 bg-white hover:bg-slate-50"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-xs font-medium ${l.textPrimary}`,children:R.message}),s.jsx("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:Ba(R)})]}),s.jsx(Ke,{label:R.status,tone:Ea(R.status)})]}),(Ne||ce||q)&&s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[Ne&&s.jsx("button",{type:"button",onClick:je=>{je.stopPropagation(),G(Ne)},className:l.isDark?"text-[11px] text-slate-300 underline underline-offset-2 transition hover:text-white":"text-[11px] text-slate-600 underline underline-offset-2 transition hover:text-slate-900",children:"View node"}),ce&&s.jsx("button",{type:"button",onClick:je=>{je.stopPropagation(),E(ce.nodeId,ce.session.sessionId)},className:l.isDark?"text-[11px] text-slate-300 underline underline-offset-2 transition hover:text-white":"text-[11px] text-slate-600 underline underline-offset-2 transition hover:text-slate-900",children:"View session"}),q&&s.jsx("button",{type:"button",onClick:je=>{je.stopPropagation(),P(q)},className:l.isDark?"text-[11px] text-sky-200 underline underline-offset-2 transition hover:text-white":"text-[11px] text-sky-700 underline underline-offset-2 transition hover:text-sky-900",children:"Open chat"})]})]},R.id)})})})]}),s.jsx(hr,{title:"Sessions",subtitle:"Node-level active session roster.",children:s.jsx("div",{className:"max-h-[22vh] overflow-y-auto pr-1",children:A.length===0?s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"No active session metadata in this mesh snapshot."}):s.jsx("div",{className:"flex flex-col gap-2",children:A.map(R=>{const q=R.session.state||R.session.lifecycle||"unknown";return s.jsx("button",{type:"button",onClick:()=>{m(R.nodeId),h({kind:"session",nodeId:R.nodeId,sessionId:R.session.sessionId})},className:`rounded-xl border px-3 py-2 text-left transition ${(u==null?void 0:u.kind)==="session"&&u.nodeId===R.nodeId&&u.sessionId===R.session.sessionId?l.isDark?"border-sky-400/30 bg-sky-500/10":"border-sky-300 bg-sky-50":l.isDark?"border-white/10 bg-white/[0.03] hover:bg-white/[0.06]":"border-slate-200 bg-white hover:bg-slate-50"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-xs font-medium ${l.textPrimary}`,children:R.machineLabel}),s.jsxs("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:[R.session.title||R.session.providerType||"unknown provider"," · ",R.branch||"no branch"]})]}),s.jsxs("div",{className:"flex flex-col items-end gap-1",children:[s.jsx(Ke,{label:q,tone:cn(q)}),s.jsx("button",{type:"button",onClick:ce=>{ce.stopPropagation(),P(R.session.sessionId)},className:l.isDark?"text-[11px] text-sky-200 underline underline-offset-2 transition hover:text-white":"text-[11px] text-sky-700 underline underline-offset-2 transition hover:text-sky-900",children:"Open chat"})]})]})},`${R.nodeId}:${R.session.sessionId}`)})})})}),s.jsx(hr,{title:"Nodes",subtitle:"Health, branch, drift, and provider view per node.",children:s.jsx("div",{className:"max-h-[22vh] overflow-y-auto pr-1",children:s.jsx("div",{className:"flex flex-col gap-2",children:t.nodes.map(R=>s.jsx("button",{type:"button",onClick:()=>{m(R.nodeId),h({kind:"node",nodeId:R.nodeId})},className:`rounded-xl border px-3 py-2 text-left transition ${(u==null?void 0:u.kind)==="node"&&u.nodeId===R.nodeId?l.isDark?"border-sky-400/30 bg-sky-500/10":"border-sky-300 bg-sky-50":l.isDark?"border-white/10 bg-white/[0.03] hover:bg-white/[0.06]":"border-slate-200 bg-white hover:bg-slate-50"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-xs font-medium ${l.textPrimary}`,children:R.machineLabel}),s.jsx("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:Kl(R)}),s.jsx("div",{className:(l.isDark,"mt-1 truncate text-[11px] text-slate-500"),children:(R.providers??[]).join(", ")||"no provider metadata"}),s.jsxs("div",{className:"mt-1 flex flex-wrap gap-1",children:[s.jsx(Ke,{label:`launchReady ${$a(R.launchReady)}`,tone:R.launchReady?"good":"warn"}),s.jsx(Ke,{label:Au(R.connection),tone:Fl(R.connection)})]})]}),s.jsxs("div",{className:"flex flex-col items-end gap-1",children:[s.jsx(Ke,{label:R.health,tone:Ol(R.health)}),R.machineStatus&&s.jsx(Ke,{label:R.machineStatus,tone:R.machineStatus==="online"?"good":"warn"}),R.activeSessions.length>0&&s.jsx(Ke,{label:`${R.activeSessions.length} sessions`,tone:"info"})]})]})},R.nodeId))})})}),s.jsx(hr,{title:"Recent mesh events",subtitle:"Read-only ledger tail from mesh_status.",children:s.jsx("div",{className:"max-h-[18vh] overflow-y-auto pr-1",children:(((de=t.ledger)==null?void 0:de.entries)??[]).length===0?s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"No recent ledger entries."}):s.jsx("div",{className:"flex flex-col gap-2",children:(((re=t.ledger)==null?void 0:re.entries)??[]).map(R=>s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("span",{className:`font-medium ${l.textPrimary}`,children:R.kind}),s.jsx("span",{className:(l.isDark,"text-[11px] text-slate-500"),children:ps(R.timestamp)??R.timestamp})]}),s.jsx("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:R.nodeId||R.sessionId||R.providerType||"mesh-wide event"})]},R.id))})})})]})]})})}function kt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Re(...e){for(const t of e){if(typeof t!="string")continue;const r=t.trim();if(r)return r}}function $t(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function Dt(...e){for(const t of e)if(typeof t=="boolean")return t}function Fa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function _0(e){if(!Array.isArray(e))return;const t=e.map(r=>{const n=kt(r),a=Re(n.path),o=Re(n.commit),l=Re(n.repoPath,n.repo_root);return!a||!o||!l?null:{path:a,commit:o,repoPath:l,dirty:Dt(n.dirty)??!1,outOfSync:Dt(n.outOfSync,n.out_of_sync)??!1,lastCheckedAt:$t(n.lastCheckedAt,n.last_checked_at)??Date.now(),...Re(n.error)?{error:Re(n.error)}:{}}}).filter(r=>r!==null);return t.length>0?t:void 0}function ko(e,t,r){const n=Dt(e.isGitRepo);if(!Object.keys(e).length||n===void 0)return;const a=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(u=>typeof u=="string"):[],o=$t(e.conflicts)??a.length,l=Dt(e.hasConflicts)??o>0,c=_0(e.submodules),d=Re(e.upstreamStatus,e.upstream_status),m=Re(e.error);return{workspace:Re(e.workspace,t.workspace)||"",repoRoot:Re(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,t.workspace)||null,isGitRepo:n,branch:Re(e.branch)??null,headCommit:Re(e.headCommit)??null,headMessage:Re(e.headMessage)??null,upstream:Re(e.upstream)??null,upstreamStatus:d??"unchecked",ahead:$t(e.ahead)??0,behind:$t(e.behind)??0,staged:$t(e.staged)??0,modified:$t(e.modified)??0,untracked:$t(e.untracked)??0,deleted:$t(e.deleted)??0,renamed:$t(e.renamed)??0,hasConflicts:l,conflictFiles:a,stashCount:$t(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??$t(e.lastCheckedAt,e.last_checked_at)??Date.now(),...c?{submodules:c}:{},...m?{error:m}:{}}}function L0(e){const t=kt(e.lastGit??e.last_git),r=kt(t.result),n=kt(t.status),a=kt(r.status),o=kt(e.lastProbe??e.last_probe),l=kt(o.git),c=kt(l.result),d=kt(l.status),m=kt(c.status),u=Object.keys(n).length?n:Object.keys(a).length?a:Object.keys(d).length?d:Object.keys(m).length?m:{};return ko(u,e,{lastCheckedAt:Date.now()})}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 P0(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 zl(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=R0(e);return t.outOfSync?"degraded":t.dirty||P0(e)?"dirty":"online"}function D0(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=kt(o),c=Re(l.sessionId,l.session_id,l.id);return c?{sessionId:c,...Re(l.providerType,l.provider)?{providerType:Re(l.providerType,l.provider)}:{},...Re(l.state,l.status)?{state:Re(l.state,l.status)}:{},...Re(l.lifecycle)?{lifecycle:Re(l.lifecycle)}:{},...Re(l.surfaceKind,l.surface_kind)?{surfaceKind:Re(l.surfaceKind,l.surface_kind)}:{},...Re(l.recoveryState,l.recovery_state)?{recoveryState:Re(l.recoveryState,l.recovery_state)}:{},...Re(l.workspace)?{workspace:Re(l.workspace)}:{},...Re(l.title)?{title:Re(l.title)}:{},...Re(l.lastActivityAt,l.last_activity_at)?{lastActivityAt:Re(l.lastActivityAt,l.last_activity_at)}:{},...Dt(l.isCached,l.is_cached)!==void 0?{isCached:Dt(l.isCached,l.is_cached)}:{}}:null}).filter(o=>o!==null);if(a.length>0)return a}const r=kt(e.activeSession??e.active_session),n=Re(r.id,r.sessionId,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id);if(n)return[{sessionId:n,...Re(r.providerType,r.provider)?{providerType:Re(r.providerType,r.provider)}:{},...Re(r.state,r.status)?{state:Re(r.state,r.status)}:{}}]}function Vl(e){const t=kt(e.connection);return Object.keys(t).length>0?t:void 0}function E0(e){const t=kt(e),r=Re(t.nodeId,t.id);if(!r)return null;const n=kt(t.cachedStatus),a=L0(t),o=a?void 0:ko(kt(t.git),t),l=a??o,c=l?void 0:ko(kt(n.git),t),d=l??c,m=Re(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),u=a?zl(d):Re(t.health)||(d?zl(d):void 0)||Re(n.health)||m||Re(t.status)||"unknown",x=(a?void 0:Re(t.error))??(l?void 0:Re(n.error)),S=D0(t),b=Fa(t.activeSessions),p=(S==null?void 0:S.map(v=>v.sessionId))??[],g=Fa(t.providerPriority);return{nodeId:r,machineLabel:Re(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:Re(t.workspace,d==null?void 0:d.workspace)||"",...Re(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:Re(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},...Re(t.daemonId,t.daemon_id)?{daemonId:Re(t.daemonId,t.daemon_id)}:{},...Re(t.machineId,t.machine_id)?{machineId:Re(t.machineId,t.machine_id)}:{},...m?{machineStatus:m}:{},...Dt(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Dt(t.isLocalWorktree,t.is_local_worktree)}:{},...Re(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:Re(t.worktreeBranch,t.worktree_branch)}:{},health:u,...d?{git:d}:{},...Dt(t.gitProbePending,t.git_probe_pending)!==void 0?{gitProbePending:Dt(t.gitProbePending,t.git_probe_pending)}:{},providers:Fa(t.providers),activeSessions:b.length>0?b:p,...S&&S.length>0?{activeSessionDetails:S}:{},...g.length>0?{providerPriority:g}:{},...Dt(t.launchReady)!==void 0?{launchReady:Dt(t.launchReady)}:{},...Re(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:Re(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},...Re(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:Re(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...Vl(t)?{connection:Vl(t)}:{},...x?{error:x}:{}}}function $0(e){const t=Re(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(c=>E0(c)).filter(c=>c!==null):null;if(!t||!n)return null;const a=Re(e.meshName,e.mesh_name,e.name),o=Re(e.repoIdentity,e.repo_identity),l=Re(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!a||!o||!l?null:{...e,meshId:t,meshName:a,repoIdentity:o,refreshedAt:l,nodes:n}}function Lu(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];for(const n of r){const a=$0(kt(n));if(a)return a}return null}function B0({activeConv:e,sendDaemonCommand:t,onClose:r}){var A;const n=typeof((A=e.settings)==null?void 0:A.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null,a=e.daemonId??null,o=Vd(),{theme:l}=er(),c=i.useMemo(()=>tr(l),[l]),[d,m]=i.useState(null),[u,h]=i.useState(null),[x,S]=i.useState(!1),[b,p]=i.useState(null),[g,v]=i.useState(null),f=i.useCallback(async()=>{if(!a||!n){p("This coordinator does not expose a live mesh id."),m(null),h(null);return}S(!0),p(null);try{const _=o!=null&&o.loadMeshStatus?await o.loadMeshStatus(a,n):await t(a,"mesh_status",{meshId:n}),N=Lu(_);if(!N){m(null),h(null),p("mesh_status returned an unexpected payload.");return}const w=ju(N);h(N),m(w),v(N.refreshedAt||new Date().toISOString())}catch(_){m(null),h(null),p(_ instanceof Error?_.message:"Failed to load live mesh status")}finally{S(!1)}},[a,n,o,t]);i.useEffect(()=>{f()},[f]),i.useEffect(()=>{const _=N=>{N.key==="Escape"&&r()};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[r]);const T=(d==null?void 0:d.meshName)||(u==null?void 0:u.meshName)||n||"Repo Mesh",I=g?new Date(g).toLocaleTimeString():null,k=i.useMemo(()=>x?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[x]);return s.jsx("div",{className:c.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:c.dialogShellClass,onClick:_=>_.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(as,{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:T}),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:[I&&s.jsxs("span",{className:c.dialogRefreshedChipClass,children:["Refreshed ",I]}),s.jsx("button",{type:"button",onClick:f,disabled:x,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:x?"Refreshing…":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:c.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:s.jsx(wt,{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&&u?s.jsx(_u,{graph:d,status:u,emptyMessage:k,daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:c.dialogEmptyClass,children:k})})]})})}function O0(e,t){const{sendCommand:r}=jt(),[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=F0(n);return{remoteUrl:n,githubUrl:c,loading:o}}function F0(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 Ru=5e3;function W0(e){return`git:${e}`}function K0({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Ru}){return{type:"subscribe",topic:"workspace.git",key:W0(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function mi(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 H0(e){const t=mi(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 U0(e){const t=mi(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 Wa(e){return e===void 0||typeof e=="boolean"}function z0(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Wa(t.binary)&&Wa(t.truncated)&&Wa(t.staged)}function V0(e){const t=mi(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Ms(t,"Git file diff request failed")}:z0(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 G0({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Ru}){const{sendCommand:o,sendData:l}=jt(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[m,u]=i.useState(null),[h,x]=i.useState(null),[S,b]=i.useState(!1),[p,g]=i.useState(null),v=i.useCallback(async()=>{if(!(!d||!e||!c)){b(!0),g(null);try{const T=H0(await o(e,"git_status",{workspace:c}));if(T.error){u(null),x(null),g(T.error);return}if(u(T.status),!n){x(null);return}const I=U0(await o(e,"git_diff_summary",{workspace:c}));if(I.error){x(null),g(I.error);return}x(I.diffSummary)}catch(T){g(Ms(T,"Git status request failed"))}finally{b(!1)}}},[d,e,n,o,c]),f=i.useMemo(()=>c?K0({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return i.useEffect(()=>{if(!d||!e||!c||!f){u(null),x(null),b(!1),g(null);return}const T=l?Qt.subscribe({sendData:l},e,f,I=>{var k,A;I.workspace===c&&(u(I.status),x(I.diffSummary??null),g(((k=I.status)==null?void 0:k.error)||((A=I.diffSummary)==null?void 0:A.error)||null),b(!1))},{retryIntervalMs:1e3}):null;return v(),()=>{T==null||T()}},[d,e,v,f,l,c]),{status:m,diffSummary:h,loading:S,error:p,refresh:v}}const q0={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},Y0={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 Gl(e){return e.split("/").pop()??e}function X0(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function J0({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=q0[o.status]??"?",d=Y0[o.status]??"text-zinc-400",m=X0(o.path),u=Gl(o.path),h=o.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${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:["← ",Gl(o.oldPath)]}),h]}),!o.binary&&(o.insertions>0||o.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",o.insertions]}),o.insertions>0&&o.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),o.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",o.deletions]})]}),o.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${o.path}-${o.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function Q0(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 Z0({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
- `);return s.jsxs("div",{ref:l,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((d,m)=>Q0(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 ev(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
- `)}function Pu({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=jt(),{status:a,diffSummary:o,loading:l,error:c,refresh:d}=G0({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=i.useState(null),[h,x]=i.useState(null),[S,b]=i.useState(""),[p,g]=i.useState(!1),[v,f]=i.useState(!1),[T,I]=i.useState(null),[k,A]=i.useState(null),{githubUrl:_}=O0(e,t),N=i.useCallback(async H=>{if(!((m==null?void 0:m.path)===H.path&&!m.loading)){u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const $=await n(e,"git_diff_file",{workspace:t,path:H.path,staged:H.staged}),C=V0($);if(C.error||!C.diff){u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C.error??"Failed to load diff"});return}u({path:H.path,diff:C.diff.diff,binary:C.diff.binary??!1,truncated:C.diff.truncated??!1,loading:!1,error:null})}catch($){const C=$ instanceof Error?$.message:"Failed to load diff";u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C})}}},[e,n,m,t]),w=i.useCallback(H=>{b(""),g(!1),I(null),A(null),x(H)},[]),D=i.useCallback(()=>{x(null),I(null),f(!1)},[]),M=i.useCallback(async()=>{var H,$,C;if(h){f(!0),I(null);try{let y;h==="checkpoint"?y=await n(e,"git_checkpoint",{workspace:t,message:S,includeUntracked:p}):h==="stash"?y=await n(e,"git_stash_push",{workspace:t,message:S,includeUntracked:p}):h==="stash_pop"?y=await n(e,"git_stash_pop",{workspace:t}):h==="checkout_files"&&m&&(y=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const F=(y==null?void 0:y.result)??y;if((F==null?void 0:F.success)===!1||F!=null&&F.error){I((F==null?void 0:F.error)??"Action failed"),f(!1);return}h==="checkpoint"?A(`Checkpoint created: ${(($=(H=F==null?void 0:F.checkpoint)==null?void 0:H.commit)==null?void 0:$.slice(0,7))??"done"}`):h==="stash"?A(`Stashed as ${((C=F==null?void 0:F.stash)==null?void 0:C.stashRef)??"stash@{0}"}`):h==="stash_pop"?A("Stash restored"):(A("File reverted"),u(null)),x(null),await d()}catch(y){I(y instanceof Error?y.message:"Action failed")}finally{f(!1)}}},[h,n,e,t,S,p,m,d]),j=!!(a!=null&&a.hasConflicts),W=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:H=>{H.target===H.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}),_&&s.jsx("a",{href:`${_}/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(wt,{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"}),W===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(J0,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:N}),!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(Z0,{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"})})]}),k&&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:k}),s.jsx("button",{onClick:()=>A(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:()=>w("checkpoint"),disabled:j,title:j?"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:()=>w("stash"),disabled:j,title:j?"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:()=>w("stash_pop"),disabled:j||!(a!=null&&a.stashCount),title:j?"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:()=>w("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 H=ev((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(H),A("Copied to clipboard"),setTimeout(()=>A(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),h&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[h==="checkpoint"&&"Create checkpoint commit",h==="stash"&&"Stash changes",h==="stash_pop"&&"Restore latest stash?",h==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(h==="checkpoint"||h==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:S,onChange:H=>b(H.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:p,onChange:H=>g(H.target.checked)}),"Include untracked files"]})]}),T&&s.jsx("p",{className:"text-xs text-red-400",children:T}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:D,disabled:v,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:M,disabled:v||(h==="checkpoint"||h==="stash")&&!S.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:v?"Working…":"Confirm"})]})]})})]})})}function tv({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),[h,x]=i.useState(!1),[S,b]=i.useState("quickstart"),[p,g]=i.useState("workspace"),v=i.useMemo(()=>!t&&!e,[t,e]),f=i.useCallback(N=>{a(N),N&&l(!1)},[]),T=i.useCallback(N=>{l(N),N&&a(!1)},[]),I=i.useCallback(()=>{b(r===0?"quickstart":"shortcuts"),g("workspace"),d(!0),a(!1),l(!1)},[r]),k=i.useCallback(()=>{d(!1)},[]),A=i.useCallback(()=>{u(!0)},[]),_=i.useCallback(()=>{u(!1)},[]);return i.useEffect(()=>{if(!v){x(!1);return}x(!0);const N=window.setTimeout(()=>{x(!1)},1e4);return()=>window.clearTimeout(N)},[v]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:m,guideNudgeVisible:h,guideTab:S,shortcutSection:p,isDesktopDashboard:v,setGuideTab:b,setShortcutSection:g,handleInboxOpenChange:f,handleHiddenOpenChange:T,handleOpenShortcutHelp:I,closeShortcutHelp:k,openNewSession:A,closeNewSession:_}}function sv(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 rv(e){return e instanceof Error?e.message:String(e||"")}function nv(e){const t=rv(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function av({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:l,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:h,ides:x,actionLogs:S,sendDaemonCommand:b,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:v,initialDataLoaded:f,userName:T,requestedMobileTabKey:I,onRequestedMobileTabConsumed:k,requestedMachineId:A,onRequestedMachineConsumed:_,requestedMobileSection:N,onRequestedMobileSectionConsumed:w,containerRef:D,isSplitMode:M,numGroups:j,groupSizes:W,groupedConvs:H,clearedTabs:$,focusedGroup:C,focusGroup:y,moveTabToGroup:F,splitTabRelative:P,closeGroup:E,handleResizeStart:G,groupActiveTabIds:J,setGroupActiveTab:ye,groupTabOrders:he,setGroupTabOrder:ne,toggleHiddenTab:ue,visibleConversations:Se,requestedDesktopTabKey:ve,onRequestedDesktopTabConsumed:X,onDesktopActiveTabChange:xe,onRequestScrollToBottom:fe,onHideConversation:we,onShowHiddenConversation:be,onShowAllHiddenConversations:Ce,scrollToBottomRequest:ee,machineEntries:me,layoutProfile:ie,onBrowseMachineDirectory:pe,onSaveMachineWorkspace:le,onLaunchMachineIde:B,onLaunchMachineProvider:z,onListMachineMeshes:de,onLaunchMeshCoordinator:re,onListMachineSavedSessions:R,notifications:q,notificationUnreadCount:ce,liveSessionInboxState:Ne,onMarkNotificationRead:je,onMarkNotificationUnread:O,onDeleteNotification:Ie}){const Le=Nt.useRef(null),{inboxOpen:He,hiddenOpen:ze,shortcutHelpOpen:Xe,newSessionOpen:Je,guideNudgeVisible:rt,guideTab:pt,shortcutSection:xt,isDesktopDashboard:vt,setGuideTab:Te,setShortcutSection:Ve,handleInboxOpenChange:tt,handleHiddenOpenChange:Ge,handleOpenShortcutHelp:ot,closeShortcutHelp:U,openNewSession:V,closeNewSession:Z}=tv({isMobile:t,showMobileChatMode:e,visibleConversationCount:Se.length}),[ae,K]=Nt.useState(null),[Y,se]=Nt.useState(null),oe=Nt.useCallback((L,Q)=>{K({daemonId:L,workspace:Q})},[]),ke=Nt.useCallback(L=>{se(L)},[]),Pe=Nt.useCallback(L=>{var Q;Tr.flushSync(()=>{be(L)}),(Q=Le.current)==null||Q.restoreHiddenTabToSavedLocation(L.tabKey)},[be]),Ee=Nt.useCallback(L=>{var ge;const Q=u.find(Be=>uo(Be,L))||h.find(Be=>uo(Be,L));Q&&(h.some(Be=>Be.tabKey===Q.tabKey)&&Pe(Q),xe(Q.tabKey),(ge=Le.current)==null||ge.activateConversationTab(Q.tabKey),fe(Q.tabKey,"notification-open")),je(L.id),tt(!1)},[Pe,h,u,xe,je,fe]),Ae=Nt.useCallback(()=>{var Q;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Q=Le.current)==null||Q.resetAllPanelsToMain(),Ge(!1))},[Ge]),$e=Nt.useCallback(async L=>{var Oe;if(!r)return;const Q=(Oe=r.modalButtons)==null?void 0:Oe[L];if(!Q)return;const ge=Gs(r);if(!ge)return;const Be=Q.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),_e=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Be);try{await b(ge,"resolve_action",{button:Q,action:_e?"approve":"reject",buttonIndex:L,...xs(r)})}catch(nt){nv(nt)||console.error("[Shortcut approval] Failed:",nt)}},[r,b]),{isMac:Fe,actionDefinitions:Me,actionShortcuts:Qe,shortcutListening:et,shortcutListeningDraft:bt,setShortcutListening:gt,setShortcutListeningDraft:dt,saveShortcuts:ht}=Iy({enabled:vt&&!Xe,onTrigger:L=>{var Q,ge,Be,_e,Oe,nt,Mt,ft,ss,Fr,Wr,Kr,Hr,Ur,zr,Vr;if(L==="openShortcutHelp"){ot();return}if(L==="openNewSession"){V();return}if(L==="hideCurrentTab"){r&&we(r);return}if(L==="toggleHiddenTabs"){Ge(!ze);return}if(L==="openHistoryForActiveTab"){r&&!st(r)&&o(r);return}if(L==="openRemoteForActiveTab"){r&&!at(r)&&!st(r)&&l(r);return}if(L==="splitActiveTabRight"){(Q=Le.current)==null||Q.splitActiveTabRight();return}if(L==="splitActiveTabDown"){(ge=Le.current)==null||ge.splitActiveTabDown();return}if(L==="floatActiveTab"){(Be=Le.current)==null||Be.floatActiveTab();return}if(L==="popoutActiveTab"){(_e=Le.current)==null||_e.popoutActiveTab();return}if(L==="dockActiveTab"){(Oe=Le.current)==null||Oe.dockActiveTab();return}if(L==="focusLeftPane"){(nt=Le.current)==null||nt.focusLeftPane();return}if(L==="focusRightPane"){(Mt=Le.current)==null||Mt.focusRightPane();return}if(L==="focusUpPane"){(ft=Le.current)==null||ft.focusUpPane();return}if(L==="focusDownPane"){(ss=Le.current)==null||ss.focusDownPane();return}if(L==="moveActiveTabToLeftPane"){(Fr=Le.current)==null||Fr.moveActiveTabToLeftPane();return}if(L==="moveActiveTabToRightPane"){(Wr=Le.current)==null||Wr.moveActiveTabToRightPane();return}if(L==="moveActiveTabToUpPane"){(Kr=Le.current)==null||Kr.moveActiveTabToUpPane();return}if(L==="moveActiveTabToDownPane"){(Hr=Le.current)==null||Hr.moveActiveTabToDownPane();return}if(L==="triggerPrimaryApprovalAction"){$e(0);return}if(L==="triggerSecondaryApprovalAction"){$e(1);return}if(L==="triggerTertiaryApprovalAction"){$e(2);return}if(L==="setActiveTabShortcut"){(Ur=Le.current)==null||Ur.setShortcutForActiveTab();return}if(L==="selectPreviousGroupTab"){(zr=Le.current)==null||zr.activatePreviousTabInGroup();return}if(L==="selectNextGroupTab"){(Vr=Le.current)==null||Vr.activateNextTabInGroup();return}!r||!at(r)||st(r)||L==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),Ue=Nt.useCallback(()=>{U(),gt(null),dt([])},[U,gt,dt]),Kt=Nt.useMemo(()=>xt==="all"?Me:Me.filter(L=>sv(L)===xt),[Me,xt]),te=Nt.useCallback(()=>{const L=Object.fromEntries(Me.map(Q=>[Q.id,""]));ht(L)},[Me,ht]),De=Nt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const L=Object.fromEntries(Me.map(Q=>[Q.id,Q.defaultShortcut]));ht(L)},[Me,ht]);return Nt.useEffect(()=>{const L=Q=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Q.metaKey&&Q.key.toLowerCase()==="w":Q.ctrlKey&&Q.key.toLowerCase()==="w")&&(Q.preventDefault(),r&&we&&we(r))};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[r,we]),Nt.useEffect(()=>{if(!Xe||et)return;const L=Q=>{Q.key==="Escape"&&(Q.preventDefault(),Ue())};return window.addEventListener("keydown",L,!0),()=>window.removeEventListener("keydown",L,!0)},[Ue,Xe,et]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(Nx,{activeConv:r,wsStatus:n,isConnected:a,conversations:Se,hiddenConversations:h,onOpenHistory:o,onHideConversation:we,onShowConversation:Pe,onShowAllHidden:Ce,onResetPanelsToMain:Ae,notifications:q,notificationUnreadCount:ce,onOpenNotification:Ee,onMarkNotificationRead:je,onMarkNotificationUnread:O,onDeleteNotification:Ie,inboxOpen:He,onInboxOpenChange:tt,hiddenOpen:ze,onHiddenOpenChange:Ge,onOpenNewSession:t?void 0:V,onOpenDashboardGuide:ot,guideNudgeVisible:rt,actionShortcuts:Qe,onOpenRemote:()=>{!r||at(r)||st(r)||l(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:oe,onOpenMeshGraph:ke}),e?s.jsx(fy,{conversations:u,hiddenConversations:h,ides:x,actionLogs:S,sendDaemonCommand:b,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:v,userName:T,requestedActiveTabKey:I,onRequestedActiveTabConsumed:k,requestedMachineId:A,onRequestedMachineConsumed:_,requestedMobileSection:N,onRequestedMobileSectionConsumed:w,onOpenHistory:o,onOpenRemote:l,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Ce,onHideConversation:we,onOpenMeshGraph:ke,onOpenNewSession:V,liveSessionInboxState:Ne}):t?s.jsx(ky,{containerRef:D,isSplitMode:M,numGroups:j,groupSizes:W,groupedConvs:H,clearedTabs:$,ides:x,actionLogs:S,sendDaemonCommand:b,setActionLogs:p,isStandalone:v,hasRegisteredMachines:me.length>0,userName:T,focusedGroup:C,focusGroup:y,moveTabToGroup:F,splitTabRelative:P,closeGroup:E,handleResizeStart:G,groupActiveTabIds:J,setGroupActiveTab:ye,groupTabOrders:he,setGroupTabOrder:ne,toggleHiddenTab:ue,onOpenNewSession:V,allowTabShortcuts:!1,liveSessionInboxState:Ne}):s.jsx(Wy,{visibleConversations:Se,clearedTabs:$,ides:x,actionLogs:S,sendDaemonCommand:b,setActionLogs:p,isStandalone:v,hasRegisteredMachines:me.length>0,initialDataLoaded:f,userName:T,toggleHiddenTab:ue,actionShortcuts:Qe,registerActionHandlers:L=>{Le.current=L},onActiveTabChange:xe,requestedActiveTabKey:ve,onRequestedActiveTabConsumed:X,onRequestScrollToBottom:fe,scrollToBottomRequest:ee,onOpenNewSession:V,liveSessionInboxState:Ne,layoutProfile:ie}),Je&&s.jsx(Vy,{machines:me,ides:x,onClose:Z,onBrowseDirectory:pe,onSaveWorkspace:le,onLaunchIde:B,onLaunchProvider:z,onListMeshes:de,onLaunchMeshCoordinator:re,onListSavedSessions:R}),Y&&s.jsx(B0,{activeConv:Y,sendDaemonCommand:b,onClose:()=>se(null)}),ae&&s.jsx(Pu,{daemonId:ae.daemonId,workspace:ae.workspace,onClose:()=>K(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:Ue,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:L=>L.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:Ue,"aria-label":"Close dashboard guide",children:s.jsx(wt,{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(L=>s.jsx("button",{type:"button",className:`btn btn-sm ${pt===L.id?"btn-primary":"btn-secondary"}`,onClick:()=>Te(L.id),children:L.label},L.id))}),pt==="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 ",Fe?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),pt==="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."]})]})]})]}),pt==="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(L=>s.jsx("button",{type:"button",className:`btn btn-sm ${xt===L.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ve(L.id),children:L.label},L.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:te,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:De,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Kt.map(L=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${et===L.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:L.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:L.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:L.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===L.id?bt.length>0?`${bt.join(" ")} ...`:"Listening...":Qe[L.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{gt(L.id),dt([])},children:et===L.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Q={...Qe};Q[L.id]="",ht(Q)},children:"Disable"})]})]})},L.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Fe?"⌘⇧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 Ka=[{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 ov({onClose:e}){const[t,r]=i.useState(0),n=Ka[t],a=t===Ka.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(wt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Ka.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:`
64
+ `,Y.style.top="52px",Y.style.height="calc(100% - 52px)";const $e=Ae.querySelector("[data-adhdev-popout-focus]");$e&&($e.onclick=()=>{window.focus()});const Fe=Ae.querySelector("[data-adhdev-popout-dock]");Fe&&(Fe.disabled=!se,Fe.style.opacity=se?"1":"0.5",Fe.style.cursor=se?"pointer":"default",Fe.onclick=()=>{var Me;se&&ve(se),(Me=K.defaultView)==null||Me.focus()})}},[G,ve]),ie=i.useCallback(U=>{var ae;const V=N.current,Z=V==null?void 0:V.getPanel(U);if(!(!V||!Z)){Z.group.model.openPanel(Z),Z.api.setActive(),he(U,"dockview-shortcut");try{const K=Z.group.model.location;K.type==="popout"?K.getWindow().focus():_a((ae=Z.group.element)==null?void 0:ae.ownerDocument)}catch{}}},[he]),pe=i.useCallback(U=>{const V=N.current,Z=V==null?void 0:V.activePanel,ae=(V==null?void 0:V.activeGroup)||(Z==null?void 0:Z.group);if(!V||!Z||!ae)return;const K=ae.panels||[];if(K.length<=1)return;const Y=K.findIndex(ke=>ke.id===Z.id);if(Y<0)return;const se=(Y+U+K.length)%K.length,oe=K[se];oe&&(oe.group.model.openPanel(oe),oe.api.setActive(),Bt(oe.id)||he(oe.id,"dockview-shortcut"))},[he]),le=i.useCallback(U=>{var $e;const V=N.current,Z=(V==null?void 0:V.activeGroup)||(($e=V==null?void 0:V.activePanel)==null?void 0:$e.group);if(!V||!Z)return;const ae=V.groups||[],K=ae.find(Fe=>Fe.id===Z.id);if(!K)return;const Y=K.element.getBoundingClientRect(),se=Y.left+Y.width/2,oe=Y.top+Y.height/2,ke=(Fe,Me,Qe,et)=>Math.max(0,Math.min(Me,et)-Math.max(Fe,Qe)),Pe=Fe=>{const Me=Fe.element.getBoundingClientRect(),Qe=Me.left+Me.width/2,et=Me.top+Me.height/2;let bt=0,gt=0,dt=0,ht=!1;if(U==="left"?(ht=Qe<se,bt=Math.max(0,Y.left-Me.right),gt=Math.abs(et-oe),dt=ke(Y.top,Y.bottom,Me.top,Me.bottom)):U==="right"?(ht=Qe>se,bt=Math.max(0,Me.left-Y.right),gt=Math.abs(et-oe),dt=ke(Y.top,Y.bottom,Me.top,Me.bottom)):U==="above"?(ht=et<oe,bt=Math.max(0,Y.top-Me.bottom),gt=Math.abs(Qe-se),dt=ke(Y.left,Y.right,Me.left,Me.right)):(ht=et>oe,bt=Math.max(0,Me.top-Y.bottom),gt=Math.abs(Qe-se),dt=ke(Y.left,Y.right,Me.left,Me.right)),!ht)return Number.POSITIVE_INFINITY;const Ue=dt>0?0:120;return bt*3+gt+Ue};let Ee=null,Ae=Number.POSITIVE_INFINITY;for(const Fe of ae){if(Fe.id===K.id)continue;const Me=Pe(Fe);Number.isFinite(Me)&&(Me>=Ae||(Ae=Me,Ee=Fe))}return Ee||void 0},[]),B=i.useCallback(U=>{var ae;const V=le(U);if(!V)return;const Z=V.activePanel||V.panels[0];Z&&(V.model.openPanel(Z),Z.api.setActive(),Bt(Z.id)||he(Z.id,"dockview-focus"),_a((ae=V.element)==null?void 0:ae.ownerDocument))},[le,he]),z=i.useCallback((U,V)=>{const Z=N.current,ae=Z==null?void 0:Z.activePanel,K=(Z==null?void 0:Z.activeGroup)||(ae==null?void 0:ae.group);if(!Z||!ae||!K)return;let Y=le(U);!Y&&(V!=null&&V.createGroupIfMissing)&&(Y=Z.addGroup({referenceGroup:K,direction:U})),Y&&(ae.api.moveTo({group:Y,position:"center"}),ae.group.model.openPanel(ae),ae.api.setActive(),Bt(ae.id)||he(ae.id,V!=null&&V.createGroupIfMissing?"dockview-split":"dockview-move"))},[le,he]),{isMac:de,tabShortcuts:re,shortcutListening:R,setShortcutListening:q,saveShortcuts:ce}=nu({sortedTabKeys:e.map(U=>U.tabKey),onFocus:ye,onSelectTab:ie}),Ne=i.useCallback(()=>{var Z;const U=N.current;if(!U)return;const V=U.activePanel;if(V){if(Bt(V.id)){const ae=((Z=V.params)==null?void 0:Z.routeId)||V.id.slice(7),K=Wt(e,ae);K!=null&&K.tabKey&&q(K.tabKey);return}G.has(V.id)&&q(V.id)}},[G,ie,q,e]),je=i.useCallback(U=>{const V=[];return U.metaKey&&V.push(de?"⌘":"Meta"),U.ctrlKey&&V.push("Ctrl"),U.altKey&&V.push(de?"⌥":"Alt"),U.shiftKey&&U.key.length!==1&&V.push(de?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(U.key)?null:(V.push(lu(U.key)),V.join("+"))},[de]),O=i.useCallback(U=>{var V,Z;switch(U){case"splitActiveTabRight":z("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":z("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const ae=be();ae&&fe(ae);return}case"popoutActiveTab":{const ae=be();ae&&Se(ae);return}case"dockActiveTab":{const ae=be();if(!ae)return;X(ae)?ve(ae):we(ae)&&Ce(ae);return}case"focusLeftPane":B("left");return;case"focusRightPane":B("right");return;case"focusUpPane":B("above");return;case"focusDownPane":B("below");return;case"moveActiveTabToLeftPane":z("left");return;case"moveActiveTabToRightPane":z("right");return;case"moveActiveTabToUpPane":z("above");return;case"moveActiveTabToDownPane":z("below");return;case"selectPreviousGroupTab":pe(-1);return;case"selectNextGroupTab":pe(1);return;case"setActiveTabShortcut":Ne();return;case"hideCurrentTab":{const ae=(Z=(V=N.current)==null?void 0:V.activePanel)==null?void 0:Z.id;ae&&!Bt(ae)&&xe(ae);return}default:return}},[pe,Ce,B,fe,be,xe,we,X,ve,z,Se,Ne]);i.useEffect(()=>{if(!C)return;const U=C.sourceDocument,V=U.defaultView??window,Z=ae=>{const K=U.querySelector("[data-dockview-tab-context-menu]");K&&K.contains(ae.target)||y(null)};return V.addEventListener("mousedown",Z,!0),V!==window&&window.addEventListener("mousedown",()=>y(null),!0),()=>{V.removeEventListener("mousedown",Z,!0),V!==window&&window.removeEventListener("mousedown",()=>y(null),!0)}},[C]);const Ie=i.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:G,hasDetachedConversationPanels:J,ides:r,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:b,liveSessionInboxState:I,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:xe,userName:m,scrollToBottomRequest:T,tabShortcuts:re,openTabContextMenu:({x:U,y:V,tabKey:Z,sourceDocument:ae})=>y({x:U,y:V,tabKey:Z,sourceDocument:ae??document}),popoutTab:Se,moveTabBackToMain:ve,isTabInPopout:X,floatTab:fe,isTabFloating:we}),[n,t,G,J,r,l,c,b,I,a,o,xe,m,T,re,Se,ve,X,fe,we]),Le=C?Ty({isTabInPopout:X(C.tabKey),isTabFloating:we(C.tabKey),tabShortcut:re[C.tabKey],actionShortcuts:h}):[],He=i.useCallback(U=>{var ae;const V=N.current;if((((ae=V==null?void 0:V.activePanel)==null?void 0:ae.id)??null)===U.id){U.group.model.openPanel(U);return}U.group.model.openPanel(U),U.api.setActive()},[]),ze=i.useCallback((U,V="requested-tab")=>{if(!U)return!1;const Z=N.current;if(!Z)return!1;const ae=Z.getPanel(U);return ae?(He(ae),he(U,V),f==null||f(),!0):!1},[He,f,he]),Xe=i.useCallback(()=>{if(W.current)return!1;const U=ze(H.current,"stored-layout-restore");return U&&(W.current=!0),U},[ze]),Je=i.useCallback(()=>{var V;const U=N.current;U&&ag(k,{activeTabId:((V=U.activePanel)==null?void 0:V.id)??null,layout:U.toJSON()})},[k]),rt=i.useCallback(()=>{ig(k,E.current)},[k]),pt=i.useCallback(U=>{var ae,K,Y,se;const V=N.current;if(!V)return{kind:"grid"};const Z=V.toJSON();for(const oe of Z.floatingGroups||[])if((K=(ae=oe.data)==null?void 0:ae.views)!=null&&K.includes(U)&&oe.position)return{kind:"floating",position:oe.position};for(const oe of Z.popoutGroups||[])if((se=(Y=oe.data)==null?void 0:Y.views)!=null&&se.includes(U))return{kind:"popout",position:oe.position,popoutUrl:oe.url};return{kind:"grid"}},[]),xt=i.useCallback(U=>{const V=N.current;if(!V)return;const Z=V.getPanel(U),ae=E.current[U];if(!Z||!ae||ae.kind==="grid")return;if(Z.group.model.location.type===ae.kind){delete E.current[U],rt();return}if(ae.kind==="floating"){V.addFloatingGroup(Z,{x:ae.position.left??24,y:ae.position.top??24,width:ae.position.width,height:ae.position.height}),delete E.current[U],rt();return}delete E.current[U],rt()},[rt]);i.useEffect(()=>(x==null||x({setShortcutForActiveTab:Ne,restoreHiddenTabToSavedLocation:xt,activateConversationTab:ie,resetAllPanelsToMain:ee,activatePreviousTabInGroup:()=>pe(-1),activateNextTabInGroup:()=>pe(1),floatActiveTab:()=>{const U=be();U&&fe(U)},popoutActiveTab:()=>{const U=be();U&&Se(U)},dockActiveTab:()=>{const U=be();U&&(X(U)?ve(U):we(U)&&Ce(U))},splitActiveTabRight:()=>z("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>z("below",{createGroupIfMissing:!0}),focusLeftPane:()=>B("left"),focusRightPane:()=>B("right"),focusUpPane:()=>B("above"),focusDownPane:()=>B("below"),moveActiveTabToLeftPane:()=>z("left"),moveActiveTabToRightPane:()=>z("right"),moveActiveTabToUpPane:()=>z("above"),moveActiveTabToDownPane:()=>z("below")}),()=>x==null?void 0:x(null)),[pe,Ce,fe,B,be,we,X,z,ve,Se,x,ee,xt,ie,Ne]),i.useEffect(()=>()=>{var U;(U=D.current)==null||U.call(D),D.current=null},[]);const vt=i.useCallback(U=>{var Z,ae;N.current=U.api,(Z=D.current)==null||Z.call(D),D.current=null;const V=ng(k);if(H.current=(V==null?void 0:V.activeTabId)??null,V!=null&&V.layout&&U.api.fromJSON(V.layout,{reuseExistingPanels:!1}),j.current=kl({hasStoredLayout:!!(V!=null&&V.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),j.current||(Ml(U.api,e),Al(U.api,e,v)),U.api.totalPanels===0&&e.length>0){const K=Ey(U.api,e,g);if(K){const Y=U.api.getPanel(K);Y&&He(Y)}}else!j.current&&!ze(g)&&Xe();if(M.current=!0,U.api.onDidActivePanelChange(K=>{var se;if(H.current=(K==null?void 0:K.id)??null,W.current=!0,me(),K&&Bt(K.id)){const oe=((se=K.params)==null?void 0:se.routeId)||K.id.slice(7),ke=Wt(e,oe);S((ke==null?void 0:ke.tabKey)??null),Je();return}if(S((K==null?void 0:K.id)??null),Je(),!K)return;const Y=G.get(K.id);(Y==null?void 0:Y.streamSource)==="agent-stream"&&Y.agentType&&_(Y.routeId,Gc(),{agentType:Y.agentType,...Y.sessionId&&{targetSessionId:Y.sessionId}}).catch(()=>{})}),U.api.onDidLayoutChange(()=>{Je(),me(),P(K=>K+1)}),Ly()){const K=Ae=>({clientX:Ae.clientX,clientY:Ae.clientY}),Y=Ae=>{const $e=Ae==null?void 0:Ae.getBoundingClientRect();return $e?{left:$e.left,right:$e.right,top:$e.top,bottom:$e.bottom}:null},se=Ae=>{var Fe;const $e=(Fe=w.current)==null?void 0:Fe.getBoundingClientRect();return $e?Ae.clientX<$e.left||Ae.clientX>$e.right||Ae.clientY<$e.top||Ae.clientY>$e.bottom:!1},oe=_y({detachDelayMs:du,onDetach:({panelId:Ae,clientX:$e,clientY:Fe})=>{var dt,ht;const Me=U.api.getPanel(Ae);if(!Me)return;try{if(Me.group.model.location.type!=="grid")return}catch{return}const Qe=(dt=w.current)==null?void 0:dt.getBoundingClientRect(),et=(ht=Me.group.element)==null?void 0:ht.getBoundingClientRect(),bt=Math.round(Math.min(Math.max((et==null?void 0:et.width)??600,360),720)),gt=Math.round(Math.min(Math.max((et==null?void 0:et.height)??500,260),640));U.api.addFloatingGroup(Me,{x:Qe?Math.max(0,$e-Qe.left-32):void 0,y:Qe?Math.max(0,Fe-Qe.top-18):void 0,width:bt,height:gt}),Me.api.setActive(),Je(),me(),P(Ue=>Ue+1)}}),ke=[U.api.onWillDragPanel(Ae=>{if(!(Ae.nativeEvent.defaultPrevented||Ae.nativeEvent.shiftKey)){try{if(Ae.panel.group.model.location.type!=="grid")return}catch{return}oe.startDrag({panelId:Ae.panel.id,selfPanelBounds:Y(Ae.panel.group.element),...K(Ae.nativeEvent)})}}),U.api.onWillShowOverlay(Ae=>{if(oe.hasDetached()){Ae.preventDefault();return}oe.markDockTarget(K(Ae.nativeEvent))}),U.api.onWillDrop(Ae=>{if(oe.hasDetached()){Ae.preventDefault(),oe.endDrag();return}oe.markDockTarget(K(Ae.nativeEvent))}),U.api.onDidDrop(()=>oe.endDrag()),U.api.onUnhandledDragOverEvent(Ae=>{oe.isDragging()&&oe.markSelfPanel(K(Ae.nativeEvent))})],Pe=Ae=>{if(!oe.isDragging())return;const $e=K(Ae);se($e)&&oe.markNonSelfPanel($e)},Ee=()=>oe.endDrag();window.addEventListener("dragover",Pe,!0),window.addEventListener("drop",Ee,!0),window.addEventListener("dragend",Ee,!0),D.current=()=>{oe.dispose();for(const Ae of ke)Ae.dispose();window.removeEventListener("dragover",Pe,!0),window.removeEventListener("drop",Ee,!0),window.removeEventListener("dragend",Ee,!0)}}U.api.onDidAddGroup(K=>{requestAnimationFrame(()=>{var Y,se;try{const oe=(Y=K.element)==null?void 0:Y.ownerDocument;if(!oe||oe===document)return;(se=oe.getElementById("dv-popout-window"))==null||se.classList.add("adhdev-dockview");const ke=document.documentElement.getAttribute("data-theme");ke&&oe.documentElement.setAttribute("data-theme",ke),oe.body.className=document.body.className;const Pe=document.documentElement.getAttribute("style");Pe&&oe.documentElement.setAttribute("style",Pe)}catch{}me(),P(oe=>oe+1)})}),S(((ae=U.api.activePanel)==null?void 0:ae.id)??null)},[He,ze,G,r,d,k,S,Je,g,v,_,me,e]);i.useLayoutEffect(()=>{const U=N.current;if(!U||!M.current||j.current&&kl({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;j.current&&(j.current=!1);const V=$.current,Z=new Set(V),ae=e.map(Ee=>Ee.tabKey),K=new Set(ae),Y=My({previousVisibleConversationCount:V.length,visibleConversationCount:e.length,ides:r});let se=!1;for(const Ee of V)K.has(Ee)||Y||(E.current[Ee]=pt(Ee),se=!0);se&&rt(),Y||(Ml(U,e),Al(U,e,v));const oe=ae.filter(Ee=>!Z.has(Ee));let ke=!1;for(const Ee of oe){const Ae=U.getPanel(Ee),$e=E.current[Ee];if(!Ae||!$e||$e.kind==="grid")continue;if(Ae.group.model.location.type===$e.kind){delete E.current[Ee],ke=!0;continue}if($e.kind==="floating"){U.addFloatingGroup(Ae,{x:$e.position.left??24,y:$e.position.top??24,width:$e.position.width,height:$e.position.height}),delete E.current[Ee],ke=!0;continue}}if(ke&&rt(),$.current=ae,g&&ze(g))return;!U.activePanel&&U.panels[0]&&He(U.panels[0]),!!(U.activePanel&&U.getPanel(U.activePanel.id))||Xe()},[He,ze,Xe,r,d,rt,pt,g,v,e]),i.useEffect(()=>{M.current&&ze(g)},[ze,g]),i.useEffect(()=>{const U=Z=>{const ae=Z.target;if(!ae)return;const K=ae.querySelector("[data-tab-key]")||ae.closest("[data-tab-key]");if(K){const Y=K.getAttribute("data-tab-key");if(Y&&Z.dataTransfer){const se=ae.closest(".dv-tab")||K.closest(".dv-tab")||K;Z.dataTransfer.effectAllowed="move",Z.dataTransfer.setData("text/tab-key",Y),se instanceof HTMLElement&&Z.dataTransfer.setDragImage(se,Math.max(12,Math.round(se.clientWidth/2)),Math.max(10,Math.round(se.clientHeight/2)))}}};window.addEventListener("dragstart",U);const V=Tl(N.current);for(const Z of V)Z.addEventListener("dragstart",U);return()=>{window.removeEventListener("dragstart",U);for(const Z of V)Z.removeEventListener("dragstart",U)}},[F]),i.useEffect(()=>{var V;const U=(V=w.current)==null?void 0:V.querySelector(".adhdev-dockview");U instanceof HTMLElement&&La(U,A),ue(),me()},[me,ue,A]),i.useEffect(()=>{me()},[me]),i.useEffect(()=>{const U=V=>{if(V.defaultPrevented||R)return;const Z=je(V);if(!Z)return;const ae=V.metaKey||V.ctrlKey||V.altKey;wo(V.target)&&!ae||On(de).setActiveTabShortcut!==Z||(V.preventDefault(),V.stopPropagation(),Ne())};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[je,de,R,Ne]),i.useEffect(()=>{const U=w.current;if(!U)return;const V=Z=>{var oe,ke;if(!Z.isTrusted)return;const ae=(ke=(oe=Z.target)==null?void 0:oe.closest)==null?void 0:ke.call(oe,".dv-scrollable");if(!ae)return;Z.preventDefault(),Z.stopPropagation();const K=Math.abs(Z.deltaX),Y=Math.abs(Z.deltaY),se=K>Y?Z.deltaX:Z.deltaY;ae.dispatchEvent(new WheelEvent("wheel",{deltaY:se,deltaMode:Z.deltaMode,bubbles:!1,cancelable:!0}))};return U.addEventListener("wheel",V,{passive:!1,capture:!0}),()=>U.removeEventListener("wheel",V,{capture:!0})},[]),i.useEffect(()=>{const U=Tl(N.current);if(U.length===0)return;const V=U.map(Z=>{let ae=[],K=null;const Y=()=>{K!=null&&Z.clearTimeout(K),K=null,ae=[]},se=()=>{K!=null&&Z.clearTimeout(K),K=Z.setTimeout(()=>{K=null,ae=[]},1200)},oe=Pe=>{if(!Pe.ctrlKey&&!Pe.metaKey&&!Pe.altKey)return;const Ee=je(Pe);if(!Ee)return;const Ae=ru();for(const[$e,Fe]of Object.entries(Ae))if(e.some(Me=>Me.tabKey===$e)&&Fe===Ee){Pe.preventDefault(),ie($e);return}},ke=Pe=>{if(Pe.defaultPrevented||R)return;const Ee=je(Pe);if(!Ee)return;const Ae=Pe.metaKey||Pe.ctrlKey||Pe.altKey;if(wo(Pe.target))return;const $e=On(de),Fe=Object.entries($e).filter(([Ue,Kt])=>!!Kt&&(Ue==="splitActiveTabRight"||Ue==="splitActiveTabDown"||Ue==="floatActiveTab"||Ue==="popoutActiveTab"||Ue==="dockActiveTab"||Ue==="focusLeftPane"||Ue==="focusRightPane"||Ue==="focusUpPane"||Ue==="focusDownPane"||Ue==="moveActiveTabToLeftPane"||Ue==="moveActiveTabToRightPane"||Ue==="moveActiveTabToUpPane"||Ue==="moveActiveTabToDownPane"||Ue==="selectPreviousGroupTab"||Ue==="selectNextGroupTab"||Ue==="setActiveTabShortcut"||Ue==="hideCurrentTab")),Me=Ae?[Ee]:[...ae.slice(-1),Ee].slice(-2),Qe=Me.join(" "),et=Me[Me.length-1],bt=Fe.find(([,Ue])=>Ue===Qe);if(bt){Pe.preventDefault(),Y(),O(bt[0]);return}if(Fe.some(([,Ue])=>Ue.startsWith(`${Qe} `))){Pe.preventDefault(),ae=Me,se();return}const dt=Fe.find(([,Ue])=>Ue===et);if(dt){Pe.preventDefault(),Y(),O(dt[0]);return}if(Fe.some(([,Ue])=>Ue.startsWith(`${et} `))){Pe.preventDefault(),ae=[et],se();return}Y()};return Z.addEventListener("keydown",oe),Z.addEventListener("keydown",ke),()=>{Y(),Z.removeEventListener("keydown",oe),Z.removeEventListener("keydown",ke)}});return()=>{for(const Z of V)Z()}},[je,de,F,ie,R,O,e]);const Te=A==="light"?eo:to,Ve=((ot=(Ge=(tt=N.current)==null?void 0:tt.activePanel)==null?void 0:Ge.group.element)==null?void 0:ot.ownerDocument)??document;return s.jsxs(uu.Provider,{value:Ie,children:[s.jsx("div",{ref:w,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(pm,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:$y,remote:By},defaultTabComponent:Fy,watermarkComponent:Oy,onReady:vt,singleTabMode:"default",tabAnimation:"smooth",theme:Te,popoutUrl:"/popout.html"})}),C&&Tr.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:Le.map(U=>{if(U.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},U.id);let V=s.jsx(xp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{};switch(U.id){case"dockInWindow":case"dockBackToGrid":V=s.jsx(gp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{Ce(C.tabKey),y(null)};break;case"moveBackToMain":V=s.jsx(fp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{ve(C.tabKey),y(null)};break;case"floatAsPanel":V=s.jsx(bp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{fe(C.tabKey),y(null)};break;case"openInNewWindow":V=s.jsx(hp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{Se(C.tabKey),y(null)};break;case"setShortcut":Z=ae=>{ae.stopPropagation(),q(C.tabKey),y(null)};break;case"removeShortcut":V=s.jsx(wt,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{const ae={...re};delete ae[C.tabKey],ce(ae),y(null)};break;case"hideTab":V=s.jsx(Lo,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{xe(C.tabKey),y(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${U.tone==="muted"?"text-text-muted":""}`,onMouseDown:Py,onClick:Z,children:[V,s.jsx("span",{className:"flex-1 min-w-0",children:U.label}),U.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:U.shortcut}):null]},U.id)})}),C.sourceDocument.body),R&&Tr.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:()=>q(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:U=>U.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",de?"⌘+1":"Ctrl+1",", ",de?"⌥+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"})]})}),Ve.body)]})}const mu="adhdev-recent-launch-args-v1",Ky=8;function pu(e){return String(e||"").trim().replace(/\s+/g," ")}function di(e,t){return`${e.trim()}::${t.trim()}`}function ui(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(mu)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function hu(e){if(!(typeof window>"u"))try{window.localStorage.setItem(mu,JSON.stringify(e))}catch{}}function jo(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=ui().byKey[di(r,n)])==null?void 0:o.items)||[]}function fu(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=pu(r);if(!n||!a||!o)return;const l=ui(),c=di(n,a),d=((u=l.byKey[c])==null?void 0:u.items)||[],m=[o,...d.filter(h=>h!==o)].slice(0,Ky);l.byKey[c]={items:m},hu(l)}function Hy(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=pu(r);if(!n||!a||!o)return;const l=ui(),c=di(n,a),m=(((u=l.byKey[c])==null?void 0:u.items)||[]).filter(h=>h!==o);m.length>0?l.byKey[c]={items:m}:delete l.byKey[c],hu(l)}function xu(e){return!e.hasLoadedInitialResults&&!e.isLoading}function wn({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 Uy({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 bu({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:l,onOpenHistory:c,onClearSelection:d}){const m=o?eu(o):null,u=Uy({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(wn,{title:"Saved history",description:Jo(),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:_x()})]}),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 gu({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 zy({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 Ra(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>Ts(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>Ts(a,"acp"))?"acp":null}function on(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Vy({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:l,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Ue,Kt;const u=Er(),h=i.useMemo(()=>[...e].sort(Fo),[e]),[x,S]=i.useState(((Ue=h[0])==null?void 0:Ue.id)||""),b=i.useMemo(()=>h.find(te=>te.id===x)||h[0],[x,h]),p=i.useMemo(()=>((b==null?void 0:b.workspaces)||[]).map(te=>({id:te.id,path:te.path,label:te.label})),[b]),g=(b==null?void 0:b.defaultWorkspaceId)||null,[v,f]=i.useState("workspace"),[T,I]=i.useState(""),[k,A]=i.useState(""),[_,N]=i.useState([]),[w,D]=i.useState(""),[M,j]=i.useState(!1),[W,H]=i.useState(null),[$,C]=i.useState(""),[y,F]=i.useState(Ra(h[0])),[P,E]=i.useState(""),[G,J]=i.useState(""),[ye,he]=i.useState([]),[ne,ue]=i.useState(""),[Se,ve]=i.useState([]),[X,xe]=i.useState(!1),[fe,we]=i.useState(!1),[be,Ce]=i.useState(""),[ee,me]=i.useState(!1),[ie,pe]=i.useState(()=>Ct()),[le,B]=i.useState(null),[z,de]=i.useState(!1),[re,R]=i.useState(""),[q,ce]=i.useState(null),[Ne,je]=i.useState(!1),[O,Ie]=i.useState(""),[Le,He]=i.useState([]),[ze,Xe]=i.useState(!1),[Je,rt]=i.useState(""),[pt,xt]=i.useState(!1),vt=i.useRef(null),Te=i.useRef(0);i.useEffect(()=>{var te;!x&&((te=h[0])!=null&&te.id)&&S(h[0].id)},[x,h]),i.useEffect(()=>{!b||!(!b.workspaces||!b.availableProviders||!b.detectedIdes||!b.recentLaunches)||u(b.id,{minFreshMs:3e4}).catch(()=>{})},[u,b]);const Ve=i.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(te=>Ts(te,"cli")),[b]),tt=i.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(te=>Ts(te,"acp")),[b]),Ge=i.useMemo(()=>((b==null?void 0:b.detectedIdes)||[]).map(te=>({id:te.type,label:te.name||te.type,meta:te.running?"Detected locally":"Available to open"})),[b]),ot=i.useMemo(()=>y==="cli"?Ve.map(te=>({id:te.type,label:te.displayName||te.type,meta:"CLI provider"})):y==="acp"?tt.map(te=>({id:te.type,label:te.displayName||te.type,meta:"ACP provider"})):Ge,[tt,y,Ve,Ge]),U=i.useMemo(()=>_.find(te=>te.id===w)||null,[_,w]),V=i.useMemo(()=>Ve.find(te=>te.type===P)||null,[Ve,P]),Z=i.useMemo(()=>Gd(V==null?void 0:V.meshCoordinator,{meshId:(U==null?void 0:U.id)||"",workspace:(U==null?void 0:U.workspace)||""}),[V,U]),ae=q||Z,K=i.useCallback(async te=>{j(!0),C("");try{const De=await c(te);N(De),D(L=>{var Q;return De.some(ge=>ge.id===L)?L:((Q=De[0])==null?void 0:Q.id)||""}),H(te)}catch(De){N([]),D(""),H(te),C(De instanceof Error?De.message:"Could not load meshes")}finally{j(!1)}},[c]);i.useEffect(()=>{var De;if(!b)return;if(vt.current!==b.id){vt.current=b.id,f("workspace"),I(g||((De=p[0])==null?void 0:De.id)||"__home__"),A(""),N([]),D(""),H(null),C(""),F(Ra(b)),E(""),J(""),ue(""),ve([]),we(!1),Ce(""),pe(Ct()),R(""),ce(null);return}I(L=>{var Q;return L==="__custom__"||L==="__home__"||p.some(ge=>ge.id===L)?L:g||((Q=p[0])==null?void 0:Q.id)||"__home__"}),F(L=>L==="ide"&&Ge.length>0||L==="cli"&&Ve.length>0||L==="acp"&&tt.length>0?L:Ra(b))},[tt.length,Ve.length,g,Ge.length,b,p]),i.useEffect(()=>{!b||v!=="mesh"||W===b.id||M||K(b.id)},[K,W,M,b,v]),i.useEffect(()=>{v==="mesh"&&y!=="cli"&&Ve.length>0&&F("cli")},[y,Ve.length,v]),i.useEffect(()=>{var te;y&&(ot.some(De=>De.id===P)||E(((te=ot[0])==null?void 0:te.id)||""))},[y,ot,P]),i.useEffect(()=>{ce(null)},[b==null?void 0:b.id,w,P,v]);const Y=i.useCallback(async(te,De)=>{const L=Te.current+1;return Te.current=L,xe(!0),Ce(""),m(te,De).then(Q=>{Te.current===L&&ve(Q)}).catch(Q=>{Te.current===L&&(ve([]),Ce(Q instanceof Error?Q.message:"Could not load saved sessions"))}).finally(()=>{Te.current===L&&(xe(!1),we(!0))})},[m]),se=i.useCallback((te,De)=>{he(jo(te,De))},[]);i.useEffect(()=>{Te.current+=1,ue(""),pe(Ct()),!b||!P||y==="ide"?he([]):se(b.id,P),we(!1),ve([]),Ce(""),xe(!1)},[y,se,Y,b,P]),i.useEffect(()=>{if(!ne)return;const te=Se.find(De=>De.providerSessionId===ne);te!=null&&te.canResume||ue("")},[Se,ne]);const oe=T==="__custom__"?k.trim():T==="__home__"?"":((Kt=p.find(te=>te.id===T))==null?void 0:Kt.path)||"",ke=i.useMemo(()=>b?t.filter(te=>te.id!==b.id&&te.daemonId===b.id).map(te=>te.workspace):[],[t,b]),Pe=i.useMemo(()=>((b==null?void 0:b.recentLaunches)||[]).map(te=>te.workspace),[b]),Ee=i.useCallback(te=>{const De=String(te.workspace||"").trim();if(!De)return;const L=p.find(Q=>on(Q.path)===on(De));if(L){I(L.id),A("");return}I("__custom__"),A(De)},[p]),Ae=i.useCallback(te=>{const De=String(te.workspace||"").trim();if(!De)return{workspaceId:null,workspacePath:null};const L=p.find(Q=>on(Q.path)===on(De));return L?{workspaceId:L.id,workspacePath:null}:{workspaceId:null,workspacePath:De}},[p]),$e=i.useMemo(()=>Se.find(te=>te.providerSessionId===ne)||null,[Se,ne]),Fe=i.useMemo(()=>{var De;if(y!=="cli"||!b||!P)return null;const te=((De=Ve.find(L=>L.type===P))==null?void 0:De.displayName)||P;return{routeId:b.id,daemonId:b.id,providerSessionId:ne||void 0,transport:"pty",mode:"chat",agentName:te,agentType:P,status:"idle",title:te,messages:[],ideType:P,workspaceName:oe,workspacePath:oe,displayPrimary:te,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${b.id}:${P}`,machineName:At(b,{fallbackId:b.id})}},[y,Ve,oe,b,ne,P]),Me=i.useCallback(()=>{var De;if(!b)return;I("__custom__"),je(!0),rt("");const te=Qn(b.platform,Jn(k.trim(),oe,ke,Pe,b.defaultWorkspacePath,(De=p.find(L=>L.id===g))==null?void 0:De.path,p.map(L=>L.path)));Xe(!0),n(b.id,te).then(L=>{Ie(L.path),A(L.path),He(L.directories)}).catch(L=>{rt(L instanceof Error?L.message:"Could not load folder")}).finally(()=>Xe(!1))},[k,g,Pe,ke,n,oe,b,p]),Qe=i.useCallback(te=>{b&&(Xe(!0),rt(""),n(b.id,te).then(De=>{Ie(De.path),A(De.path),He(De.directories)}).catch(De=>{rt(De instanceof Error?De.message:"Could not load folder")}).finally(()=>Xe(!1)))},[n,b]),et=i.useCallback(async()=>{if(!b||!oe)return;xt(!0),R("");const te=await a(b.id,oe);if(xt(!1),!te.ok){R(te.error||"Could not save workspace");return}R("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,oe,b]),bt=i.useCallback(async()=>{if(!b)return;if(v==="mesh"){if(!w||!P)return;de(!0),R(""),ce(null);const L=await d(b.id,w,P);if(de(!1),!L.ok){if(L.code==="mesh_coordinator_manual_mcp_setup_required"&&L.manualSetup){ce(L.manualSetup),R("Manual MCP setup required before this provider can act as mesh coordinator.");return}R(L.error||"Could not start mesh coordinator");return}r();return}if(!y||!P)return;de(!0),R("");const te=G.trim()?G.trim().split(/\s+/).filter(Boolean):[],De=y==="ide"?await o(b.id,P,{workspacePath:oe||null}):await l(b.id,y,P,{workspaceId:T!=="__home__"&&T!=="__custom__"?T:null,workspacePath:T==="__custom__"&&oe||null,resumeSessionId:y==="cli"&&ne?ne:null,cliArgs:te});if(de(!1),!De.ok){R(De.error||"Could not start session");return}y!=="ide"&&G.trim()&&(fu(b.id,P,G),se(b.id,P)),r()},[y,G,se,r,o,d,l,oe,b,w,ne,P,T,v]),gt=v==="mesh"?"Start mesh coordinator":y?pd(y,y==="cli"&&!!ne):"Start",dt=v==="mesh"?"Starting coordinator…":y?hd(y,y==="cli"&&!!ne):"Starting…",ht=h.length>5;return b?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(wt,{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(wn,{title:"Machine",children:ht?s.jsx("select",{"aria-label":"Machine",value:b.id,onChange:te=>S(te.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:z,children:h.map(te=>s.jsx("option",{value:te.id,children:At(te,{fallbackId:te.id})},te.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:h.map(te=>{const De=At(te,{fallbackId:te.id}),L=b.id===te.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${De}`,"aria-pressed":L,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${L?"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:()=>S(te.id),disabled:z,title:De,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${te.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:De})]},te.id)})})}),s.jsxs(wn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:v==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Me,disabled:z,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(te=>s.jsxs("button",{type:"button",role:"radio","aria-checked":v===te.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${v===te.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{f(te.id),R(""),te.id==="mesh"&&b&&W!==b.id&&!M&&K(b.id)},disabled:z,children:[s.jsx("div",{className:"text-sm font-semibold",children:te.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:te.desc})]},te.id))}),v==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:T,onChange:te=>{const De=te.target.value;I(De),De==="__custom__"?Me():R("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:z,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),p.map(te=>s.jsxs("option",{value:te.id,children:[te.id===g?"⭐ ":"",Vn(te.path,te.label)||te.path]},te.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:T==="__home__"?"Launch without a workspace.":oe||"Select a workspace folder."}),T==="__custom__"&&oe&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Me,disabled:z,children:[s.jsx(Ns,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:et,disabled:z||pt,children:pt?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[M&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!M&&$&&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:$}),!M&&!$&&_.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."}),_.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:_.map(te=>s.jsxs("button",{type:"button",role:"radio","aria-checked":w===te.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${w===te.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>D(te.id),disabled:z,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:te.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[te.repoIdentity||"Repo mesh",typeof te.nodesCount=="number"?` · ${te.nodesCount} node${te.nodesCount===1?"":"s"}`:""]}),te.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",te.workspace]})]},te.id))}),U&&s.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),s.jsx(zy,{workspaceMode:v,activeKind:y,cliEnabled:Ve.length>0,ideEnabled:Ge.length>0,acpEnabled:tt.length>0,busy:z,onSelect:F}),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:y==="ide"?"Choose IDE":y==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[ot.map(te=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${P===te.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>E(te.id),disabled:z,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:te.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:te.meta})]},te.id)),ot.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."})]})]}),v==="mesh"&&ae&&s.jsx(gu,{setup:ae,providerName:(V==null?void 0:V.displayName)||(V==null?void 0:V.name)||P}),v!=="mesh"&&y!=="ide"&&s.jsxs(wn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:G,onChange:te=>J(te.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:z}),ye.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:ye.map(te=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>J(te),disabled:z,title:te,children:te},te))})]}),v!=="mesh"&&y==="cli"&&s.jsx(bu,{busy:z,savedSessionsLoading:X,savedSessionsError:be,selectedSession:$e,onRefresh:()=>{!b||!P||Y(b.id,P)},onOpenHistory:()=>{!b||!P||(me(!0),xu({hasLoadedInitialResults:fe,isLoading:X})&&Y(b.id,P))},onClearSelection:()=>ue("")}),re&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${re.includes("saved")||re.includes("requested")||re.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:re})]}),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:z,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:bt,disabled:z||(v==="mesh"?!w||!P||y!=="cli"||M:!y||!P||T==="__custom__"&&!oe),children:[s.jsx(Po,{size:14}),z?dt:gt]})]})]})}),Ne&&s.jsx(ea,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:O,directories:Le,busy:ze,error:Je,onClose:()=>je(!1),onNavigate:Qe,onConfirm:te=>{A(te),Ie(te),I("__custom__"),je(!1)}}),ee&&Fe&&s.jsx(ei,{activeConv:Fe,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:Se,isSavedSessionsLoading:X,isResumingSavedSessionId:le,savedHistoryFilters:ie,missingWorkspaceResumePath:oe||null,onSavedHistoryFiltersChange:pe,onClose:()=>me(!1),onNewChat:()=>{ue(""),me(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!b||!P||Y(b.id,P)},onResumeSavedSession:te=>{if(!b||!P||le||!te.canResume)return;const De=Ae(te);ue(te.providerSessionId),Ee(te),B(te.providerSessionId),me(!1),de(!0),R(""),l(b.id,"cli",P,{workspaceId:De.workspaceId,workspacePath:De.workspacePath,resumeSessionId:te.providerSessionId}).then(L=>{if(!L.ok){R(L.error||"Could not resume session");return}r()}).finally(()=>{de(!1),B(L=>L===te.providerSessionId?null:L)})}})]}):null}const Gy=5*60*1e3;function yu(e){var t,r;return((t=e.git)==null?void 0:t.isGitRepo)===!0?!1:!!(e.gitProbePending||((r=e.connection)==null?void 0:r.state)==="connecting")}function qy(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function vu(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function wu(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function Fn(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function Yy(e){return Fn(e)?"degraded":wu(e)?"dirty":"online"}function Xy(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function _l(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 Pa(e){return e.length===0?"unknown":e.reduce((t,r)=>_l(r)>_l(t)?r:t)}function Jy(e){var o,l,c,d,m;const t=new Map,r=new Map;for(const u of e){const h=(l=(o=u.git)==null?void 0:o.branch)==null?void 0:l.trim();h&&(r.set(h,(r.get(h)??0)+1),(c=u.git)!=null&&c.upstream&&t.set(h,(t.get(h)??0)+1))}const n=[...t.entries()].sort((u,h)=>{if(h[1]!==u[1])return h[1]-u[1];const x=["main","master","develop","dev"],S=x.indexOf(u[0]),b=x.indexOf(h[0]);return S!==-1||b!==-1?S===-1?1:b===-1?-1:S-b:u[0].localeCompare(h[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((m=[...r.entries()].sort((u,h)=>h[1]-u[1])[0])==null?void 0:m[0])??null}function Qy(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 Ll(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 Zy(e){return e.reduce((t,r)=>Ll(r.status)>Ll(t.status)?r:t)}function e0(e,t){if(!t||yu(e))return null;const r=e.git,n=(r==null?void 0:r.branch)??null,a=(r==null?void 0:r.upstream)??null,o=(r==null?void 0:r.upstreamStatus)??null,l=(r==null?void 0:r.ahead)??0,c=(r==null?void 0:r.behind)??0,d=vu(r)||wu(r),m=!!(r!=null&&r.hasConflicts)||Fn(r),u={branch:n,defaultBranch:t,upstream:a,upstreamStatus:o,ahead:l,behind:c,dirty:d,hasConflicts:m};return(r==null?void 0:r.isGitRepo)!==!0?{...u,status:"blocked_review",needsConvergence:!0,reason:"git_status_unavailable",nextStep:`Resolve git status for '${e.machineLabel||e.nodeId}' before declaring the mesh converged.`}:n?m||d?{...u,status:"not_mergeable",needsConvergence:!0,reason:r!=null&&r.hasConflicts?"conflicts_present":Fn(r)?"submodule_out_of_sync":"dirty_workspace",nextStep:`Commit, checkpoint, or resolve '${n}' before any convergence step into ${t}.`}:a&&o&&o!=="fresh"?{...u,status:"blocked_review",needsConvergence:!0,reason:"upstream_unverified",nextStep:`Refresh '${n}' against ${a} before claiming the mesh is converged.`}:n===t?l>0||c>0?{...u,status:"blocked_review",needsConvergence:!0,reason:"default_branch_not_even_with_upstream",nextStep:`Bring ${t} even with ${a??"its upstream"} before declaring convergence complete.`}:{...u,status:"merged_to_main",needsConvergence:!1,reason:"clean_default_branch",nextStep:null}:e.isLocalWorktree?{...u,status:"cleanup_candidate",needsConvergence:!0,reason:"clean_non_default_worktree_branch",nextStep:`Run refine / cleanup for '${n}' or explicitly classify the worktree before ending the task.`}:!a||l>0||c>0?{...u,status:"blocked_review",needsConvergence:!0,reason:a?"feature_branch_not_even_with_upstream":"feature_branch_missing_upstream",nextStep:`Push or reconcile '${n}', then merge it into ${t} or mark it blocked with a reason.`}:{...u,status:"pushed_feature_branch_needs_merge",needsConvergence:!0,reason:"clean_non_default_branch",nextStep:`Review and merge '${n}' into ${t}; do not treat it as fully complete while it remains off ${t}.`}:{...u,status:"blocked_review",needsConvergence:!0,reason:"branch_unknown",nextStep:`Inspect '${e.machineLabel||e.nodeId}' and confirm which branch should converge into ${t}.`}}function t0(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function s0(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(yu(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const h=t.health==="online"||t.machineStatus==="online"||((d=t.connection)==null?void 0:d.state)==="connected"||((m=t.connection)==null?void 0:m.state)==="self";return a.push(h?`${o} is online but no peer git snapshot is visible yet.`:`${o} has no peer git snapshot visible yet.`),{snapshotCompleteness:"missing_git",snapshotWarnings:a}}const c=new Set((l.submodules??[]).map(h=>h.path));if(r.size>0){const h=[...r].filter(x=>!c.has(x));h.length>0&&a.push(`${o} is missing submodule visibility for ${h.join(", ")} even though another peer reported it.`)}return((u=t.connection)==null?void 0:u.state)!=="self"&&n!==null&&typeof l.lastCheckedAt=="number"&&n-l.lastCheckedAt>Gy&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(h=>h.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(h=>h.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function ju(e){var D;const r=(typeof e.defaultBranch=="string"&&e.defaultBranch.trim().length>0?e.defaultBranch.trim():null)??Jy(e.nodes),n=qy(e.refreshedAt),a=new Set(e.nodes.flatMap(M=>{var j;return(((j=M.git)==null?void 0:j.submodules)??[]).map(W=>W.path)})),o=[],l=[],c=[],d=new Map;for(const M of e.nodes){const j=M.git,W=(j==null?void 0:j.branch)??null,H=Yy(j),$=vu(j)||H==="dirty",C=Qy(M,r),y=e0(M,r),F=s0({nodeStatus:M,expectedSubmodulePaths:a,refreshedAtMs:n}),P={id:M.nodeId,type:C.length>0?"orphanNode":"worktreeNode",label:M.machineLabel||M.nodeId.slice(0,8),workspace:M.workspace,branch:W,upstream:(j==null?void 0:j.upstream)??null,upstreamStatus:(j==null?void 0:j.upstreamStatus)??null,machineLabel:M.machineLabel||null,health:Pa([M.health,H]),ahead:(j==null?void 0:j.ahead)??0,behind:(j==null?void 0:j.behind)??0,dirty:$,dirtyFiles:Xy(j),hasConflicts:(j==null?void 0:j.hasConflicts)??!1,activeSessionCount:((D=M.activeSessions)==null?void 0:D.length)??0,activeSessions:M.activeSessions??[],providers:M.providers??[],isOrphan:C.length>0,orphanReasons:C,error:M.error,nextStepHint:F.snapshotWarnings[0]??C[0]??(y==null?void 0:y.nextStep)??void 0,parentNodeId:null,submodulePath:null,submoduleCommit:(j==null?void 0:j.headCommit)??null,outOfSync:Fn(j),snapshotCompleteness:F.snapshotCompleteness,snapshotWarnings:F.snapshotWarnings,branchConvergence:y,source:M};if(o.push(P),W){const E=d.get(W)??[];E.push(P.id),d.set(W,E)}for(const E of(j==null?void 0:j.submodules)??[]){const G=`${P.id}::submodule::${E.path}`,J=E.path.split("/").filter(Boolean).pop()||E.path;o.push({id:G,type:"submoduleNode",label:J,workspace:E.repoPath,branch:null,upstream:null,upstreamStatus:null,machineLabel:P.machineLabel,health:t0(E),ahead:0,behind:0,dirty:E.dirty,dirtyFiles:E.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],error:E.error,nextStepHint:E.error||(E.outOfSync?`${E.path} is out of sync with the parent checkout`:E.dirty?`${E.path} has local changes`:`${E.path} is in sync with the parent checkout`),parentNodeId:P.id,submodulePath:E.path,submoduleCommit:E.commit,outOfSync:E.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:P.id,parentWorkspace:M.workspace,submodule:E}}),l.push({id:`${P.id}--${G}`,source:P.id,target:G,type:"submoduleLink",label:E.outOfSync?"submodule out of sync":"submodule"})}}const m=r?`__branch_${r}`:null;if(m&&r){const j=(d.get(r)??[]).map(y=>o.find(F=>F.id===y)).filter(Boolean),W=j.map(y=>y.branchConvergence).filter(Boolean),H=W.length>0?Zy(W):null,$=W.filter(y=>y.needsConvergence).length,C={id:m,type:"defaultBranchNode",label:r,workspace:e.repoIdentity,branch:r,upstream:null,upstreamStatus:null,machineLabel:"default branch",health:Pa(j.map(y=>y.health)),ahead:0,behind:0,dirty:j.some(y=>y.dirty),dirtyFiles:j.reduce((y,F)=>y+F.dirtyFiles,0),hasConflicts:j.some(y=>y.hasConflicts),activeSessionCount:j.reduce((y,F)=>y+F.activeSessionCount,0),activeSessions:j.flatMap(y=>y.activeSessions),providers:[...new Set(j.flatMap(y=>y.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:$>0?`${$} workspace(s) on ${r} still need follow-up`:j.length>0?`${j.length} workspace(s) currently on ${r}`:"No workspaces currently checked out to the default branch",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:H,source:{nodeId:m,machineLabel:r,workspace:e.repoIdentity,health:Pa(j.map(y=>y.health)),providers:[],activeSessions:[]}};o.push(C);for(const y of o)if(!(y.id===m||y.type==="submoduleNode")){if(y.branch===r){l.push({id:`${m}--${y.id}`,source:m,target:y.id,type:"parentBranch",label:"checked out"});continue}if(y.branch){l.push({id:`${m}--${y.id}`,source:m,target:y.id,type:y.isOrphan?"orphanLink":"parentBranch",label:y.branch});continue}y.isOrphan&&l.push({id:`${m}--${y.id}`,source:m,target:y.id,type:"orphanLink",label:"detached"})}}for(const[M,j]of d){if(j.length<2)continue;const W=j.map(H=>o.find($=>$.id===H)).filter(Boolean);W.sort((H,$)=>H.label.localeCompare($.label));for(let H=1;H<W.length;H+=1)l.push({id:`wt_${W[H-1].id}--${W[H].id}`,source:W[H-1].id,target:W[H].id,type:"worktreeLink",label:H===1?`${M} peers`:void 0})}const u=o.filter(M=>M.type!=="defaultBranchNode"),h=u.filter(M=>M.isOrphan).length,x=u.filter(M=>M.hasConflicts).length,S=u.filter(M=>M.health==="offline").length,b=u.filter(M=>M.type==="submoduleNode"&&M.outOfSync).length,p=u.filter(M=>{var j;return M.type!=="submoduleNode"&&((j=M.branchConvergence)==null?void 0:j.needsConvergence)}).length,g=u.filter(M=>{var j;return((j=M.branchConvergence)==null?void 0:j.status)==="blocked_review"}).length,v=u.filter(M=>{var j;return((j=M.branchConvergence)==null?void 0:j.status)==="pushed_feature_branch_needs_merge"}).length,f=u.filter(M=>{var j;return((j=M.branchConvergence)==null?void 0:j.status)==="cleanup_candidate"}).length,T=u.filter(M=>{var j;return((j=M.branchConvergence)==null?void 0:j.status)==="not_mergeable"}).length,I=u.filter(M=>M.snapshotWarnings.length>0).length,k=u.filter(M=>M.snapshotCompleteness==="pending_git").length,A=u.filter(M=>M.snapshotCompleteness==="missing_git").length,_=u.filter(M=>M.snapshotCompleteness==="missing_submodule_report").length,N=u.filter(M=>M.snapshotCompleteness==="stale").length,w=[k>0?`${k} node(s) are still waiting for a live peer git snapshot`:null,A>0?`${A} node(s) have no visible peer git snapshot`:null,_>0?`${_} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,N>0?`${N} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return p>0&&c.push(`${p} workspace(s) still need follow-up before the mesh is converged`),h>0&&c.push(`${h} workspace(s) need attention before safe coordination`),g>0&&c.push(`${g} workspace(s) are blocked on branch convergence or upstream sync`),v>0&&c.push(`${v} clean feature branch workspace(s) still need merge follow-up`),f>0&&c.push(`${f} worktree workspace(s) are ready for refine / cleanup`),T>0&&c.push(`${T} workspace(s) have local changes or conflicts blocking convergence`),x>0&&c.push(`${x} workspace(s) report merge conflicts`),S>0&&c.push(`${S} node(s) are currently offline`),b>0&&c.push(`${b} submodule(s) are out of sync with their parent checkout`),c.push(...w),r||c.push("Could not infer a default branch from live mesh status"),{meshId:e.meshId,meshName:e.meshName,repoIdentity:e.repoIdentity,refreshedAt:e.refreshedAt,nodes:o,edges:l,stats:{totalNodes:u.length,onlineNodes:u.filter(M=>M.health==="online").length,dirtyNodes:u.filter(M=>M.dirty).length,orphanNodes:h,errorNodes:u.filter(M=>!!M.error||M.outOfSync).length,offlineNodes:S,followUpNodes:p,blockedReviewNodes:g,mergeReadyNodes:v,cleanupCandidateNodes:f,notMergeableNodes:T,incompleteSnapshotNodes:I,missingGitSnapshotNodes:A,missingSubmoduleSnapshotNodes:_,staleGitSnapshotNodes:N,totalActiveSessions:u.reduce((M,j)=>M+j.activeSessionCount,0)},warnings:c,snapshotWarnings:w}}function ku(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 Su(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=ku(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 Nu(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function r0(e){var t;return!Nu(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 ln(e){return[...new Set(e.filter(t=>!!t))]}function Cu(e){return e.nodes.filter(t=>t.type!=="submoduleNode")}function n0(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=Cu(e);return t||n.length>0?ln([t==null?void 0:t.id,...n.map(l=>l.id)]):a.length>0?ln(a.map(l=>l.id)):o.length>0?ln(o.map(l=>l.id)):ln(e.nodes.map(l=>l.id))}function a0(e){const t=Cu(e),r=new Set(t.map(o=>o.branch).filter(o=>!!o)).size,n=e.nodes.filter(o=>o.type==="submoduleNode").length,a=t.filter(o=>o.isOrphan).length;return t.length>=6||r>=3||n>=3||a>0}function Iu(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 o0(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${Iu(e)}::${n}x${a}`}const i0={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"},l0={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"},c0={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"},d0={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 tr(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",graphMiniMapClass:"!bottom-4 !right-4 !bg-white/95 !border !border-slate-200 !rounded-xl !shadow-md",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=>l0[t],actionButton:t=>d0[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",graphMiniMapClass:"!bottom-4 !right-4 !bg-slate-950/85 !border !border-white/10 !rounded-xl",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=>i0[t],actionButton:t=>c0[t]}}const Rl=390,Pl=192,Dl=120,u0=36,El=148,m0=24,Tu=i.createContext(tr("dark"));function p0(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=Su(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 qt(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 h0(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 Mu(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 f0(e){return e.replace(/_/g," ")}function x0(e){return!e.upstream||e.upstreamStatus==="fresh"}function b0(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),!x0(e))t.push("upstream unverified");else{const n=ku(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 g0({data:e,selected:t}){const r=i.useContext(Tu),n=e.graphNode,a=n.type==="defaultBranchNode",o=n.type==="submoduleNode",l=r0(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=Su(n),u=b0(n),h=Nu(n);return s.jsxs("div",{className:`${o?"w-[204px]":"w-[220px]"} rounded-2xl border px-3.5 py-3 backdrop-blur-sm transition-all ${p0(n,t,r.isDark)}`,children:[s.jsx(ki,{type:"target",position:Si.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:Mu(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] ${h0(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 ${qt("health",r.isDark)}`,children:f0(n.health)}),o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("submodule",r.isDark)}`,children:"submodule"}),n.branch&&!o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("meta",r.isDark)}`,children:n.branch}),d&&o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("meta",r.isDark)}`,children:d}),n.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("dirty",r.isDark)}`,children:o?"local changes":`${n.dirtyFiles} dirty`}),n.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("conflict",r.isDark)}`,children:"out of sync"}),n.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("conflict",r.isDark)}`,children:"conflicts"}),!o&&n.upstream&&n.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("orphan",r.isDark)}`,children:"upstream unverified"}),n.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("orphan",r.isDark)}`,children:"needs follow-up"})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,children:u}),l&&h&&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:h}),s.jsx(ki,{type:"source",position:Si.Bottom,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const y0={meshNode:g0};function Da(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 v0(e,t=tr("dark")){const r=[...e.nodes].sort(Da),n=r.find(p=>p.type==="defaultBranchNode")??null,a=new Map;for(const p of r){if(p.type!=="submoduleNode"||!p.parentNodeId)continue;const g=a.get(p.parentNodeId)??[];g.push(p),a.set(p.parentNodeId,g)}const o=r.filter(p=>p.id!==(n==null?void 0:n.id)&&p.type!=="submoduleNode"),l=new Map,c=[];for(const p of o){if(p.isOrphan||!p.branch){c.push(p);continue}const g=p.branch,v=l.get(g)??[];v.push(p),l.set(g,v)}const d=[...l.entries()].sort(([p],[g])=>n!=null&&n.branch&&p===n.branch&&g!==n.branch?-1:n!=null&&n.branch&&g===n.branch&&p!==n.branch?1:p.localeCompare(g));c.length>0&&d.push(["__orphans__",[...c].sort(Da)]),d.length===0&&d.push(["__nodes__",[]]);const m=[],u=d.length,h=Math.max(1,u-1)*Rl,x=n?0:80,S=n?Pl:0;n&&m.push({id:n.id,type:"meshNode",position:{x:h/2,y:x},data:{graphNode:n},selected:!1,draggable:!1,selectable:!0}),d.forEach(([p,g],v)=>{const f=v*Rl,T=g.length>0?g:o.length>0?o:[];let I=S;T.forEach(k=>{m.push({id:k.id,type:"meshNode",position:{x:f,y:I},data:{graphNode:k},selected:!1,draggable:!1,selectable:!0});const A=[...a.get(k.id)??[]].sort(Da);if(A.length>0){A.forEach((_,N)=>{m.push({id:_.id,type:"meshNode",position:{x:f+u0,y:I+El+N*Dl},data:{graphNode:_},selected:!1,draggable:!1,selectable:!0})}),I+=El+A.length*Dl+m0;return}I+=Pl}),p==="__nodes__"&&o.length===0&&n&&m.push({id:`${n.id}__placeholder`,type:"meshNode",position:{x:f,y:S},data:{graphNode:{id:`${n.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:e.repoIdentity,branch:n.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:`${n.id}__placeholder`,machineLabel:"",workspace:e.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}},selected:!1,draggable:!1,selectable:!1})});const b=e.edges.map(p=>({id:p.id,source:p.source,target:p.target,label:p.label,type:p.type==="worktreeLink"||p.type==="submoduleLink"?"smoothstep":"bezier",animated:p.type==="orphanLink",markerEnd:{type:ym.ArrowClosed,width:p.type==="submoduleLink"?16:18,height:p.type==="submoduleLink"?16:18,color:$l(p)},style:{stroke:$l(p),strokeWidth:p.type==="orphanLink"?2.25:p.type==="submoduleLink"?1.7:p.type==="worktreeLink"?1.8:2,strokeDasharray:p.type==="orphanLink"?"5 4":p.type==="submoduleLink"?"4 3":void 0},labelStyle:{fill:t.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:t.edgeLabelBackgroundColor,fillOpacity:1,stroke:t.edgeLabelBorderColor},labelBgPadding:[5,3],labelBgBorderRadius:6}));return{nodes:m,edges:b}}function $l(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 w0({data:e,viewportKey:t}){const r=vm(),n=wm(),a=i.useRef(null),o=i.useMemo(()=>Iu(e),[e]),l=i.useMemo(()=>n0(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?.2:.16,maxZoom:m?1.04:.96,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(d)}},[e.nodes.length,l,o,r,n,t]),null}function j0({data:e,selectedNodeId:t=null,onNodeClick:r}){const{theme:n}=er(),a=i.useMemo(()=>tr(n),[n]),o=i.useMemo(()=>v0(e,a),[e,a]),l=i.useMemo(()=>a0(e),[e]),c=i.useRef(null),[d,m]=i.useState({width:0,height:0}),u=i.useMemo(()=>o0(e,d.width,d.height),[e,d.height,d.width]),h=i.useMemo(()=>o.nodes.map(x=>({...x,selected:x.id===t})),[o.nodes,t]);return i.useEffect(()=>{const x=c.current;if(!x)return;const S=()=>{const p=Math.max(0,Math.round(x.clientWidth)),g=Math.max(0,Math.round(x.clientHeight));m(v=>v.width===p&&v.height===g?v:{width:p,height:g})};S();const b=typeof ResizeObserver=="function"?new ResizeObserver(()=>S()):null;return b==null||b.observe(x),window.addEventListener("resize",S),()=>{b==null||b.disconnect(),window.removeEventListener("resize",S)}},[]),s.jsx(Tu.Provider,{value:a,children:s.jsxs("div",{ref:c,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-[420px] w-full min-w-0 min-h-[420px] sm:h-[520px] xl:h-[640px]",children:s.jsxs(hm,{nodes:h,edges:o.edges,nodeTypes:y0,minZoom:.25,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!1,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(x,S)=>r==null?void 0:r(S.data.graphNode),className:"h-full w-full",colorMode:a.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(w0,{data:e,viewportKey:u}),l&&s.jsx(fm,{className:a.graphMiniMapClass,nodeColor:x=>Mu(x.data.graphNode.health)}),s.jsx(xm,{className:a.graphControlsClass,showInteractive:!1}),s.jsx(bm,{variant:gm.Dots,gap:18,size:1.2,color:a.graphBackgroundDotColor})]})})]})})}const Bl=new Set(["pending","assigned"]),k0={pending:0,assigned:0},S0={recentFailures:0},Or=i.createContext(tr("dark"));function Ke({label:e,tone:t="default"}){const r=i.useContext(Or);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 hr({title:e,subtitle:t,children:r,className:n=""}){const a=i.useContext(Or);return s.jsxs("section",{className:`${a.cardClass} ${n}`,children:[s.jsxs("div",{className:a.cardHeaderClass,children:[s.jsx("div",{className:a.cardTitleClass,children:e}),t&&s.jsx("div",{className:a.cardSubtitleClass,children:t})]}),s.jsx("div",{className:"px-4 py-3",children:r})]})}function qe({label:e,value:t}){const r=i.useContext(Or);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 Ht({label:e,onClick:t,tone:r="default"}){const n=i.useContext(Or);return s.jsx("button",{type:"button",onClick:t,className:`rounded-full border px-2.5 py-1 text-[11px] transition ${n.actionButton(r)}`,children:e})}function ps(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function Rs(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleString()}function Ea(e){switch(e){case"completed":return"good";case"failed":case"cancelled":return"danger";case"assigned":return"info";case"pending":return"warn";default:return"default"}}function Ol(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 cn(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 Fl(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 Au(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 $a(e){return e===!0?"yes":e===!1?"no":"unknown"}function Wl(e,t){if(!t)return null;const r=new URLSearchParams;return e&&r.set("daemonId",e),r.set("targetSessionId",t),`/dashboard?${r.toString()}`}function Kl(e){if(e.gitProbePending)return"Git probe pending";const t=e.git;if(!t)return"No git probe";const r=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),n=[];t.branch&&n.push(t.branch),t.upstream&&t.upstreamStatus!=="fresh"&&n.push("upstream unverified"),t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&n.push(`↑${t.ahead??0}/↓${t.behind??0}`),r>0&&n.push(`${r} dirty`);const a=(t.submodules??[]).filter(l=>l.dirty),o=(t.submodules??[]).filter(l=>l.outOfSync||l.error);return a.length>0&&n.push(`${a.length} submodule dirty`),o.length>0&&n.push(`${o.length} submodule drift`),t.hasConflicts&&n.push("conflicts"),n.join(" · ")||"Clean"}function N0(e){switch(e){case"merged_to_main":return"merged to default branch";case"pushed_feature_branch_needs_merge":return"feature branch still needs merge";case"cleanup_candidate":return"worktree still needs refine / cleanup";case"blocked_review":return"review blocked before convergence";case"not_mergeable":return"not mergeable yet";default:return null}}function C0(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 Ba(e){const t=e.assignedNodeId||e.targetNodeId||"unbound",r=e.assignedSessionId||e.targetSessionId||"no session";return`${t} · ${r}`}function dn(e){return e.assignedNodeId||e.targetNodeId||null}function Oa(e){var t;return e.assignedSessionId||e.targetSessionId||((t=e.autoLaunch)==null?void 0:t.sessionId)||null}function Cr(e){return e?e.slice(0,7):null}function I0(e,t){var o,l,c;const r=Cr((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?[Cr(a.commit),a.message].filter(Boolean).join(" · "):null}function T0(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 M0(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 A0(e){return(e.providers??[]).length>0?e.providers.join(", "):((e.providerPriority??[]).length>0,"not reported yet")}function Hl(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":Au(e.connection)}function Ul(e,t){return ps(e)??e??(t?"pending live refresh":"not reported")}function _u({graph:e,status:t,emptyMessage:r="No live mesh graph is available for this coordinator yet.",daemonId:n=null,sendDaemonCommand:a=null}){var Se,ve,X,xe,fe,we,be,Ce,ee,me,ie,pe,le,B,z,de,re;const{theme:o}=er(),l=i.useMemo(()=>tr(o),[o]),c=As(),[d,m]=i.useState(null),[u,h]=i.useState(null),[x,S]=i.useState("active"),[b,p]=i.useState({}),g=i.useMemo(()=>new Map(t.nodes.map(R=>[R.nodeId,R])),[t.nodes]),v=i.useMemo(()=>new Map(e.nodes.map(R=>[R.id,R])),[e.nodes]),f=((Se=t.queue)==null?void 0:Se.tasks)??[],T=((ve=t.queue)==null?void 0:ve.summary)??null,I=(T==null?void 0:T.activeCounts)??k0,k=((X=t.ledger)==null?void 0:X.summary)??S0,A=i.useMemo(()=>C0(t),[t]),_=i.useMemo(()=>{const R=new Map;for(const q of A){const ce=q.session.state||q.session.lifecycle||"unknown";R.set(ce,(R.get(ce)??0)+1)}return[...R.entries()].sort((q,ce)=>ce[1]-q[1])},[A]),N=i.useMemo(()=>x==="all"?f:x==="active"?f.filter(R=>Bl.has(R.status)):f.filter(R=>!Bl.has(R.status)),[x,f]);i.useEffect(()=>{d&&(v.has(d)||(m(null),h(R=>!R||"nodeId"in R&&R.nodeId===d?null:R)))},[v,d]);const w=d?v.get(d)??null:null,D=d?g.get(d)??null:null,M=(u==null?void 0:u.kind)==="queue"?f.find(R=>R.id===u.taskId)??null:null,j=(u==null?void 0:u.kind)==="session"?A.find(R=>R.nodeId===u.nodeId&&R.session.sessionId===u.sessionId)??null:null,W=i.useMemo(()=>A.filter(R=>R.nodeId===d),[d,A]),H=i.useMemo(()=>f.filter(R=>dn(R)===d),[f,d]),$=M0({coordinatorDaemonId:n,selectedNodeStatus:D,selectedSessionEntry:j}),C=($==null?void 0:$.workspace)??null,y=C?b[C]??null:null,F=D!=null&&D.gitProbePending&&!((xe=y==null?void 0:y.entries)!=null&&xe.length)?"Pending live git probe":I0(D,(y==null?void 0:y.entries)??[]),P=i.useCallback(R=>{R&&c(Zt(R),{state:{openRemoteForTabKey:R}})},[c]),E=i.useCallback((R,q)=>{m(R),h({kind:"session",nodeId:R,sessionId:q})},[]),G=i.useCallback(R=>{m(R),h({kind:"node",nodeId:R})},[]);i.useEffect(()=>{if(!$||!a)return;const{daemonId:R,workspace:q}=$,ce=b[q];if(ce!=null&&ce.loading||ce&&(ce.entries.length>0||ce.error))return;let Ne=!1;return p(je=>{var O;return{...je,[q]:{loading:!0,error:null,entries:((O=je[q])==null?void 0:O.entries)??[]}}}),a(R,"git_log",{workspace:q,limit:5}).then(je=>{Ne||p(O=>({...O,[q]:{loading:!1,error:null,entries:T0(je)}}))}).catch(je=>{Ne||p(O=>({...O,[q]:{loading:!1,error:je instanceof Error?je.message:"git_log failed",entries:[]}}))}),()=>{Ne=!0}},[b,$,a]);const J=[...e.warnings??[],...t.nodes.filter(R=>R.machineStatus&&R.machineStatus!=="online").map(R=>`${R.machineLabel}: ${R.machineStatus}`)],ye=e.stats.incompleteSnapshotNodes>0,he=e.stats.followUpNodes>0?`${e.stats.followUpNodes} need follow-up`:ye?"mesh visibility incomplete":"mesh converged",ne=e.stats.followUpNodes>0?"danger":ye?"warn":"good",ue=!!(M||j||w);return s.jsx(Or.Provider,{value:l,children:s.jsxs("div",{className:"flex min-h-0 flex-col gap-4 xl:flex-row",children:[s.jsx("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-4",children:s.jsxs("div",{className:`${l.cardClass} min-h-0 flex-1 rounded-[28px] p-3 sm:p-4`,style:{minHeight:420},children:[s.jsxs("div",{className:`mb-3 flex flex-wrap items-start justify-between gap-3 rounded-2xl px-3.5 py-3 ${l.isDark?"border border-white/10 bg-slate-950/45":"border border-slate-200 bg-white/95 shadow-sm"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-wrap gap-2 text-xs ${l.textSecondary}`,children:[s.jsx(Ke,{label:he,tone:ne}),e.stats.blockedReviewNodes>0&&s.jsx(Ke,{label:`${e.stats.blockedReviewNodes} blocked review`,tone:"danger"}),e.stats.notMergeableNodes>0&&s.jsx(Ke,{label:`${e.stats.notMergeableNodes} not mergeable`,tone:"danger"}),e.stats.mergeReadyNodes>0&&s.jsx(Ke,{label:`${e.stats.mergeReadyNodes} need merge`,tone:"warn"}),e.stats.cleanupCandidateNodes>0&&s.jsx(Ke,{label:`${e.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),e.stats.offlineNodes>0&&s.jsx(Ke,{label:`${e.stats.offlineNodes} offline`,tone:"danger"}),e.stats.incompleteSnapshotNodes>0&&s.jsx(Ke,{label:`${e.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),e.stats.missingGitSnapshotNodes>0&&s.jsx(Ke,{label:`${e.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),e.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Ke,{label:`${e.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),e.stats.staleGitSnapshotNodes>0&&s.jsx(Ke,{label:`${e.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((T==null?void 0:T.active)??0)>0&&s.jsx(Ke,{label:`${(T==null?void 0:T.active)??0} active queue`,tone:"info"}),s.jsx(Ke,{label:`${e.stats.totalNodes} nodes`,tone:"default"}),e.stats.totalActiveSessions>0&&s.jsx(Ke,{label:`${e.stats.totalActiveSessions} active sessions`,tone:"info"})]}),s.jsxs("details",{className:`max-w-full rounded-xl px-3 py-2 text-xs ${l.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 ${l.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(Ke,{label:`${e.stats.dirtyNodes} dirty`,tone:e.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Ke,{label:`${e.stats.orphanNodes} orphan`,tone:e.stats.orphanNodes>0?"warn":"good"}),s.jsx(Ke,{label:`${k.recentFailures} recent failures`,tone:k.recentFailures>0?"danger":"good"}),_.length===0?s.jsx(Ke,{label:"no session metadata"}):_.slice(0,2).map(([R,q])=>s.jsx(Ke,{label:`${q} ${R}`,tone:cn(R)},R))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ke,{label:"Anchor = default branch",tone:"info"}),s.jsx(Ke,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Ke,{label:"Submodule link = child checkout",tone:"warn"})]}),J.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:J.map(R=>s.jsx("span",{className:l.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:R},R))}),s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"Click a node only when you want drill-down details. The graph itself now carries the convergence state."})]})]})]}),e.nodes.length>0?s.jsx(j0,{data:e,selectedNodeId:d,onNodeClick:R=>{if((u==null?void 0:u.kind)==="node"&&d===R.id){m(null),h(null);return}m(R.id),h({kind:"node",nodeId:R.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:r})]})}),ue&&s.jsxs("div",{className:"flex w-full shrink-0 flex-col gap-4 xl:w-[420px]",children:[s.jsx(hr,{title:"Selected detail",subtitle:"Node, session, or queue item drill-down.",children:s.jsx("div",{className:"flex flex-col gap-3",children:(u==null?void 0:u.kind)==="queue"&&M?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(Ke,{label:M.status,tone:Ea(M.status)}),s.jsx(Ke,{label:M.id.slice(0,8),tone:"default"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[dn(M)&&s.jsx(Ht,{label:"View node",onClick:()=>G(dn(M)||"")}),(()=>{const R=Oa(M);if(!R)return null;const q=A.find(ce=>ce.session.sessionId===R)??null;return s.jsxs(s.Fragment,{children:[q&&s.jsx(Ht,{label:"View session",onClick:()=>E(q.nodeId,q.session.sessionId)}),s.jsx(Ht,{label:"Open chat",tone:"info",onClick:()=>P(R)})]})})()]}),s.jsx(qe,{label:"Message",value:M.message}),s.jsx(qe,{label:"Routing",value:Ba(M)}),s.jsx(qe,{label:"Created",value:ps(M.createdAt)??"unknown"}),s.jsx(qe,{label:"Updated",value:ps(M.updatedAt)??"unknown"}),s.jsx(qe,{label:"Requeues",value:M.requeueCount??0}),s.jsx(qe,{label:"Auto-launch",value:M.autoLaunch?`${M.autoLaunch.status}${M.autoLaunch.providerType?` · ${M.autoLaunch.providerType}`:""}`:"none"}),(()=>{var Ne,je,O;const R=M.assignedSessionId||M.targetSessionId||((Ne=M.autoLaunch)==null?void 0:Ne.sessionId)||null,q=M.assignedNodeId||M.targetNodeId||((je=M.autoLaunch)==null?void 0:je.nodeId)||null,ce=Wl(q?(O=g.get(q))==null?void 0:O.daemonId:null,R);return ce?s.jsx("a",{href:ce,className:l.isDark?"inline-flex w-fit items-center rounded-full border border-sky-400/30 bg-sky-500/10 px-3 py-1 text-xs font-medium text-sky-100 transition hover:bg-sky-500/20":"inline-flex w-fit items-center rounded-full border border-sky-300 bg-sky-50 px-3 py-1 text-xs font-medium text-sky-700 transition hover:bg-sky-100",children:"Open linked dashboard chat"}):null})(),M.cancelReason&&s.jsx(qe,{label:"Cancel reason",value:M.cancelReason}),M.requeueReason&&s.jsx(qe,{label:"Requeue reason",value:M.requeueReason})]}):(u==null?void 0:u.kind)==="session"&&j?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(Ke,{label:j.session.state||j.session.lifecycle||"unknown",tone:cn(j.session.state||j.session.lifecycle)}),j.session.providerType&&s.jsx(Ke,{label:j.session.providerType,tone:"info"}),j.session.isCached&&s.jsx(Ke,{label:"cached",tone:"default"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ht,{label:"View node",onClick:()=>G(j.nodeId)}),s.jsx(Ht,{label:"Open chat",tone:"info",onClick:()=>P(j.session.sessionId)})]}),s.jsx(qe,{label:"Session id",value:j.session.sessionId}),s.jsx(qe,{label:"Node",value:j.machineLabel}),s.jsx(qe,{label:"Workspace",value:j.workspace}),s.jsx(qe,{label:"Branch",value:j.branch??"unknown"}),s.jsx(qe,{label:"Node health",value:j.nodeHealth}),s.jsx(qe,{label:"Lifecycle",value:j.session.lifecycle??"unknown"}),j.session.surfaceKind&&s.jsx(qe,{label:"Surface",value:j.session.surfaceKind}),j.session.recoveryState&&s.jsx(qe,{label:"Recovery",value:j.session.recoveryState}),j.session.lastActivityAt&&s.jsx(qe,{label:"Last activity",value:ps(j.session.lastActivityAt)??j.session.lastActivityAt}),(()=>{var q;const R=Wl((q=g.get(j.nodeId))==null?void 0:q.daemonId,j.session.sessionId);return R?s.jsx("a",{href:R,className:l.isDark?"inline-flex w-fit items-center rounded-full border border-sky-400/30 bg-sky-500/10 px-3 py-1 text-xs font-medium text-sky-100 transition hover:bg-sky-500/20":"inline-flex w-fit items-center rounded-full border border-sky-300 bg-sky-50 px-3 py-1 text-xs font-medium text-sky-700 transition hover:bg-sky-100",children:"Open dashboard chat"}):null})(),s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-slate-950/40 p-3":"rounded-xl border border-slate-200 bg-slate-50 p-3",children:[s.jsx("div",{className:`mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Git context"}),s.jsxs("div",{className:`flex flex-col gap-2 text-xs ${l.textSecondary}`,children:[s.jsx("div",{children:F||"HEAD subject not present in cached mesh_status."}),(y==null?void 0:y.loading)&&s.jsx("div",{className:"text-slate-500",children:"Loading recent commits…"}),(y==null?void 0:y.error)&&s.jsxs("div",{className:"text-amber-200",children:["Recent history unavailable: ",y.error]}),((y==null?void 0:y.entries)??[]).slice(0,5).map(R=>s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-2.5 py-2":"rounded-lg border border-slate-200 bg-white px-2.5 py-2",children:[s.jsxs("div",{className:`font-medium ${l.textPrimary}`,children:[Cr(R.commit)," · ",R.message]}),s.jsxs("div",{className:"mt-1 text-[11px] text-slate-500",children:[R.authorName||"unknown author",Rs(R.committedAt)?` · ${Rs(R.committedAt)}`:""]})]},R.commit))]})]})]}):w?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-slate-950/40 p-3":"rounded-xl border border-slate-200 bg-slate-50 p-3",children:[s.jsxs("div",{className:"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 ${l.textPrimary}`,children:w.label}),s.jsx("div",{className:`mt-1 break-all text-xs ${l.textMuted}`,children:(D==null?void 0:D.workspace)??w.workspace})]}),s.jsx("button",{type:"button",onClick:()=>{m(null),h(null)},className:l.isDark?"rounded-full border border-white/10 bg-white/[0.03] px-2 py-1 text-xs text-slate-300 transition hover:bg-white/[0.06] hover:text-white":"rounded-full border border-slate-200 bg-white px-2 py-1 text-xs text-slate-600 transition hover:bg-slate-50 hover:text-slate-900",children:"Close"})]}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[w.branch&&s.jsx(Ke,{label:w.branch,tone:"default"}),((fe=w.branchConvergence)==null?void 0:fe.status)&&s.jsx(Ke,{label:w.branchConvergence.status,tone:w.branchConvergence.needsConvergence?"warn":"good"}),w.snapshotWarnings.length>0&&s.jsx(Ke,{label:`snapshot ${w.snapshotCompleteness}`,tone:"warn"})]}),s.jsxs("div",{className:"mt-3 flex flex-col gap-0.5",children:[s.jsx(qe,{label:"Graph branch",value:w.branch??"unknown"}),s.jsx(qe,{label:"Graph upstream",value:w.upstream??"none"}),s.jsx(qe,{label:"Convergence",value:N0((we=w.branchConvergence)==null?void 0:we.status)??"not classified"})]}),w.snapshotWarnings.length>0&&s.jsxs("div",{className:l.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:"Peer snapshot warning"}),s.jsx("div",{className:"mt-1",children:w.snapshotWarnings[0]})]}),((be=w.branchConvergence)==null?void 0:be.nextStep)&&s.jsxs("div",{className:l.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:"Convergence follow-up"}),s.jsx("div",{className:"mt-1",children:w.branchConvergence.nextStep})]})]}),D&&s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-slate-950/40 p-3":"rounded-xl border border-slate-200 bg-slate-50 p-3",children:[s.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[s.jsx(Ke,{label:D.health,tone:Ol(D.health)}),D.machineStatus&&s.jsx(Ke,{label:D.machineStatus,tone:D.machineStatus==="online"?"good":"warn"}),s.jsx(Ke,{label:`launchReady ${$a(D.launchReady)}`,tone:D.launchReady?"good":"warn"}),s.jsx(Ke,{label:Hl(D),tone:Fl(D.connection)}),D.worktreeBranch&&s.jsx(Ke,{label:D.worktreeBranch,tone:"info"})]}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsx(qe,{label:"Repo root",value:D.repoRoot??D.workspace}),s.jsx(qe,{label:"Provider(s)",value:A0(D)}),s.jsx(qe,{label:"Provider priority",value:(D.providerPriority??[]).join(", ")||"not configured"}),s.jsx(qe,{label:"Drift",value:Kl(D)}),s.jsx(qe,{label:"HEAD",value:F??(D.gitProbePending?"Pending live git probe":"Not available")}),s.jsx(qe,{label:"Daemon",value:D.daemonId??"unknown"}),s.jsx(qe,{label:"Machine",value:D.machineId??D.machineLabel}),s.jsx(qe,{label:"Launch ready",value:$a(D.launchReady)}),s.jsx(qe,{label:"Mesh connection",value:Hl(D)}),s.jsx(qe,{label:"Transport",value:((Ce=D.connection)==null?void 0:Ce.transport)??"unknown"}),s.jsx(qe,{label:"Connection source",value:((ee=D.connection)==null?void 0:ee.source)??"unknown"}),s.jsx(qe,{label:"Last seen",value:Ul(D.lastSeenAt,!!D.gitProbePending)}),s.jsx(qe,{label:"Updated",value:Ul(D.updatedAt,!!D.gitProbePending)}),((me=D.connection)==null?void 0:me.lastConnectedAt)&&s.jsx(qe,{label:"Last connected",value:ps(D.connection.lastConnectedAt)??D.connection.lastConnectedAt}),((ie=D.connection)==null?void 0:ie.lastCommandAt)&&s.jsx(qe,{label:"Last mesh command",value:ps(D.connection.lastCommandAt)??D.connection.lastCommandAt}),((pe=D.connection)==null?void 0:pe.reason)&&s.jsx(qe,{label:"Connection reason",value:D.connection.reason}),s.jsx(qe,{label:"Sessions",value:D.activeSessions.length}),D.error&&s.jsx(qe,{label:"Error",value:D.error})]}),W.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Active sessions"}),s.jsx("div",{className:"flex flex-col gap-2",children:W.map(R=>{const q=R.session.state||R.session.lifecycle||"unknown";return s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",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:`truncate font-medium ${l.textPrimary}`,children:R.session.title||R.session.sessionId}),s.jsxs("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:[R.session.providerType||"unknown provider"," · ",q]})]}),s.jsx(Ke,{label:q,tone:cn(q)})]}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[s.jsx(Ht,{label:"View session",onClick:()=>E(R.nodeId,R.session.sessionId)}),s.jsx(Ht,{label:"Open chat",tone:"info",onClick:()=>P(R.session.sessionId)})]})]},`${R.nodeId}:${R.session.sessionId}`)})})]}),H.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Related queue items"}),s.jsx("div",{className:"flex flex-col gap-2",children:H.map(R=>{const q=Oa(R),ce=q?A.find(Ne=>Ne.session.sessionId===q)??null:null;return s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",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:`truncate font-medium ${l.textPrimary}`,children:R.message}),s.jsx("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:Ba(R)})]}),s.jsx(Ke,{label:R.status,tone:Ea(R.status)})]}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[s.jsx(Ht,{label:"View queue detail",onClick:()=>h({kind:"queue",taskId:R.id})}),ce&&s.jsx(Ht,{label:"View session",onClick:()=>E(ce.nodeId,ce.session.sessionId)}),q&&s.jsx(Ht,{label:"Open chat",tone:"info",onClick:()=>P(q)})]})]},R.id)})})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Recent commits"}),s.jsxs("div",{className:"flex flex-col gap-2",children:[(y==null?void 0:y.loading)&&s.jsx("div",{className:(l.isDark,"text-xs text-slate-500"),children:"Loading recent commits…"}),(y==null?void 0:y.error)&&s.jsxs("div",{className:"text-xs text-amber-200",children:["Recent history unavailable: ",y.error]}),!(y!=null&&y.loading)&&!(y!=null&&y.error)&&((y==null?void 0:y.entries)??[]).length===0&&s.jsx("div",{className:(l.isDark,"text-xs text-slate-500"),children:"Recent commit history not available from the current mesh snapshot yet."}),((y==null?void 0:y.entries)??[]).slice(0,5).map(R=>s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",children:[s.jsxs("div",{className:`font-medium ${l.textPrimary}`,children:[Cr(R.commit)," · ",R.message]}),s.jsxs("div",{className:"mt-1 text-[11px] text-slate-500",children:[R.authorName||"unknown author",Rs(R.committedAt)?` · ${Rs(R.committedAt)}`:""]})]},R.commit))]})]}),(((B=(le=D.git)==null?void 0:le.submodules)==null?void 0:B.length)??0)>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Submodules"}),s.jsx("div",{className:"flex flex-col gap-2",children:(((z=D.git)==null?void 0:z.submodules)??[]).map(R=>s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"font-medium",children:R.path}),R.dirty&&s.jsx(Ke,{label:"dirty",tone:"warn"}),(R.outOfSync||R.error)&&s.jsx(Ke,{label:"drift",tone:"danger"})]}),s.jsx("div",{className:"mt-1 break-all text-[11px] text-slate-400",children:R.repoPath}),s.jsx("div",{className:"mt-1 text-[11px] text-slate-500",children:"Select the submodule node in the graph for its own HEAD and recent history."}),R.error&&s.jsx("div",{className:"mt-1 text-[11px] text-rose-200",children:R.error})]},`${D.nodeId}:${R.path}`))})]})]}),!D&&s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-slate-950/40 p-3":"rounded-xl border border-slate-200 bg-slate-50 p-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Git context"}),s.jsx("div",{className:"text-xs text-slate-300",children:F??"No daemon-owned node status is attached to this graph node."}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Recent commits"}),s.jsxs("div",{className:"flex flex-col gap-2",children:[(y==null?void 0:y.loading)&&s.jsx("div",{className:(l.isDark,"text-xs text-slate-500"),children:"Loading recent commits…"}),(y==null?void 0:y.error)&&s.jsxs("div",{className:"text-xs text-amber-200",children:["Recent history unavailable: ",y.error]}),!(y!=null&&y.loading)&&!(y!=null&&y.error)&&((y==null?void 0:y.entries)??[]).length===0&&s.jsx("div",{className:(l.isDark,"text-xs text-slate-500"),children:"Recent commit history not available for this detached graph node yet."}),((y==null?void 0:y.entries)??[]).slice(0,5).map(R=>s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",children:[s.jsxs("div",{className:`font-medium ${l.textPrimary}`,children:[Cr(R.commit)," · ",R.message]}),s.jsxs("div",{className:"mt-1 text-[11px] text-slate-500",children:[R.authorName||"unknown author",Rs(R.committedAt)?` · ${Rs(R.committedAt)}`:""]})]},R.commit))]})]})]})]}):s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"Select a node, session, or queue item."})})}),s.jsxs(hr,{title:"Queue",subtitle:"Active work plus recent history from mesh_status.",children:[s.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:["active","history","all"].map(R=>s.jsx("button",{type:"button",onClick:()=>S(R),className:`rounded-full border px-3 py-1 text-xs transition ${x===R?l.isDark?"border-sky-400/30 bg-sky-500/10 text-sky-100":"border-sky-300 bg-sky-50 text-sky-700":l.isDark?"border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.06]":"border-slate-200 bg-white text-slate-600 hover:bg-slate-50"}`,children:R},R))}),s.jsxs("div",{className:"mb-3 grid grid-cols-2 gap-2 text-xs sm:grid-cols-4 xl:grid-cols-2",children:[s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-600",children:["Active ",s.jsx("span",{className:`ml-1 ${l.textPrimary}`,children:(T==null?void 0:T.active)??0})]}),s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-600",children:["Pending ",s.jsx("span",{className:`ml-1 ${l.textPrimary}`,children:I.pending})]}),s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-600",children:["Assigned ",s.jsx("span",{className:`ml-1 ${l.textPrimary}`,children:I.assigned})]}),s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-600",children:["History ",s.jsx("span",{className:`ml-1 ${l.textPrimary}`,children:(T==null?void 0:T.historical)??0})]})]}),s.jsx("div",{className:"max-h-[24vh] overflow-y-auto pr-1",children:N.length===0?s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"No queue items for this filter."}):s.jsx("div",{className:"flex flex-col gap-2",children:N.map(R=>{const q=Oa(R),ce=q?A.find(je=>je.session.sessionId===q)??null:null,Ne=dn(R);return s.jsxs("button",{type:"button",onClick:()=>h({kind:"queue",taskId:R.id}),className:`rounded-xl border px-3 py-2 text-left transition ${(u==null?void 0:u.kind)==="queue"&&u.taskId===R.id?l.isDark?"border-sky-400/30 bg-sky-500/10":"border-sky-300 bg-sky-50":l.isDark?"border-white/10 bg-white/[0.03] hover:bg-white/[0.06]":"border-slate-200 bg-white hover:bg-slate-50"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-xs font-medium ${l.textPrimary}`,children:R.message}),s.jsx("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:Ba(R)})]}),s.jsx(Ke,{label:R.status,tone:Ea(R.status)})]}),(Ne||ce||q)&&s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[Ne&&s.jsx("button",{type:"button",onClick:je=>{je.stopPropagation(),G(Ne)},className:l.isDark?"text-[11px] text-slate-300 underline underline-offset-2 transition hover:text-white":"text-[11px] text-slate-600 underline underline-offset-2 transition hover:text-slate-900",children:"View node"}),ce&&s.jsx("button",{type:"button",onClick:je=>{je.stopPropagation(),E(ce.nodeId,ce.session.sessionId)},className:l.isDark?"text-[11px] text-slate-300 underline underline-offset-2 transition hover:text-white":"text-[11px] text-slate-600 underline underline-offset-2 transition hover:text-slate-900",children:"View session"}),q&&s.jsx("button",{type:"button",onClick:je=>{je.stopPropagation(),P(q)},className:l.isDark?"text-[11px] text-sky-200 underline underline-offset-2 transition hover:text-white":"text-[11px] text-sky-700 underline underline-offset-2 transition hover:text-sky-900",children:"Open chat"})]})]},R.id)})})})]}),s.jsx(hr,{title:"Sessions",subtitle:"Node-level active session roster.",children:s.jsx("div",{className:"max-h-[22vh] overflow-y-auto pr-1",children:A.length===0?s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"No active session metadata in this mesh snapshot."}):s.jsx("div",{className:"flex flex-col gap-2",children:A.map(R=>{const q=R.session.state||R.session.lifecycle||"unknown";return s.jsx("button",{type:"button",onClick:()=>{m(R.nodeId),h({kind:"session",nodeId:R.nodeId,sessionId:R.session.sessionId})},className:`rounded-xl border px-3 py-2 text-left transition ${(u==null?void 0:u.kind)==="session"&&u.nodeId===R.nodeId&&u.sessionId===R.session.sessionId?l.isDark?"border-sky-400/30 bg-sky-500/10":"border-sky-300 bg-sky-50":l.isDark?"border-white/10 bg-white/[0.03] hover:bg-white/[0.06]":"border-slate-200 bg-white hover:bg-slate-50"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-xs font-medium ${l.textPrimary}`,children:R.machineLabel}),s.jsxs("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:[R.session.title||R.session.providerType||"unknown provider"," · ",R.branch||"no branch"]})]}),s.jsxs("div",{className:"flex flex-col items-end gap-1",children:[s.jsx(Ke,{label:q,tone:cn(q)}),s.jsx("button",{type:"button",onClick:ce=>{ce.stopPropagation(),P(R.session.sessionId)},className:l.isDark?"text-[11px] text-sky-200 underline underline-offset-2 transition hover:text-white":"text-[11px] text-sky-700 underline underline-offset-2 transition hover:text-sky-900",children:"Open chat"})]})]})},`${R.nodeId}:${R.session.sessionId}`)})})})}),s.jsx(hr,{title:"Nodes",subtitle:"Health, branch, drift, and provider view per node.",children:s.jsx("div",{className:"max-h-[22vh] overflow-y-auto pr-1",children:s.jsx("div",{className:"flex flex-col gap-2",children:t.nodes.map(R=>s.jsx("button",{type:"button",onClick:()=>{m(R.nodeId),h({kind:"node",nodeId:R.nodeId})},className:`rounded-xl border px-3 py-2 text-left transition ${(u==null?void 0:u.kind)==="node"&&u.nodeId===R.nodeId?l.isDark?"border-sky-400/30 bg-sky-500/10":"border-sky-300 bg-sky-50":l.isDark?"border-white/10 bg-white/[0.03] hover:bg-white/[0.06]":"border-slate-200 bg-white hover:bg-slate-50"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-xs font-medium ${l.textPrimary}`,children:R.machineLabel}),s.jsx("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:Kl(R)}),s.jsx("div",{className:(l.isDark,"mt-1 truncate text-[11px] text-slate-500"),children:(R.providers??[]).join(", ")||"no provider metadata"}),s.jsxs("div",{className:"mt-1 flex flex-wrap gap-1",children:[s.jsx(Ke,{label:`launchReady ${$a(R.launchReady)}`,tone:R.launchReady?"good":"warn"}),s.jsx(Ke,{label:Au(R.connection),tone:Fl(R.connection)})]})]}),s.jsxs("div",{className:"flex flex-col items-end gap-1",children:[s.jsx(Ke,{label:R.health,tone:Ol(R.health)}),R.machineStatus&&s.jsx(Ke,{label:R.machineStatus,tone:R.machineStatus==="online"?"good":"warn"}),R.activeSessions.length>0&&s.jsx(Ke,{label:`${R.activeSessions.length} sessions`,tone:"info"})]})]})},R.nodeId))})})}),s.jsx(hr,{title:"Recent mesh events",subtitle:"Read-only ledger tail from mesh_status.",children:s.jsx("div",{className:"max-h-[18vh] overflow-y-auto pr-1",children:(((de=t.ledger)==null?void 0:de.entries)??[]).length===0?s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"No recent ledger entries."}):s.jsx("div",{className:"flex flex-col gap-2",children:(((re=t.ledger)==null?void 0:re.entries)??[]).map(R=>s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("span",{className:`font-medium ${l.textPrimary}`,children:R.kind}),s.jsx("span",{className:(l.isDark,"text-[11px] text-slate-500"),children:ps(R.timestamp)??R.timestamp})]}),s.jsx("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:R.nodeId||R.sessionId||R.providerType||"mesh-wide event"})]},R.id))})})})]})]})})}function kt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Re(...e){for(const t of e){if(typeof t!="string")continue;const r=t.trim();if(r)return r}}function $t(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function Dt(...e){for(const t of e)if(typeof t=="boolean")return t}function Fa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function _0(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 L0(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=kt(n),o=Re(a.path),l=Re(a.commit),c=Re(a.repoPath,a.repo_root)??_0(t,o);return!o||!l||!c?null:{path:o,commit:l,repoPath:c,dirty:Dt(a.dirty)??!1,outOfSync:Dt(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:$t(a.lastCheckedAt,a.last_checked_at)??Date.now(),...Re(a.error)?{error:Re(a.error)}:{}}}).filter(n=>n!==null);return r.length>0?r:void 0}function ko(e,t,r){const n=Dt(e.isGitRepo);if(!Object.keys(e).length||n===void 0)return;const a=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(h=>typeof h=="string"):[],o=$t(e.conflicts)??a.length,l=Dt(e.hasConflicts)??o>0,c=Re(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,d=L0(e.submodules,c),m=Re(e.upstreamStatus,e.upstream_status),u=Re(e.error);return{workspace:Re(e.workspace,t.workspace)||"",repoRoot:c??null,isGitRepo:n,branch:Re(e.branch)??null,headCommit:Re(e.headCommit)??null,headMessage:Re(e.headMessage)??null,upstream:Re(e.upstream)??null,upstreamStatus:m??"unchecked",ahead:$t(e.ahead)??0,behind:$t(e.behind)??0,staged:$t(e.staged)??0,modified:$t(e.modified)??0,untracked:$t(e.untracked)??0,deleted:$t(e.deleted)??0,renamed:$t(e.renamed)??0,hasConflicts:l,conflictFiles:a,stashCount:$t(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??$t(e.lastCheckedAt,e.last_checked_at)??Date.now(),...d?{submodules:d}:{},...u?{error:u}:{}}}function R0(e){const t=kt(e.lastGit??e.last_git),r=kt(t.result),n=kt(t.status),a=kt(r.status),o=kt(e.lastProbe??e.last_probe),l=kt(o.git),c=kt(l.result),d=kt(l.status),m=kt(c.status),u=Object.keys(n).length?n:Object.keys(a).length?a:Object.keys(d).length?d:Object.keys(m).length?m:{};return ko(u,e,{lastCheckedAt:Date.now()})}function P0(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 D0(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 zl(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=P0(e);return t.outOfSync?"degraded":t.dirty||D0(e)?"dirty":"online"}function E0(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=kt(o),c=Re(l.sessionId,l.session_id,l.id);return c?{sessionId:c,...Re(l.providerType,l.provider)?{providerType:Re(l.providerType,l.provider)}:{},...Re(l.state,l.status)?{state:Re(l.state,l.status)}:{},...Re(l.lifecycle)?{lifecycle:Re(l.lifecycle)}:{},...Re(l.surfaceKind,l.surface_kind)?{surfaceKind:Re(l.surfaceKind,l.surface_kind)}:{},...Re(l.recoveryState,l.recovery_state)?{recoveryState:Re(l.recoveryState,l.recovery_state)}:{},...Re(l.workspace)?{workspace:Re(l.workspace)}:{},...Re(l.title)?{title:Re(l.title)}:{},...Re(l.lastActivityAt,l.last_activity_at)?{lastActivityAt:Re(l.lastActivityAt,l.last_activity_at)}:{},...Dt(l.isCached,l.is_cached)!==void 0?{isCached:Dt(l.isCached,l.is_cached)}:{}}:null}).filter(o=>o!==null);if(a.length>0)return a}const r=kt(e.activeSession??e.active_session),n=Re(r.id,r.sessionId,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id);if(n)return[{sessionId:n,...Re(r.providerType,r.provider)?{providerType:Re(r.providerType,r.provider)}:{},...Re(r.state,r.status)?{state:Re(r.state,r.status)}:{}}]}function Vl(e){const t=kt(e.connection);return Object.keys(t).length>0?t:void 0}function $0(e){const t=kt(e),r=Re(t.nodeId,t.id);if(!r)return null;const n=kt(t.cachedStatus),a=R0(t),o=a?void 0:ko(kt(t.git),t),l=a??o,c=l?void 0:ko(kt(n.git),t),d=l??c,m=Re(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),u=a?zl(d):Re(t.health)||(d?zl(d):void 0)||Re(n.health)||m||Re(t.status)||"unknown",x=(a?void 0:Re(t.error))??(l?void 0:Re(n.error)),S=E0(t),b=Fa(t.activeSessions),p=(S==null?void 0:S.map(v=>v.sessionId))??[],g=Fa(t.providerPriority);return{nodeId:r,machineLabel:Re(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:Re(t.workspace,d==null?void 0:d.workspace)||"",...Re(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:Re(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},...Re(t.daemonId,t.daemon_id)?{daemonId:Re(t.daemonId,t.daemon_id)}:{},...Re(t.machineId,t.machine_id)?{machineId:Re(t.machineId,t.machine_id)}:{},...m?{machineStatus:m}:{},...Dt(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Dt(t.isLocalWorktree,t.is_local_worktree)}:{},...Re(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:Re(t.worktreeBranch,t.worktree_branch)}:{},health:u,...d?{git:d}:{},...Dt(t.gitProbePending,t.git_probe_pending)!==void 0?{gitProbePending:Dt(t.gitProbePending,t.git_probe_pending)}:{},providers:Fa(t.providers),activeSessions:b.length>0?b:p,...S&&S.length>0?{activeSessionDetails:S}:{},...g.length>0?{providerPriority:g}:{},...Dt(t.launchReady)!==void 0?{launchReady:Dt(t.launchReady)}:{},...Re(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:Re(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},...Re(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:Re(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...Vl(t)?{connection:Vl(t)}:{},...x?{error:x}:{}}}function B0(e){const t=Re(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(c=>$0(c)).filter(c=>c!==null):null;if(!t||!n)return null;const a=Re(e.meshName,e.mesh_name,e.name),o=Re(e.repoIdentity,e.repo_identity),l=Re(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!a||!o||!l?null:{...e,meshId:t,meshName:a,repoIdentity:o,refreshedAt:l,nodes:n}}function Lu(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];for(const n of r){const a=B0(kt(n));if(a)return a}return null}function O0({activeConv:e,sendDaemonCommand:t,onClose:r}){var A;const n=typeof((A=e.settings)==null?void 0:A.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null,a=e.daemonId??null,o=Vd(),{theme:l}=er(),c=i.useMemo(()=>tr(l),[l]),[d,m]=i.useState(null),[u,h]=i.useState(null),[x,S]=i.useState(!1),[b,p]=i.useState(null),[g,v]=i.useState(null),f=i.useCallback(async()=>{if(!a||!n){p("This coordinator does not expose a live mesh id."),m(null),h(null);return}S(!0),p(null);try{const _=o!=null&&o.loadMeshStatus?await o.loadMeshStatus(a,n):await t(a,"mesh_status",{meshId:n}),N=Lu(_);if(!N){m(null),h(null),p("mesh_status returned an unexpected payload.");return}const w=ju(N);h(N),m(w),v(N.refreshedAt||new Date().toISOString())}catch(_){m(null),h(null),p(_ instanceof Error?_.message:"Failed to load live mesh status")}finally{S(!1)}},[a,n,o,t]);i.useEffect(()=>{f()},[f]),i.useEffect(()=>{const _=N=>{N.key==="Escape"&&r()};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[r]);const T=(d==null?void 0:d.meshName)||(u==null?void 0:u.meshName)||n||"Repo Mesh",I=g?new Date(g).toLocaleTimeString():null,k=i.useMemo(()=>x?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[x]);return s.jsx("div",{className:c.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:c.dialogShellClass,onClick:_=>_.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(as,{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:T}),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:[I&&s.jsxs("span",{className:c.dialogRefreshedChipClass,children:["Refreshed ",I]}),s.jsx("button",{type:"button",onClick:f,disabled:x,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:x?"Refreshing…":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:c.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:s.jsx(wt,{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&&u?s.jsx(_u,{graph:d,status:u,emptyMessage:k,daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:c.dialogEmptyClass,children:k})})]})})}function F0(e,t){const{sendCommand:r}=jt(),[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 Ru=5e3;function K0(e){return`git:${e}`}function H0({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Ru}){return{type:"subscribe",topic:"workspace.git",key:K0(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function mi(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 U0(e){const t=mi(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 z0(e){const t=mi(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 Wa(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"&&Wa(t.binary)&&Wa(t.truncated)&&Wa(t.staged)}function G0(e){const t=mi(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 q0({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Ru}){const{sendCommand:o,sendData:l}=jt(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[m,u]=i.useState(null),[h,x]=i.useState(null),[S,b]=i.useState(!1),[p,g]=i.useState(null),v=i.useCallback(async()=>{if(!(!d||!e||!c)){b(!0),g(null);try{const T=U0(await o(e,"git_status",{workspace:c}));if(T.error){u(null),x(null),g(T.error);return}if(u(T.status),!n){x(null);return}const I=z0(await o(e,"git_diff_summary",{workspace:c}));if(I.error){x(null),g(I.error);return}x(I.diffSummary)}catch(T){g(Ms(T,"Git status request failed"))}finally{b(!1)}}},[d,e,n,o,c]),f=i.useMemo(()=>c?H0({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return i.useEffect(()=>{if(!d||!e||!c||!f){u(null),x(null),b(!1),g(null);return}const T=l?Qt.subscribe({sendData:l},e,f,I=>{var k,A;I.workspace===c&&(u(I.status),x(I.diffSummary??null),g(((k=I.status)==null?void 0:k.error)||((A=I.diffSummary)==null?void 0:A.error)||null),b(!1))},{retryIntervalMs:1e3}):null;return v(),()=>{T==null||T()}},[d,e,v,f,l,c]),{status:m,diffSummary:h,loading:S,error:p,refresh:v}}const Y0={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},X0={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 Gl(e){return e.split("/").pop()??e}function J0(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function Q0({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=Y0[o.status]??"?",d=X0[o.status]??"text-zinc-400",m=J0(o.path),u=Gl(o.path),h=o.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${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:["← ",Gl(o.oldPath)]}),h]}),!o.binary&&(o.insertions>0||o.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",o.insertions]}),o.insertions>0&&o.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),o.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",o.deletions]})]}),o.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${o.path}-${o.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function Z0(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 ev({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
+ `);return s.jsxs("div",{ref:l,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((d,m)=>Z0(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 tv(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
+ `)}function Pu({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=jt(),{status:a,diffSummary:o,loading:l,error:c,refresh:d}=q0({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=i.useState(null),[h,x]=i.useState(null),[S,b]=i.useState(""),[p,g]=i.useState(!1),[v,f]=i.useState(!1),[T,I]=i.useState(null),[k,A]=i.useState(null),{githubUrl:_}=F0(e,t),N=i.useCallback(async H=>{if(!((m==null?void 0:m.path)===H.path&&!m.loading)){u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const $=await n(e,"git_diff_file",{workspace:t,path:H.path,staged:H.staged}),C=G0($);if(C.error||!C.diff){u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C.error??"Failed to load diff"});return}u({path:H.path,diff:C.diff.diff,binary:C.diff.binary??!1,truncated:C.diff.truncated??!1,loading:!1,error:null})}catch($){const C=$ instanceof Error?$.message:"Failed to load diff";u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C})}}},[e,n,m,t]),w=i.useCallback(H=>{b(""),g(!1),I(null),A(null),x(H)},[]),D=i.useCallback(()=>{x(null),I(null),f(!1)},[]),M=i.useCallback(async()=>{var H,$,C;if(h){f(!0),I(null);try{let y;h==="checkpoint"?y=await n(e,"git_checkpoint",{workspace:t,message:S,includeUntracked:p}):h==="stash"?y=await n(e,"git_stash_push",{workspace:t,message:S,includeUntracked:p}):h==="stash_pop"?y=await n(e,"git_stash_pop",{workspace:t}):h==="checkout_files"&&m&&(y=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const F=(y==null?void 0:y.result)??y;if((F==null?void 0:F.success)===!1||F!=null&&F.error){I((F==null?void 0:F.error)??"Action failed"),f(!1);return}h==="checkpoint"?A(`Checkpoint created: ${(($=(H=F==null?void 0:F.checkpoint)==null?void 0:H.commit)==null?void 0:$.slice(0,7))??"done"}`):h==="stash"?A(`Stashed as ${((C=F==null?void 0:F.stash)==null?void 0:C.stashRef)??"stash@{0}"}`):h==="stash_pop"?A("Stash restored"):(A("File reverted"),u(null)),x(null),await d()}catch(y){I(y instanceof Error?y.message:"Action failed")}finally{f(!1)}}},[h,n,e,t,S,p,m,d]),j=!!(a!=null&&a.hasConflicts),W=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:H=>{H.target===H.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}),_&&s.jsx("a",{href:`${_}/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(wt,{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"}),W===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(Q0,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:N}),!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(ev,{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"})})]}),k&&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:k}),s.jsx("button",{onClick:()=>A(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:()=>w("checkpoint"),disabled:j,title:j?"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:()=>w("stash"),disabled:j,title:j?"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:()=>w("stash_pop"),disabled:j||!(a!=null&&a.stashCount),title:j?"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:()=>w("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 H=tv((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(H),A("Copied to clipboard"),setTimeout(()=>A(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),h&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[h==="checkpoint"&&"Create checkpoint commit",h==="stash"&&"Stash changes",h==="stash_pop"&&"Restore latest stash?",h==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(h==="checkpoint"||h==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:S,onChange:H=>b(H.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:p,onChange:H=>g(H.target.checked)}),"Include untracked files"]})]}),T&&s.jsx("p",{className:"text-xs text-red-400",children:T}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:D,disabled:v,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:M,disabled:v||(h==="checkpoint"||h==="stash")&&!S.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:v?"Working…":"Confirm"})]})]})})]})})}function sv({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),[h,x]=i.useState(!1),[S,b]=i.useState("quickstart"),[p,g]=i.useState("workspace"),v=i.useMemo(()=>!t&&!e,[t,e]),f=i.useCallback(N=>{a(N),N&&l(!1)},[]),T=i.useCallback(N=>{l(N),N&&a(!1)},[]),I=i.useCallback(()=>{b(r===0?"quickstart":"shortcuts"),g("workspace"),d(!0),a(!1),l(!1)},[r]),k=i.useCallback(()=>{d(!1)},[]),A=i.useCallback(()=>{u(!0)},[]),_=i.useCallback(()=>{u(!1)},[]);return i.useEffect(()=>{if(!v){x(!1);return}x(!0);const N=window.setTimeout(()=>{x(!1)},1e4);return()=>window.clearTimeout(N)},[v]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:m,guideNudgeVisible:h,guideTab:S,shortcutSection:p,isDesktopDashboard:v,setGuideTab:b,setShortcutSection:g,handleInboxOpenChange:f,handleHiddenOpenChange:T,handleOpenShortcutHelp:I,closeShortcutHelp:k,openNewSession:A,closeNewSession:_}}function rv(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 nv(e){return e instanceof Error?e.message:String(e||"")}function av(e){const t=nv(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function ov({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:l,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:h,ides:x,actionLogs:S,sendDaemonCommand:b,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:v,initialDataLoaded:f,userName:T,requestedMobileTabKey:I,onRequestedMobileTabConsumed:k,requestedMachineId:A,onRequestedMachineConsumed:_,requestedMobileSection:N,onRequestedMobileSectionConsumed:w,containerRef:D,isSplitMode:M,numGroups:j,groupSizes:W,groupedConvs:H,clearedTabs:$,focusedGroup:C,focusGroup:y,moveTabToGroup:F,splitTabRelative:P,closeGroup:E,handleResizeStart:G,groupActiveTabIds:J,setGroupActiveTab:ye,groupTabOrders:he,setGroupTabOrder:ne,toggleHiddenTab:ue,visibleConversations:Se,requestedDesktopTabKey:ve,onRequestedDesktopTabConsumed:X,onDesktopActiveTabChange:xe,onRequestScrollToBottom:fe,onHideConversation:we,onShowHiddenConversation:be,onShowAllHiddenConversations:Ce,scrollToBottomRequest:ee,machineEntries:me,layoutProfile:ie,onBrowseMachineDirectory:pe,onSaveMachineWorkspace:le,onLaunchMachineIde:B,onLaunchMachineProvider:z,onListMachineMeshes:de,onLaunchMeshCoordinator:re,onListMachineSavedSessions:R,notifications:q,notificationUnreadCount:ce,liveSessionInboxState:Ne,onMarkNotificationRead:je,onMarkNotificationUnread:O,onDeleteNotification:Ie}){const Le=Nt.useRef(null),{inboxOpen:He,hiddenOpen:ze,shortcutHelpOpen:Xe,newSessionOpen:Je,guideNudgeVisible:rt,guideTab:pt,shortcutSection:xt,isDesktopDashboard:vt,setGuideTab:Te,setShortcutSection:Ve,handleInboxOpenChange:tt,handleHiddenOpenChange:Ge,handleOpenShortcutHelp:ot,closeShortcutHelp:U,openNewSession:V,closeNewSession:Z}=sv({isMobile:t,showMobileChatMode:e,visibleConversationCount:Se.length}),[ae,K]=Nt.useState(null),[Y,se]=Nt.useState(null),oe=Nt.useCallback((L,Q)=>{K({daemonId:L,workspace:Q})},[]),ke=Nt.useCallback(L=>{se(L)},[]),Pe=Nt.useCallback(L=>{var Q;Tr.flushSync(()=>{be(L)}),(Q=Le.current)==null||Q.restoreHiddenTabToSavedLocation(L.tabKey)},[be]),Ee=Nt.useCallback(L=>{var ge;const Q=u.find(Be=>uo(Be,L))||h.find(Be=>uo(Be,L));Q&&(h.some(Be=>Be.tabKey===Q.tabKey)&&Pe(Q),xe(Q.tabKey),(ge=Le.current)==null||ge.activateConversationTab(Q.tabKey),fe(Q.tabKey,"notification-open")),je(L.id),tt(!1)},[Pe,h,u,xe,je,fe]),Ae=Nt.useCallback(()=>{var Q;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Q=Le.current)==null||Q.resetAllPanelsToMain(),Ge(!1))},[Ge]),$e=Nt.useCallback(async L=>{var Oe;if(!r)return;const Q=(Oe=r.modalButtons)==null?void 0:Oe[L];if(!Q)return;const ge=Gs(r);if(!ge)return;const Be=Q.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),_e=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Be);try{await b(ge,"resolve_action",{button:Q,action:_e?"approve":"reject",buttonIndex:L,...xs(r)})}catch(nt){av(nt)||console.error("[Shortcut approval] Failed:",nt)}},[r,b]),{isMac:Fe,actionDefinitions:Me,actionShortcuts:Qe,shortcutListening:et,shortcutListeningDraft:bt,setShortcutListening:gt,setShortcutListeningDraft:dt,saveShortcuts:ht}=Iy({enabled:vt&&!Xe,onTrigger:L=>{var Q,ge,Be,_e,Oe,nt,Mt,ft,ss,Fr,Wr,Kr,Hr,Ur,zr,Vr;if(L==="openShortcutHelp"){ot();return}if(L==="openNewSession"){V();return}if(L==="hideCurrentTab"){r&&we(r);return}if(L==="toggleHiddenTabs"){Ge(!ze);return}if(L==="openHistoryForActiveTab"){r&&!st(r)&&o(r);return}if(L==="openRemoteForActiveTab"){r&&!at(r)&&!st(r)&&l(r);return}if(L==="splitActiveTabRight"){(Q=Le.current)==null||Q.splitActiveTabRight();return}if(L==="splitActiveTabDown"){(ge=Le.current)==null||ge.splitActiveTabDown();return}if(L==="floatActiveTab"){(Be=Le.current)==null||Be.floatActiveTab();return}if(L==="popoutActiveTab"){(_e=Le.current)==null||_e.popoutActiveTab();return}if(L==="dockActiveTab"){(Oe=Le.current)==null||Oe.dockActiveTab();return}if(L==="focusLeftPane"){(nt=Le.current)==null||nt.focusLeftPane();return}if(L==="focusRightPane"){(Mt=Le.current)==null||Mt.focusRightPane();return}if(L==="focusUpPane"){(ft=Le.current)==null||ft.focusUpPane();return}if(L==="focusDownPane"){(ss=Le.current)==null||ss.focusDownPane();return}if(L==="moveActiveTabToLeftPane"){(Fr=Le.current)==null||Fr.moveActiveTabToLeftPane();return}if(L==="moveActiveTabToRightPane"){(Wr=Le.current)==null||Wr.moveActiveTabToRightPane();return}if(L==="moveActiveTabToUpPane"){(Kr=Le.current)==null||Kr.moveActiveTabToUpPane();return}if(L==="moveActiveTabToDownPane"){(Hr=Le.current)==null||Hr.moveActiveTabToDownPane();return}if(L==="triggerPrimaryApprovalAction"){$e(0);return}if(L==="triggerSecondaryApprovalAction"){$e(1);return}if(L==="triggerTertiaryApprovalAction"){$e(2);return}if(L==="setActiveTabShortcut"){(Ur=Le.current)==null||Ur.setShortcutForActiveTab();return}if(L==="selectPreviousGroupTab"){(zr=Le.current)==null||zr.activatePreviousTabInGroup();return}if(L==="selectNextGroupTab"){(Vr=Le.current)==null||Vr.activateNextTabInGroup();return}!r||!at(r)||st(r)||L==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),Ue=Nt.useCallback(()=>{U(),gt(null),dt([])},[U,gt,dt]),Kt=Nt.useMemo(()=>xt==="all"?Me:Me.filter(L=>rv(L)===xt),[Me,xt]),te=Nt.useCallback(()=>{const L=Object.fromEntries(Me.map(Q=>[Q.id,""]));ht(L)},[Me,ht]),De=Nt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const L=Object.fromEntries(Me.map(Q=>[Q.id,Q.defaultShortcut]));ht(L)},[Me,ht]);return Nt.useEffect(()=>{const L=Q=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Q.metaKey&&Q.key.toLowerCase()==="w":Q.ctrlKey&&Q.key.toLowerCase()==="w")&&(Q.preventDefault(),r&&we&&we(r))};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[r,we]),Nt.useEffect(()=>{if(!Xe||et)return;const L=Q=>{Q.key==="Escape"&&(Q.preventDefault(),Ue())};return window.addEventListener("keydown",L,!0),()=>window.removeEventListener("keydown",L,!0)},[Ue,Xe,et]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(Nx,{activeConv:r,wsStatus:n,isConnected:a,conversations:Se,hiddenConversations:h,onOpenHistory:o,onHideConversation:we,onShowConversation:Pe,onShowAllHidden:Ce,onResetPanelsToMain:Ae,notifications:q,notificationUnreadCount:ce,onOpenNotification:Ee,onMarkNotificationRead:je,onMarkNotificationUnread:O,onDeleteNotification:Ie,inboxOpen:He,onInboxOpenChange:tt,hiddenOpen:ze,onHiddenOpenChange:Ge,onOpenNewSession:t?void 0:V,onOpenDashboardGuide:ot,guideNudgeVisible:rt,actionShortcuts:Qe,onOpenRemote:()=>{!r||at(r)||st(r)||l(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:oe,onOpenMeshGraph:ke}),e?s.jsx(fy,{conversations:u,hiddenConversations:h,ides:x,actionLogs:S,sendDaemonCommand:b,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:v,userName:T,requestedActiveTabKey:I,onRequestedActiveTabConsumed:k,requestedMachineId:A,onRequestedMachineConsumed:_,requestedMobileSection:N,onRequestedMobileSectionConsumed:w,onOpenHistory:o,onOpenRemote:l,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Ce,onHideConversation:we,onOpenMeshGraph:ke,onOpenNewSession:V,liveSessionInboxState:Ne}):t?s.jsx(ky,{containerRef:D,isSplitMode:M,numGroups:j,groupSizes:W,groupedConvs:H,clearedTabs:$,ides:x,actionLogs:S,sendDaemonCommand:b,setActionLogs:p,isStandalone:v,hasRegisteredMachines:me.length>0,userName:T,focusedGroup:C,focusGroup:y,moveTabToGroup:F,splitTabRelative:P,closeGroup:E,handleResizeStart:G,groupActiveTabIds:J,setGroupActiveTab:ye,groupTabOrders:he,setGroupTabOrder:ne,toggleHiddenTab:ue,onOpenNewSession:V,allowTabShortcuts:!1,liveSessionInboxState:Ne}):s.jsx(Wy,{visibleConversations:Se,clearedTabs:$,ides:x,actionLogs:S,sendDaemonCommand:b,setActionLogs:p,isStandalone:v,hasRegisteredMachines:me.length>0,initialDataLoaded:f,userName:T,toggleHiddenTab:ue,actionShortcuts:Qe,registerActionHandlers:L=>{Le.current=L},onActiveTabChange:xe,requestedActiveTabKey:ve,onRequestedActiveTabConsumed:X,onRequestScrollToBottom:fe,scrollToBottomRequest:ee,onOpenNewSession:V,liveSessionInboxState:Ne,layoutProfile:ie}),Je&&s.jsx(Vy,{machines:me,ides:x,onClose:Z,onBrowseDirectory:pe,onSaveWorkspace:le,onLaunchIde:B,onLaunchProvider:z,onListMeshes:de,onLaunchMeshCoordinator:re,onListSavedSessions:R}),Y&&s.jsx(O0,{activeConv:Y,sendDaemonCommand:b,onClose:()=>se(null)}),ae&&s.jsx(Pu,{daemonId:ae.daemonId,workspace:ae.workspace,onClose:()=>K(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:Ue,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:L=>L.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:Ue,"aria-label":"Close dashboard guide",children:s.jsx(wt,{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(L=>s.jsx("button",{type:"button",className:`btn btn-sm ${pt===L.id?"btn-primary":"btn-secondary"}`,onClick:()=>Te(L.id),children:L.label},L.id))}),pt==="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 ",Fe?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),pt==="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."]})]})]})]}),pt==="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(L=>s.jsx("button",{type:"button",className:`btn btn-sm ${xt===L.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ve(L.id),children:L.label},L.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:te,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:De,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Kt.map(L=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${et===L.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:L.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:L.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:L.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===L.id?bt.length>0?`${bt.join(" ")} ...`:"Listening...":Qe[L.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{gt(L.id),dt([])},children:et===L.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Q={...Qe};Q[L.id]="",ht(Q)},children:"Disable"})]})]})},L.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Fe?"⌘⇧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 Ka=[{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 iv({onClose:e}){const[t,r]=i.useState(0),n=Ka[t],a=t===Ka.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(wt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Ka.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 } }
68
68
  @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
69
- `})]})}function iv({hasExtensions:e,ideName:t,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?s.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[s.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${r==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a("native"),children:t}),n.map(o=>{const l=r===o.tabKey,c=o.status==="waiting_approval",d=o.status==="generating";return s.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${l?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(o.tabKey),children:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:c?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),o.title,c&&s.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},o.tabKey)})]}):null}function lv({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,l]=i.useState(()=>a||"native"),c=i.useMemo(()=>xd(t),[t]),d=i.useMemo(()=>e?ti(e,{machineNames:c,connectionStates:r,defaultConnectionState:"new"}):[],[e,c,r]),m=i.useMemo(()=>d.find(p=>p.streamSource==="native"),[d]),u=i.useMemo(()=>d.filter(p=>p.streamSource==="agent-stream"),[d]),h=i.useMemo(()=>e?Wt(d,e.id):null,[d,e]);i.useEffect(()=>{a&&l(a)},[a]),i.useEffect(()=>{if(a||!h)return;const p=h.streamSource==="native"?"native":h.tabKey;!p||o===p||o==="native"&&l(p)},[o,h,a]),i.useEffect(()=>{var p;o!=="native"&&(u.some(g=>g.tabKey===o)||l(((p=u[0])==null?void 0:p.tabKey)||"native"))},[o,u]),i.useEffect(()=>{o==="native"&&(m||u[0]&&l(u[0].tabKey))},[o,m,u]);const x=i.useMemo(()=>o==="native"&&m?m:u.find(p=>p.tabKey===o)||h||m||u[0],[o,m,h,u]),S=i.useMemo(()=>u.map(p=>({tabKey:p.tabKey,title:cd(p)||n,status:p.status})),[u,n]),b=i.useCallback(p=>{if(p)return d.find(g=>uo(g,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[d]);return{activeChatTab:o,setActiveChatTab:l,activeConv:x,conversations:d,extensionTabs:S,hasExtensions:S.length>0,resolveConversationByTarget:b}}function cv({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:l,isStandalone:c,userName:d,onOpenHistory:m,onConversationChange:u,onClose:h}){const[x,S]=i.useState("split"),[b,p]=i.useState(()=>ls(e)?"native":e.tabKey),g=i.useRef(null),v=i.useMemo(()=>t||r.find(y=>y.id===e.routeId),[e.routeId,t,r]),f=i.useMemo(()=>ct((v==null?void 0:v.type)||""),[v==null?void 0:v.type]),{conversations:T,extensionTabs:I,hasExtensions:k}=lv({ideData:v,allIdes:r,connectionStates:n,ideName:f||"IDE",preferredTabKey:ls(e)?void 0:e.tabKey}),A=i.useMemo(()=>v?Wt(T,v.id):null,[v,T]);i.useEffect(()=>{const y=g.current,F={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(g.current=F,!(y&&y.routeId===F.routeId&&y.tabKey===F.tabKey&&y.streamSource===F.streamSource)){if(ls(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),i.useEffect(()=>{if(b==="native"){if(T.some(y=>y.streamSource==="native"))return;(A==null?void 0:A.streamSource)==="agent-stream"&&p(A.tabKey);return}if(!T.some(y=>y.tabKey===b)){if((A==null?void 0:A.streamSource)==="agent-stream"){p(A.tabKey);return}p("native")}},[T,b,A]);const _=i.useMemo(()=>b==="native"?T.find(y=>y.streamSource==="native")||e:T.find(y=>y.tabKey===b)||e,[e,T,b]),N=Md(_),w=i.useMemo(()=>N.status||N.modalMessage||N.modalButtons?{..._,...N.status?{status:N.status}:{},...N.modalMessage!==void 0?{modalMessage:N.modalMessage}:{},...N.modalButtons!==void 0?{modalButtons:N.modalButtons}:{}}:_,[_,N]),D=Dr(w),M=qn({sendDaemonCommand:o,activeConv:w,setActionLogs:l,isStandalone:c}),{connScreenshot:j,screenshotUsage:W,handleRemoteAction:H}=au({doId:D,targetSessionId:Vc(w),connState:w.connectionState||"new",viewMode:x}),$=i.useMemo(()=>a.filter(y=>y.routeId===w.tabKey),[a,w.tabKey]);i.useEffect(()=>{u==null||u(w)},[w,u]),i.useEffect(()=>{const y=F=>{F.key==="Escape"&&h()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[h]);const C=i.useCallback(y=>{y.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:h,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:C,children:[s.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[s.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(_t,{size:16})}),s.jsx("span",{className:"truncate",children:Ho(_)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(y=>{const F=x===y;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${F?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>S(y),title:y==="split"?"Split view":"Remote only",children:y==="split"?s.jsx(sp,{size:15}):s.jsx(_t,{size:15})},y)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>m(_),title:"Chat History",children:[s.jsx(_o,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:h,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${x==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[x!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${x==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(iv,{hasExtensions:k,ideName:f||"IDE",activeChatTab:b,extensionTabs:I,onSelectTab:p}),s.jsx(Lc,{activeConv:w,onModalButton:M.handleModalButton}),s.jsx(po,{activeConv:w,ideEntry:v,showMetaChips:!1,handleSendChat:M.handleSendChat,isSendingChat:M.isSendingChat,sendFeedbackMessage:M.sendFeedbackMessage,handleFocusAgent:M.handleFocusAgent,isFocusingAgent:M.isFocusingAgent,actionLogs:$,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${x==="split"?"order-1 md:order-2":""}`,children:s.jsx(Ac,{addLog:()=>{},connState:w.connectionState||"new",connScreenshot:j,screenshotUsage:W,transportType:w.transport,onAction:H})})]})]})})}function dv({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=hx(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[s.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",o,"?"]}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:t?"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.":"This provider does not support graceful stop. Force Stop will end the runtime immediately."})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&s.jsx("button",{onClick:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),s.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:"Force Stop"}),s.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function uv({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o}){var l;return s.jsxs(s.Fragment,{children:[s.jsx(yx,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(ei,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,missingWorkspaceResumePath:e.missingWorkspaceResumePath,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),t.conversation&&s.jsx(cv,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose}),r.open&&r.targetConv&&(at(r.targetConv)||st(r.targetConv))&&s.jsx(dv,{activeConv:r.targetConv,canSaveAndStop:at(r.targetConv)&&!st(r.targetConv)&&!!((l=r.targetConv.resume)!=null&&l.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(fd,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),o.open&&s.jsx(ov,{onClose:o.onClose})]})}function mv({daemons:e,targetVersion:t,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:o}){return e.length===0?null:s.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:r?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:r?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[s.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:s.jsx(Rr,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[r?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(l=>{const c=At(l,{fallbackId:l.id}),d=n[l.id],m=l.version||l.daemonVersion||"unknown",u=l.versionUpdateRequired===!0,x=Hd(l)==="preview"?"Update to preview":u?"Update now":"Upgrade";return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:c}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),u&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),d==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:u?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):d==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(l.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:u?"var(--status-danger)":"var(--status-warning)",background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(l.id),children:x})]},l.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:s.jsx(wt,{size:16})})]})}function pv(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function hv(e){const t=e.machine;return typeof(t==null?void 0:t.cpus)!="number"||typeof(t==null?void 0:t.totalMem)!="number"||typeof(t==null?void 0:t.arch)!="string"||typeof(t==null?void 0:t.release)!="string"}function fv(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>hv(t)).map(t=>t.id)}}function xv(){var yi,vi,wi,ji;const{sendCommand:e}=jt(),t=Er(),r=Td(),n=To(),a=As(),[o,l]=jm(),c=o.get("activeTab"),d=((yi=n.state)==null?void 0:yi.openRemoteForTabKey)||null,m=((vi=n.state)==null?void 0:vi.openMachineId)||null,u=((wi=n.state)==null?void 0:wi.mobileSection)||null,h=ad(),x=h.ides||[],S=h.initialLoaded??!0,{updateRouteChats:b,setToasts:p}=h,[g,v]=i.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),f=h.toasts||[],T=h.wsStatus||"connected",I=h.isConnected??!0,k=h.connectionStates||{},A=h.showReconnected||!1,{layoutProfile:_,groupAssignments:N,updateGroupAssignments:w,focusedGroup:D,updateFocusedGroup:M,focusGroup:j,groupActiveTabIds:W,updateGroupActiveTabIds:H,setGroupActiveTab:$,groupTabOrders:C,updateGroupTabOrders:y,setGroupTabOrder:F,groupSizes:P,updateGroupSizes:E,isMobile:G,hasHydratedStoredLayout:J,hydrateStoredLayout:ye,focusConversationTab:he}=dg(),[ne,ue]=i.useState(()=>ni());i.useEffect(()=>jb(ue),[]);const Se=i.useMemo(()=>pv({isMobile:G,mobileViewMode:ne}),[G,ne]),[ve,X]=i.useState([]),[xe,fe]=i.useState({}),[we,be]=i.useState({});Pr("Dashboard",{ideCount:x.length,toastCount:f.length,focusedGroup:D,groupCount:Object.keys(N).length,actionLogCount:ve.length});const Ce=i.useMemo(()=>x.filter(Ye=>Ye.type==="adhdev-daemon").sort(Fo),[x]),ee=Ce[0],me=!!ee;i.useEffect(()=>{const{metadataDaemonIds:Ye,runtimeDaemonIds:Et}=fv(Ce);for(const sr of Ye)t(sr,{minFreshMs:3e4}).catch(()=>{});for(const sr of Et)r(sr,{minFreshMs:3e4}).catch(()=>{})},[t,r,Ce]);const ie=(ee==null?void 0:ee.terminalBackend)||null,pe=ee?At(ee,{fallbackId:ee.id}):null,le=(ee==null?void 0:ee.id)||null,B=i.useMemo(()=>Eb(x,xe),[x,xe]),{hiddenTabs:z,autoHiddenTabs:de,autoHideTarget:re,hideTarget:R,toggleTarget:q,showTarget:ce,showAllTabs:Ne}=Db(),{conversations:je,visibleConversations:O,visibleTabKeys:Ie,resolveConversationBySessionId:Le,resolveConversationByTarget:He}=Yb({ides:B,connectionStates:k,clearedTabs:we,hiddenTabs:z}),ze=i.useMemo(()=>new Map(je.map(Ye=>[Ye.tabKey,Ye])),[je]),Xe=i.useMemo(()=>Pb(je,z,de),[je,z,de]);i.useEffect(()=>{for(const Ye of Xe)re(Ye)},[Xe,re]),zf(O,Se),i.useEffect(()=>{Object.keys(xe).length!==0&&fe(Ye=>$b(Ye,x))},[x,xe]);const Je=i.useMemo(()=>Qp(x),[x]),{notifications:rt,unreadCount:pt}=Cg({conversations:je,liveSessionInboxState:Je}),{handleMarkDashboardNotificationRead:xt,handleMarkDashboardNotificationUnread:vt,handleDeleteDashboardNotification:Te}=Ig({notifications:rt,sendDaemonCommand:e}),{containerRef:Ve,normalizedGroupAssignments:tt,numGroups:Ge,isSplitMode:ot,groupedConvs:U,moveTabToGroup:V,closeGroup:Z,handleResizeStart:ae,splitTabRelative:K}=bg({groupAssignments:N,updateGroupAssignments:w,updateFocusedGroup:M,updateGroupActiveTabIds:H,updateGroupTabOrders:y,groupSizes:P,updateGroupSizes:E,isMobile:G,visibleConversations:O,visibleTabKeys:Ie}),{activeConv:Y,openDesktopConversation:se,requestScrollToBottom:oe,scrollToBottomRequest:ke,setDesktopActiveTab:Pe}=Wg({isMobile:G,conversations:je,visibleConversations:O,groupActiveTabIds:W,focusedGroup:D,groupedConvs:U,setSearchParams:l});Ug({activeConv:Y,isMobile:G,liveSessionInboxState:Je,sendDaemonCommand:e});const{requestedDesktopTabKey:Ee,requestedMobileTabKey:Ae,consumeRequestedActiveTab:$e}=Xb({isMobile:G,urlActiveTab:c,resolveConversationBySessionId:Le,setSearchParams:l}),{remoteDialogConv:Fe,remoteDialogIdeEntry:Me,remoteDialogActiveConv:Qe,setRemoteDialogActiveConv:et,openRemoteDialog:bt,closeRemoteDialog:gt,cliStopDialogOpen:dt,cliStopTargetConv:ht,requestCliStop:Ue,cancelCliStop:Kt,confirmCliStop:te}=Gg({isMobile:G,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:Ee,conversations:je,ides:x,resolveConversationByTarget:He,activeConv:Y,sendDaemonCommand:e}),{historyModalOpen:De,openHistoryModal:L,closeHistoryModal:Q,historyTargetConv:ge,isSavedSessionHistoryTarget:Be,isHistoryCreatingChat:_e,isHistoryRefreshingHistory:Oe,handleHistorySwitchSession:nt,handleHistoryNewChat:Mt,handleHistoryRefresh:ft,savedHistorySessions:ss,savedHistoryFilters:Fr,setSavedHistoryFilters:Wr,missingWorkspaceResumePath:Kr,isSavedHistoryLoading:Hr,resumingSavedHistorySessionId:Ur,handleRefreshSavedHistory:zr,handleResumeSavedHistorySession:Vr}=zg({activeConv:Y,remoteDialogConv:Fe,remoteDialogActiveConv:Qe,ides:x,sendDaemonCommand:e,updateRouteChats:b,setToasts:p,setClearedTabs:be,setSearchParams:l}),Ou=i.useMemo(()=>O,[O]),Gr=G&&ne==="chat",Fu=i.useMemo(()=>je.filter(Ye=>Xn(z,Ye)),[je,z]),xi=i.useCallback(Ye=>{const Et=new URLSearchParams(o);Et.set("activeTab",Ye),l(Et,{replace:!0})},[o,l]),{trackPendingLaunch:Wu}=$g({ides:x,conversations:je,onOpenSession:xi}),{handleBrowseMachineDirectory:Ku,handleSaveMachineWorkspace:Hu,handleLaunchMachineIde:Uu,handleLaunchMachineProvider:zu,handleListMachineMeshes:Vu,handleLaunchMeshCoordinator:Gu,handleListMachineSavedSessions:qu,setActiveCliViewMode:Yu}=Bg({sendDaemonCommand:e,trackPendingLaunch:Wu,onOpenSession:xi,activeConv:Y,ides:x,setCliViewModeOverrides:fe});Bb({visibleConversations:O,clearedTabs:we,setClearedTabs:be,setActionLogs:X}),Jb({ides:x,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:He});const{isRefreshingHistory:Xu,handleRefreshHistory:Ju}=Kd({sendDaemonCommand:e,activeConv:Y,chats:(ji=x.find(Ye=>Ye.id===(Y==null?void 0:Y.routeId)))==null?void 0:ji.chats,updateRouteChats:b,setToasts:p,setClearedTabs:be});mg({urlActiveTab:G&&!Gr?c:null,conversations:je,resolveConversationBySessionId:Le,normalizedGroupAssignments:tt,hasHydratedStoredLayout:G&&!Gr?J:!0,hydrateStoredLayout:G&&!Gr?ye:()=>{},focusConversationTab:he,setSearchParams:l,historyModalOpen:De,activeConv:Y,isRefreshingHistory:Xu,ides:x,handleRefreshHistory:Ju});const Qu=i.useMemo(()=>!Y||!at(Y)||st(Y)?null:Zs(Y),[Y]),{versionMismatchDaemons:Zu,hasRequiredVersionDaemons:bi,targetVersion:em,versionBannerDismissed:tm,setVersionBannerDismissed:sm,upgradingDaemons:rm,handleBannerUpgrade:nm}=yg({ides:x,sendDaemonCommand:e}),gi=i.useCallback(Ye=>{ce(Ye),se(Ye)},[se,ce]),am=i.useCallback(Ye=>{R(Ye)},[R]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[s.jsx(vx,{terminalBackend:ie,isStandalone:me,machineLabel:pe,machineKey:le}),(!tm||bi)&&s.jsx(mv,{daemons:Zu,targetVersion:em,required:bi,upgradingDaemons:rm,onUpgrade:nm,onDismiss:()=>sm(!0)}),s.jsx(av,{showMobileChatMode:Gr,isMobile:G,activeConv:Y,wsStatus:T,isConnected:I,onOpenHistory:Ye=>{Ye&&et(Ye),L()},onOpenRemote:bt,onStopCli:Ue,activeCliViewMode:Qu,onSetActiveCliViewMode:Yu,mobileChatConversations:Ou,ides:x,actionLogs:ve,sendDaemonCommand:e,setActionLogs:X,setCliViewModeOverrides:fe,isStandalone:me,initialDataLoaded:S,userName:h.userName,requestedMobileTabKey:Ae,onRequestedMobileTabConsumed:$e,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:u,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:Ve,isSplitMode:ot,numGroups:Ge,groupSizes:P,groupedConvs:U,clearedTabs:we,focusedGroup:D,focusGroup:j,moveTabToGroup:V,splitTabRelative:K,closeGroup:Z,handleResizeStart:ae,groupActiveTabIds:W,setGroupActiveTab:$,groupTabOrders:C,setGroupTabOrder:F,toggleHiddenTab:Ye=>q(ze.get(Ye)||{tabKey:Ye}),visibleConversations:O,hiddenConversations:Fu,requestedDesktopTabKey:Ee,onRequestedDesktopTabConsumed:$e,onDesktopActiveTabChange:Pe,onRequestScrollToBottom:oe,onHideConversation:am,onShowHiddenConversation:gi,onShowAllHiddenConversations:Ne,scrollToBottomRequest:ke,machineEntries:Ce,layoutProfile:_,onBrowseMachineDirectory:Ku,onSaveMachineWorkspace:Hu,onLaunchMachineIde:Uu,onLaunchMachineProvider:zu,onListMachineMeshes:Vu,onLaunchMeshCoordinator:Gu,onListMachineSavedSessions:qu,notifications:rt,notificationUnreadCount:pt,liveSessionInboxState:Je,onMarkNotificationRead:xt,onMarkNotificationUnread:vt,onDeleteNotification:Te}),s.jsx("style",{children:`
69
+ `})]})}function lv({hasExtensions:e,ideName:t,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?s.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[s.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${r==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a("native"),children:t}),n.map(o=>{const l=r===o.tabKey,c=o.status==="waiting_approval",d=o.status==="generating";return s.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${l?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(o.tabKey),children:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:c?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),o.title,c&&s.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},o.tabKey)})]}):null}function cv({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,l]=i.useState(()=>a||"native"),c=i.useMemo(()=>xd(t),[t]),d=i.useMemo(()=>e?ti(e,{machineNames:c,connectionStates:r,defaultConnectionState:"new"}):[],[e,c,r]),m=i.useMemo(()=>d.find(p=>p.streamSource==="native"),[d]),u=i.useMemo(()=>d.filter(p=>p.streamSource==="agent-stream"),[d]),h=i.useMemo(()=>e?Wt(d,e.id):null,[d,e]);i.useEffect(()=>{a&&l(a)},[a]),i.useEffect(()=>{if(a||!h)return;const p=h.streamSource==="native"?"native":h.tabKey;!p||o===p||o==="native"&&l(p)},[o,h,a]),i.useEffect(()=>{var p;o!=="native"&&(u.some(g=>g.tabKey===o)||l(((p=u[0])==null?void 0:p.tabKey)||"native"))},[o,u]),i.useEffect(()=>{o==="native"&&(m||u[0]&&l(u[0].tabKey))},[o,m,u]);const x=i.useMemo(()=>o==="native"&&m?m:u.find(p=>p.tabKey===o)||h||m||u[0],[o,m,h,u]),S=i.useMemo(()=>u.map(p=>({tabKey:p.tabKey,title:cd(p)||n,status:p.status})),[u,n]),b=i.useCallback(p=>{if(p)return d.find(g=>uo(g,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[d]);return{activeChatTab:o,setActiveChatTab:l,activeConv:x,conversations:d,extensionTabs:S,hasExtensions:S.length>0,resolveConversationByTarget:b}}function dv({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:l,isStandalone:c,userName:d,onOpenHistory:m,onConversationChange:u,onClose:h}){const[x,S]=i.useState("split"),[b,p]=i.useState(()=>ls(e)?"native":e.tabKey),g=i.useRef(null),v=i.useMemo(()=>t||r.find(y=>y.id===e.routeId),[e.routeId,t,r]),f=i.useMemo(()=>ct((v==null?void 0:v.type)||""),[v==null?void 0:v.type]),{conversations:T,extensionTabs:I,hasExtensions:k}=cv({ideData:v,allIdes:r,connectionStates:n,ideName:f||"IDE",preferredTabKey:ls(e)?void 0:e.tabKey}),A=i.useMemo(()=>v?Wt(T,v.id):null,[v,T]);i.useEffect(()=>{const y=g.current,F={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(g.current=F,!(y&&y.routeId===F.routeId&&y.tabKey===F.tabKey&&y.streamSource===F.streamSource)){if(ls(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),i.useEffect(()=>{if(b==="native"){if(T.some(y=>y.streamSource==="native"))return;(A==null?void 0:A.streamSource)==="agent-stream"&&p(A.tabKey);return}if(!T.some(y=>y.tabKey===b)){if((A==null?void 0:A.streamSource)==="agent-stream"){p(A.tabKey);return}p("native")}},[T,b,A]);const _=i.useMemo(()=>b==="native"?T.find(y=>y.streamSource==="native")||e:T.find(y=>y.tabKey===b)||e,[e,T,b]),N=Md(_),w=i.useMemo(()=>N.status||N.modalMessage||N.modalButtons?{..._,...N.status?{status:N.status}:{},...N.modalMessage!==void 0?{modalMessage:N.modalMessage}:{},...N.modalButtons!==void 0?{modalButtons:N.modalButtons}:{}}:_,[_,N]),D=Dr(w),M=qn({sendDaemonCommand:o,activeConv:w,setActionLogs:l,isStandalone:c}),{connScreenshot:j,screenshotUsage:W,handleRemoteAction:H}=au({doId:D,targetSessionId:Vc(w),connState:w.connectionState||"new",viewMode:x}),$=i.useMemo(()=>a.filter(y=>y.routeId===w.tabKey),[a,w.tabKey]);i.useEffect(()=>{u==null||u(w)},[w,u]),i.useEffect(()=>{const y=F=>{F.key==="Escape"&&h()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[h]);const C=i.useCallback(y=>{y.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:h,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:C,children:[s.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[s.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(_t,{size:16})}),s.jsx("span",{className:"truncate",children:Ho(_)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(y=>{const F=x===y;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${F?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>S(y),title:y==="split"?"Split view":"Remote only",children:y==="split"?s.jsx(sp,{size:15}):s.jsx(_t,{size:15})},y)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>m(_),title:"Chat History",children:[s.jsx(_o,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:h,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${x==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[x!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${x==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(lv,{hasExtensions:k,ideName:f||"IDE",activeChatTab:b,extensionTabs:I,onSelectTab:p}),s.jsx(Lc,{activeConv:w,onModalButton:M.handleModalButton}),s.jsx(po,{activeConv:w,ideEntry:v,showMetaChips:!1,handleSendChat:M.handleSendChat,isSendingChat:M.isSendingChat,sendFeedbackMessage:M.sendFeedbackMessage,handleFocusAgent:M.handleFocusAgent,isFocusingAgent:M.isFocusingAgent,actionLogs:$,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${x==="split"?"order-1 md:order-2":""}`,children:s.jsx(Ac,{addLog:()=>{},connState:w.connectionState||"new",connScreenshot:j,screenshotUsage:W,transportType:w.transport,onAction:H})})]})]})})}function uv({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=hx(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[s.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",o,"?"]}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:t?"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.":"This provider does not support graceful stop. Force Stop will end the runtime immediately."})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&s.jsx("button",{onClick:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),s.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:"Force Stop"}),s.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function mv({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o}){var l;return s.jsxs(s.Fragment,{children:[s.jsx(yx,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(ei,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,missingWorkspaceResumePath:e.missingWorkspaceResumePath,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),t.conversation&&s.jsx(dv,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose}),r.open&&r.targetConv&&(at(r.targetConv)||st(r.targetConv))&&s.jsx(uv,{activeConv:r.targetConv,canSaveAndStop:at(r.targetConv)&&!st(r.targetConv)&&!!((l=r.targetConv.resume)!=null&&l.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(fd,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),o.open&&s.jsx(iv,{onClose:o.onClose})]})}function pv({daemons:e,targetVersion:t,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:o}){return e.length===0?null:s.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:r?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:r?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[s.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:s.jsx(Rr,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[r?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(l=>{const c=At(l,{fallbackId:l.id}),d=n[l.id],m=l.version||l.daemonVersion||"unknown",u=l.versionUpdateRequired===!0,x=Hd(l)==="preview"?"Update to preview":u?"Update now":"Upgrade";return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:c}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),u&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),d==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:u?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):d==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(l.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:u?"var(--status-danger)":"var(--status-warning)",background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(l.id),children:x})]},l.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:s.jsx(wt,{size:16})})]})}function hv(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function fv(e){const t=e.machine;return typeof(t==null?void 0:t.cpus)!="number"||typeof(t==null?void 0:t.totalMem)!="number"||typeof(t==null?void 0:t.arch)!="string"||typeof(t==null?void 0:t.release)!="string"}function xv(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>fv(t)).map(t=>t.id)}}function bv(){var yi,vi,wi,ji;const{sendCommand:e}=jt(),t=Er(),r=Td(),n=To(),a=As(),[o,l]=jm(),c=o.get("activeTab"),d=((yi=n.state)==null?void 0:yi.openRemoteForTabKey)||null,m=((vi=n.state)==null?void 0:vi.openMachineId)||null,u=((wi=n.state)==null?void 0:wi.mobileSection)||null,h=ad(),x=h.ides||[],S=h.initialLoaded??!0,{updateRouteChats:b,setToasts:p}=h,[g,v]=i.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),f=h.toasts||[],T=h.wsStatus||"connected",I=h.isConnected??!0,k=h.connectionStates||{},A=h.showReconnected||!1,{layoutProfile:_,groupAssignments:N,updateGroupAssignments:w,focusedGroup:D,updateFocusedGroup:M,focusGroup:j,groupActiveTabIds:W,updateGroupActiveTabIds:H,setGroupActiveTab:$,groupTabOrders:C,updateGroupTabOrders:y,setGroupTabOrder:F,groupSizes:P,updateGroupSizes:E,isMobile:G,hasHydratedStoredLayout:J,hydrateStoredLayout:ye,focusConversationTab:he}=dg(),[ne,ue]=i.useState(()=>ni());i.useEffect(()=>jb(ue),[]);const Se=i.useMemo(()=>hv({isMobile:G,mobileViewMode:ne}),[G,ne]),[ve,X]=i.useState([]),[xe,fe]=i.useState({}),[we,be]=i.useState({});Pr("Dashboard",{ideCount:x.length,toastCount:f.length,focusedGroup:D,groupCount:Object.keys(N).length,actionLogCount:ve.length});const Ce=i.useMemo(()=>x.filter(Ye=>Ye.type==="adhdev-daemon").sort(Fo),[x]),ee=Ce[0],me=!!ee;i.useEffect(()=>{const{metadataDaemonIds:Ye,runtimeDaemonIds:Et}=xv(Ce);for(const sr of Ye)t(sr,{minFreshMs:3e4}).catch(()=>{});for(const sr of Et)r(sr,{minFreshMs:3e4}).catch(()=>{})},[t,r,Ce]);const ie=(ee==null?void 0:ee.terminalBackend)||null,pe=ee?At(ee,{fallbackId:ee.id}):null,le=(ee==null?void 0:ee.id)||null,B=i.useMemo(()=>Eb(x,xe),[x,xe]),{hiddenTabs:z,autoHiddenTabs:de,autoHideTarget:re,hideTarget:R,toggleTarget:q,showTarget:ce,showAllTabs:Ne}=Db(),{conversations:je,visibleConversations:O,visibleTabKeys:Ie,resolveConversationBySessionId:Le,resolveConversationByTarget:He}=Yb({ides:B,connectionStates:k,clearedTabs:we,hiddenTabs:z}),ze=i.useMemo(()=>new Map(je.map(Ye=>[Ye.tabKey,Ye])),[je]),Xe=i.useMemo(()=>Pb(je,z,de),[je,z,de]);i.useEffect(()=>{for(const Ye of Xe)re(Ye)},[Xe,re]),zf(O,Se),i.useEffect(()=>{Object.keys(xe).length!==0&&fe(Ye=>$b(Ye,x))},[x,xe]);const Je=i.useMemo(()=>Qp(x),[x]),{notifications:rt,unreadCount:pt}=Cg({conversations:je,liveSessionInboxState:Je}),{handleMarkDashboardNotificationRead:xt,handleMarkDashboardNotificationUnread:vt,handleDeleteDashboardNotification:Te}=Ig({notifications:rt,sendDaemonCommand:e}),{containerRef:Ve,normalizedGroupAssignments:tt,numGroups:Ge,isSplitMode:ot,groupedConvs:U,moveTabToGroup:V,closeGroup:Z,handleResizeStart:ae,splitTabRelative:K}=bg({groupAssignments:N,updateGroupAssignments:w,updateFocusedGroup:M,updateGroupActiveTabIds:H,updateGroupTabOrders:y,groupSizes:P,updateGroupSizes:E,isMobile:G,visibleConversations:O,visibleTabKeys:Ie}),{activeConv:Y,openDesktopConversation:se,requestScrollToBottom:oe,scrollToBottomRequest:ke,setDesktopActiveTab:Pe}=Wg({isMobile:G,conversations:je,visibleConversations:O,groupActiveTabIds:W,focusedGroup:D,groupedConvs:U,setSearchParams:l});Ug({activeConv:Y,isMobile:G,liveSessionInboxState:Je,sendDaemonCommand:e});const{requestedDesktopTabKey:Ee,requestedMobileTabKey:Ae,consumeRequestedActiveTab:$e}=Xb({isMobile:G,urlActiveTab:c,resolveConversationBySessionId:Le,setSearchParams:l}),{remoteDialogConv:Fe,remoteDialogIdeEntry:Me,remoteDialogActiveConv:Qe,setRemoteDialogActiveConv:et,openRemoteDialog:bt,closeRemoteDialog:gt,cliStopDialogOpen:dt,cliStopTargetConv:ht,requestCliStop:Ue,cancelCliStop:Kt,confirmCliStop:te}=Gg({isMobile:G,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:Ee,conversations:je,ides:x,resolveConversationByTarget:He,activeConv:Y,sendDaemonCommand:e}),{historyModalOpen:De,openHistoryModal:L,closeHistoryModal:Q,historyTargetConv:ge,isSavedSessionHistoryTarget:Be,isHistoryCreatingChat:_e,isHistoryRefreshingHistory:Oe,handleHistorySwitchSession:nt,handleHistoryNewChat:Mt,handleHistoryRefresh:ft,savedHistorySessions:ss,savedHistoryFilters:Fr,setSavedHistoryFilters:Wr,missingWorkspaceResumePath:Kr,isSavedHistoryLoading:Hr,resumingSavedHistorySessionId:Ur,handleRefreshSavedHistory:zr,handleResumeSavedHistorySession:Vr}=zg({activeConv:Y,remoteDialogConv:Fe,remoteDialogActiveConv:Qe,ides:x,sendDaemonCommand:e,updateRouteChats:b,setToasts:p,setClearedTabs:be,setSearchParams:l}),Ou=i.useMemo(()=>O,[O]),Gr=G&&ne==="chat",Fu=i.useMemo(()=>je.filter(Ye=>Xn(z,Ye)),[je,z]),xi=i.useCallback(Ye=>{const Et=new URLSearchParams(o);Et.set("activeTab",Ye),l(Et,{replace:!0})},[o,l]),{trackPendingLaunch:Wu}=$g({ides:x,conversations:je,onOpenSession:xi}),{handleBrowseMachineDirectory:Ku,handleSaveMachineWorkspace:Hu,handleLaunchMachineIde:Uu,handleLaunchMachineProvider:zu,handleListMachineMeshes:Vu,handleLaunchMeshCoordinator:Gu,handleListMachineSavedSessions:qu,setActiveCliViewMode:Yu}=Bg({sendDaemonCommand:e,trackPendingLaunch:Wu,onOpenSession:xi,activeConv:Y,ides:x,setCliViewModeOverrides:fe});Bb({visibleConversations:O,clearedTabs:we,setClearedTabs:be,setActionLogs:X}),Jb({ides:x,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:He});const{isRefreshingHistory:Xu,handleRefreshHistory:Ju}=Kd({sendDaemonCommand:e,activeConv:Y,chats:(ji=x.find(Ye=>Ye.id===(Y==null?void 0:Y.routeId)))==null?void 0:ji.chats,updateRouteChats:b,setToasts:p,setClearedTabs:be});mg({urlActiveTab:G&&!Gr?c:null,conversations:je,resolveConversationBySessionId:Le,normalizedGroupAssignments:tt,hasHydratedStoredLayout:G&&!Gr?J:!0,hydrateStoredLayout:G&&!Gr?ye:()=>{},focusConversationTab:he,setSearchParams:l,historyModalOpen:De,activeConv:Y,isRefreshingHistory:Xu,ides:x,handleRefreshHistory:Ju});const Qu=i.useMemo(()=>!Y||!at(Y)||st(Y)?null:Zs(Y),[Y]),{versionMismatchDaemons:Zu,hasRequiredVersionDaemons:bi,targetVersion:em,versionBannerDismissed:tm,setVersionBannerDismissed:sm,upgradingDaemons:rm,handleBannerUpgrade:nm}=yg({ides:x,sendDaemonCommand:e}),gi=i.useCallback(Ye=>{ce(Ye),se(Ye)},[se,ce]),am=i.useCallback(Ye=>{R(Ye)},[R]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[s.jsx(vx,{terminalBackend:ie,isStandalone:me,machineLabel:pe,machineKey:le}),(!tm||bi)&&s.jsx(pv,{daemons:Zu,targetVersion:em,required:bi,upgradingDaemons:rm,onUpgrade:nm,onDismiss:()=>sm(!0)}),s.jsx(ov,{showMobileChatMode:Gr,isMobile:G,activeConv:Y,wsStatus:T,isConnected:I,onOpenHistory:Ye=>{Ye&&et(Ye),L()},onOpenRemote:bt,onStopCli:Ue,activeCliViewMode:Qu,onSetActiveCliViewMode:Yu,mobileChatConversations:Ou,ides:x,actionLogs:ve,sendDaemonCommand:e,setActionLogs:X,setCliViewModeOverrides:fe,isStandalone:me,initialDataLoaded:S,userName:h.userName,requestedMobileTabKey:Ae,onRequestedMobileTabConsumed:$e,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:u,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:Ve,isSplitMode:ot,numGroups:Ge,groupSizes:P,groupedConvs:U,clearedTabs:we,focusedGroup:D,focusGroup:j,moveTabToGroup:V,splitTabRelative:K,closeGroup:Z,handleResizeStart:ae,groupActiveTabIds:W,setGroupActiveTab:$,groupTabOrders:C,setGroupTabOrder:F,toggleHiddenTab:Ye=>q(ze.get(Ye)||{tabKey:Ye}),visibleConversations:O,hiddenConversations:Fu,requestedDesktopTabKey:Ee,onRequestedDesktopTabConsumed:$e,onDesktopActiveTabChange:Pe,onRequestScrollToBottom:oe,onHideConversation:am,onShowHiddenConversation:gi,onShowAllHiddenConversations:Ne,scrollToBottomRequest:ke,machineEntries:Ce,layoutProfile:_,onBrowseMachineDirectory:Ku,onSaveMachineWorkspace:Hu,onLaunchMachineIde:Uu,onLaunchMachineProvider:zu,onListMachineMeshes:Vu,onLaunchMeshCoordinator:Gu,onListMachineSavedSessions:qu,notifications:rt,notificationUnreadCount:pt,liveSessionInboxState:Je,onMarkNotificationRead:xt,onMarkNotificationUnread:vt,onDeleteNotification:Te}),s.jsx("style",{children:`
70
70
  body { overflow: hidden; overscroll-behavior: none; }
71
- `}),s.jsx(uv,{historyModal:{open:De,targetConv:ge,ides:x,isCreatingChat:_e,isRefreshingHistory:Be?!1:Oe,savedSessions:ss,savedHistoryFilters:Fr,missingWorkspaceResumePath:Kr||null,onSavedHistoryFiltersChange:Wr,isSavedSessionsLoading:Hr,isResumingSavedSessionId:Ur,onClose:Q,onNewChat:Mt,onSwitchSession:nt,onRefreshHistory:Be?zr:ft,onResumeSavedSession:Vr},remoteDialog:{conversation:Fe,ideEntry:Me,ides:x,connectionStates:k,actionLogs:ve,sendDaemonCommand:e,setActionLogs:X,isStandalone:me,userName:h.userName,onOpenHistory:Ye=>{Ye&&et(Ye),L()},onConversationChange:et,onClose:gt},cliStopDialog:{open:dt,targetConv:ht,onCancel:Kt,onStopNow:async()=>{await te("hard")},onSaveAndStop:async()=>{await te("save")}},connectionBanner:{wsStatus:T,showReconnected:A,loginUrl:h.connectionLoginUrl,onReconnect:h.retryServerConnection},toastOverlay:{toasts:f,onDismiss:Ye=>p(Et=>Et.filter(sr=>sr.id!==Ye)),onClick:Ye=>{if(Ye.targetKey){const Et=He(Ye.targetKey);Et&&(he(Et.tabKey,tt),gi(Et),oe(Et.tabKey,"toast-open"))}}},onboarding:{open:g,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}v(!1)}}})]})}function bv({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[o,l]=i.useState([]),[c,d]=i.useState(null),[m,u]=i.useState(null),[h,x]=i.useState(!1),[S,b]=i.useState(null),[p,g]=i.useState(!1),[v,f]=i.useState(""),T=i.useRef(null),I=i.useCallback(P=>{T.current=P},[]),k=i.useCallback((P,E,G=!1)=>{l(J=>[...J.slice(-100),{timestamp:Date.now(),level:P,message:E}]),setTimeout(()=>{var J;return(J=a.current)==null?void 0:J.scrollIntoView({behavior:"smooth"})},100),G&&it.showToast(E,P==="error"||P==="warn"?"warning":"success")},[a]),A=i.useCallback(P=>{const E=P instanceof Error?P.message:String(P||"");return E.includes("P2P command timeout")||E.includes("P2P not connected")||E.includes("P2P not available")},[]),_=i.useCallback(async(P,E)=>{var G;if(!e||c)return!1;d(P),k("info",`Launching ${ct(P)}${E!=null&&E.workspace?` in ${E.workspace}`:""}...`);try{const J={ideType:P,enableCdp:!0};(G=E==null?void 0:E.workspace)!=null&&G.trim()?J.workspace=E.workspace.trim():E!=null&&E.useDefaultWorkspace&&(J.useDefaultWorkspace=!0);const ye=await r(e,"launch_ide",J);return k(ye!=null&&ye.success?"info":"error",ye!=null&&ye.success?`${ct(P)} launched`:`Failed: ${ye==null?void 0:ye.error}`,!0),!!(ye!=null&&ye.success)}catch(J){return k("error",`Launch error: ${J.message}`,!0),!1}finally{d(null)}},[e,c,k,r]),N=i.useCallback(async P=>{if(!e)return{success:!1};const{cliType:E,dir:G,workspaceId:J,useDefaultWorkspace:ye,useHome:he,argsStr:ne,model:ue,resumeSessionId:Se}=P;if(!E)return k("warn","Select a CLI or ACP provider first",!0),{success:!1};const ve=ne?ne.split(/\s+/).filter(Boolean):void 0,X=(G==null?void 0:G.trim())||(J?"(saved id)":ye?"(default workspace)":he?"(home)":"");k("info",`Launching ${E}${X?` in ${X}`:""}${ue?` (model: ${ue})`:""}...`),u(E);try{const xe={cliType:E,cliArgs:ve,initialModel:ue||void 0};G!=null&&G.trim()?xe.dir=G.trim():J?xe.workspaceId=J:ye?xe.useDefaultWorkspace=!0:he&&(xe.useHome=!0),Se&&(xe.resumeSessionId=Se);const fe=await r(e,"launch_cli",xe),we=(fe==null?void 0:fe.result)||fe;return fe!=null&&fe.success?(k("info",`${E} launched`,!0),(we==null?void 0:we.launchSource)==="home"?k("info","📂 Running in home directory (explicit choice)"):(we==null?void 0:we.launchSource)==="defaultWorkspace"&&k("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:we==null?void 0:we.sessionId}):(k("error",`Failed: ${(fe==null?void 0:fe.error)||(we==null?void 0:we.error)}`,!0),(fe==null?void 0:fe.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&b({cliType:E,argsStr:ne,model:ue}),{success:!1,sessionId:we==null?void 0:we.sessionId})}catch(xe){return A(xe)?(k("warn",`${E} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(k("error",`Launch error: ${xe.message}`,!0),{success:!1})}finally{u(null)}},[e,k,A,r]),w=i.useCallback(async(P,E,G,J)=>e?P?E.trim()?N({cliType:P,dir:E,argsStr:G,model:J}):(b({cliType:P,argsStr:G,model:J}),{success:!1}):(k("warn","Select a provider",!0),{success:!1}):{success:!1},[e,k,N]),D=i.useCallback(async(P,E,G)=>{if(e&&window.confirm(`Stop ${P}?
71
+ `}),s.jsx(mv,{historyModal:{open:De,targetConv:ge,ides:x,isCreatingChat:_e,isRefreshingHistory:Be?!1:Oe,savedSessions:ss,savedHistoryFilters:Fr,missingWorkspaceResumePath:Kr||null,onSavedHistoryFiltersChange:Wr,isSavedSessionsLoading:Hr,isResumingSavedSessionId:Ur,onClose:Q,onNewChat:Mt,onSwitchSession:nt,onRefreshHistory:Be?zr:ft,onResumeSavedSession:Vr},remoteDialog:{conversation:Fe,ideEntry:Me,ides:x,connectionStates:k,actionLogs:ve,sendDaemonCommand:e,setActionLogs:X,isStandalone:me,userName:h.userName,onOpenHistory:Ye=>{Ye&&et(Ye),L()},onConversationChange:et,onClose:gt},cliStopDialog:{open:dt,targetConv:ht,onCancel:Kt,onStopNow:async()=>{await te("hard")},onSaveAndStop:async()=>{await te("save")}},connectionBanner:{wsStatus:T,showReconnected:A,loginUrl:h.connectionLoginUrl,onReconnect:h.retryServerConnection},toastOverlay:{toasts:f,onDismiss:Ye=>p(Et=>Et.filter(sr=>sr.id!==Ye)),onClick:Ye=>{if(Ye.targetKey){const Et=He(Ye.targetKey);Et&&(he(Et.tabKey,tt),gi(Et),oe(Et.tabKey,"toast-open"))}}},onboarding:{open:g,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}v(!1)}}})]})}function gv({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[o,l]=i.useState([]),[c,d]=i.useState(null),[m,u]=i.useState(null),[h,x]=i.useState(!1),[S,b]=i.useState(null),[p,g]=i.useState(!1),[v,f]=i.useState(""),T=i.useRef(null),I=i.useCallback(P=>{T.current=P},[]),k=i.useCallback((P,E,G=!1)=>{l(J=>[...J.slice(-100),{timestamp:Date.now(),level:P,message:E}]),setTimeout(()=>{var J;return(J=a.current)==null?void 0:J.scrollIntoView({behavior:"smooth"})},100),G&&it.showToast(E,P==="error"||P==="warn"?"warning":"success")},[a]),A=i.useCallback(P=>{const E=P instanceof Error?P.message:String(P||"");return E.includes("P2P command timeout")||E.includes("P2P not connected")||E.includes("P2P not available")},[]),_=i.useCallback(async(P,E)=>{var G;if(!e||c)return!1;d(P),k("info",`Launching ${ct(P)}${E!=null&&E.workspace?` in ${E.workspace}`:""}...`);try{const J={ideType:P,enableCdp:!0};(G=E==null?void 0:E.workspace)!=null&&G.trim()?J.workspace=E.workspace.trim():E!=null&&E.useDefaultWorkspace&&(J.useDefaultWorkspace=!0);const ye=await r(e,"launch_ide",J);return k(ye!=null&&ye.success?"info":"error",ye!=null&&ye.success?`${ct(P)} launched`:`Failed: ${ye==null?void 0:ye.error}`,!0),!!(ye!=null&&ye.success)}catch(J){return k("error",`Launch error: ${J.message}`,!0),!1}finally{d(null)}},[e,c,k,r]),N=i.useCallback(async P=>{if(!e)return{success:!1};const{cliType:E,dir:G,workspaceId:J,useDefaultWorkspace:ye,useHome:he,argsStr:ne,model:ue,resumeSessionId:Se}=P;if(!E)return k("warn","Select a CLI or ACP provider first",!0),{success:!1};const ve=ne?ne.split(/\s+/).filter(Boolean):void 0,X=(G==null?void 0:G.trim())||(J?"(saved id)":ye?"(default workspace)":he?"(home)":"");k("info",`Launching ${E}${X?` in ${X}`:""}${ue?` (model: ${ue})`:""}...`),u(E);try{const xe={cliType:E,cliArgs:ve,initialModel:ue||void 0};G!=null&&G.trim()?xe.dir=G.trim():J?xe.workspaceId=J:ye?xe.useDefaultWorkspace=!0:he&&(xe.useHome=!0),Se&&(xe.resumeSessionId=Se);const fe=await r(e,"launch_cli",xe),we=(fe==null?void 0:fe.result)||fe;return fe!=null&&fe.success?(k("info",`${E} launched`,!0),(we==null?void 0:we.launchSource)==="home"?k("info","📂 Running in home directory (explicit choice)"):(we==null?void 0:we.launchSource)==="defaultWorkspace"&&k("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:we==null?void 0:we.sessionId}):(k("error",`Failed: ${(fe==null?void 0:fe.error)||(we==null?void 0:we.error)}`,!0),(fe==null?void 0:fe.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&b({cliType:E,argsStr:ne,model:ue}),{success:!1,sessionId:we==null?void 0:we.sessionId})}catch(xe){return A(xe)?(k("warn",`${E} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(k("error",`Launch error: ${xe.message}`,!0),{success:!1})}finally{u(null)}},[e,k,A,r]),w=i.useCallback(async(P,E,G,J)=>e?P?E.trim()?N({cliType:P,dir:E,argsStr:G,model:J}):(b({cliType:P,argsStr:G,model:J}),{success:!1}):(k("warn","Select a provider",!0),{success:!1}):{success:!1},[e,k,N]),D=i.useCallback(async(P,E,G)=>{if(e&&window.confirm(`Stop ${P}?
72
72
  This will terminate the process.`))try{const J=await r(e,"stop_cli",{cliType:P,dir:E,targetSessionId:G});J!=null&&J.success?k("info",`${P} stopped`,!0):k("error",`Stop failed: ${(J==null?void 0:J.error)||"Unknown error"}`,!0)}catch(J){k("error",`Stop failed: ${J.message}`,!0)}},[e,k,r]),M=i.useCallback(async P=>{try{await r(P.daemonId,"restart_ide",{ideType:P.type}),k("info",`${ct(P.type)} restart initiated`,!0)}catch(E){k("error",`Restart failed: ${E.message}`,!0)}},[k,r]),j=i.useCallback(async P=>{if(window.confirm(`Stop ${ct(P.type)}?
73
- This will disconnect CDP and optionally kill the process.`))try{const E=await r(P.daemonId,"stop_ide",{ideType:P.type,killProcess:!0});E!=null&&E.success?k("info",`${ct(P.type)} stopped`,!0):k("error",`Stop failed: ${(E==null?void 0:E.error)||"Unknown error"}`,!0)}catch(E){k("error",`Stop failed: ${E.message}`,!0)}},[k,r]),W=i.useCallback(async()=>{if(e)try{const P=await r(e,"detect_ides",{});k("info",`Found ${((P==null?void 0:P.result)||[]).length} IDE(s)`,!0)}catch(P){k("error",`Detection failed: ${P.message}`,!0)}},[e,k,r]),H=i.useCallback(async P=>{if(!e||!P.trim())return!1;x(!0);try{const E=await r(e,"workspace_add",{path:P.trim()});return E!=null&&E.success?(k("info",`Workspace added: ${P.trim()}`),!0):(k("error",(E==null?void 0:E.error)||"workspace_add failed"),!1)}catch(E){return k("error",E.message),!1}finally{x(!1)}},[e,k,r]),$=i.useCallback(async P=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){x(!0);try{const E=await r(e,"workspace_remove",{id:P});E!=null&&E.success?k("info","Workspace removed",!0):k("error",(E==null?void 0:E.error)||"workspace_remove failed",!0)}catch(E){k("error",E.message,!0)}finally{x(!1)}}},[e,k,r]),C=i.useCallback(async P=>{var E;if(e){x(!0);try{const G=await r(e,"workspace_set_default",P===null?{clear:!0}:{id:P});if(G!=null&&G.success){k("info",P?"Default workspace updated":"Default workspace cleared",!0);const J=typeof G.defaultWorkspacePath=="string"?G.defaultWorkspacePath:"";J&&((E=T.current)==null||E.call(T,J))}else k("error",(G==null?void 0:G.error)||"workspace_set_default failed",!0)}catch(G){k("error",G.message,!0)}finally{x(!1)}}},[e,k,r]),y=i.useCallback(async P=>{var G;if(!e||!P.trim())return;const E=P.trim();x(!0);try{const J=await r(e,"workspace_set_default",{path:E});J!=null&&J.success?(k("info","Default workspace set from history"),(G=T.current)==null||G.call(T,E)):k("error",(J==null?void 0:J.error)||"Could not set default (path missing on disk?)")}catch(J){k("error",J.message)}finally{x(!1)}},[e,k,r]),F=i.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:v}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:v})}catch(P){k("warn",`Live nickname updated, but account sync failed: ${P.message}`)}k("info",`Nickname set to "${v||"(cleared)"}"`),g(!1)}catch(P){k("error",`Failed: ${P.message}`)}},[e,v,t,k,n,r]);return{logs:o,launchingIde:c,launchingAgentType:m,workspaceBusy:h,launchPick:S,setLaunchPick:b,editingNickname:p,setEditingNickname:g,nicknameInput:v,setNicknameInput:f,addLog:k,handleLaunchIde:_,runLaunchCliCore:N,handleLaunchCli:w,handleStopCli:D,handleRestartIde:M,handleStopIde:j,handleDetectIdes:W,handleWorkspaceAdd:H,handleWorkspaceRemove:$,handleWorkspaceSetDefault:C,handleWorkspaceResumePath:y,handleSaveNickname:F,setOnDefaultWorkspaceChanged:I}}function gv({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:l}){var M;const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:m,handleWorkspaceSetDefault:u}=o,[h,x]=i.useState(!1),[S,b]=i.useState(""),[p,g]=i.useState([]),[v,f]=i.useState(!1),[T,I]=i.useState(""),k=i.useCallback(async j=>{f(!0),I("");try{const W=await Zn(l,e,j);b(W.path),g(W.directories)}catch(W){I(W instanceof Error?W.message:"Could not load folder")}finally{f(!1)}},[e,l]),A=i.useCallback(()=>{x(!0);const j=[...r.map(H=>H.workspace),...n.map(H=>H.workspace),...a.map(H=>H.workspace)],W=Qn(t.platform,Jn(j,t.defaultWorkspacePath,(t.workspaces||[]).map(H=>H.path)));k(W)},[a,n,r,k,t.defaultWorkspacePath,t.platform,t.workspaces]),_=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,N=t.availableMem??t.freeMem??t.totalMem,w=_&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-N)/t.totalMem*100))):0,D=((M=t.loadavg)==null?void 0:M[0])||0;return s.jsxs("div",{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[s.jsx(Yr,{icon:s.jsx(wc,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?nh(t.uptime):"Waiting…"}),s.jsx(Yr,{icon:s.jsx(_t,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(Yr,{icon:s.jsx(Ro,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(Yr,{icon:s.jsx(np,{size:16}),label:"ACPs",value:`${a.length}`})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),s.jsxs("div",{className:"flex gap-6",children:[s.jsx(Bi,{value:_?Math.min(Math.round(D/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:_?`${D.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(Bi,{value:w,max:100,label:"Memory",color:"#3b82f6",detail:_?`${da(t.totalMem-N)} / ${da(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${da(t.totalMem)} total`})]})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[s.jsx(Ns,{size:14})," Workspaces"]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[s.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),s.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:c,value:t.defaultWorkspaceId||"",onChange:j=>void u(j.target.value===""?null:j.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(j=>s.jsx("option",{value:j.id,children:j.label||j.path},j.id))]}),t.defaultWorkspacePath&&s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:t.defaultWorkspacePath,children:t.defaultWorkspacePath})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded transition-colors text-xs",disabled:c,onClick:A,children:"Select workspace…"}),s.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(t.workspaces||[]).length>0&&s.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(t.workspaces||[]).map(j=>s.jsxs("li",{className:"flex items-start gap-2 text-[11px] text-text-muted rounded-lg border border-border-subtle bg-bg-primary px-2.5 py-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[j.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:Vn(j.path,j.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:j.path,children:j.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void m(j.id),children:"Remove"})]},j.id))})]}),h&&s.jsx(ea,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:S,directories:p,busy:v,error:T,confirmLabel:"Add workspace",onClose:()=>x(!1),onNavigate:j=>{k(j)},onConfirm:j=>{(async()=>{if(!j)return;await d(j)&&x(!1)})()}})]})}function yv(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t;return!r.settings||typeof r.settings!="object"?null:{settings:r.settings,values:r.values&&typeof r.values=="object"?r.values:{}}}function vv(e,t,r){const n=[];for(const[a,o]of Object.entries(e.settings)){const l=r!=null&&r.filterSchema?r.filterSchema(o):o;if(l.length===0)continue;const c=t.find(d=>d.type===a);n.push({type:a,displayName:(c==null?void 0:c.displayName)||a,icon:(c==null?void 0:c.icon)||"",category:(c==null?void 0:c.category)||"unknown",schema:l,values:e.values[a]||{}})}return n}function Ha(e){if(!e||typeof e!="object")return!1;const t=e;return(t.sourceMode==="normal"||t.sourceMode==="no-upstream")&&typeof t.disableUpstream=="boolean"&&(t.explicitProviderDir===null||typeof t.explicitProviderDir=="string")&&typeof t.userDir=="string"&&typeof t.upstreamDir=="string"&&Array.isArray(t.providerRoots)}function ql(e){if(!e||typeof e!="object")return null;if(Ha(e))return e;const t=e,r=t.result;return Ha(r)?r:Ha(t.sourceConfig)?t.sourceConfig:null}function wv(e){const t=e.trim();return t||null}const Yl=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],jv=[{value:"codex-cli",label:"Codex CLI",desc:"OpenAI o3/gpt-5.4",color:"#22c55e"},{value:"claude-cli",label:"Claude Code",desc:"Anthropic Claude",color:"#a855f7"},{value:"gemini-cli",label:"Gemini CLI",desc:"Google Gemini",color:"#3b82f6"}];function kv({machineId:e,provider:t,sendDaemonCommand:r,onClose:n}){const[a,o]=i.useState("config"),[l,c]=i.useState("codex-cli"),[d,m]=i.useState([]),[u,h]=i.useState(""),[x,S]=i.useState([]),[b,p]=i.useState(""),g=i.useRef(null),v=i.useRef(null),f=N=>{m(w=>w.includes(N)?w.filter(D=>D!==N):[...w,N])},T=()=>m([...Yl]),I=()=>m([]);i.useEffect(()=>{var N;(N=g.current)==null||N.scrollIntoView({behavior:"smooth"})},[x]),i.useEffect(()=>()=>{v.current&&clearInterval(v.current)},[]);const k=i.useCallback(()=>{v.current&&clearInterval(v.current),v.current=setInterval(async()=>{try{const N=await r(e,"provider_auto_fix_status",{providerType:t.type});(N==null?void 0:N.running)===!1&&a==="running"&&(o("done"),S(w=>[...w,`
73
+ This will disconnect CDP and optionally kill the process.`))try{const E=await r(P.daemonId,"stop_ide",{ideType:P.type,killProcess:!0});E!=null&&E.success?k("info",`${ct(P.type)} stopped`,!0):k("error",`Stop failed: ${(E==null?void 0:E.error)||"Unknown error"}`,!0)}catch(E){k("error",`Stop failed: ${E.message}`,!0)}},[k,r]),W=i.useCallback(async()=>{if(e)try{const P=await r(e,"detect_ides",{});k("info",`Found ${((P==null?void 0:P.result)||[]).length} IDE(s)`,!0)}catch(P){k("error",`Detection failed: ${P.message}`,!0)}},[e,k,r]),H=i.useCallback(async P=>{if(!e||!P.trim())return!1;x(!0);try{const E=await r(e,"workspace_add",{path:P.trim()});return E!=null&&E.success?(k("info",`Workspace added: ${P.trim()}`),!0):(k("error",(E==null?void 0:E.error)||"workspace_add failed"),!1)}catch(E){return k("error",E.message),!1}finally{x(!1)}},[e,k,r]),$=i.useCallback(async P=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){x(!0);try{const E=await r(e,"workspace_remove",{id:P});E!=null&&E.success?k("info","Workspace removed",!0):k("error",(E==null?void 0:E.error)||"workspace_remove failed",!0)}catch(E){k("error",E.message,!0)}finally{x(!1)}}},[e,k,r]),C=i.useCallback(async P=>{var E;if(e){x(!0);try{const G=await r(e,"workspace_set_default",P===null?{clear:!0}:{id:P});if(G!=null&&G.success){k("info",P?"Default workspace updated":"Default workspace cleared",!0);const J=typeof G.defaultWorkspacePath=="string"?G.defaultWorkspacePath:"";J&&((E=T.current)==null||E.call(T,J))}else k("error",(G==null?void 0:G.error)||"workspace_set_default failed",!0)}catch(G){k("error",G.message,!0)}finally{x(!1)}}},[e,k,r]),y=i.useCallback(async P=>{var G;if(!e||!P.trim())return;const E=P.trim();x(!0);try{const J=await r(e,"workspace_set_default",{path:E});J!=null&&J.success?(k("info","Default workspace set from history"),(G=T.current)==null||G.call(T,E)):k("error",(J==null?void 0:J.error)||"Could not set default (path missing on disk?)")}catch(J){k("error",J.message)}finally{x(!1)}},[e,k,r]),F=i.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:v}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:v})}catch(P){k("warn",`Live nickname updated, but account sync failed: ${P.message}`)}k("info",`Nickname set to "${v||"(cleared)"}"`),g(!1)}catch(P){k("error",`Failed: ${P.message}`)}},[e,v,t,k,n,r]);return{logs:o,launchingIde:c,launchingAgentType:m,workspaceBusy:h,launchPick:S,setLaunchPick:b,editingNickname:p,setEditingNickname:g,nicknameInput:v,setNicknameInput:f,addLog:k,handleLaunchIde:_,runLaunchCliCore:N,handleLaunchCli:w,handleStopCli:D,handleRestartIde:M,handleStopIde:j,handleDetectIdes:W,handleWorkspaceAdd:H,handleWorkspaceRemove:$,handleWorkspaceSetDefault:C,handleWorkspaceResumePath:y,handleSaveNickname:F,setOnDefaultWorkspaceChanged:I}}function yv({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:l}){var M;const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:m,handleWorkspaceSetDefault:u}=o,[h,x]=i.useState(!1),[S,b]=i.useState(""),[p,g]=i.useState([]),[v,f]=i.useState(!1),[T,I]=i.useState(""),k=i.useCallback(async j=>{f(!0),I("");try{const W=await Zn(l,e,j);b(W.path),g(W.directories)}catch(W){I(W instanceof Error?W.message:"Could not load folder")}finally{f(!1)}},[e,l]),A=i.useCallback(()=>{x(!0);const j=[...r.map(H=>H.workspace),...n.map(H=>H.workspace),...a.map(H=>H.workspace)],W=Qn(t.platform,Jn(j,t.defaultWorkspacePath,(t.workspaces||[]).map(H=>H.path)));k(W)},[a,n,r,k,t.defaultWorkspacePath,t.platform,t.workspaces]),_=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,N=t.availableMem??t.freeMem??t.totalMem,w=_&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-N)/t.totalMem*100))):0,D=((M=t.loadavg)==null?void 0:M[0])||0;return s.jsxs("div",{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[s.jsx(Yr,{icon:s.jsx(wc,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?nh(t.uptime):"Waiting…"}),s.jsx(Yr,{icon:s.jsx(_t,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(Yr,{icon:s.jsx(Ro,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(Yr,{icon:s.jsx(np,{size:16}),label:"ACPs",value:`${a.length}`})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),s.jsxs("div",{className:"flex gap-6",children:[s.jsx(Bi,{value:_?Math.min(Math.round(D/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:_?`${D.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(Bi,{value:w,max:100,label:"Memory",color:"#3b82f6",detail:_?`${da(t.totalMem-N)} / ${da(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${da(t.totalMem)} total`})]})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[s.jsx(Ns,{size:14})," Workspaces"]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[s.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),s.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:c,value:t.defaultWorkspaceId||"",onChange:j=>void u(j.target.value===""?null:j.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(j=>s.jsx("option",{value:j.id,children:j.label||j.path},j.id))]}),t.defaultWorkspacePath&&s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:t.defaultWorkspacePath,children:t.defaultWorkspacePath})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded transition-colors text-xs",disabled:c,onClick:A,children:"Select workspace…"}),s.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(t.workspaces||[]).length>0&&s.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(t.workspaces||[]).map(j=>s.jsxs("li",{className:"flex items-start gap-2 text-[11px] text-text-muted rounded-lg border border-border-subtle bg-bg-primary px-2.5 py-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[j.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:Vn(j.path,j.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:j.path,children:j.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void m(j.id),children:"Remove"})]},j.id))})]}),h&&s.jsx(ea,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:S,directories:p,busy:v,error:T,confirmLabel:"Add workspace",onClose:()=>x(!1),onNavigate:j=>{k(j)},onConfirm:j=>{(async()=>{if(!j)return;await d(j)&&x(!1)})()}})]})}function vv(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t;return!r.settings||typeof r.settings!="object"?null:{settings:r.settings,values:r.values&&typeof r.values=="object"?r.values:{}}}function wv(e,t,r){const n=[];for(const[a,o]of Object.entries(e.settings)){const l=r!=null&&r.filterSchema?r.filterSchema(o):o;if(l.length===0)continue;const c=t.find(d=>d.type===a);n.push({type:a,displayName:(c==null?void 0:c.displayName)||a,icon:(c==null?void 0:c.icon)||"",category:(c==null?void 0:c.category)||"unknown",schema:l,values:e.values[a]||{}})}return n}function Ha(e){if(!e||typeof e!="object")return!1;const t=e;return(t.sourceMode==="normal"||t.sourceMode==="no-upstream")&&typeof t.disableUpstream=="boolean"&&(t.explicitProviderDir===null||typeof t.explicitProviderDir=="string")&&typeof t.userDir=="string"&&typeof t.upstreamDir=="string"&&Array.isArray(t.providerRoots)}function ql(e){if(!e||typeof e!="object")return null;if(Ha(e))return e;const t=e,r=t.result;return Ha(r)?r:Ha(t.sourceConfig)?t.sourceConfig:null}function jv(e){const t=e.trim();return t||null}const Yl=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],kv=[{value:"codex-cli",label:"Codex CLI",desc:"OpenAI o3/gpt-5.4",color:"#22c55e"},{value:"claude-cli",label:"Claude Code",desc:"Anthropic Claude",color:"#a855f7"},{value:"gemini-cli",label:"Gemini CLI",desc:"Google Gemini",color:"#3b82f6"}];function Sv({machineId:e,provider:t,sendDaemonCommand:r,onClose:n}){const[a,o]=i.useState("config"),[l,c]=i.useState("codex-cli"),[d,m]=i.useState([]),[u,h]=i.useState(""),[x,S]=i.useState([]),[b,p]=i.useState(""),g=i.useRef(null),v=i.useRef(null),f=N=>{m(w=>w.includes(N)?w.filter(D=>D!==N):[...w,N])},T=()=>m([...Yl]),I=()=>m([]);i.useEffect(()=>{var N;(N=g.current)==null||N.scrollIntoView({behavior:"smooth"})},[x]),i.useEffect(()=>()=>{v.current&&clearInterval(v.current)},[]);const k=i.useCallback(()=>{v.current&&clearInterval(v.current),v.current=setInterval(async()=>{try{const N=await r(e,"provider_auto_fix_status",{providerType:t.type});(N==null?void 0:N.running)===!1&&a==="running"&&(o("done"),S(w=>[...w,`
74
74
  ✅ Auto-fix completed!`]),v.current&&clearInterval(v.current))}catch{}},3e3)},[e,t.type,r,a]),A=async()=>{if(d.length!==0){o("running"),S(["🚀 Starting auto-fix...",`Agent: ${l}`,`Scripts: ${d.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),p("");try{const N=await r(e,"provider_auto_fix",{providerType:t.type,functions:d,agent:l,...u?{comment:u}:{}});N!=null&&N.success&&(N!=null&&N.started||N!=null&&N.running)?(S(w=>[...w,"✅ Agent started. Monitoring progress..."]),k()):(o("error"),p((N==null?void 0:N.error)||"Failed to start auto-fix"))}catch(N){o("error"),p((N==null?void 0:N.message)||"Connection failed")}}},_=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:t.type}),S(N=>[...N,`
75
- ⚠️ Auto-fix cancelled.`]),o("done"),v.current&&clearInterval(v.current)}catch{}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm 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",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:N=>N.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:t.icon||"🔧"}),s.jsxs("div",{children:[s.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",t.displayName]}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),s.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),s.jsx("div",{className:"flex gap-2",children:jv.map(N=>s.jsxs("button",{onClick:()=>c(N.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:l===N.value?N.color+"66":"var(--border-subtle)",background:l===N.value?N.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:l===N.value?N.color:"var(--text-primary)"},children:N.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:N.desc})]},N.value))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:T,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),s.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),s.jsx("button",{onClick:I,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Yl.map(N=>s.jsxs("button",{onClick:()=>f(N),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(N)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(N)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(N)?"#a78bfa":"var(--text-secondary)"},children:[d.includes(N)?"☑ ":"☐ ",N]},N))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",s.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),s.jsx("textarea",{value:u,onChange:N=>h(N.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[x.map((N,w)=>s.jsx("div",{className:N.startsWith("✅")?"text-green-400":"",style:N.startsWith("❌")||N.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:N},w)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:g})]}),b&&s.jsx("div",{className:"mt-2 px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:b})]})]}),s.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[s.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&d.length>0&&`${d.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),s.jsxs("div",{className:"flex gap-2",children:[a==="config"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:A,disabled:d.length===0,className:"machine-btn",style:{background:d.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:d.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:d.length>0?"#a78bfa":void 0,opacity:d.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&s.jsx("button",{onClick:_,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{o("config"),S([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Sv({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var k;const o=t.filter(A=>A.category==="ide"),[l,c]=i.useState(((k=o[0])==null?void 0:k.type)||""),[d,m]=i.useState(""),[u,h]=i.useState(""),[x,S]=i.useState(!1),[b,p]=i.useState(""),[g,v]=i.useState(!1),f=A=>{const _=A.toLowerCase().replace(/[^a-z0-9-]/g,"");m(_),(!u||u===T(d))&&h(T(_))},T=A=>A.split("-").map(_=>_.charAt(0).toUpperCase()+_.slice(1)).join(" "),I=async()=>{if(!(!d||!u||!l)){S(!0),p("");try{const A=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:l});A!=null&&A.success||A!=null&&A.created?(v(!0),a==null||a(d)):p((A==null?void 0:A.error)||"Failed to create provider")}catch(A){p((A==null?void 0:A.message)||"Connection failed")}S(!1)}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm 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",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:A=>A.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:g?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:d})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:o.map(A=>s.jsxs("button",{onClick:()=>c(A.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:l===A.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:l===A.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:A.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:l===A.type?"#a78bfa":"var(--text-secondary)"},children:A.displayName})]},A.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:d,onChange:A=>f(A.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",d||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:u,onChange:A=>h(A.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),b&&s.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:b})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:g?s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:I,disabled:!d||!u||x,className:"machine-btn",style:{background:d&&u?"rgba(34,197,94,0.12)":void 0,borderColor:d&&u?"rgba(34,197,94,0.3)":void 0,color:d&&u?"#86efac":void 0,opacity:!d||!u||x?.4:1},children:x?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Xl(e){return e==="cli"||e==="acp"}function Nv(e){switch(e){case"detected":return"Detected";case"not_detected":return"Not detected";case"enabled_unchecked":return"Enabled, not checked";case"disabled":return"Disabled";default:return"Disabled"}}function Cv(e){switch(e){case"detected":return"bg-green-500/[0.10] border-green-500/25 text-green-400";case"not_detected":return"bg-red-500/[0.10] border-red-500/25 text-red-400";case"enabled_unchecked":return"bg-yellow-500/[0.10] border-yellow-500/25 text-yellow-400";case"disabled":default:return"bg-white/[0.04] border-white/[0.10] text-text-muted"}}function Jl(e){if(!e)return"No result yet";const t=e.stage||"check",r=e.ok?"OK":"Failed",n=e.message||e.path||e.command||"";return n?`${t}: ${r} — ${n}`:`${t}: ${r}`}function Iv({machineId:e,providers:t,sendDaemonCommand:r}){var H;const[n,a]=i.useState([]),[o,l]=i.useState(!1),[c,d]=i.useState(null),[m,u]=i.useState("all"),[h,x]=i.useState(null),[S,b]=i.useState(!1),[p,g]=i.useState(null),[v,f]=i.useState("normal"),[T,I]=i.useState(""),[k,A]=i.useState(!1),_=i.useCallback(async()=>{if(e)try{const $=await r(e,"get_provider_source_config",{}),C=ql($);C&&(g(C),f(C.sourceMode),I(C.explicitProviderDir||""))}catch{}},[e,r]),N=i.useCallback(async()=>{if(e){l(!0);try{const $=await r(e,"get_provider_settings",{}),C=yv($);if(C){const y=vv(C,t,{filterSchema:F=>F.filter(P=>P.key!=="enabled")});y.sort((F,P)=>F.category.localeCompare(P.category)||F.displayName.localeCompare(P.displayName)),a(y)}}catch{}l(!1)}},[e,t,r]);i.useEffect(()=>{n.length===0&&N(),p||_()},[]);const w=async($,C,y)=>{d(`${$}.${C}`),a(F=>F.map(P=>P.type===$?{...P,values:{...P.values,[C]:y}}:P));try{const F=await r(e,"set_provider_setting",{providerType:$,key:C,value:y});F!=null&&F.success||N()}catch{N()}d(null)},D=async($,C)=>{await w($,"enabled",C),await N()},M=async $=>{d(`${$}.detect`);try{await r(e,"detect_provider",{providerType:$})}finally{await N(),d(null)}},j=async $=>{await w($,"executablePath",""),await w($,"executableArgs",""),await N()},W=async()=>{A(!0);try{const $=await r(e,"set_provider_source_config",{providerSourceMode:v,providerDir:wv(T)}),C=ql($);C?(g(C),f(C.sourceMode),I(C.explicitProviderDir||"")):await _(),await N()}catch{await _()}A(!1)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex justify-between items-center mb-4",children:[s.jsxs("div",{className:"flex gap-1 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map($=>s.jsx("button",{onClick:()=>u($),className:`machine-btn text-[10px] px-2 py-0.5 ${m===$?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:$.toUpperCase()},$))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>b(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),s.jsx("button",{onClick:N,disabled:o,className:"machine-btn",children:o?"⏳ Loading...":"↻ Refresh"})]})]}),s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Running CLI sessions refresh provider scripts/config; process binary changes still apply on next launch."})]}),s.jsx("button",{onClick:_,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),s.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),s.jsxs("select",{value:v,onChange:$=>f($.target.value),className:"machine-input text-[11px]",children:[s.jsx("option",{value:"normal",children:"normal"}),s.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),s.jsx("input",{type:"text",value:T,onChange:$=>I($.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void W(),disabled:k,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:k?"Applying…":"Apply + Reload"})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(p==null?void 0:p.userDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(p==null?void 0:p.upstreamDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((H=p==null?void 0:p.providerRoots)==null?void 0:H.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter($=>$.category===m).length>1&&(()=>{const $=n.filter(P=>P.category===m),C=new Map;for(const P of $)for(const E of P.schema){if(E.type!=="boolean")continue;const G=C.get(E.key),J=!!(P.values[E.key]??E.default);G?(G.onCount+=J?1:0,G.total+=1):C.set(E.key,{label:E.label||E.key,onCount:J?1:0,total:1})}const y=[...C.entries()].filter(([,P])=>P.total===$.length);if(y.length===0)return null;const F=async(P,E)=>{for(const G of $)await w(G.type,P,E)};return s.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[s.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",m.toUpperCase()," providers (",$.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:y.map(([P,E])=>{const G=E.onCount===E.total,J=E.onCount===0;return s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:"text-text-secondary font-medium",children:E.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",E.onCount,"/",E.total,")"]}),s.jsx("button",{onClick:()=>void F(P,!0),disabled:G,className:`machine-btn text-[9px] px-1.5 py-px ${G?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void F(P,!1),disabled:J,className:`machine-btn text-[9px] px-1.5 py-px ${J?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},P)})})]})})(),o&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):s.jsx("div",{className:"flex flex-col gap-2",children:n.filter($=>m==="all"||$.category===m).map($=>s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[s.jsx("span",{className:"text-lg",children:$.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:$.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:$.category==="acp"?"rgba(139,92,246,0.08)":$.category==="cli"?"rgba(59,130,246,0.08)":$.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:$.category==="acp"?"#a78bfa":$.category==="cli"?"#60a5fa":$.category==="ide"?"#86efac":"var(--status-warning)"},children:$.category}),Xl($.category)&&(()=>{const C=t.find(P=>P.type===$.type),y=(C==null?void 0:C.enabled)===!0||$.values.enabled===!0,F=(C==null?void 0:C.machineStatus)||(y?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${Cv(F)}`,children:Nv(F)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void D($.type,!y),disabled:c===`${$.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${y?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:y?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void M($.type),disabled:!y||c===`${$.type}.detect`,title:y?"Run detection for the configured executable":"Enable this provider before detection",className:`machine-btn text-[9px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${y?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void j($.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),$.category==="ide"&&s.jsx("button",{onClick:()=>x(t.find(C=>C.type===$.type)||{type:$.type,name:$.displayName,displayName:$.displayName,icon:$.icon,category:$.category}),className:"ml-auto machine-btn text-[9px] px-2 py-0.5 bg-violet-500/[0.06] border-violet-500/20 text-violet-400 hover:bg-violet-500/[0.12]",children:"🔧 Auto-Fix"})]}),Xl($.category)&&(()=>{const C=t.find(y=>y.type===$.type);return s.jsxs("div",{className:"mb-2.5 grid gap-1 rounded-lg border border-white/[0.06] bg-bg-primary/40 px-3 py-2 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Detection:"})," ",Jl(C==null?void 0:C.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",Jl(C==null?void 0:C.lastVerification)]}),s.jsx("div",{className:"text-[9px] text-text-muted",children:"Supported catalog entry only becomes launchable after Enable + Detect succeeds. Custom executable path/args below are machine-local overrides."})]})})(),s.jsx("div",{className:"flex flex-col gap-2",children:$.schema.map(C=>s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[C.label||C.key,c===`${$.type}.${C.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),C.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:C.description})]}),s.jsx("div",{className:"shrink-0",children:C.type==="boolean"?s.jsx("button",{onClick:()=>w($.type,C.key,!($.values[C.key]??C.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:$.values[C.key]??C.default?"#8b5cf6":"var(--border-subtle)"},children:s.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:$.values[C.key]??C.default?21:3}})}):C.type==="number"?s.jsx("input",{type:"number",value:Number($.values[C.key]??C.default??0)||0,min:C.min,max:C.max,onChange:y=>{const F=parseInt(y.target.value)||0;C.min!==void 0&&F<C.min||C.max!==void 0&&F>C.max||w($.type,C.key,F)},className:"machine-input w-20 text-center text-[11px]"}):C.type==="select"&&C.options?s.jsx("select",{value:String($.values[C.key]??C.default??""),onChange:y=>w($.type,C.key,y.target.value),className:"machine-input text-[11px]",children:C.options.map(y=>s.jsx("option",{value:y,children:y},y))}):s.jsx("input",{type:"text",value:String($.values[C.key]??C.default??""),onBlur:y=>w($.type,C.key,y.target.value),className:"machine-input w-[120px] text-[11px]"})})]},C.key))})]},$.type))}),h&&s.jsx(kv,{machineId:e,provider:h,sendDaemonCommand:r,onClose:()=>x(null)}),S&&s.jsx(Sv,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>b(!1),onCreated:()=>{b(!1),N()}})]})}const Tv=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Mv({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function Av(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function _v(e){return e.trim().toLowerCase()}function sa(e,t){const r=_v(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function pi(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Js(e,t=220){const r=pi(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function Lv(e){const t=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(t))return{kind:t.length>0?"structured":"empty",entries:t.map(r=>{const n=r;return{timestamp:Number(n.ts)||0,level:n.level||"info",message:`[${String(n.category||"daemon")}] ${String(n.message||"")}`.trim()}}),rawText:""};if(typeof t=="string"){const r=t.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function Rv(e,t){return e.filter(r=>sa([r.level,r.message],t))}function Ql(e){return`${e.timestamp}:${e.level}:${e.message}`}function Pv(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const l of e.entries)n.set(Ql(l),l);for(const l of t.entries)n.set(Ql(l),l);const a=Array.from(n.values()).sort((l,c)=>l.timestamp-c.timestamp).slice(-r),o=a.reduce((l,c)=>Math.max(l,Number(c.timestamp||0)),e.lastTs);return{entries:a,kind:"structured",rawText:"",lastTs:o}}return t.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:t.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function Dv(e,t,r=120){if(t.length===0)return e;const n=new Map;for(const a of e)n.set(a.id,a);for(const a of t)n.set(a.id,a);return Array.from(n.values()).sort((a,o)=>a.ts-o.ts).slice(-r)}function Ev(e,t){return e.split(`
76
- `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>sa([r],t))}function $v(e,t){return e.filter(r=>sa([r.level,r.category,r.stage,r.interactionId,pi(r.payload)],t))}function Bv(e,t){return e.filter(r=>sa([r.kind,r.topic,r.interactionId,pi(r.payload)],t))}function Zl(e){return e==="warn"||e==="error"}function Ov({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){return{all:e.length+t.length+r.length+n.length,info:e.filter(a=>a.level!=="debug").length+r.filter(a=>a.level!=="debug").length+n.length,issues:e.filter(a=>Zl(a.level)).length+r.filter(a=>Zl(a.level)).length}}function Fv({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(o=>`${new Date(o.timestamp).toISOString()} ${o.level.toUpperCase()} ${o.message}`)].join(`
75
+ ⚠️ Auto-fix cancelled.`]),o("done"),v.current&&clearInterval(v.current)}catch{}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm 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",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:N=>N.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:t.icon||"🔧"}),s.jsxs("div",{children:[s.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",t.displayName]}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),s.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),s.jsx("div",{className:"flex gap-2",children:kv.map(N=>s.jsxs("button",{onClick:()=>c(N.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:l===N.value?N.color+"66":"var(--border-subtle)",background:l===N.value?N.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:l===N.value?N.color:"var(--text-primary)"},children:N.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:N.desc})]},N.value))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:T,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),s.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),s.jsx("button",{onClick:I,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Yl.map(N=>s.jsxs("button",{onClick:()=>f(N),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(N)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(N)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(N)?"#a78bfa":"var(--text-secondary)"},children:[d.includes(N)?"☑ ":"☐ ",N]},N))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",s.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),s.jsx("textarea",{value:u,onChange:N=>h(N.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[x.map((N,w)=>s.jsx("div",{className:N.startsWith("✅")?"text-green-400":"",style:N.startsWith("❌")||N.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:N},w)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:g})]}),b&&s.jsx("div",{className:"mt-2 px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:b})]})]}),s.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[s.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&d.length>0&&`${d.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),s.jsxs("div",{className:"flex gap-2",children:[a==="config"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:A,disabled:d.length===0,className:"machine-btn",style:{background:d.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:d.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:d.length>0?"#a78bfa":void 0,opacity:d.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&s.jsx("button",{onClick:_,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{o("config"),S([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Nv({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var k;const o=t.filter(A=>A.category==="ide"),[l,c]=i.useState(((k=o[0])==null?void 0:k.type)||""),[d,m]=i.useState(""),[u,h]=i.useState(""),[x,S]=i.useState(!1),[b,p]=i.useState(""),[g,v]=i.useState(!1),f=A=>{const _=A.toLowerCase().replace(/[^a-z0-9-]/g,"");m(_),(!u||u===T(d))&&h(T(_))},T=A=>A.split("-").map(_=>_.charAt(0).toUpperCase()+_.slice(1)).join(" "),I=async()=>{if(!(!d||!u||!l)){S(!0),p("");try{const A=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:l});A!=null&&A.success||A!=null&&A.created?(v(!0),a==null||a(d)):p((A==null?void 0:A.error)||"Failed to create provider")}catch(A){p((A==null?void 0:A.message)||"Connection failed")}S(!1)}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm 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",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:A=>A.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:g?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:d})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:o.map(A=>s.jsxs("button",{onClick:()=>c(A.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:l===A.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:l===A.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:A.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:l===A.type?"#a78bfa":"var(--text-secondary)"},children:A.displayName})]},A.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:d,onChange:A=>f(A.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",d||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:u,onChange:A=>h(A.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),b&&s.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:b})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:g?s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:I,disabled:!d||!u||x,className:"machine-btn",style:{background:d&&u?"rgba(34,197,94,0.12)":void 0,borderColor:d&&u?"rgba(34,197,94,0.3)":void 0,color:d&&u?"#86efac":void 0,opacity:!d||!u||x?.4:1},children:x?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Xl(e){return e==="cli"||e==="acp"}function Cv(e){switch(e){case"detected":return"Detected";case"not_detected":return"Not detected";case"enabled_unchecked":return"Enabled, not checked";case"disabled":return"Disabled";default:return"Disabled"}}function Iv(e){switch(e){case"detected":return"bg-green-500/[0.10] border-green-500/25 text-green-400";case"not_detected":return"bg-red-500/[0.10] border-red-500/25 text-red-400";case"enabled_unchecked":return"bg-yellow-500/[0.10] border-yellow-500/25 text-yellow-400";case"disabled":default:return"bg-white/[0.04] border-white/[0.10] text-text-muted"}}function Jl(e){if(!e)return"No result yet";const t=e.stage||"check",r=e.ok?"OK":"Failed",n=e.message||e.path||e.command||"";return n?`${t}: ${r} — ${n}`:`${t}: ${r}`}function Tv({machineId:e,providers:t,sendDaemonCommand:r}){var H;const[n,a]=i.useState([]),[o,l]=i.useState(!1),[c,d]=i.useState(null),[m,u]=i.useState("all"),[h,x]=i.useState(null),[S,b]=i.useState(!1),[p,g]=i.useState(null),[v,f]=i.useState("normal"),[T,I]=i.useState(""),[k,A]=i.useState(!1),_=i.useCallback(async()=>{if(e)try{const $=await r(e,"get_provider_source_config",{}),C=ql($);C&&(g(C),f(C.sourceMode),I(C.explicitProviderDir||""))}catch{}},[e,r]),N=i.useCallback(async()=>{if(e){l(!0);try{const $=await r(e,"get_provider_settings",{}),C=vv($);if(C){const y=wv(C,t,{filterSchema:F=>F.filter(P=>P.key!=="enabled")});y.sort((F,P)=>F.category.localeCompare(P.category)||F.displayName.localeCompare(P.displayName)),a(y)}}catch{}l(!1)}},[e,t,r]);i.useEffect(()=>{n.length===0&&N(),p||_()},[]);const w=async($,C,y)=>{d(`${$}.${C}`),a(F=>F.map(P=>P.type===$?{...P,values:{...P.values,[C]:y}}:P));try{const F=await r(e,"set_provider_setting",{providerType:$,key:C,value:y});F!=null&&F.success||N()}catch{N()}d(null)},D=async($,C)=>{await w($,"enabled",C),await N()},M=async $=>{d(`${$}.detect`);try{await r(e,"detect_provider",{providerType:$})}finally{await N(),d(null)}},j=async $=>{await w($,"executablePath",""),await w($,"executableArgs",""),await N()},W=async()=>{A(!0);try{const $=await r(e,"set_provider_source_config",{providerSourceMode:v,providerDir:jv(T)}),C=ql($);C?(g(C),f(C.sourceMode),I(C.explicitProviderDir||"")):await _(),await N()}catch{await _()}A(!1)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex justify-between items-center mb-4",children:[s.jsxs("div",{className:"flex gap-1 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map($=>s.jsx("button",{onClick:()=>u($),className:`machine-btn text-[10px] px-2 py-0.5 ${m===$?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:$.toUpperCase()},$))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>b(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),s.jsx("button",{onClick:N,disabled:o,className:"machine-btn",children:o?"⏳ Loading...":"↻ Refresh"})]})]}),s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Running CLI sessions refresh provider scripts/config; process binary changes still apply on next launch."})]}),s.jsx("button",{onClick:_,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),s.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),s.jsxs("select",{value:v,onChange:$=>f($.target.value),className:"machine-input text-[11px]",children:[s.jsx("option",{value:"normal",children:"normal"}),s.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),s.jsx("input",{type:"text",value:T,onChange:$=>I($.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void W(),disabled:k,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:k?"Applying…":"Apply + Reload"})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(p==null?void 0:p.userDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(p==null?void 0:p.upstreamDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((H=p==null?void 0:p.providerRoots)==null?void 0:H.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter($=>$.category===m).length>1&&(()=>{const $=n.filter(P=>P.category===m),C=new Map;for(const P of $)for(const E of P.schema){if(E.type!=="boolean")continue;const G=C.get(E.key),J=!!(P.values[E.key]??E.default);G?(G.onCount+=J?1:0,G.total+=1):C.set(E.key,{label:E.label||E.key,onCount:J?1:0,total:1})}const y=[...C.entries()].filter(([,P])=>P.total===$.length);if(y.length===0)return null;const F=async(P,E)=>{for(const G of $)await w(G.type,P,E)};return s.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[s.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",m.toUpperCase()," providers (",$.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:y.map(([P,E])=>{const G=E.onCount===E.total,J=E.onCount===0;return s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:"text-text-secondary font-medium",children:E.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",E.onCount,"/",E.total,")"]}),s.jsx("button",{onClick:()=>void F(P,!0),disabled:G,className:`machine-btn text-[9px] px-1.5 py-px ${G?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void F(P,!1),disabled:J,className:`machine-btn text-[9px] px-1.5 py-px ${J?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},P)})})]})})(),o&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):s.jsx("div",{className:"flex flex-col gap-2",children:n.filter($=>m==="all"||$.category===m).map($=>s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[s.jsx("span",{className:"text-lg",children:$.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:$.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:$.category==="acp"?"rgba(139,92,246,0.08)":$.category==="cli"?"rgba(59,130,246,0.08)":$.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:$.category==="acp"?"#a78bfa":$.category==="cli"?"#60a5fa":$.category==="ide"?"#86efac":"var(--status-warning)"},children:$.category}),Xl($.category)&&(()=>{const C=t.find(P=>P.type===$.type),y=(C==null?void 0:C.enabled)===!0||$.values.enabled===!0,F=(C==null?void 0:C.machineStatus)||(y?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${Iv(F)}`,children:Cv(F)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void D($.type,!y),disabled:c===`${$.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${y?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:y?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void M($.type),disabled:!y||c===`${$.type}.detect`,title:y?"Run detection for the configured executable":"Enable this provider before detection",className:`machine-btn text-[9px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${y?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void j($.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),$.category==="ide"&&s.jsx("button",{onClick:()=>x(t.find(C=>C.type===$.type)||{type:$.type,name:$.displayName,displayName:$.displayName,icon:$.icon,category:$.category}),className:"ml-auto machine-btn text-[9px] px-2 py-0.5 bg-violet-500/[0.06] border-violet-500/20 text-violet-400 hover:bg-violet-500/[0.12]",children:"🔧 Auto-Fix"})]}),Xl($.category)&&(()=>{const C=t.find(y=>y.type===$.type);return s.jsxs("div",{className:"mb-2.5 grid gap-1 rounded-lg border border-white/[0.06] bg-bg-primary/40 px-3 py-2 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Detection:"})," ",Jl(C==null?void 0:C.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",Jl(C==null?void 0:C.lastVerification)]}),s.jsx("div",{className:"text-[9px] text-text-muted",children:"Supported catalog entry only becomes launchable after Enable + Detect succeeds. Custom executable path/args below are machine-local overrides."})]})})(),s.jsx("div",{className:"flex flex-col gap-2",children:$.schema.map(C=>s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[C.label||C.key,c===`${$.type}.${C.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),C.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:C.description})]}),s.jsx("div",{className:"shrink-0",children:C.type==="boolean"?s.jsx("button",{onClick:()=>w($.type,C.key,!($.values[C.key]??C.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:$.values[C.key]??C.default?"#8b5cf6":"var(--border-subtle)"},children:s.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:$.values[C.key]??C.default?21:3}})}):C.type==="number"?s.jsx("input",{type:"number",value:Number($.values[C.key]??C.default??0)||0,min:C.min,max:C.max,onChange:y=>{const F=parseInt(y.target.value)||0;C.min!==void 0&&F<C.min||C.max!==void 0&&F>C.max||w($.type,C.key,F)},className:"machine-input w-20 text-center text-[11px]"}):C.type==="select"&&C.options?s.jsx("select",{value:String($.values[C.key]??C.default??""),onChange:y=>w($.type,C.key,y.target.value),className:"machine-input text-[11px]",children:C.options.map(y=>s.jsx("option",{value:y,children:y},y))}):s.jsx("input",{type:"text",value:String($.values[C.key]??C.default??""),onBlur:y=>w($.type,C.key,y.target.value),className:"machine-input w-[120px] text-[11px]"})})]},C.key))})]},$.type))}),h&&s.jsx(Sv,{machineId:e,provider:h,sendDaemonCommand:r,onClose:()=>x(null)}),S&&s.jsx(Nv,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>b(!1),onCreated:()=>{b(!1),N()}})]})}const Mv=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Av({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function _v(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function Lv(e){return e.trim().toLowerCase()}function sa(e,t){const r=Lv(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function pi(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Js(e,t=220){const r=pi(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function Rv(e){const t=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(t))return{kind:t.length>0?"structured":"empty",entries:t.map(r=>{const n=r;return{timestamp:Number(n.ts)||0,level:n.level||"info",message:`[${String(n.category||"daemon")}] ${String(n.message||"")}`.trim()}}),rawText:""};if(typeof t=="string"){const r=t.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function Pv(e,t){return e.filter(r=>sa([r.level,r.message],t))}function Ql(e){return`${e.timestamp}:${e.level}:${e.message}`}function Dv(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const l of e.entries)n.set(Ql(l),l);for(const l of t.entries)n.set(Ql(l),l);const a=Array.from(n.values()).sort((l,c)=>l.timestamp-c.timestamp).slice(-r),o=a.reduce((l,c)=>Math.max(l,Number(c.timestamp||0)),e.lastTs);return{entries:a,kind:"structured",rawText:"",lastTs:o}}return t.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:t.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function Ev(e,t,r=120){if(t.length===0)return e;const n=new Map;for(const a of e)n.set(a.id,a);for(const a of t)n.set(a.id,a);return Array.from(n.values()).sort((a,o)=>a.ts-o.ts).slice(-r)}function $v(e,t){return e.split(`
76
+ `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>sa([r],t))}function Bv(e,t){return e.filter(r=>sa([r.level,r.category,r.stage,r.interactionId,pi(r.payload)],t))}function Ov(e,t){return e.filter(r=>sa([r.kind,r.topic,r.interactionId,pi(r.payload)],t))}function Zl(e){return e==="warn"||e==="error"}function Fv({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){return{all:e.length+t.length+r.length+n.length,info:e.filter(a=>a.level!=="debug").length+r.filter(a=>a.level!=="debug").length+n.length,issues:e.filter(a=>Zl(a.level)).length+r.filter(a=>Zl(a.level)).length}}function Wv({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(o=>`${new Date(o.timestamp).toISOString()} ${o.level.toUpperCase()} ${o.message}`)].join(`
77
77
  `)):t.length>0&&a.push(["[daemon logs]",...t].join(`
78
78
  `)),r.length>0&&a.push(["[trace]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${Js(o.payload,500)}`.trim())].join(`
79
79
  `)),n.length>0&&a.push(["[browser events]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${Js(o.payload,500)}`.trim())].join(`
80
80
  `)),a.join(`
81
81
 
82
- `)}function Wv({machineId:e,sendDaemonCommand:t}){const[r,n]=i.useState([]),[a,o]=i.useState("empty"),[l,c]=i.useState(""),[d,m]=i.useState([]),[u,h]=i.useState([]),[x,S]=i.useState(null),[b,p]=i.useState(!0),[g,v]=i.useState("info"),[f,T]=i.useState("all"),[I,k]=i.useState(!0),[A,_]=i.useState(!0),[N,w]=i.useState(""),[D,M]=i.useState(""),[j,W]=i.useState(0),H=i.useRef(0),$=i.useRef(0),C=i.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),y=i.useRef([]),F=i.useCallback(()=>{const ne={entries:[],kind:"empty",rawText:"",lastTs:0};C.current=ne,H.current=0,n([]),c(""),o("empty"),k(!0)},[]),P=i.useCallback(()=>{y.current=[],$.current=0,m([]),_(!0)},[]),E=i.useCallback(ne=>{ne!==g&&(F(),v(ne))},[g,F]),G=i.useCallback(ne=>{T(ue=>ue===ne?ue:ne)},[]),J=i.useCallback(()=>{F(),P(),h([]),S(null),w(""),M(""),Hs.clear()},[F,P]),ye=i.useCallback(()=>{W(ne=>ne+1)},[]),he=i.useCallback(async()=>{if(!e)return;const ne=H.current,ue=$.current,[Se,ve]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:g,since:ne}),t(e,"get_debug_trace",Mv({count:120,since:ue,category:f}))]);if(Se.status==="fulfilled"){const X=Se.value,xe=(X==null?void 0:X.result)||X,fe=Lv(xe),we=Pv(C.current,fe,300);C.current=we,H.current=we.lastTs,k(!1),w((X==null?void 0:X.success)===!1?String((X==null?void 0:X.error)||"Could not load daemon logs"):""),o(we.kind),c(we.rawText),n(we.entries)}else k(!1),w(Se.reason instanceof Error?Se.reason.message:"Could not load daemon logs");if(ve.status==="fulfilled"){const X=ve.value,xe=(X==null?void 0:X.result)||X;if((X==null?void 0:X.success)===!1)M(String((X==null?void 0:X.error)||"Could not load daemon trace"));else if(Array.isArray(xe==null?void 0:xe.trace)){const fe=xe.trace,we=Dv(y.current,fe,120),be=fe.reduce((Ce,ee)=>Math.max(Ce,Number(ee.ts||0)),ue);y.current=we,be>ue&&($.current=be),M(""),m(we)}else M("");_(!1)}else _(!1),M(ve.reason instanceof Error?ve.reason.message:"Could not load daemon trace");h(Hs.list({limit:120})),S(Date.now())},[g,e,t,f]);return i.useEffect(()=>{P()},[P,f]),i.useEffect(()=>{if(!e||(he(),!b))return;const ne=setInterval(()=>{he()},3e3);return()=>clearInterval(ne)},[b,he,e,j]),{daemonLogs:r,daemonLogKind:a,daemonRawText:l,debugTrace:d,webEvents:u,lastUpdatedAt:x,autoRefresh:b,logLevel:g,traceCategory:f,daemonLoading:I,traceLoading:A,daemonFetchError:N,traceFetchError:D,setAutoRefresh:p,setLogLevel:E,setTraceCategory:G,refresh:ye,clear:J}}function Kv({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:l,traceCount:c,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":o>0||l>0?"ok":"empty",detail:r||(a==="text"?`${l} raw file-fallback line(s)`:`${o} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:n?"error":t?"loading":c>0?"ok":"empty",detail:n||`${c} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:d>0?"ok":"empty",detail:d>0?`${d} local browser event(s)`:"No browser events captured"}]}function ec(e){return e==="warn"||e==="error"}function Hv(e){const t=e.toLowerCase();return/\[(err|error)\]/i.test(e)||t.includes(" error ")||t.includes(" failed")?"error":/\[(wrn|warn|warning)\]/i.test(e)||t.includes(" warning ")||t.includes(" timeout")?"warn":/\[(dbg|debug)\]/i.test(e)?"debug":"info"}function Uv(e,t){const r=e.match(/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\b/);if(r){const n=Date.parse(r[0]);if(Number.isFinite(n))return n}return Number.MAX_SAFE_INTEGER-1e5+t}function tc(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function zv(e){const t=Js(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function Vv(e){const t=Js(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function Gv({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.forEach((o,l)=>{a.push({id:`daemon-log-${o.timestamp}-${l}`,source:"daemon_log",ts:Number(o.timestamp||0),severity:o.level,message:o.message,raw:o.message})}),n.forEach(o=>{a.push({id:`browser-event-${o.id}`,source:"browser_event",ts:Number(o.ts||0),severity:"info",message:Vv(o),topic:o.topic,interactionId:o.interactionId,payload:o.payload})}),r.forEach(o=>{a.push({id:`daemon-trace-${o.id}`,source:"daemon_trace",ts:Number(o.ts||0),severity:o.level,message:zv(o),category:o.category,stage:o.stage,interactionId:o.interactionId,payload:o.payload})}),t.forEach((o,l)=>{a.push({id:`raw-file-${l}`,source:"raw_file",ts:Uv(o,l),severity:Hv(o),message:o,raw:o})}),a.sort((o,l)=>o.ts!==l.ts?o.ts-l.ts:tc(o.source)-tc(l.source))}function qv(e){return`${e.source}:${e.severity}:${e.message}`}function Yv(e){const t=e.filter(n=>ec(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!ec(n.severity))continue;const a=qv(n),o=r.get(a);o?(o.count+=1,o.firstTs=Math.min(o.firstTs,n.ts),o.lastTs=Math.max(o.lastTs,n.ts)):r.set(a,{key:a,source:n.source,severity:n.severity,message:n.message,count:1,firstTs:n.ts,lastTs:n.ts})}return{totalCount:e.length,issueCount:t.length,latestIssue:t[0]||null,repeatedPatterns:Array.from(r.values()).filter(n=>n.count>1).sort((n,a)=>a.count!==n.count?a.count-n.count:a.lastTs-n.lastTs).slice(0,5)}}function Xv(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function sc(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${Xv(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function Jv({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
82
+ `)}function Kv({machineId:e,sendDaemonCommand:t}){const[r,n]=i.useState([]),[a,o]=i.useState("empty"),[l,c]=i.useState(""),[d,m]=i.useState([]),[u,h]=i.useState([]),[x,S]=i.useState(null),[b,p]=i.useState(!0),[g,v]=i.useState("info"),[f,T]=i.useState("all"),[I,k]=i.useState(!0),[A,_]=i.useState(!0),[N,w]=i.useState(""),[D,M]=i.useState(""),[j,W]=i.useState(0),H=i.useRef(0),$=i.useRef(0),C=i.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),y=i.useRef([]),F=i.useCallback(()=>{const ne={entries:[],kind:"empty",rawText:"",lastTs:0};C.current=ne,H.current=0,n([]),c(""),o("empty"),k(!0)},[]),P=i.useCallback(()=>{y.current=[],$.current=0,m([]),_(!0)},[]),E=i.useCallback(ne=>{ne!==g&&(F(),v(ne))},[g,F]),G=i.useCallback(ne=>{T(ue=>ue===ne?ue:ne)},[]),J=i.useCallback(()=>{F(),P(),h([]),S(null),w(""),M(""),Hs.clear()},[F,P]),ye=i.useCallback(()=>{W(ne=>ne+1)},[]),he=i.useCallback(async()=>{if(!e)return;const ne=H.current,ue=$.current,[Se,ve]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:g,since:ne}),t(e,"get_debug_trace",Av({count:120,since:ue,category:f}))]);if(Se.status==="fulfilled"){const X=Se.value,xe=(X==null?void 0:X.result)||X,fe=Rv(xe),we=Dv(C.current,fe,300);C.current=we,H.current=we.lastTs,k(!1),w((X==null?void 0:X.success)===!1?String((X==null?void 0:X.error)||"Could not load daemon logs"):""),o(we.kind),c(we.rawText),n(we.entries)}else k(!1),w(Se.reason instanceof Error?Se.reason.message:"Could not load daemon logs");if(ve.status==="fulfilled"){const X=ve.value,xe=(X==null?void 0:X.result)||X;if((X==null?void 0:X.success)===!1)M(String((X==null?void 0:X.error)||"Could not load daemon trace"));else if(Array.isArray(xe==null?void 0:xe.trace)){const fe=xe.trace,we=Ev(y.current,fe,120),be=fe.reduce((Ce,ee)=>Math.max(Ce,Number(ee.ts||0)),ue);y.current=we,be>ue&&($.current=be),M(""),m(we)}else M("");_(!1)}else _(!1),M(ve.reason instanceof Error?ve.reason.message:"Could not load daemon trace");h(Hs.list({limit:120})),S(Date.now())},[g,e,t,f]);return i.useEffect(()=>{P()},[P,f]),i.useEffect(()=>{if(!e||(he(),!b))return;const ne=setInterval(()=>{he()},3e3);return()=>clearInterval(ne)},[b,he,e,j]),{daemonLogs:r,daemonLogKind:a,daemonRawText:l,debugTrace:d,webEvents:u,lastUpdatedAt:x,autoRefresh:b,logLevel:g,traceCategory:f,daemonLoading:I,traceLoading:A,daemonFetchError:N,traceFetchError:D,setAutoRefresh:p,setLogLevel:E,setTraceCategory:G,refresh:ye,clear:J}}function Hv({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:l,traceCount:c,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":o>0||l>0?"ok":"empty",detail:r||(a==="text"?`${l} raw file-fallback line(s)`:`${o} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:n?"error":t?"loading":c>0?"ok":"empty",detail:n||`${c} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:d>0?"ok":"empty",detail:d>0?`${d} local browser event(s)`:"No browser events captured"}]}function ec(e){return e==="warn"||e==="error"}function Uv(e){const t=e.toLowerCase();return/\[(err|error)\]/i.test(e)||t.includes(" error ")||t.includes(" failed")?"error":/\[(wrn|warn|warning)\]/i.test(e)||t.includes(" warning ")||t.includes(" timeout")?"warn":/\[(dbg|debug)\]/i.test(e)?"debug":"info"}function zv(e,t){const r=e.match(/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\b/);if(r){const n=Date.parse(r[0]);if(Number.isFinite(n))return n}return Number.MAX_SAFE_INTEGER-1e5+t}function tc(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function Vv(e){const t=Js(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function Gv(e){const t=Js(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function qv({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.forEach((o,l)=>{a.push({id:`daemon-log-${o.timestamp}-${l}`,source:"daemon_log",ts:Number(o.timestamp||0),severity:o.level,message:o.message,raw:o.message})}),n.forEach(o=>{a.push({id:`browser-event-${o.id}`,source:"browser_event",ts:Number(o.ts||0),severity:"info",message:Gv(o),topic:o.topic,interactionId:o.interactionId,payload:o.payload})}),r.forEach(o=>{a.push({id:`daemon-trace-${o.id}`,source:"daemon_trace",ts:Number(o.ts||0),severity:o.level,message:Vv(o),category:o.category,stage:o.stage,interactionId:o.interactionId,payload:o.payload})}),t.forEach((o,l)=>{a.push({id:`raw-file-${l}`,source:"raw_file",ts:zv(o,l),severity:Uv(o),message:o,raw:o})}),a.sort((o,l)=>o.ts!==l.ts?o.ts-l.ts:tc(o.source)-tc(l.source))}function Yv(e){return`${e.source}:${e.severity}:${e.message}`}function Xv(e){const t=e.filter(n=>ec(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!ec(n.severity))continue;const a=Yv(n),o=r.get(a);o?(o.count+=1,o.firstTs=Math.min(o.firstTs,n.ts),o.lastTs=Math.max(o.lastTs,n.ts)):r.set(a,{key:a,source:n.source,severity:n.severity,message:n.message,count:1,firstTs:n.ts,lastTs:n.ts})}return{totalCount:e.length,issueCount:t.length,latestIssue:t[0]||null,repeatedPatterns:Array.from(r.values()).filter(n=>n.count>1).sort((n,a)=>a.count!==n.count?a.count-n.count:a.lastTs-n.lastTs).slice(0,5)}}function Jv(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function sc(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${Jv(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function Qv({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
83
83
  `)),a.push(["[source status]",...r.map(l=>`${l.label}: ${l.status} - ${l.detail}`)].join(`
84
84
  `)),t.latestIssue&&a.push(["[latest issue]",sc(t.latestIssue)].join(`
85
85
  `)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(l=>`${l.count}x ${l.severity.toUpperCase()} ${l.source} ${l.message}`)].join(`
86
86
  `));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(sc):["No diagnostic events captured."]].join(`
87
87
  `)),a.join(`
88
88
 
89
- `)}function Qv(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Zv(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function ew({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:l,searchQuery:c,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:h}){const x=Av(n,o),S=Rv(e,c),b=Ev(t,c),p=$v(x,c),g=Bv(a,c),v=Qv(S,l),f=l==="all"?b:[],T=Zv(p,l),I=l==="issues"?[]:g,k=Ov({daemonLogs:S,daemonRawLines:b,trace:p,webEvents:g}),A=Gv({daemonLogs:v,daemonRawLines:f,trace:T,webEvents:I}),_=Yv(A),N=Kv({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:h,daemonLogKind:r,daemonLogsCount:S.length,daemonRawLineCount:b.length,traceCount:p.length,webEventCount:g.length});return{filteredDaemonLogs:S,filteredDaemonRawLines:b,filteredTraceEntries:p,filteredWebEvents:g,visibleDaemonLogs:v,visibleDaemonRawLines:f,visibleTraceEntries:T,visibleWebEvents:I,quickFilterCounts:k,diagnosticEvents:A,diagnosticsSummary:_,sourceStates:N}}function tw(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Du(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function So(e){return e==="error"?"text-red-300 border-red-500/25 bg-red-500/[0.05]":e==="warn"?"text-amber-200 border-amber-500/25 bg-amber-500/[0.05]":e==="debug"?"text-slate-300 border-slate-500/25 bg-slate-500/[0.05]":"text-text-secondary border-border-subtle bg-bg-primary"}function Ua(e){return e==="good"?"border-emerald-500/20 bg-emerald-500/[0.05]":e==="warning"?"border-amber-500/20 bg-amber-500/[0.05]":e==="danger"?"border-red-500/20 bg-red-500/[0.05]":"border-border-subtle bg-bg-secondary"}function hi(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function sw({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${So(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Du(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:hi(e.source)}),e.category&&e.stage&&s.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&s.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&s.jsxs("span",{children:["ix=",e.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function rw({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:l,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:m,onClear:u}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(h=>s.jsx("button",{type:"button",onClick:()=>a(h.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===h.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:h.label},h.id))}),s.jsx("input",{value:r,onChange:h=>o(h.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:l,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:d,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function nw({logLevel:e,traceCategory:t,onLogLevelChange:r,onTraceCategoryChange:n}){return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-3",children:s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(a=>s.jsxs("button",{onClick:()=>r(a),className:`machine-btn text-[10px] px-2 py-0.5 ${e===a?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",a.toUpperCase(),"+"]},a))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:Tv.map(a=>s.jsx("button",{onClick:()=>n(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function aw({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:l,traceFetchError:c}){var u,h;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((h=e.latestIssue)==null?void 0:h.severity)==="warn"?"warning":"good",m=l||c?"danger":o?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Ua(e.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:n.trim()?`Filtered by “${n.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Ua(d)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[hi(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:Du(e.latestIssue.ts)})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Ua(m)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:l||c?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",tw(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(x=>s.jsxs("div",{children:[x.label,": ",x.status]},x.id))})]})]})}function ow({patterns:e}){return e.length===0?null:s.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(t=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[s.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[t.count,"× ",t.severity.toUpperCase()," · ",hi(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function iw({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:l,visibleWebEvents:c,quickFilter:d,searchQuery:m}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,timeline:!u.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(u=>s.jsx(sw,{event:u},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,daemon:!u.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&o.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:d==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((u,h)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${h}`)),e.daemonLogKind!=="text"&&a.map((u,h)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${So(u.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:u.level==="error"?"ERR":u.level==="warn"?"WRN":u.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:u.message})]},`log-${h}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,trace:!u.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[l.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&l.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&l.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&l.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No trace entries match the current search.":e.traceCategory==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),l.map(u=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${So(u.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.level.toUpperCase()}),s.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Js(u.payload,360)||"No payload"})]},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,web:!u.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[c.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),c.map(u=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.kind}),u.topic&&s.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Js(u.payload,360)||"No payload"})]},u.id))]})]})]})}function lw({machineId:e,sendDaemonCommand:t}){const r=Wv({machineId:e,sendDaemonCommand:t}),[n,a]=i.useState("info"),[o,l]=i.useState(""),[c,d]=i.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=i.useRef(null),u=i.useRef(!1),h=i.useMemo(()=>ew({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:o,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,o,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);i.useEffect(()=>{if(r.autoRefresh&&h.diagnosticEvents.length>0){const b=u.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:b}),u.current=!0},50)}},[h.diagnosticEvents.length,r.autoRefresh]);const x=i.useCallback(async()=>{var p;const b=Fv({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!b.trim()){it.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(b)),it.showToast("Copied visible logs to clipboard.","success")}catch(g){it.showToast(g instanceof Error?g.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),S=i.useCallback(async()=>{var p;const b=Jv({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(b)),it.showToast("Copied diagnostic bundle to clipboard.","success")}catch(g){it.showToast(g instanceof Error?g.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(rw,{quickFilter:n,quickFilterCounts:h.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:l,onCopyDiagnostics:()=>{S()},onCopyVisible:()=>{x()},onToggleAutoRefresh:()=>r.setAutoRefresh(b=>!b),onRefresh:r.refresh,onClear:r.clear}),s.jsx(nw,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(aw,{diagnosticsSummary:h.diagnosticsSummary,diagnosticEventsCount:h.diagnosticEvents.length,sourceStates:h.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(ow,{patterns:h.diagnosticsSummary.repeatedPatterns}),s.jsx(iw,{streams:r,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:m})]})}function cw(e){return e.diagnostics?{label:"Managed",toneClass:"bg-green-500/[0.08] text-green-500"}:e.loading||e.refreshing?{label:"Checking…",toneClass:"bg-sky-500/[0.08] text-sky-400"}:e.error?{label:"Diagnostics issue",toneClass:"bg-amber-500/[0.08] text-amber-400"}:{label:"Unavailable",toneClass:"bg-red-500/[0.08] text-red-400"}}function Eu(e){const t=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return t?t==="auto_resumed"?"restored after restart":t==="resume_failed"?"restore failed":t==="host_restart_interrupted"?"host restart interrupted":t==="orphan_snapshot"?"snapshot recovered":t.replace(/_/g," "):null}function dw(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const l=String((o==null?void 0:o.lifecycle)||"").trim(),c=Eu((o==null?void 0:o.meta)||void 0),d=((a=o==null?void 0:o.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(l)?t.push(o):(l==="stopped"||l==="failed")&&(d||c)?r.push(o):n.push(o)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function uw(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function za(e){return e==="live"?"These runtimes are live now and are the only attachable targets.":e==="recovery"?"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.":"These inactive records are shown for reference and usually need restart before they are useful again."}function Va(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Ga(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function rc(e){if(!e)return"unknown";const t=Date.now()-e,r=Math.max(0,Math.round(t/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const a=Math.round(n/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function mw(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function pw(e){switch(e){case"running":return"bg-green-500/[0.08] text-green-500";case"starting":return"bg-sky-500/[0.08] text-sky-400";case"stopping":return"bg-orange-500/[0.08] text-orange-400";case"interrupted":return"bg-amber-500/[0.08] text-amber-400";case"failed":return"bg-red-500/[0.08] text-red-500";default:return"bg-[#ffffff0a] text-text-muted"}}function hw(e){var r;const t=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const a=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!a)continue;const o=`${n.providerType}::${n.workspace}::${a}`;t.set(o,(t.get(o)||0)+1)}return Array.from(t.values()).filter(n=>n>1).length}function fw({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=i.useState(""),[o,l]=i.useState(null),[c,d]=i.useState(!1),m=Mb(e,{enabled:!!e,includeSessions:!0,limit:qi,intervalMs:Nf}),u=m.diagnostics,h=m.loading,x=m.applyDiagnostics,S=i.useMemo(()=>cw({diagnostics:u,loading:h,refreshing:c,error:n}),[u,h,c,n]),b=i.useMemo(()=>new Map(t.map(M=>[M.sessionId||M.id,M])),[t]),p=i.useCallback(async()=>{if(e){d(!0);try{const M=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:qi}),j=Va(M);if(!(j!=null&&j.success))throw new Error((j==null?void 0:j.error)||"Could not load hosted runtime diagnostics");x(j.diagnostics||j.result||null),a("")}catch(M){const j=M instanceof Error?M.message:"Could not load hosted runtime diagnostics";a(j)}finally{d(!1)}}},[x,e,r]);i.useEffect(()=>{!e||u||h||c||p()},[u,h,e,p,c]);const g=i.useCallback(async(M,j)=>{const W=`${M}:${j.sessionId}`;if(!(M==="session_host_stop_session"&&!window.confirm(`Stop ${j.displayName}?
89
+ `)}function Zv(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function ew(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function tw({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:l,searchQuery:c,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:h}){const x=_v(n,o),S=Pv(e,c),b=$v(t,c),p=Bv(x,c),g=Ov(a,c),v=Zv(S,l),f=l==="all"?b:[],T=ew(p,l),I=l==="issues"?[]:g,k=Fv({daemonLogs:S,daemonRawLines:b,trace:p,webEvents:g}),A=qv({daemonLogs:v,daemonRawLines:f,trace:T,webEvents:I}),_=Xv(A),N=Hv({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:h,daemonLogKind:r,daemonLogsCount:S.length,daemonRawLineCount:b.length,traceCount:p.length,webEventCount:g.length});return{filteredDaemonLogs:S,filteredDaemonRawLines:b,filteredTraceEntries:p,filteredWebEvents:g,visibleDaemonLogs:v,visibleDaemonRawLines:f,visibleTraceEntries:T,visibleWebEvents:I,quickFilterCounts:k,diagnosticEvents:A,diagnosticsSummary:_,sourceStates:N}}function sw(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Du(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function So(e){return e==="error"?"text-red-300 border-red-500/25 bg-red-500/[0.05]":e==="warn"?"text-amber-200 border-amber-500/25 bg-amber-500/[0.05]":e==="debug"?"text-slate-300 border-slate-500/25 bg-slate-500/[0.05]":"text-text-secondary border-border-subtle bg-bg-primary"}function Ua(e){return e==="good"?"border-emerald-500/20 bg-emerald-500/[0.05]":e==="warning"?"border-amber-500/20 bg-amber-500/[0.05]":e==="danger"?"border-red-500/20 bg-red-500/[0.05]":"border-border-subtle bg-bg-secondary"}function hi(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function rw({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${So(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Du(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:hi(e.source)}),e.category&&e.stage&&s.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&s.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&s.jsxs("span",{children:["ix=",e.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function nw({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:l,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:m,onClear:u}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(h=>s.jsx("button",{type:"button",onClick:()=>a(h.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===h.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:h.label},h.id))}),s.jsx("input",{value:r,onChange:h=>o(h.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:l,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:d,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function aw({logLevel:e,traceCategory:t,onLogLevelChange:r,onTraceCategoryChange:n}){return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-3",children:s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(a=>s.jsxs("button",{onClick:()=>r(a),className:`machine-btn text-[10px] px-2 py-0.5 ${e===a?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",a.toUpperCase(),"+"]},a))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:Mv.map(a=>s.jsx("button",{onClick:()=>n(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function ow({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:l,traceFetchError:c}){var u,h;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((h=e.latestIssue)==null?void 0:h.severity)==="warn"?"warning":"good",m=l||c?"danger":o?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Ua(e.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:n.trim()?`Filtered by “${n.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Ua(d)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[hi(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:Du(e.latestIssue.ts)})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Ua(m)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:l||c?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",sw(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(x=>s.jsxs("div",{children:[x.label,": ",x.status]},x.id))})]})]})}function iw({patterns:e}){return e.length===0?null:s.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(t=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[s.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[t.count,"× ",t.severity.toUpperCase()," · ",hi(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function lw({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:l,visibleWebEvents:c,quickFilter:d,searchQuery:m}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,timeline:!u.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(u=>s.jsx(rw,{event:u},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,daemon:!u.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&o.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:d==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((u,h)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${h}`)),e.daemonLogKind!=="text"&&a.map((u,h)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${So(u.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:u.level==="error"?"ERR":u.level==="warn"?"WRN":u.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:u.message})]},`log-${h}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,trace:!u.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[l.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&l.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&l.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&l.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No trace entries match the current search.":e.traceCategory==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),l.map(u=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${So(u.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.level.toUpperCase()}),s.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Js(u.payload,360)||"No payload"})]},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,web:!u.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[c.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),c.map(u=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.kind}),u.topic&&s.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Js(u.payload,360)||"No payload"})]},u.id))]})]})]})}function cw({machineId:e,sendDaemonCommand:t}){const r=Kv({machineId:e,sendDaemonCommand:t}),[n,a]=i.useState("info"),[o,l]=i.useState(""),[c,d]=i.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=i.useRef(null),u=i.useRef(!1),h=i.useMemo(()=>tw({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:o,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,o,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);i.useEffect(()=>{if(r.autoRefresh&&h.diagnosticEvents.length>0){const b=u.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:b}),u.current=!0},50)}},[h.diagnosticEvents.length,r.autoRefresh]);const x=i.useCallback(async()=>{var p;const b=Wv({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!b.trim()){it.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(b)),it.showToast("Copied visible logs to clipboard.","success")}catch(g){it.showToast(g instanceof Error?g.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),S=i.useCallback(async()=>{var p;const b=Qv({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(b)),it.showToast("Copied diagnostic bundle to clipboard.","success")}catch(g){it.showToast(g instanceof Error?g.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(nw,{quickFilter:n,quickFilterCounts:h.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:l,onCopyDiagnostics:()=>{S()},onCopyVisible:()=>{x()},onToggleAutoRefresh:()=>r.setAutoRefresh(b=>!b),onRefresh:r.refresh,onClear:r.clear}),s.jsx(aw,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(ow,{diagnosticsSummary:h.diagnosticsSummary,diagnosticEventsCount:h.diagnosticEvents.length,sourceStates:h.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(iw,{patterns:h.diagnosticsSummary.repeatedPatterns}),s.jsx(lw,{streams:r,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:m})]})}function dw(e){return e.diagnostics?{label:"Managed",toneClass:"bg-green-500/[0.08] text-green-500"}:e.loading||e.refreshing?{label:"Checking…",toneClass:"bg-sky-500/[0.08] text-sky-400"}:e.error?{label:"Diagnostics issue",toneClass:"bg-amber-500/[0.08] text-amber-400"}:{label:"Unavailable",toneClass:"bg-red-500/[0.08] text-red-400"}}function Eu(e){const t=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return t?t==="auto_resumed"?"restored after restart":t==="resume_failed"?"restore failed":t==="host_restart_interrupted"?"host restart interrupted":t==="orphan_snapshot"?"snapshot recovered":t.replace(/_/g," "):null}function uw(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const l=String((o==null?void 0:o.lifecycle)||"").trim(),c=Eu((o==null?void 0:o.meta)||void 0),d=((a=o==null?void 0:o.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(l)?t.push(o):(l==="stopped"||l==="failed")&&(d||c)?r.push(o):n.push(o)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function mw(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function za(e){return e==="live"?"These runtimes are live now and are the only attachable targets.":e==="recovery"?"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.":"These inactive records are shown for reference and usually need restart before they are useful again."}function Va(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Ga(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function rc(e){if(!e)return"unknown";const t=Date.now()-e,r=Math.max(0,Math.round(t/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const a=Math.round(n/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function pw(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function hw(e){switch(e){case"running":return"bg-green-500/[0.08] text-green-500";case"starting":return"bg-sky-500/[0.08] text-sky-400";case"stopping":return"bg-orange-500/[0.08] text-orange-400";case"interrupted":return"bg-amber-500/[0.08] text-amber-400";case"failed":return"bg-red-500/[0.08] text-red-500";default:return"bg-[#ffffff0a] text-text-muted"}}function fw(e){var r;const t=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const a=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!a)continue;const o=`${n.providerType}::${n.workspace}::${a}`;t.set(o,(t.get(o)||0)+1)}return Array.from(t.values()).filter(n=>n>1).length}function xw({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=i.useState(""),[o,l]=i.useState(null),[c,d]=i.useState(!1),m=Mb(e,{enabled:!!e,includeSessions:!0,limit:qi,intervalMs:Nf}),u=m.diagnostics,h=m.loading,x=m.applyDiagnostics,S=i.useMemo(()=>dw({diagnostics:u,loading:h,refreshing:c,error:n}),[u,h,c,n]),b=i.useMemo(()=>new Map(t.map(M=>[M.sessionId||M.id,M])),[t]),p=i.useCallback(async()=>{if(e){d(!0);try{const M=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:qi}),j=Va(M);if(!(j!=null&&j.success))throw new Error((j==null?void 0:j.error)||"Could not load hosted runtime diagnostics");x(j.diagnostics||j.result||null),a("")}catch(M){const j=M instanceof Error?M.message:"Could not load hosted runtime diagnostics";a(j)}finally{d(!1)}}},[x,e,r]);i.useEffect(()=>{!e||u||h||c||p()},[u,h,e,p,c]);const g=i.useCallback(async(M,j)=>{const W=`${M}:${j.sessionId}`;if(!(M==="session_host_stop_session"&&!window.confirm(`Stop ${j.displayName}?
90
90
  This will terminate the hosted runtime.`))){l(W);try{const H=await r(e,M,{sessionId:j.sessionId}),$=Va(H);if(!($!=null&&$.success))throw new Error(($==null?void 0:$.error)||"Session host action failed");const C=M==="session_host_resume_session"?"resumed":M==="session_host_restart_session"?"restarted":"stopped";it.showToast(`Session host ${C}: ${j.displayName}`,"success"),await p()}catch(H){const $=H instanceof Error?H.message:"Session host action failed";it.showToast($,"warning"),a($)}finally{l(H=>H===W?null:H)}}},[e,p,r]),v=i.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
91
- The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){l("session_host_prune_duplicate_sessions");try{const j=await r(e,"session_host_prune_duplicate_sessions",{}),W=Va(j);if(!(W!=null&&W.success))throw new Error((W==null?void 0:W.error)||"Duplicate prune failed");const H=W.result||{},$=Array.isArray(H.prunedSessionIds)?H.prunedSessionIds.length:0,C=typeof H.duplicateGroupCount=="number"?H.duplicateGroupCount:0;it.showToast(`Pruned ${$} duplicate runtime(s) across ${C} group(s)`,"success"),await p()}catch(j){const W=j instanceof Error?j.message:"Duplicate prune failed";it.showToast(W,"warning"),a(W)}finally{l(j=>j==="session_host_prune_duplicate_sessions"?null:j)}}},[e,p,r]),f=i.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((M,j)=>(j.lastActivityAt||0)-(M.lastActivityAt||0)),[u==null?void 0:u.sessions]),T=i.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:dw(f),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,f]),I=T.liveRuntimes,k=T.recoverySnapshots,A=T.inactiveRecords,_=i.useMemo(()=>hw(I),[I]),N=i.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),w=i.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(M=>M.level==="warn"||M.level==="error")||null,[u==null?void 0:u.recentLogs]),D=(M,j)=>{var G;const W=o===`session_host_resume_session:${M.sessionId}`,H=o===`session_host_restart_session:${M.sessionId}`,$=o===`session_host_stop_session:${M.sessionId}`,C=Eu(M.meta),y=b.get(M.sessionId),F=M.attachedClients.length===1?"1 client":`${M.attachedClients.length} clients`,P=j==="recovery"?"Recover":"Resume",E=uw(j);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:M.displayName||(y==null?void 0:y.cliName)||M.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${pw(M.lifecycle)}`,children:M.lifecycle}),C&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:C})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:M.workspaceLabel||(y==null?void 0:y.runtimeWorkspaceLabel)||M.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:M.runtimeKey}),M.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",M.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((G=M.writeOwner)==null?void 0:G.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:mw(M.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(bc,{size:11})," ",F]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",rc(M.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",E]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[j==="recovery"&&(M.lifecycle==="interrupted"||M.lifecycle==="failed"||M.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{g("session_host_resume_session",M)},children:W?`${P}ing…`:P}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{g("session_host_restart_session",M)},children:H?"Restarting…":"Restart"}),j==="live"&&(M.lifecycle==="running"||M.lifecycle==="starting"||M.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{g("session_host_stop_session",M)},children:$?"Stopping…":"Stop"})]})]})},M.sessionId)};return s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(is,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Ax()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[_>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{v()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${_})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${S.toneClass}`,children:S.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:h||c,children:[s.jsx(Rr,{size:13}),h||c?"Refreshing…":"Refresh"]})]})]}),n&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(Ar,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:k.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:rc(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Ga(u.hostStartedAt)})]})]}),w&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(Ar,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:w.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Ga(w.timestamp),w.sessionId?` · ${w.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Ro,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:za("live")}),I.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:I.map(M=>D(M,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(is,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:za("recovery")}),k.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:k.map(M=>D(M,"recovery"))})]}),A.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:za("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:A.map(M=>D(M,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),N.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:N.map(M=>{var W;const j=f.find(H=>H.sessionId===M.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(j==null?void 0:j.displayName)||((W=b.get(M.sessionId))==null?void 0:W.cliName)||M.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[M.action,M.lifecycle?` · ${M.lifecycle}`:"",M.detail?` · ${M.detail}`:"",M.error?` · ${M.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${M.success===!1?"text-red-300":"text-text-secondary"}`,children:Ga(M.timestamp)})]},`${M.sessionId}:${M.timestamp}:${M.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function xw({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(o=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{a(null),n({cliType:t.cliType,workspaceId:o.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:o.label||o.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:o.path})]},o.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function qa({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function Ya({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function bw({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:l}){const c=n.slice(0,6),d=r.slice(0,4),m="0.9.81",u=Hd(e),h=$s(e,m),x=Sr(e,h),S=u==="preview"?"Update to preview":"Update daemon";return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[c.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(qa,{icon:s.jsx(es,{size:13}),children:"Current Chats"}),s.jsx(Ya,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(b=>{const p=yo(b);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>l(b),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:ut(b)}),p>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Un(p)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Is(b)})]},b.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(qa,{icon:s.jsx(wc,{size:13}),children:"Recent Launches"}),s.jsx(Ya,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(b=>{const{metaText:p,updatedLabel:g}=tu(b);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>o(b),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:b.label}),g&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:g})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:p})]},b.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(qa,{icon:s.jsx(Ar,{size:13}),children:"Daemon Update"}),s.jsx(Ya,{className:"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:x?"Daemon update required":"Version mismatch detected"}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[x?"This machine is on an incompatible daemon version. Update it before starting more sessions.":u==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",h&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",h,u?` (${u})`:""]})]}),s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[s.jsx(Rr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:S})]})]})})]})]})}function gw(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function yw({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:o,onCustomPathChange:l,onOpenBrowseDialog:c}){return s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:t,onChange:d=>{const m=d.target.value;if(o(m),m==="__custom__"&&a){c();return}m!=="__custom__"&&l("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(e.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(d=>s.jsxs("option",{value:d.id,children:[d.id===e.defaultWorkspaceId?"⭐ ":"",Vn(d.path,d.label)]},d.id)),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),t==="__custom__"&&(a?s.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:c,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:d=>l(d.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:t==="__custom__"?r?s.jsx("span",{className:"font-mono truncate block",title:r,children:r}):a?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":r?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:t===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const vw={ide:{label:"IDE",plural:"IDEs",accent:"border-blue-500/[0.12]"},cli:{label:"CLI",plural:"CLIs",accent:"border-violet-500/[0.12]"},acp:{label:"ACP Agent",plural:"ACP agents",accent:"border-emerald-500/[0.12]"}};function un(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Xa({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:l,sendDaemonCommand:c,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const h=As(),{handleLaunchIde:x,handleStopCli:S,handleRestartIde:b,handleStopIde:p,handleDetectIdes:g,launchingIde:v,launchingAgentType:f,addLog:T}=l,[I,k]=i.useState(null),A=i.useCallback(L=>{L&&h(Zt(L))},[h]),_=vw[e],N=e==="ide",w=e==="acp",D=i.useMemo(()=>n.filter(L=>Ts(L,e)),[e,n]),M=i.useMemo(()=>new Map(D.map(L=>[L.type,L.displayName||L.type])),[D]),[j,W]=i.useState(""),[H,$]=i.useState(""),[C,y]=i.useState([]),[F,P]=i.useState(""),[E,G]=i.useState(""),[J,ye]=i.useState([]),[he,ne]=i.useState(!1),[ue,Se]=i.useState(!1),[ve,X]=i.useState(""),[xe,fe]=i.useState(!1),[we,be]=i.useState(()=>Ct()),[Ce,ee]=i.useState(null),[me,ie]=i.useState(m?"__custom__":d||t.defaultWorkspaceId||""),[pe,le]=i.useState(m||""),[B,z]=i.useState([]),[de,re]=i.useState(!1),[R,q]=i.useState(""),[ce,Ne]=i.useState([]),[je,O]=i.useState(!1),[Ie,Le]=i.useState(""),He=i.useRef(null),[ze,Xe]=i.useState(null),Je=i.useRef("__home__"),[rt,pt]=i.useState("__home__"),[xt,vt]=i.useState(!1),Te=i.useRef(0),Ve=B.filter(L=>!a.some(Q=>Q.type===L&&yt(Q.status)!=="stopped")),tt=i.useRef({});i.useEffect(()=>{t.defaultWorkspaceId&&!me&&ie(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),i.useEffect(()=>{if(m){ie("__custom__"),le(m);return}d&&(ie(d),le(""))},[d,m]),i.useEffect(()=>{N||j&&(D.some(L=>L.type===j)||(W(""),G("")))},[D,N,j]);const Ge=(()=>{if(me==="__custom__")return pe.trim();if(!me)return"";const L=(t.workspaces||[]).find(Q=>Q.id===me);return(L==null?void 0:L.path)||""})(),ot=i.useCallback(L=>{const Q=tt.current[L];Q&&(clearTimeout(Q),delete tt.current[L]),z(ge=>ge.includes(L)?ge.filter(Be=>Be!==L):ge)},[]),U=i.useRef(new Set),V=i.useCallback(async L=>{if(c){O(!0),Le("");try{const Q=await Zn(c,r,L);q(Q.path),le(Q.path),Ne(Q.directories)}catch(Q){Le(Q instanceof Error?Q.message:"Could not load folder")}finally{O(!1)}}},[r,c]),Z=i.useCallback(()=>{if(!c)return;ie("__custom__"),re(!0);const L=a.map(ge=>ge.workspace),Q=Qn(t.platform,Jn(pe.trim(),Ge,m,L,t.defaultWorkspacePath,(t.workspaces||[]).map(ge=>ge.path)));V(Q)},[pe,m,V,t.defaultWorkspacePath,t.platform,t.workspaces,a,Ge,c]),ae=i.useCallback(L=>{const Q=String(L.workspace||"").trim();if(!Q)return;const ge=(t.workspaces||[]).find(Be=>un(Be.path)===un(Q));if(ge){ie(ge.id),le("");return}ie("__custom__"),le(Q)},[t.workspaces]),K=i.useCallback(L=>{const Q=String(L.workspace||"").trim();if(!Q)return{workspaceId:null,workspacePath:"",useHome:!0};const ge=(t.workspaces||[]).find(Be=>un(Be.path)===un(Q));return ge?{workspaceId:ge.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Q,useHome:!1}},[t.workspaces]),Y=i.useCallback(async L=>{if(!c||!L||e!=="cli"){ye([]),ne(!1),Se(!1),X("");return}const Q=Te.current+1;Te.current=Q,ne(!0),X("");try{const ge=await c(r,"list_saved_sessions",{providerType:L,kind:"cli",limit:30});if(Te.current!==Q)return;const Be=(ge==null?void 0:ge.result)??ge;ye(Array.isArray(Be==null?void 0:Be.sessions)?Be.sessions:[])}catch(ge){if(Te.current!==Q)return;ye([]),X(ge instanceof Error?ge.message:"Could not load saved sessions")}finally{Te.current===Q&&(ne(!1),Se(!0))}},[e,r,c]),se=i.useMemo(()=>{if(e!=="cli"||!j)return null;const L=M.get(j)||j;return{routeId:r,daemonId:r,providerSessionId:E||void 0,transport:"pty",mode:"chat",agentName:L,agentType:j,status:"idle",title:L,messages:[],ideType:j,workspaceName:Ge,workspacePath:Ge,displayPrimary:L,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${j}`}},[e,r,M,Ge,E,j]),oe=i.useCallback(L=>{if(e==="ide"||!L){y([]);return}y(jo(r,L))},[e,r]),ke=i.useCallback((L,Q)=>{e==="ide"||!L||(Hy(r,L,Q),y(jo(r,L)))},[e,r]);i.useEffect(()=>{Te.current+=1,G(""),oe(j),Se(!1),ye([]),X(""),ne(!1)},[e,oe,Y,j]);const Pe=i.useMemo(()=>J.find(L=>L.providerSessionId===E)||null,[J,E]);i.useEffect(()=>{if(!E)return;const L=J.find(Q=>Q.providerSessionId===E);L!=null&&L.canResume||G("")},[J,E]);const Ee=i.useCallback((L,Q)=>{He.current=Q,Je.current=L.selectedWorkspaceKey||"__home__",pt(L.selectedWorkspaceKey||"__home__"),Xe(L)},[]),Ae=i.useCallback(()=>{He.current&&(vt(!0),He.current().finally(()=>{He.current=null,vt(!1),Xe(null)}))},[]),$e=i.useCallback(L=>{if(!L)return;z(ge=>ge.includes(L)?ge:[...ge,L]);const Q=tt.current[L];Q&&clearTimeout(Q),tt.current[L]=setTimeout(()=>{z(ge=>ge.includes(L)?ge.filter(Be=>Be!==L):ge),delete tt.current[L]},2e4)},[]);i.useEffect(()=>{for(const Q of a)yt(Q.status)!=="stopped"&&(B.includes(Q.type)&&!U.current.has(Q.type)&&(U.current.add(Q.type),T("info",`${M.get(Q.type)||Q.type} launched`,!0)),ot(Q.type));const L=new Set(a.filter(Q=>yt(Q.status)!=="stopped").map(Q=>Q.type));U.current.forEach(Q=>{!B.includes(Q)&&!L.has(Q)&&U.current.delete(Q)})},[T,ot,a,B,M]),i.useEffect(()=>()=>{Object.values(tt.current).forEach(clearTimeout),tt.current={}},[]);const[Fe,Me]=i.useState({}),[Qe,et]=i.useState(null);i.useEffect(()=>{if(!N||!r||!c)return;(async()=>{try{const Q=await c(r,"get_ide_extensions",{}),ge=(Q==null?void 0:Q.result)||Q;ge!=null&&ge.success&&(ge!=null&&ge.ideExtensions)&&Me(ge.ideExtensions)}catch{}})()},[N,r,c]);const bt=L=>N?ct(L.type):e==="cli"?L.cliName:L.acpName,gt=N?t.detectedIdes||[]:[],dt=i.useCallback(async L=>{const Q=(L==null?void 0:L.type)||j,ge=(L==null?void 0:L.workspacePath)??Ge;if(N){await x(Q,ge?{workspace:ge}:void 0)&&$e(Q);return}const Be=await l.runLaunchCliCore({cliType:Q,dir:L!=null&&L.workspaceId?void 0:ge||void 0,workspaceId:(L==null?void 0:L.workspaceId)||void 0,useHome:(L==null?void 0:L.useHome)||!(L!=null&&L.workspaceId)&&!ge,argsStr:(L==null?void 0:L.argsStr)??(H||void 0),model:(L==null?void 0:L.model)??(w&&F||void 0),resumeSessionId:(L==null?void 0:L.resumeSessionId)||!w&&e==="cli"&&Q===j&&E||void 0});if(Be.success||Be.pending){const _e=(L==null?void 0:L.argsStr)??H;!N&&(_e!=null&&_e.trim())&&(fu(r,Q,_e),oe(Q)),$e(Q),Be.success&&Be.sessionId&&A(Be.sessionId)}},[l,x,w,N,H,F,oe,$e,r,A,Ge,E,j]),ht=pd(N?"ide":w?"acp":"cli",!N&&!w&&!!E),Ue=hd(N?"ide":w?"acp":"cli",!N&&!w&&!!E),Kt=()=>{var _e;const L=N?ct(j):M.get(j)||j,Q=!N&&!w&&!!E,{options:ge,selectedKey:Be}=ks({machine:t,currentWorkspaceId:me&&me!=="__custom__"?me:null,currentWorkspacePath:Ge});Ee({title:Q?Qo(L):gs("start-fresh",L),description:Q?Zo():ys("start-fresh"),confirmLabel:ht,busyLabel:Ue,workspaceOptions:ge,selectedWorkspaceKey:Be,details:[{label:"Mode",value:_.label},{label:"Provider",value:L},...!N&&e==="cli"&&E?[{label:"Resume",value:((_e=J.find(Oe=>Oe.providerSessionId===E))==null?void 0:_e.title)||E}]:[],...!N&&H.trim()?[{label:"Arguments",value:H.trim()}]:[],...w&&F.trim()?[{label:"Model",value:F.trim()}]:[]]},async()=>{const Oe=ge.find(nt=>nt.key===Je.current);Oe!=null&&Oe.workspaceId?(ie(Oe.workspaceId),le("")):Oe!=null&&Oe.workspacePath?(ie("__custom__"),le(Oe.workspacePath)):(ie(""),le("")),await dt({workspaceId:(Oe==null?void 0:Oe.workspaceId)??null,workspacePath:(Oe==null?void 0:Oe.workspacePath)??"",useHome:!(Oe!=null&&Oe.workspaceId)&&!(Oe!=null&&Oe.workspacePath)})})},te=L=>{N?p(L):S(L.type,L.workspace,L.id)},De=i.useCallback(async(L,Q,ge=!1)=>{if(L.mode===Q){ge&&L.sessionId&&A(L.sessionId);return}if(!c||!L.sessionId){ge&&L.sessionId&&A(L.sessionId);return}try{await c(r,"set_cli_view_mode",{targetSessionId:L.sessionId,cliType:L.type,mode:Q}),ge&&A(L.sessionId)}catch(Be){const _e=Pd(Be);Rd(Be)?console.warn(_e?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Be instanceof Error?Be.message:String(Be)):console.error("Failed to switch CLI view mode:",Be)}},[r,A,c]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${_.accent} relative overflow-hidden`,children:[s.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",_.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:N?gt.length>0?gt.map(L=>{const Q=a.find(nt=>(nt.type||"").toLowerCase()===(L.type||"").toLowerCase()&&yt(nt.status)!=="stopped"),ge=L.running||!!Q,Be=!!Q&&Q.cdpConnected,_e=B.includes(L.type||L.id||""),Oe=j===(L.type||"");return s.jsxs("button",{onClick:()=>{if(Be&&Q){const nt=Q.sessionId;nt?h(Zt(nt),{state:{openRemoteForTabKey:nt}}):h("/dashboard",{state:{openRemoteForTabKey:Q.id}});return}_e||W(nt=>nt===(L.type||"")?"":L.type||"")},disabled:!!v||_e,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Be?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Oe?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:v&&v!==L.type?.4:1},children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:o(L.type)}),ge&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Be?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:L.name||ct(L.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Be?"text-green-400":_e?"text-orange-400":Oe?"text-accent-primary":"text-text-muted"}`,children:Be?"Open Session":_e?"Starting...":Oe?"Configure":"Select"})]})]},L.type)}):s.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",s.jsxs("button",{onClick:g,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[s.jsx(Zm,{size:14})," Scan System"]})]}):D.length>0?D.map(L=>{const Q=j===L.type,ge=B.includes(L.type),_e=!!a.find(Oe=>Oe.type===L.type&&yt(Oe.status)!=="stopped");return s.jsxs("button",{onClick:()=>W(Oe=>Oe===L.type?"":L.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Q?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:L.icon}),_e&&s.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:L.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ge?"text-orange-400":Q?"text-accent-primary":"text-text-muted"}`,children:ge?"Starting...":Q?"Configure":"Select"})]})]},L.type)}):s.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),j&&(N?gt.find(L=>L.type===j):D.find(L=>L.type===j))&&s.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:N?ct(j):M.get(j)||j})]}),s.jsx(yw,{machine:t,selectedWorkspace:me,resolvedWorkspacePath:Ge,customPath:pe,canBrowse:!!c,onWorkspaceChange:ie,onCustomPathChange:le,onOpenBrowseDialog:Z}),!N&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&s.jsx(bu,{busy:!!f||!!v||B.includes(j),savedSessionsLoading:he,savedSessionsError:ve,savedSessionsLoaded:ue,savedSessionsCount:J.length,selectedSession:Pe,onRefresh:()=>void Y(j),onOpenHistory:()=>{j&&(fe(!0),xu({hasLoadedInitialResults:ue,isLoading:he})&&Y(j))},onClearSelection:()=>G("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[w&&s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),s.jsx("input",{type:"text",placeholder:"Leave empty for default",value:F,onChange:L=>P(L.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),s.jsx("input",{type:"text",placeholder:"Optional flags...",value:H,onChange:L=>$(L.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),C.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:C.map(L=>s.jsxs("div",{className:"inline-flex max-w-full items-stretch overflow-hidden rounded-md border border-[#ffffff1a] bg-bg-tertiary text-xs text-text-secondary transition-colors hover:border-accent-primary/40 hover:text-text-primary",title:L,children:[s.jsx("button",{type:"button",className:"min-w-0 max-w-[220px] truncate px-2.5 py-1.5 text-left",onClick:()=>$(L),children:L}),s.jsx("button",{type:"button",className:"flex items-center justify-center border-l border-[#ffffff1a] px-1.5 text-text-muted transition-colors hover:bg-status-error/10 hover:text-status-error focus:outline-none focus:ring-1 focus:ring-status-error/50",onClick:()=>ke(j,L),"aria-label":`Remove startup arguments: ${L}`,title:"Remove startup arguments",children:s.jsx(wt,{size:12})})]},L))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:Kt,disabled:!!f||!!v||B.includes(j),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:f===j||v===j?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+B.filter(L=>!a.some(Q=>Q.type===L&&yt(Q.status)!=="stopped")).length,")"]}),a.length===0&&Ve.length===0?s.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",_.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ve.map(L=>s.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:o(L)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:N?ct(L):M.get(L)||L}),s.jsx("div",{className:"text-[11px] text-text-muted",children:f===L?"Launching process...":"Waiting for process and session to register..."})]})]}),s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${L}`)),a.map(L=>{const Q=N?L:null,ge=!N&&!w?L:null,Be=yt(L.status);return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:o(L.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[bt(L),(Q==null?void 0:Q.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Q.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex min-w-0 flex-wrap items-center gap-2",children:[s.jsx("span",{className:"truncate",children:L.workspace||"—"}),u&&L.git&&L.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:_e=>{_e.stopPropagation(),u(L.daemonId??r,L.workspace)},children:s.jsx(qs,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(qs,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(ge==null?void 0:ge.mode)&&s.jsx("span",{className:ge.mode==="chat"?"text-violet-400":"text-text-secondary",children:ge.mode==="chat"?"Chat view":"Terminal view"})]}),ge&&(ge.runtimeKey||ge.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ge.runtimeKey&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),s.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",ge.runtimeKey]}),s.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var _e;(_e=navigator.clipboard)==null||_e.writeText(`adhdev attach ${ge.runtimeKey}`),k(ge.runtimeKey||null),window.setTimeout(()=>{k(Oe=>Oe===ge.runtimeKey?null:Oe)},1200)},children:I===ge.runtimeKey?"Copied":"Copy"})]}),ge.runtimeWriteOwner&&s.jsx("span",{style:{color:ge.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ge.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:gw(ge.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Be==="stopped"?"bg-red-500/[0.08] text-red-500":Be==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Be}),N&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const _e=L.sessionId;if(_e){h(Zt(_e),{state:{openRemoteForTabKey:_e}});return}h("/dashboard",{state:{openRemoteForTabKey:L.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:s.jsx(_t,{size:13})}),s.jsx("button",{onClick:()=>{const _e=L.workspace||"",{options:Oe,selectedKey:nt}=ks({machine:t,currentWorkspacePath:_e});Ee({title:gs("restart-ide",ct(L.type)),description:ys("restart-ide"),confirmLabel:Ys("restart-ide"),busyLabel:Xs("restart-ide"),workspaceOptions:Oe,selectedWorkspaceKey:nt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:ct(L.type)}]},async()=>{const Mt=Oe.find(ss=>ss.key===Je.current),ft=(Mt==null?void 0:Mt.workspacePath)??"";if(ft&&ft!==_e){await dt({type:L.type,workspacePath:ft});return}await b(L)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:s.jsx(Rr,{size:14})})]}),w&&s.jsx("button",{onClick:()=>{const _e=L.sessionId;_e&&A(_e)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!L.sessionId,children:s.jsx(es,{size:14})}),ge&&Be!=="stopped"&&s.jsxs(s.Fragment,{children:[ge.mode&&s.jsx(Yo,{mode:ge.mode,onChange:_e=>void De(ge,_e,!1),compact:!0}),s.jsx("button",{onClick:()=>{const _e=L.sessionId;_e&&A(_e)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!L.sessionId,children:ge.mode==="chat"?s.jsx(es,{size:14}):s.jsx(_t,{size:13})})]}),Be==="stopped"?s.jsx("button",{onClick:()=>{const _e=L.workspace||"",Oe=N?ct(L.type):bt(L),{options:nt,selectedKey:Mt}=ks({machine:t,currentWorkspacePath:_e});Ee({title:gs("restart-stopped",Oe),description:ys("restart-stopped"),confirmLabel:Ys("restart-stopped"),busyLabel:Xs("restart-stopped"),workspaceOptions:nt,selectedWorkspaceKey:Mt,details:[{label:"Mode",value:_.label},{label:"Provider",value:Oe}]},async()=>{const ft=nt.find(ss=>ss.key===Je.current);await dt({type:L.type,workspaceId:(ft==null?void 0:ft.workspaceId)??null,workspacePath:(ft==null?void 0:ft.workspacePath)??"",useHome:!(ft!=null&&ft.workspaceId)&&!(ft!=null&&ft.workspacePath)})})},disabled:B.includes(L.type),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-green-500/20 text-green-400 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",title:"Restart",children:B.includes(L.type)?"⏳":s.jsx(Po,{size:14})}):s.jsx("button",{onClick:()=>te(L),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:s.jsx(wt,{size:14})})]})]}),Q&&Q.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Q.aiAgents.map(_e=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Mn(_e.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[_e.name," · ",yt(_e.status)]},_e.id))}),Q&&(Fe[Q.type]||[]).length>0&&c&&s.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[s.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:(Fe[Q.type]||[]).map(_e=>s.jsxs("button",{disabled:Qe===`${Q.type}.${_e.type}`,onClick:async()=>{const Oe=`${Q.type}.${_e.type}`;et(Oe);try{await c(r,"set_ide_extension",{ideType:Q.type,extensionType:_e.type,enabled:!_e.enabled}),Me(nt=>({...nt,[Q.type]:(nt[Q.type]||[]).map(Mt=>Mt.type===_e.type?{...Mt,enabled:!Mt.enabled}:Mt)}))}catch(nt){console.error("Extension toggle failed:",nt)}finally{et(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${_e.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${_e.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),_e.name,s.jsx("span",{className:"text-[9px] font-normal",children:_e.enabled?"ON":"OFF"})]},_e.type))})]})]},L.id)})]}),de&&c&&s.jsx(ea,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:R,directories:ce,busy:je,error:Ie,confirmLabel:"Use this folder",onClose:()=>re(!1),onNavigate:L=>{V(L)},onConfirm:L=>{le(L),ie("__custom__"),re(!1)}}),ze&&s.jsx(li,{title:ze.title,description:ze.description,details:ze.details,workspaceOptions:ze.workspaceOptions,selectedWorkspaceKey:rt,onWorkspaceChange:L=>{Je.current=L,pt(L)},confirmLabel:ze.confirmLabel,busyLabel:ze.busyLabel,busy:xt,onConfirm:Ae,onCancel:()=>{He.current=null,Xe(null)}}),xe&&se&&s.jsx(ei,{activeConv:se,ides:[],isCreatingChat:!1,isRefreshingHistory:he,savedSessions:J,isSavedSessionsLoading:he,isResumingSavedSessionId:Ce,savedHistoryFilters:we,missingWorkspaceResumePath:Ge||null,onSavedHistoryFiltersChange:be,onClose:()=>fe(!1),onNewChat:()=>{G(""),fe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Y(j)},onResumeSavedSession:L=>{if(!L.canResume||Ce)return;const Q=K(L);G(L.providerSessionId),ae(L),ee(L.providerSessionId),fe(!1),dt({type:L.providerType,workspaceId:Q.workspaceId,workspacePath:Q.workspacePath,useHome:Q.useHome,resumeSessionId:L.providerSessionId}).finally(()=>{ee(ge=>ge===L.providerSessionId?null:ge)})}})]})}const nc=[{id:"ide",label:"IDE",helper:"Open a graphical workspace and attach CDP"},{id:"cli",label:"CLI",helper:"Launch a terminal-first workspace on this machine"},{id:"acp",label:"ACP",helper:"Launch an ACP-backed workspace on this machine"}];function ww({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:l,getIcon:c,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:h,onOpenGitDialog:x}){var g;const[S,b]=i.useState(d);i.useEffect(()=>{b(d)},[d]);const p=i.useMemo(()=>({ide:n.length,cli:a.length,acp:o.length}),[n.length,a.length,o.length]);return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[s.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:nc.map(v=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${S===v.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>b(v.id),children:[s.jsx("span",{children:v.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${S===v.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:p[v.id]})]},v.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(g=nc.find(v=>v.id===S))==null?void 0:g.helper})]}),S==="ide"&&s.jsx(Xa,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),S==="cli"&&s.jsx(Xa,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),S==="acp"&&s.jsx(Xa,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:o,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x})]})}function jw({onNicknameSynced:e}={}){var le,B,z,de,re,R,q,ce,Ne,je;const{id:t}=km(),r=As(),n=To(),{sendCommand:a}=jt(),o=Er(),l=Td(),c=ad(),d=c.ides||[],m=c.initialLoaded??!0,u=d.find(O=>O.id===t&&O.type==="adhdev-daemon"),h=d.some(O=>O.type==="adhdev-daemon"),x=t?(le=c.connectionRetryStatuses)==null?void 0:le[t]:void 0,S=!!(x!=null&&x.blocked),[b,p]=i.useState("workspace"),[g,v]=i.useState(null),f=i.useCallback((O,Ie)=>{v({daemonId:O,workspace:Ie})},[]),[T,I]=i.useState("ide"),k=i.useRef(null),[A,_]=i.useState(null),N=i.useRef("__home__"),[w,D]=i.useState("__home__"),[M,j]=i.useState(!1),W=i.useRef(null);i.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||o(t,{minFreshMs:3e4}).catch(()=>{})},[o,u,t]),i.useEffect(()=>{if(!t||!u||b!=="overview")return;const O=u.machine;(typeof(O==null?void 0:O.cpus)!="number"||typeof(O==null?void 0:O.totalMem)!="number"||typeof(O==null?void 0:O.arch)!="string"||typeof(O==null?void 0:O.release)!="string")&&l(t,{minFreshMs:3e4}).catch(()=>{})},[b,l,u,t]),Tb(t&&b==="overview"?[t]:[],{enabled:b==="overview",intervalMs:wf});const H=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},$=bv({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:W});i.useEffect(()=>it.onToast(Ie=>{c.setToasts(He=>{if(He.some(Je=>Je.message===Ie.message&&Ie.timestamp-Je.timestamp<3e3))return He;const Xe={id:Ie.id,message:Ie.message,type:Ie.type,timestamp:Ie.timestamp,targetKey:Ie.targetKey,actions:Ie.actions};return[...He.slice(-4),Xe]});const Le=Ie.duration||5e3;setTimeout(()=>c.setToasts(He=>He.filter(ze=>ze.id!==Ie.id)),Le)}),[c]);const C=(u==null?void 0:u.availableProviders)||[],y={};for(const O of C)y[O.type]=O.icon;const F=O=>y[O]||"",P=u?{id:u.id,hostname:Rc(u,{fallbackId:u.id}),platform:((B=u.machine)==null?void 0:B.platform)||"unknown",arch:((z=u.machine)==null?void 0:z.arch)||"",cpus:((de=u.machine)==null?void 0:de.cpus)||0,totalMem:((re=u.machine)==null?void 0:re.totalMem)||0,freeMem:(R=u.machine)==null?void 0:R.freeMem,availableMem:(q=u.machine)==null?void 0:q.availableMem,loadavg:(ce=u.machine)==null?void 0:ce.loadavg,uptime:(Ne=u.machine)==null?void 0:Ne.uptime,release:((je=u.machine)==null?void 0:je.release)||"",cdpConnected:!!u.cdpConnected,machineNickname:u.machineNickname||null,p2p:u.p2p?{screenshotActive:!1,...u.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:u.detectedIdes||[],workspaces:u.workspaces||[],defaultWorkspaceId:u.defaultWorkspaceId??u.activeWorkspaceId??null,defaultWorkspacePath:u.defaultWorkspacePath??u.activeWorkspacePath??null}:null,E=d.filter(O=>O.daemonId===t&&O.type!=="adhdev-daemon").filter(O=>!_r(O)&&!Fs(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,version:O.version||"",instanceId:O.instanceId||"",status:O.status,workspace:O.workspace||null,terminals:O.terminals||0,aiAgents:mh(O.aiAgents||(O.agents||[]).map(Ie=>({id:Ie.name,name:Ie.name,status:Ie.status,version:Ie.version}))),activeChat:O.activeChat||null,chats:O.chats||[],childSessions:O.childSessions||[],cdpConnected:O.cdpConnected||!1,daemonId:t,lastMessageAt:O.lastMessageAt})),G=d.filter(O=>O.daemonId===t&&_r(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,cliName:O.cliName||O.type,status:O.status,workspace:O.workspace||"",activeChat:O.activeChat||null,providerSessionId:O.providerSessionId,mode:O.mode,runtimeKey:O.runtimeKey,runtimeDisplayName:O.runtimeDisplayName,runtimeWorkspaceLabel:O.runtimeWorkspaceLabel,runtimeWriteOwner:O.runtimeWriteOwner||null,runtimeAttachedClients:O.runtimeAttachedClients||[],daemonId:t,lastMessageAt:O.lastMessageAt})),J=d.filter(O=>O.daemonId===t&&Fs(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,acpName:O.cliName||O.type,status:O.status,workspace:O.workspace||"",activeChat:O.activeChat||null,providerSessionId:O.providerSessionId,daemonId:t,lastMessageAt:O.lastMessageAt})),ye=u?At(u,{fallbackId:t}):"",he="workspace",ne=n.state,ue=ne==null?void 0:ne.initialMachineTab,Se=ne==null?void 0:ne.initialWorkspaceCategory,ve=ne==null?void 0:ne.initialWorkspaceId,X=ne==null?void 0:ne.initialWorkspacePath,xe=ue==="ides"||ue==="clis"||ue==="acps"?"workspace":ue||he,fe=ue==="ides"?"ide":ue==="clis"?"cli":ue==="acps"?"acp":Se,we=[...E.map(O=>{var Ie;return{id:`ide:${O.type}:${O.workspace||""}`,label:((Ie=O.activeChat)==null?void 0:Ie.title)||O.type,kind:"ide",providerType:O.type,subtitle:O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:O.lastMessageAt||0}}),...G.map(O=>{var Ie;return{id:`cli:${O.type}:${O.workspace||""}`,label:((Ie=O.activeChat)==null?void 0:Ie.title)||O.cliName,kind:"cli",providerType:O.type,providerSessionId:O.providerSessionId,subtitle:O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:O.lastMessageAt||0}}),...J.map(O=>{var Ie;return{id:`acp:${O.type}:${O.workspace||""}`,label:((Ie=O.activeChat)==null?void 0:Ie.title)||O.acpName,kind:"acp",providerType:O.type,providerSessionId:O.providerSessionId,subtitle:Cs(O.summaryMetadata)||O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:O.lastMessageAt||0}})].sort((O,Ie)=>(Ie.lastLaunchedAt||0)-(O.lastLaunchedAt||0)),be=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(O=>({id:O.id,label:O.title||O.providerName||O.providerType,kind:O.kind,providerType:O.providerType,providerSessionId:O.providerSessionId,subtitle:Cs(O.summaryMetadata)||O.workspace||void 0,workspace:O.workspace,summaryMetadata:O.summaryMetadata,lastLaunchedAt:O.lastLaunchedAt})):we,Ce=i.useMemo(()=>{var Ie;const O=((Ie=c.connectionStates)==null?void 0:Ie[t||""])||void 0;return d.filter(Le=>Le.daemonId===t&&Le.type!=="adhdev-daemon").flatMap(Le=>ti(Le,{connectionStates:t&&O?{[t]:O}:void 0,defaultConnectionState:O})).filter(Le=>!(Le.transport==="pty"&&Le.mode==="terminal")).sort((Le,He)=>yo(He)-yo(Le))},[d,c.connectionStates,t]),ee=i.useCallback(O=>{const Ie=qd(O);Ie&&r(Zt(Ie))},[r]),me=i.useCallback(()=>{k.current&&(j(!0),k.current().finally(()=>{k.current=null,j(!1),_(null)}))},[]),ie=i.useCallback(O=>{if(!P)return;const{options:Ie,selectedKey:Le}=ks({machine:P,currentWorkspacePath:O.workspace}),He=async()=>{I(O.kind),p("workspace")};k.current=async()=>{const ze=Ie.find(rt=>rt.key===N.current),Xe=(ze==null?void 0:ze.workspacePath)??null,Je=(ze==null?void 0:ze.workspaceId)??null;if(O.kind==="ide"&&O.providerType){await $.handleLaunchIde(O.providerType,Xe?{workspace:Xe}:void 0);return}if((O.kind==="cli"||O.kind==="acp")&&O.providerType){await $.runLaunchCliCore({cliType:O.providerType,dir:Je?void 0:Xe||"",workspaceId:Je||void 0,model:O.kind==="acp"&&Dc(O.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:O.providerSessionId});return}await He()},N.current=Le,D(Le),_({title:O.kind==="ide"?gs("restart-ide",O.label):O.providerSessionId?Qo(O.label):gs("start-fresh",O.label),description:O.kind==="ide"?ys("restart-ide"):O.providerSessionId?Zo():ys("start-fresh"),confirmLabel:O.kind==="ide"?Ys("restart-ide"):O.providerSessionId?Pn(!0):Ys("start-fresh"),busyLabel:O.kind==="ide"?Xs("restart-ide"):O.providerSessionId?Xo(!0):Xs("start-fresh"),workspaceOptions:Ie,details:[{label:"Mode",value:O.kind.toUpperCase()},...O.providerType?[{label:"Provider",value:O.providerType}]:[]]})},[$,P]);if(i.useEffect(()=>{p(xe)},[he,xe,t]),i.useEffect(()=>{fe&&I(fe)},[fe,t]),!P)return m?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:H,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const pe=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_t,{size:14})," Workspace"]}),count:E.length+G.length+J.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(is,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Kn,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(tp,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Jm,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:H,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[$.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:$.nicknameInput,onChange:O=>$.setNicknameInput(O.target.value),onKeyDown:O=>{O.key==="Enter"&&$.handleSaveNickname(),O.key==="Escape"&&$.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:$.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>$.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{$.setEditingNickname(!0),$.setNicknameInput(P.machineNickname||"")},title:"Click to set nickname",children:ye}),S?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),c.retryConnection&&t&&s.jsx("button",{onClick:()=>c.retryConnection(t),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:"Reconnect"})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[P.platform," · ",P.arch]}),s.jsxs("span",{children:[P.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),P.p2p.available&&s.jsxs("span",{children:["P2P ",P.p2p.state==="connected"?"connected":P.p2p.state]}),P.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:P.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:pe.map(O=>s.jsxs("button",{onClick:()=>p(O.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${b===O.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[O.label,O.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${b===O.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:O.count})]},O.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[b==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(bw,{machineEntry:u,providers:C,recentLaunches:be,currentConversations:Ce,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",Ud(u))}catch{}},onOpenRecent:ie,onOpenConversation:ee}),s.jsx(ww,{machine:P,machineId:t,providers:C,ideSessions:E,cliSessions:G,acpSessions:J,actions:$,getIcon:F,initialCategory:T,initialWorkspaceId:ve,initialWorkspacePath:X,sendDaemonCommand:a,onOpenGitDialog:f})]}),b==="providers"&&s.jsx(Iv,{machineId:t,providers:C,sendDaemonCommand:a}),b==="overview"&&s.jsx(gv,{machineId:t,machine:P,ideSessions:E,cliSessions:G,acpSessions:J,actions:$,sendDaemonCommand:a}),b==="session-host"&&s.jsx(fw,{machineId:t,cliSessions:G,sendDaemonCommand:a}),b==="logs"&&s.jsx(lw,{machineId:t,sendDaemonCommand:a})]})})}),$.launchPick&&P&&s.jsx(xw,{machine:P,launchPick:$.launchPick,actions:$}),A&&s.jsx(li,{title:A.title,description:A.description,details:A.details,workspaceOptions:A.workspaceOptions,selectedWorkspaceKey:w,onWorkspaceChange:O=>{N.current=O,D(O)},confirmLabel:A.confirmLabel,busyLabel:A.busyLabel,busy:M,onConfirm:me,onCancel:()=>{k.current=null,_(null)}}),g&&s.jsx(Pu,{daemonId:g.daemonId,workspace:g.workspace,onClose:()=>v(null)}),s.jsx(fd,{toasts:c.toasts||[],onDismiss:O=>c.setToasts(Ie=>Ie.filter(Le=>Le.id!==O)),onClickToast:O=>{O.targetKey&&r(Zt(O.targetKey))}}),s.jsx("style",{children:`
91
+ The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){l("session_host_prune_duplicate_sessions");try{const j=await r(e,"session_host_prune_duplicate_sessions",{}),W=Va(j);if(!(W!=null&&W.success))throw new Error((W==null?void 0:W.error)||"Duplicate prune failed");const H=W.result||{},$=Array.isArray(H.prunedSessionIds)?H.prunedSessionIds.length:0,C=typeof H.duplicateGroupCount=="number"?H.duplicateGroupCount:0;it.showToast(`Pruned ${$} duplicate runtime(s) across ${C} group(s)`,"success"),await p()}catch(j){const W=j instanceof Error?j.message:"Duplicate prune failed";it.showToast(W,"warning"),a(W)}finally{l(j=>j==="session_host_prune_duplicate_sessions"?null:j)}}},[e,p,r]),f=i.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((M,j)=>(j.lastActivityAt||0)-(M.lastActivityAt||0)),[u==null?void 0:u.sessions]),T=i.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:uw(f),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,f]),I=T.liveRuntimes,k=T.recoverySnapshots,A=T.inactiveRecords,_=i.useMemo(()=>fw(I),[I]),N=i.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),w=i.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(M=>M.level==="warn"||M.level==="error")||null,[u==null?void 0:u.recentLogs]),D=(M,j)=>{var G;const W=o===`session_host_resume_session:${M.sessionId}`,H=o===`session_host_restart_session:${M.sessionId}`,$=o===`session_host_stop_session:${M.sessionId}`,C=Eu(M.meta),y=b.get(M.sessionId),F=M.attachedClients.length===1?"1 client":`${M.attachedClients.length} clients`,P=j==="recovery"?"Recover":"Resume",E=mw(j);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:M.displayName||(y==null?void 0:y.cliName)||M.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${hw(M.lifecycle)}`,children:M.lifecycle}),C&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:C})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:M.workspaceLabel||(y==null?void 0:y.runtimeWorkspaceLabel)||M.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:M.runtimeKey}),M.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",M.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((G=M.writeOwner)==null?void 0:G.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:pw(M.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(bc,{size:11})," ",F]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",rc(M.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",E]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[j==="recovery"&&(M.lifecycle==="interrupted"||M.lifecycle==="failed"||M.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{g("session_host_resume_session",M)},children:W?`${P}ing…`:P}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{g("session_host_restart_session",M)},children:H?"Restarting…":"Restart"}),j==="live"&&(M.lifecycle==="running"||M.lifecycle==="starting"||M.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{g("session_host_stop_session",M)},children:$?"Stopping…":"Stop"})]})]})},M.sessionId)};return s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(is,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Ax()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[_>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{v()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${_})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${S.toneClass}`,children:S.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:h||c,children:[s.jsx(Rr,{size:13}),h||c?"Refreshing…":"Refresh"]})]})]}),n&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(Ar,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:k.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:rc(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Ga(u.hostStartedAt)})]})]}),w&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(Ar,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:w.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Ga(w.timestamp),w.sessionId?` · ${w.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Ro,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:za("live")}),I.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:I.map(M=>D(M,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(is,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:za("recovery")}),k.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:k.map(M=>D(M,"recovery"))})]}),A.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:za("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:A.map(M=>D(M,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),N.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:N.map(M=>{var W;const j=f.find(H=>H.sessionId===M.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(j==null?void 0:j.displayName)||((W=b.get(M.sessionId))==null?void 0:W.cliName)||M.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[M.action,M.lifecycle?` · ${M.lifecycle}`:"",M.detail?` · ${M.detail}`:"",M.error?` · ${M.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${M.success===!1?"text-red-300":"text-text-secondary"}`,children:Ga(M.timestamp)})]},`${M.sessionId}:${M.timestamp}:${M.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function bw({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(o=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{a(null),n({cliType:t.cliType,workspaceId:o.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:o.label||o.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:o.path})]},o.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function qa({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function Ya({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function gw({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:l}){const c=n.slice(0,6),d=r.slice(0,4),m="0.9.81",u=Hd(e),h=$s(e,m),x=Sr(e,h),S=u==="preview"?"Update to preview":"Update daemon";return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[c.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(qa,{icon:s.jsx(es,{size:13}),children:"Current Chats"}),s.jsx(Ya,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(b=>{const p=yo(b);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>l(b),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:ut(b)}),p>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Un(p)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Is(b)})]},b.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(qa,{icon:s.jsx(wc,{size:13}),children:"Recent Launches"}),s.jsx(Ya,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(b=>{const{metaText:p,updatedLabel:g}=tu(b);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>o(b),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:b.label}),g&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:g})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:p})]},b.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(qa,{icon:s.jsx(Ar,{size:13}),children:"Daemon Update"}),s.jsx(Ya,{className:"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:x?"Daemon update required":"Version mismatch detected"}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[x?"This machine is on an incompatible daemon version. Update it before starting more sessions.":u==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",h&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",h,u?` (${u})`:""]})]}),s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[s.jsx(Rr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:S})]})]})})]})]})}function yw(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function vw({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:o,onCustomPathChange:l,onOpenBrowseDialog:c}){return s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:t,onChange:d=>{const m=d.target.value;if(o(m),m==="__custom__"&&a){c();return}m!=="__custom__"&&l("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(e.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(d=>s.jsxs("option",{value:d.id,children:[d.id===e.defaultWorkspaceId?"⭐ ":"",Vn(d.path,d.label)]},d.id)),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),t==="__custom__"&&(a?s.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:c,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:d=>l(d.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:t==="__custom__"?r?s.jsx("span",{className:"font-mono truncate block",title:r,children:r}):a?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":r?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:t===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const ww={ide:{label:"IDE",plural:"IDEs",accent:"border-blue-500/[0.12]"},cli:{label:"CLI",plural:"CLIs",accent:"border-violet-500/[0.12]"},acp:{label:"ACP Agent",plural:"ACP agents",accent:"border-emerald-500/[0.12]"}};function un(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Xa({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:l,sendDaemonCommand:c,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const h=As(),{handleLaunchIde:x,handleStopCli:S,handleRestartIde:b,handleStopIde:p,handleDetectIdes:g,launchingIde:v,launchingAgentType:f,addLog:T}=l,[I,k]=i.useState(null),A=i.useCallback(L=>{L&&h(Zt(L))},[h]),_=ww[e],N=e==="ide",w=e==="acp",D=i.useMemo(()=>n.filter(L=>Ts(L,e)),[e,n]),M=i.useMemo(()=>new Map(D.map(L=>[L.type,L.displayName||L.type])),[D]),[j,W]=i.useState(""),[H,$]=i.useState(""),[C,y]=i.useState([]),[F,P]=i.useState(""),[E,G]=i.useState(""),[J,ye]=i.useState([]),[he,ne]=i.useState(!1),[ue,Se]=i.useState(!1),[ve,X]=i.useState(""),[xe,fe]=i.useState(!1),[we,be]=i.useState(()=>Ct()),[Ce,ee]=i.useState(null),[me,ie]=i.useState(m?"__custom__":d||t.defaultWorkspaceId||""),[pe,le]=i.useState(m||""),[B,z]=i.useState([]),[de,re]=i.useState(!1),[R,q]=i.useState(""),[ce,Ne]=i.useState([]),[je,O]=i.useState(!1),[Ie,Le]=i.useState(""),He=i.useRef(null),[ze,Xe]=i.useState(null),Je=i.useRef("__home__"),[rt,pt]=i.useState("__home__"),[xt,vt]=i.useState(!1),Te=i.useRef(0),Ve=B.filter(L=>!a.some(Q=>Q.type===L&&yt(Q.status)!=="stopped")),tt=i.useRef({});i.useEffect(()=>{t.defaultWorkspaceId&&!me&&ie(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),i.useEffect(()=>{if(m){ie("__custom__"),le(m);return}d&&(ie(d),le(""))},[d,m]),i.useEffect(()=>{N||j&&(D.some(L=>L.type===j)||(W(""),G("")))},[D,N,j]);const Ge=(()=>{if(me==="__custom__")return pe.trim();if(!me)return"";const L=(t.workspaces||[]).find(Q=>Q.id===me);return(L==null?void 0:L.path)||""})(),ot=i.useCallback(L=>{const Q=tt.current[L];Q&&(clearTimeout(Q),delete tt.current[L]),z(ge=>ge.includes(L)?ge.filter(Be=>Be!==L):ge)},[]),U=i.useRef(new Set),V=i.useCallback(async L=>{if(c){O(!0),Le("");try{const Q=await Zn(c,r,L);q(Q.path),le(Q.path),Ne(Q.directories)}catch(Q){Le(Q instanceof Error?Q.message:"Could not load folder")}finally{O(!1)}}},[r,c]),Z=i.useCallback(()=>{if(!c)return;ie("__custom__"),re(!0);const L=a.map(ge=>ge.workspace),Q=Qn(t.platform,Jn(pe.trim(),Ge,m,L,t.defaultWorkspacePath,(t.workspaces||[]).map(ge=>ge.path)));V(Q)},[pe,m,V,t.defaultWorkspacePath,t.platform,t.workspaces,a,Ge,c]),ae=i.useCallback(L=>{const Q=String(L.workspace||"").trim();if(!Q)return;const ge=(t.workspaces||[]).find(Be=>un(Be.path)===un(Q));if(ge){ie(ge.id),le("");return}ie("__custom__"),le(Q)},[t.workspaces]),K=i.useCallback(L=>{const Q=String(L.workspace||"").trim();if(!Q)return{workspaceId:null,workspacePath:"",useHome:!0};const ge=(t.workspaces||[]).find(Be=>un(Be.path)===un(Q));return ge?{workspaceId:ge.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Q,useHome:!1}},[t.workspaces]),Y=i.useCallback(async L=>{if(!c||!L||e!=="cli"){ye([]),ne(!1),Se(!1),X("");return}const Q=Te.current+1;Te.current=Q,ne(!0),X("");try{const ge=await c(r,"list_saved_sessions",{providerType:L,kind:"cli",limit:30});if(Te.current!==Q)return;const Be=(ge==null?void 0:ge.result)??ge;ye(Array.isArray(Be==null?void 0:Be.sessions)?Be.sessions:[])}catch(ge){if(Te.current!==Q)return;ye([]),X(ge instanceof Error?ge.message:"Could not load saved sessions")}finally{Te.current===Q&&(ne(!1),Se(!0))}},[e,r,c]),se=i.useMemo(()=>{if(e!=="cli"||!j)return null;const L=M.get(j)||j;return{routeId:r,daemonId:r,providerSessionId:E||void 0,transport:"pty",mode:"chat",agentName:L,agentType:j,status:"idle",title:L,messages:[],ideType:j,workspaceName:Ge,workspacePath:Ge,displayPrimary:L,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${j}`}},[e,r,M,Ge,E,j]),oe=i.useCallback(L=>{if(e==="ide"||!L){y([]);return}y(jo(r,L))},[e,r]),ke=i.useCallback((L,Q)=>{e==="ide"||!L||(Hy(r,L,Q),y(jo(r,L)))},[e,r]);i.useEffect(()=>{Te.current+=1,G(""),oe(j),Se(!1),ye([]),X(""),ne(!1)},[e,oe,Y,j]);const Pe=i.useMemo(()=>J.find(L=>L.providerSessionId===E)||null,[J,E]);i.useEffect(()=>{if(!E)return;const L=J.find(Q=>Q.providerSessionId===E);L!=null&&L.canResume||G("")},[J,E]);const Ee=i.useCallback((L,Q)=>{He.current=Q,Je.current=L.selectedWorkspaceKey||"__home__",pt(L.selectedWorkspaceKey||"__home__"),Xe(L)},[]),Ae=i.useCallback(()=>{He.current&&(vt(!0),He.current().finally(()=>{He.current=null,vt(!1),Xe(null)}))},[]),$e=i.useCallback(L=>{if(!L)return;z(ge=>ge.includes(L)?ge:[...ge,L]);const Q=tt.current[L];Q&&clearTimeout(Q),tt.current[L]=setTimeout(()=>{z(ge=>ge.includes(L)?ge.filter(Be=>Be!==L):ge),delete tt.current[L]},2e4)},[]);i.useEffect(()=>{for(const Q of a)yt(Q.status)!=="stopped"&&(B.includes(Q.type)&&!U.current.has(Q.type)&&(U.current.add(Q.type),T("info",`${M.get(Q.type)||Q.type} launched`,!0)),ot(Q.type));const L=new Set(a.filter(Q=>yt(Q.status)!=="stopped").map(Q=>Q.type));U.current.forEach(Q=>{!B.includes(Q)&&!L.has(Q)&&U.current.delete(Q)})},[T,ot,a,B,M]),i.useEffect(()=>()=>{Object.values(tt.current).forEach(clearTimeout),tt.current={}},[]);const[Fe,Me]=i.useState({}),[Qe,et]=i.useState(null);i.useEffect(()=>{if(!N||!r||!c)return;(async()=>{try{const Q=await c(r,"get_ide_extensions",{}),ge=(Q==null?void 0:Q.result)||Q;ge!=null&&ge.success&&(ge!=null&&ge.ideExtensions)&&Me(ge.ideExtensions)}catch{}})()},[N,r,c]);const bt=L=>N?ct(L.type):e==="cli"?L.cliName:L.acpName,gt=N?t.detectedIdes||[]:[],dt=i.useCallback(async L=>{const Q=(L==null?void 0:L.type)||j,ge=(L==null?void 0:L.workspacePath)??Ge;if(N){await x(Q,ge?{workspace:ge}:void 0)&&$e(Q);return}const Be=await l.runLaunchCliCore({cliType:Q,dir:L!=null&&L.workspaceId?void 0:ge||void 0,workspaceId:(L==null?void 0:L.workspaceId)||void 0,useHome:(L==null?void 0:L.useHome)||!(L!=null&&L.workspaceId)&&!ge,argsStr:(L==null?void 0:L.argsStr)??(H||void 0),model:(L==null?void 0:L.model)??(w&&F||void 0),resumeSessionId:(L==null?void 0:L.resumeSessionId)||!w&&e==="cli"&&Q===j&&E||void 0});if(Be.success||Be.pending){const _e=(L==null?void 0:L.argsStr)??H;!N&&(_e!=null&&_e.trim())&&(fu(r,Q,_e),oe(Q)),$e(Q),Be.success&&Be.sessionId&&A(Be.sessionId)}},[l,x,w,N,H,F,oe,$e,r,A,Ge,E,j]),ht=pd(N?"ide":w?"acp":"cli",!N&&!w&&!!E),Ue=hd(N?"ide":w?"acp":"cli",!N&&!w&&!!E),Kt=()=>{var _e;const L=N?ct(j):M.get(j)||j,Q=!N&&!w&&!!E,{options:ge,selectedKey:Be}=ks({machine:t,currentWorkspaceId:me&&me!=="__custom__"?me:null,currentWorkspacePath:Ge});Ee({title:Q?Qo(L):gs("start-fresh",L),description:Q?Zo():ys("start-fresh"),confirmLabel:ht,busyLabel:Ue,workspaceOptions:ge,selectedWorkspaceKey:Be,details:[{label:"Mode",value:_.label},{label:"Provider",value:L},...!N&&e==="cli"&&E?[{label:"Resume",value:((_e=J.find(Oe=>Oe.providerSessionId===E))==null?void 0:_e.title)||E}]:[],...!N&&H.trim()?[{label:"Arguments",value:H.trim()}]:[],...w&&F.trim()?[{label:"Model",value:F.trim()}]:[]]},async()=>{const Oe=ge.find(nt=>nt.key===Je.current);Oe!=null&&Oe.workspaceId?(ie(Oe.workspaceId),le("")):Oe!=null&&Oe.workspacePath?(ie("__custom__"),le(Oe.workspacePath)):(ie(""),le("")),await dt({workspaceId:(Oe==null?void 0:Oe.workspaceId)??null,workspacePath:(Oe==null?void 0:Oe.workspacePath)??"",useHome:!(Oe!=null&&Oe.workspaceId)&&!(Oe!=null&&Oe.workspacePath)})})},te=L=>{N?p(L):S(L.type,L.workspace,L.id)},De=i.useCallback(async(L,Q,ge=!1)=>{if(L.mode===Q){ge&&L.sessionId&&A(L.sessionId);return}if(!c||!L.sessionId){ge&&L.sessionId&&A(L.sessionId);return}try{await c(r,"set_cli_view_mode",{targetSessionId:L.sessionId,cliType:L.type,mode:Q}),ge&&A(L.sessionId)}catch(Be){const _e=Pd(Be);Rd(Be)?console.warn(_e?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Be instanceof Error?Be.message:String(Be)):console.error("Failed to switch CLI view mode:",Be)}},[r,A,c]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${_.accent} relative overflow-hidden`,children:[s.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",_.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:N?gt.length>0?gt.map(L=>{const Q=a.find(nt=>(nt.type||"").toLowerCase()===(L.type||"").toLowerCase()&&yt(nt.status)!=="stopped"),ge=L.running||!!Q,Be=!!Q&&Q.cdpConnected,_e=B.includes(L.type||L.id||""),Oe=j===(L.type||"");return s.jsxs("button",{onClick:()=>{if(Be&&Q){const nt=Q.sessionId;nt?h(Zt(nt),{state:{openRemoteForTabKey:nt}}):h("/dashboard",{state:{openRemoteForTabKey:Q.id}});return}_e||W(nt=>nt===(L.type||"")?"":L.type||"")},disabled:!!v||_e,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Be?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Oe?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:v&&v!==L.type?.4:1},children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:o(L.type)}),ge&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Be?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:L.name||ct(L.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Be?"text-green-400":_e?"text-orange-400":Oe?"text-accent-primary":"text-text-muted"}`,children:Be?"Open Session":_e?"Starting...":Oe?"Configure":"Select"})]})]},L.type)}):s.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",s.jsxs("button",{onClick:g,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[s.jsx(Zm,{size:14})," Scan System"]})]}):D.length>0?D.map(L=>{const Q=j===L.type,ge=B.includes(L.type),_e=!!a.find(Oe=>Oe.type===L.type&&yt(Oe.status)!=="stopped");return s.jsxs("button",{onClick:()=>W(Oe=>Oe===L.type?"":L.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Q?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:L.icon}),_e&&s.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:L.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ge?"text-orange-400":Q?"text-accent-primary":"text-text-muted"}`,children:ge?"Starting...":Q?"Configure":"Select"})]})]},L.type)}):s.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),j&&(N?gt.find(L=>L.type===j):D.find(L=>L.type===j))&&s.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:N?ct(j):M.get(j)||j})]}),s.jsx(vw,{machine:t,selectedWorkspace:me,resolvedWorkspacePath:Ge,customPath:pe,canBrowse:!!c,onWorkspaceChange:ie,onCustomPathChange:le,onOpenBrowseDialog:Z}),!N&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&s.jsx(bu,{busy:!!f||!!v||B.includes(j),savedSessionsLoading:he,savedSessionsError:ve,savedSessionsLoaded:ue,savedSessionsCount:J.length,selectedSession:Pe,onRefresh:()=>void Y(j),onOpenHistory:()=>{j&&(fe(!0),xu({hasLoadedInitialResults:ue,isLoading:he})&&Y(j))},onClearSelection:()=>G("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[w&&s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),s.jsx("input",{type:"text",placeholder:"Leave empty for default",value:F,onChange:L=>P(L.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),s.jsx("input",{type:"text",placeholder:"Optional flags...",value:H,onChange:L=>$(L.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),C.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:C.map(L=>s.jsxs("div",{className:"inline-flex max-w-full items-stretch overflow-hidden rounded-md border border-[#ffffff1a] bg-bg-tertiary text-xs text-text-secondary transition-colors hover:border-accent-primary/40 hover:text-text-primary",title:L,children:[s.jsx("button",{type:"button",className:"min-w-0 max-w-[220px] truncate px-2.5 py-1.5 text-left",onClick:()=>$(L),children:L}),s.jsx("button",{type:"button",className:"flex items-center justify-center border-l border-[#ffffff1a] px-1.5 text-text-muted transition-colors hover:bg-status-error/10 hover:text-status-error focus:outline-none focus:ring-1 focus:ring-status-error/50",onClick:()=>ke(j,L),"aria-label":`Remove startup arguments: ${L}`,title:"Remove startup arguments",children:s.jsx(wt,{size:12})})]},L))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:Kt,disabled:!!f||!!v||B.includes(j),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:f===j||v===j?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+B.filter(L=>!a.some(Q=>Q.type===L&&yt(Q.status)!=="stopped")).length,")"]}),a.length===0&&Ve.length===0?s.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",_.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ve.map(L=>s.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:o(L)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:N?ct(L):M.get(L)||L}),s.jsx("div",{className:"text-[11px] text-text-muted",children:f===L?"Launching process...":"Waiting for process and session to register..."})]})]}),s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${L}`)),a.map(L=>{const Q=N?L:null,ge=!N&&!w?L:null,Be=yt(L.status);return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:o(L.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[bt(L),(Q==null?void 0:Q.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Q.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex min-w-0 flex-wrap items-center gap-2",children:[s.jsx("span",{className:"truncate",children:L.workspace||"—"}),u&&L.git&&L.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:_e=>{_e.stopPropagation(),u(L.daemonId??r,L.workspace)},children:s.jsx(qs,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(qs,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(ge==null?void 0:ge.mode)&&s.jsx("span",{className:ge.mode==="chat"?"text-violet-400":"text-text-secondary",children:ge.mode==="chat"?"Chat view":"Terminal view"})]}),ge&&(ge.runtimeKey||ge.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ge.runtimeKey&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),s.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",ge.runtimeKey]}),s.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var _e;(_e=navigator.clipboard)==null||_e.writeText(`adhdev attach ${ge.runtimeKey}`),k(ge.runtimeKey||null),window.setTimeout(()=>{k(Oe=>Oe===ge.runtimeKey?null:Oe)},1200)},children:I===ge.runtimeKey?"Copied":"Copy"})]}),ge.runtimeWriteOwner&&s.jsx("span",{style:{color:ge.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ge.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:yw(ge.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Be==="stopped"?"bg-red-500/[0.08] text-red-500":Be==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Be}),N&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const _e=L.sessionId;if(_e){h(Zt(_e),{state:{openRemoteForTabKey:_e}});return}h("/dashboard",{state:{openRemoteForTabKey:L.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:s.jsx(_t,{size:13})}),s.jsx("button",{onClick:()=>{const _e=L.workspace||"",{options:Oe,selectedKey:nt}=ks({machine:t,currentWorkspacePath:_e});Ee({title:gs("restart-ide",ct(L.type)),description:ys("restart-ide"),confirmLabel:Ys("restart-ide"),busyLabel:Xs("restart-ide"),workspaceOptions:Oe,selectedWorkspaceKey:nt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:ct(L.type)}]},async()=>{const Mt=Oe.find(ss=>ss.key===Je.current),ft=(Mt==null?void 0:Mt.workspacePath)??"";if(ft&&ft!==_e){await dt({type:L.type,workspacePath:ft});return}await b(L)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:s.jsx(Rr,{size:14})})]}),w&&s.jsx("button",{onClick:()=>{const _e=L.sessionId;_e&&A(_e)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!L.sessionId,children:s.jsx(es,{size:14})}),ge&&Be!=="stopped"&&s.jsxs(s.Fragment,{children:[ge.mode&&s.jsx(Yo,{mode:ge.mode,onChange:_e=>void De(ge,_e,!1),compact:!0}),s.jsx("button",{onClick:()=>{const _e=L.sessionId;_e&&A(_e)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!L.sessionId,children:ge.mode==="chat"?s.jsx(es,{size:14}):s.jsx(_t,{size:13})})]}),Be==="stopped"?s.jsx("button",{onClick:()=>{const _e=L.workspace||"",Oe=N?ct(L.type):bt(L),{options:nt,selectedKey:Mt}=ks({machine:t,currentWorkspacePath:_e});Ee({title:gs("restart-stopped",Oe),description:ys("restart-stopped"),confirmLabel:Ys("restart-stopped"),busyLabel:Xs("restart-stopped"),workspaceOptions:nt,selectedWorkspaceKey:Mt,details:[{label:"Mode",value:_.label},{label:"Provider",value:Oe}]},async()=>{const ft=nt.find(ss=>ss.key===Je.current);await dt({type:L.type,workspaceId:(ft==null?void 0:ft.workspaceId)??null,workspacePath:(ft==null?void 0:ft.workspacePath)??"",useHome:!(ft!=null&&ft.workspaceId)&&!(ft!=null&&ft.workspacePath)})})},disabled:B.includes(L.type),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-green-500/20 text-green-400 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",title:"Restart",children:B.includes(L.type)?"⏳":s.jsx(Po,{size:14})}):s.jsx("button",{onClick:()=>te(L),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:s.jsx(wt,{size:14})})]})]}),Q&&Q.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Q.aiAgents.map(_e=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Mn(_e.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[_e.name," · ",yt(_e.status)]},_e.id))}),Q&&(Fe[Q.type]||[]).length>0&&c&&s.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[s.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:(Fe[Q.type]||[]).map(_e=>s.jsxs("button",{disabled:Qe===`${Q.type}.${_e.type}`,onClick:async()=>{const Oe=`${Q.type}.${_e.type}`;et(Oe);try{await c(r,"set_ide_extension",{ideType:Q.type,extensionType:_e.type,enabled:!_e.enabled}),Me(nt=>({...nt,[Q.type]:(nt[Q.type]||[]).map(Mt=>Mt.type===_e.type?{...Mt,enabled:!Mt.enabled}:Mt)}))}catch(nt){console.error("Extension toggle failed:",nt)}finally{et(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${_e.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${_e.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),_e.name,s.jsx("span",{className:"text-[9px] font-normal",children:_e.enabled?"ON":"OFF"})]},_e.type))})]})]},L.id)})]}),de&&c&&s.jsx(ea,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:R,directories:ce,busy:je,error:Ie,confirmLabel:"Use this folder",onClose:()=>re(!1),onNavigate:L=>{V(L)},onConfirm:L=>{le(L),ie("__custom__"),re(!1)}}),ze&&s.jsx(li,{title:ze.title,description:ze.description,details:ze.details,workspaceOptions:ze.workspaceOptions,selectedWorkspaceKey:rt,onWorkspaceChange:L=>{Je.current=L,pt(L)},confirmLabel:ze.confirmLabel,busyLabel:ze.busyLabel,busy:xt,onConfirm:Ae,onCancel:()=>{He.current=null,Xe(null)}}),xe&&se&&s.jsx(ei,{activeConv:se,ides:[],isCreatingChat:!1,isRefreshingHistory:he,savedSessions:J,isSavedSessionsLoading:he,isResumingSavedSessionId:Ce,savedHistoryFilters:we,missingWorkspaceResumePath:Ge||null,onSavedHistoryFiltersChange:be,onClose:()=>fe(!1),onNewChat:()=>{G(""),fe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Y(j)},onResumeSavedSession:L=>{if(!L.canResume||Ce)return;const Q=K(L);G(L.providerSessionId),ae(L),ee(L.providerSessionId),fe(!1),dt({type:L.providerType,workspaceId:Q.workspaceId,workspacePath:Q.workspacePath,useHome:Q.useHome,resumeSessionId:L.providerSessionId}).finally(()=>{ee(ge=>ge===L.providerSessionId?null:ge)})}})]})}const nc=[{id:"ide",label:"IDE",helper:"Open a graphical workspace and attach CDP"},{id:"cli",label:"CLI",helper:"Launch a terminal-first workspace on this machine"},{id:"acp",label:"ACP",helper:"Launch an ACP-backed workspace on this machine"}];function jw({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:l,getIcon:c,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:h,onOpenGitDialog:x}){var g;const[S,b]=i.useState(d);i.useEffect(()=>{b(d)},[d]);const p=i.useMemo(()=>({ide:n.length,cli:a.length,acp:o.length}),[n.length,a.length,o.length]);return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[s.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:nc.map(v=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${S===v.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>b(v.id),children:[s.jsx("span",{children:v.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${S===v.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:p[v.id]})]},v.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(g=nc.find(v=>v.id===S))==null?void 0:g.helper})]}),S==="ide"&&s.jsx(Xa,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),S==="cli"&&s.jsx(Xa,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),S==="acp"&&s.jsx(Xa,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:o,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x})]})}function kw({onNicknameSynced:e}={}){var le,B,z,de,re,R,q,ce,Ne,je;const{id:t}=km(),r=As(),n=To(),{sendCommand:a}=jt(),o=Er(),l=Td(),c=ad(),d=c.ides||[],m=c.initialLoaded??!0,u=d.find(O=>O.id===t&&O.type==="adhdev-daemon"),h=d.some(O=>O.type==="adhdev-daemon"),x=t?(le=c.connectionRetryStatuses)==null?void 0:le[t]:void 0,S=!!(x!=null&&x.blocked),[b,p]=i.useState("workspace"),[g,v]=i.useState(null),f=i.useCallback((O,Ie)=>{v({daemonId:O,workspace:Ie})},[]),[T,I]=i.useState("ide"),k=i.useRef(null),[A,_]=i.useState(null),N=i.useRef("__home__"),[w,D]=i.useState("__home__"),[M,j]=i.useState(!1),W=i.useRef(null);i.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||o(t,{minFreshMs:3e4}).catch(()=>{})},[o,u,t]),i.useEffect(()=>{if(!t||!u||b!=="overview")return;const O=u.machine;(typeof(O==null?void 0:O.cpus)!="number"||typeof(O==null?void 0:O.totalMem)!="number"||typeof(O==null?void 0:O.arch)!="string"||typeof(O==null?void 0:O.release)!="string")&&l(t,{minFreshMs:3e4}).catch(()=>{})},[b,l,u,t]),Tb(t&&b==="overview"?[t]:[],{enabled:b==="overview",intervalMs:wf});const H=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},$=gv({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:W});i.useEffect(()=>it.onToast(Ie=>{c.setToasts(He=>{if(He.some(Je=>Je.message===Ie.message&&Ie.timestamp-Je.timestamp<3e3))return He;const Xe={id:Ie.id,message:Ie.message,type:Ie.type,timestamp:Ie.timestamp,targetKey:Ie.targetKey,actions:Ie.actions};return[...He.slice(-4),Xe]});const Le=Ie.duration||5e3;setTimeout(()=>c.setToasts(He=>He.filter(ze=>ze.id!==Ie.id)),Le)}),[c]);const C=(u==null?void 0:u.availableProviders)||[],y={};for(const O of C)y[O.type]=O.icon;const F=O=>y[O]||"",P=u?{id:u.id,hostname:Rc(u,{fallbackId:u.id}),platform:((B=u.machine)==null?void 0:B.platform)||"unknown",arch:((z=u.machine)==null?void 0:z.arch)||"",cpus:((de=u.machine)==null?void 0:de.cpus)||0,totalMem:((re=u.machine)==null?void 0:re.totalMem)||0,freeMem:(R=u.machine)==null?void 0:R.freeMem,availableMem:(q=u.machine)==null?void 0:q.availableMem,loadavg:(ce=u.machine)==null?void 0:ce.loadavg,uptime:(Ne=u.machine)==null?void 0:Ne.uptime,release:((je=u.machine)==null?void 0:je.release)||"",cdpConnected:!!u.cdpConnected,machineNickname:u.machineNickname||null,p2p:u.p2p?{screenshotActive:!1,...u.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:u.detectedIdes||[],workspaces:u.workspaces||[],defaultWorkspaceId:u.defaultWorkspaceId??u.activeWorkspaceId??null,defaultWorkspacePath:u.defaultWorkspacePath??u.activeWorkspacePath??null}:null,E=d.filter(O=>O.daemonId===t&&O.type!=="adhdev-daemon").filter(O=>!_r(O)&&!Fs(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,version:O.version||"",instanceId:O.instanceId||"",status:O.status,workspace:O.workspace||null,terminals:O.terminals||0,aiAgents:mh(O.aiAgents||(O.agents||[]).map(Ie=>({id:Ie.name,name:Ie.name,status:Ie.status,version:Ie.version}))),activeChat:O.activeChat||null,chats:O.chats||[],childSessions:O.childSessions||[],cdpConnected:O.cdpConnected||!1,daemonId:t,lastMessageAt:O.lastMessageAt})),G=d.filter(O=>O.daemonId===t&&_r(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,cliName:O.cliName||O.type,status:O.status,workspace:O.workspace||"",activeChat:O.activeChat||null,providerSessionId:O.providerSessionId,mode:O.mode,runtimeKey:O.runtimeKey,runtimeDisplayName:O.runtimeDisplayName,runtimeWorkspaceLabel:O.runtimeWorkspaceLabel,runtimeWriteOwner:O.runtimeWriteOwner||null,runtimeAttachedClients:O.runtimeAttachedClients||[],daemonId:t,lastMessageAt:O.lastMessageAt})),J=d.filter(O=>O.daemonId===t&&Fs(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,acpName:O.cliName||O.type,status:O.status,workspace:O.workspace||"",activeChat:O.activeChat||null,providerSessionId:O.providerSessionId,daemonId:t,lastMessageAt:O.lastMessageAt})),ye=u?At(u,{fallbackId:t}):"",he="workspace",ne=n.state,ue=ne==null?void 0:ne.initialMachineTab,Se=ne==null?void 0:ne.initialWorkspaceCategory,ve=ne==null?void 0:ne.initialWorkspaceId,X=ne==null?void 0:ne.initialWorkspacePath,xe=ue==="ides"||ue==="clis"||ue==="acps"?"workspace":ue||he,fe=ue==="ides"?"ide":ue==="clis"?"cli":ue==="acps"?"acp":Se,we=[...E.map(O=>{var Ie;return{id:`ide:${O.type}:${O.workspace||""}`,label:((Ie=O.activeChat)==null?void 0:Ie.title)||O.type,kind:"ide",providerType:O.type,subtitle:O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:O.lastMessageAt||0}}),...G.map(O=>{var Ie;return{id:`cli:${O.type}:${O.workspace||""}`,label:((Ie=O.activeChat)==null?void 0:Ie.title)||O.cliName,kind:"cli",providerType:O.type,providerSessionId:O.providerSessionId,subtitle:O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:O.lastMessageAt||0}}),...J.map(O=>{var Ie;return{id:`acp:${O.type}:${O.workspace||""}`,label:((Ie=O.activeChat)==null?void 0:Ie.title)||O.acpName,kind:"acp",providerType:O.type,providerSessionId:O.providerSessionId,subtitle:Cs(O.summaryMetadata)||O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:O.lastMessageAt||0}})].sort((O,Ie)=>(Ie.lastLaunchedAt||0)-(O.lastLaunchedAt||0)),be=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(O=>({id:O.id,label:O.title||O.providerName||O.providerType,kind:O.kind,providerType:O.providerType,providerSessionId:O.providerSessionId,subtitle:Cs(O.summaryMetadata)||O.workspace||void 0,workspace:O.workspace,summaryMetadata:O.summaryMetadata,lastLaunchedAt:O.lastLaunchedAt})):we,Ce=i.useMemo(()=>{var Ie;const O=((Ie=c.connectionStates)==null?void 0:Ie[t||""])||void 0;return d.filter(Le=>Le.daemonId===t&&Le.type!=="adhdev-daemon").flatMap(Le=>ti(Le,{connectionStates:t&&O?{[t]:O}:void 0,defaultConnectionState:O})).filter(Le=>!(Le.transport==="pty"&&Le.mode==="terminal")).sort((Le,He)=>yo(He)-yo(Le))},[d,c.connectionStates,t]),ee=i.useCallback(O=>{const Ie=qd(O);Ie&&r(Zt(Ie))},[r]),me=i.useCallback(()=>{k.current&&(j(!0),k.current().finally(()=>{k.current=null,j(!1),_(null)}))},[]),ie=i.useCallback(O=>{if(!P)return;const{options:Ie,selectedKey:Le}=ks({machine:P,currentWorkspacePath:O.workspace}),He=async()=>{I(O.kind),p("workspace")};k.current=async()=>{const ze=Ie.find(rt=>rt.key===N.current),Xe=(ze==null?void 0:ze.workspacePath)??null,Je=(ze==null?void 0:ze.workspaceId)??null;if(O.kind==="ide"&&O.providerType){await $.handleLaunchIde(O.providerType,Xe?{workspace:Xe}:void 0);return}if((O.kind==="cli"||O.kind==="acp")&&O.providerType){await $.runLaunchCliCore({cliType:O.providerType,dir:Je?void 0:Xe||"",workspaceId:Je||void 0,model:O.kind==="acp"&&Dc(O.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:O.providerSessionId});return}await He()},N.current=Le,D(Le),_({title:O.kind==="ide"?gs("restart-ide",O.label):O.providerSessionId?Qo(O.label):gs("start-fresh",O.label),description:O.kind==="ide"?ys("restart-ide"):O.providerSessionId?Zo():ys("start-fresh"),confirmLabel:O.kind==="ide"?Ys("restart-ide"):O.providerSessionId?Pn(!0):Ys("start-fresh"),busyLabel:O.kind==="ide"?Xs("restart-ide"):O.providerSessionId?Xo(!0):Xs("start-fresh"),workspaceOptions:Ie,details:[{label:"Mode",value:O.kind.toUpperCase()},...O.providerType?[{label:"Provider",value:O.providerType}]:[]]})},[$,P]);if(i.useEffect(()=>{p(xe)},[he,xe,t]),i.useEffect(()=>{fe&&I(fe)},[fe,t]),!P)return m?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:H,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const pe=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_t,{size:14})," Workspace"]}),count:E.length+G.length+J.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(is,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Kn,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(tp,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Jm,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:H,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[$.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:$.nicknameInput,onChange:O=>$.setNicknameInput(O.target.value),onKeyDown:O=>{O.key==="Enter"&&$.handleSaveNickname(),O.key==="Escape"&&$.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:$.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>$.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{$.setEditingNickname(!0),$.setNicknameInput(P.machineNickname||"")},title:"Click to set nickname",children:ye}),S?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),c.retryConnection&&t&&s.jsx("button",{onClick:()=>c.retryConnection(t),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:"Reconnect"})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[P.platform," · ",P.arch]}),s.jsxs("span",{children:[P.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),P.p2p.available&&s.jsxs("span",{children:["P2P ",P.p2p.state==="connected"?"connected":P.p2p.state]}),P.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:P.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:pe.map(O=>s.jsxs("button",{onClick:()=>p(O.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${b===O.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[O.label,O.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${b===O.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:O.count})]},O.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[b==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(gw,{machineEntry:u,providers:C,recentLaunches:be,currentConversations:Ce,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",Ud(u))}catch{}},onOpenRecent:ie,onOpenConversation:ee}),s.jsx(jw,{machine:P,machineId:t,providers:C,ideSessions:E,cliSessions:G,acpSessions:J,actions:$,getIcon:F,initialCategory:T,initialWorkspaceId:ve,initialWorkspacePath:X,sendDaemonCommand:a,onOpenGitDialog:f})]}),b==="providers"&&s.jsx(Tv,{machineId:t,providers:C,sendDaemonCommand:a}),b==="overview"&&s.jsx(yv,{machineId:t,machine:P,ideSessions:E,cliSessions:G,acpSessions:J,actions:$,sendDaemonCommand:a}),b==="session-host"&&s.jsx(xw,{machineId:t,cliSessions:G,sendDaemonCommand:a}),b==="logs"&&s.jsx(cw,{machineId:t,sendDaemonCommand:a})]})})}),$.launchPick&&P&&s.jsx(bw,{machine:P,launchPick:$.launchPick,actions:$}),A&&s.jsx(li,{title:A.title,description:A.description,details:A.details,workspaceOptions:A.workspaceOptions,selectedWorkspaceKey:w,onWorkspaceChange:O=>{N.current=O,D(O)},confirmLabel:A.confirmLabel,busyLabel:A.busyLabel,busy:M,onConfirm:me,onCancel:()=>{k.current=null,_(null)}}),g&&s.jsx(Pu,{daemonId:g.daemonId,workspace:g.workspace,onClose:()=>v(null)}),s.jsx(fd,{toasts:c.toasts||[],onDismiss:O=>c.setToasts(Ie=>Ie.filter(Le=>Le.id!==O)),onClickToast:O=>{O.targetKey&&r(Zt(O.targetKey))}}),s.jsx("style",{children:`
92
92
  @keyframes toast-in {
93
93
  from { opacity: 0; transform: translateX(40px); }
94
94
  to { opacity: 1; transform: translateX(0); }
95
95
  }
96
- `})]})}const mn=[{value:"preserve",label:"Preserve history and runtimes",description:"Keep completed chat history and leave live runtimes alone."},{value:"stop",label:"Stop live runtimes only",description:"Release running session processes, but keep chat records/transcripts."},{value:"delete_stopped",label:"Delete stopped sessions only",description:"Clean completed/stopped chat clutter without killing live runtimes."},{value:"stop_and_delete",label:"Stop and delete sessions",description:"Stop matching runtimes, then remove their session records/transcripts."}],kw={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function jn(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function Sw(e){const t=jn(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"launch not ready unless an explicit provider is selected"}}function Nw(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function Cw(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",r=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${r}`}function Iw(e,t){return[...Array.isArray(t==null?void 0:t.cliSessions)?t.cliSessions:[],...Array.isArray(t==null?void 0:t.acpSessions)?t.acpSessions:[],...Array.isArray(t==null?void 0:t.sessions)?t.sessions:[]].filter(n=>{var a;return((a=n==null?void 0:n.settings)==null?void 0:a.meshNodeId)===e.id||(n==null?void 0:n.workspace)===e.workspace}).map(n=>{var a;return{id:n.sessionId||n.id||n.instanceId||"unknown",provider:n.providerType||n.cliType||n.acpType||n.type||"unknown",status:n.status||((a=n.activeChat)==null?void 0:a.status)||"unknown"}})}function Ja(e){return{...kw,...(e==null?void 0:e.policy)||{}}}function Tw({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const o=a.id.toLowerCase(),l=a.name.toLowerCase();return o==="hermes-cli"||o.includes("hermes")||l.includes("hermes")}),n=Gd(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(St,{title:"Hermes MCP Config",description:"Hermes does not auto-import repo-local .mcp.json. Add this YAML under mcp_servers in Hermes config, then start a fresh Hermes session.",children:s.jsx(gu,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function Mw(){var le;const{sendCommand:e}=jt(),{ides:t}=cs(),r=t.find(B=>B.daemonMode||B.type==="adhdev-daemon"),n=(r==null?void 0:r.id)||"",a=[];let o=[];if(r){const B=r.availableProviders||[];o=Kx(B);for(const z of B)z.category==="cli"&&a.push({id:z.type||z.id,name:z.displayName||z.name||z.type,meshCoordinator:z.meshCoordinator})}const[l,c]=i.useState([]),[d,m]=i.useState(null),[u,h]=i.useState(!0),[x,S]=i.useState(null),[b,p]=i.useState(!1),[g,v]=i.useState(null),[f,T]=i.useState({}),[I,k]=i.useState([]),[A,_]=i.useState(null),[N,w]=i.useState(null),[D,M]=i.useState(null),[j,W]=i.useState(!1),[H,$]=i.useState(null),[C,y]=i.useState(!1),[F,P]=i.useState(""),[E,G]=i.useState(""),[J,ye]=i.useState(!1),[he,ne]=i.useState(""),[ue,Se]=i.useState([]),ve=l.find(B=>B.id===d)||null;i.useEffect(()=>{T(Object.fromEntries(((ve==null?void 0:ve.nodes)||[]).map(B=>[B.id,jn(B)])))},[ve]),i.useEffect(()=>{const B=Hx(o);J&&ue.length===0&&B.length>0&&Se(B)},[J,o,ue.length]),i.useEffect(()=>{const B=new Set(((ve==null?void 0:ve.nodes)||[]).map(z=>z.id));A&&!B.has(A)&&_(null)},[ve,A]);const X=i.useCallback(async()=>{if(n){h(!0);try{const B=await e(n,"list_meshes");B!=null&&B.success?(c(B.meshes||[]),S(null)):S((B==null?void 0:B.error)||"Failed to load meshes")}catch(B){S((B==null?void 0:B.message)||"Failed to load meshes")}finally{h(!1)}}},[n,e]),xe=i.useCallback(async B=>{if(!n||!B){k([]);return}try{const z=await e(n,"get_mesh_queue",{meshId:B});z!=null&&z.success?k(Array.isArray(z.queue)?z.queue:[]):k([])}catch{k([])}},[n,e]);i.useEffect(()=>{X()},[X]),i.useEffect(()=>{xe(d)},[xe,d]);async function fe(){if(!(!n||!d))try{W(!0),$(null);const B=await e(n,"mesh_status",{meshId:d});if((B==null?void 0:B.success)===!1){w(null),M(null),$((B==null?void 0:B.error)||"mesh_status failed");return}const z=Lu(B);if(z){const de=ju(z);w(de),M(z)}else w(null),M(null),$("mesh_status returned an unexpected payload.")}catch(B){w(null),M(null),$((B==null?void 0:B.message)||"Failed to load mesh graph")}finally{W(!1)}}i.useEffect(()=>{d&&(w(null),M(null),$(null),fe())},[d]);async function we(){var B;if(!(!n||!F.trim()))try{const z=await e(n,"create_mesh",{name:F.trim(),repoIdentity:E.trim()||void 0});z!=null&&z.success?(y(!1),P(""),G(""),await X(),m(((B=z.mesh)==null?void 0:B.id)||null)):S((z==null?void 0:z.error)||"Create failed")}catch(z){S((z==null?void 0:z.message)||"Create failed")}}async function be(B){if(!(!n||!confirm("Delete this mesh?")))try{await e(n,"delete_mesh",{meshId:B}),m(null),await X()}catch(z){S((z==null?void 0:z.message)||"Delete failed")}}async function Ce(){if(!(!n||!d||!he.trim()))try{const B=await e(n,"add_mesh_node",{meshId:d,workspace:he.trim(),providerPriority:ho(ue,o)});B!=null&&B.success?(ye(!1),ne(""),Se([]),await X(),await xe(d)):S((B==null?void 0:B.error)||"Add node failed")}catch(B){S((B==null?void 0:B.message)||"Add node failed")}}async function ee(B){var re;if(!n||!d)return;const z=Ja(ve),de=((re=mn.find(R=>R.value===z.sessionCleanupOnNodeRemove))==null?void 0:re.label)||"Preserve history and runtimes";if(confirm(`Remove this node?
96
+ `})]})}const mn=[{value:"preserve",label:"Preserve history and runtimes",description:"Keep completed chat history and leave live runtimes alone."},{value:"stop",label:"Stop live runtimes only",description:"Release running session processes, but keep chat records/transcripts."},{value:"delete_stopped",label:"Delete stopped sessions only",description:"Clean completed/stopped chat clutter without killing live runtimes."},{value:"stop_and_delete",label:"Stop and delete sessions",description:"Stop matching runtimes, then remove their session records/transcripts."}],Sw={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function jn(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function Nw(e){const t=jn(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"launch not ready unless an explicit provider is selected"}}function Cw(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function Iw(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",r=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${r}`}function Tw(e,t){return[...Array.isArray(t==null?void 0:t.cliSessions)?t.cliSessions:[],...Array.isArray(t==null?void 0:t.acpSessions)?t.acpSessions:[],...Array.isArray(t==null?void 0:t.sessions)?t.sessions:[]].filter(n=>{var a;return((a=n==null?void 0:n.settings)==null?void 0:a.meshNodeId)===e.id||(n==null?void 0:n.workspace)===e.workspace}).map(n=>{var a;return{id:n.sessionId||n.id||n.instanceId||"unknown",provider:n.providerType||n.cliType||n.acpType||n.type||"unknown",status:n.status||((a=n.activeChat)==null?void 0:a.status)||"unknown"}})}function Ja(e){return{...Sw,...(e==null?void 0:e.policy)||{}}}function Mw({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const o=a.id.toLowerCase(),l=a.name.toLowerCase();return o==="hermes-cli"||o.includes("hermes")||l.includes("hermes")}),n=Gd(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(St,{title:"Hermes MCP Config",description:"Hermes does not auto-import repo-local .mcp.json. Add this YAML under mcp_servers in Hermes config, then start a fresh Hermes session.",children:s.jsx(gu,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function Aw(){var le;const{sendCommand:e}=jt(),{ides:t}=cs(),r=t.find(B=>B.daemonMode||B.type==="adhdev-daemon"),n=(r==null?void 0:r.id)||"",a=[];let o=[];if(r){const B=r.availableProviders||[];o=Kx(B);for(const z of B)z.category==="cli"&&a.push({id:z.type||z.id,name:z.displayName||z.name||z.type,meshCoordinator:z.meshCoordinator})}const[l,c]=i.useState([]),[d,m]=i.useState(null),[u,h]=i.useState(!0),[x,S]=i.useState(null),[b,p]=i.useState(!1),[g,v]=i.useState(null),[f,T]=i.useState({}),[I,k]=i.useState([]),[A,_]=i.useState(null),[N,w]=i.useState(null),[D,M]=i.useState(null),[j,W]=i.useState(!1),[H,$]=i.useState(null),[C,y]=i.useState(!1),[F,P]=i.useState(""),[E,G]=i.useState(""),[J,ye]=i.useState(!1),[he,ne]=i.useState(""),[ue,Se]=i.useState([]),ve=l.find(B=>B.id===d)||null;i.useEffect(()=>{T(Object.fromEntries(((ve==null?void 0:ve.nodes)||[]).map(B=>[B.id,jn(B)])))},[ve]),i.useEffect(()=>{const B=Hx(o);J&&ue.length===0&&B.length>0&&Se(B)},[J,o,ue.length]),i.useEffect(()=>{const B=new Set(((ve==null?void 0:ve.nodes)||[]).map(z=>z.id));A&&!B.has(A)&&_(null)},[ve,A]);const X=i.useCallback(async()=>{if(n){h(!0);try{const B=await e(n,"list_meshes");B!=null&&B.success?(c(B.meshes||[]),S(null)):S((B==null?void 0:B.error)||"Failed to load meshes")}catch(B){S((B==null?void 0:B.message)||"Failed to load meshes")}finally{h(!1)}}},[n,e]),xe=i.useCallback(async B=>{if(!n||!B){k([]);return}try{const z=await e(n,"get_mesh_queue",{meshId:B});z!=null&&z.success?k(Array.isArray(z.queue)?z.queue:[]):k([])}catch{k([])}},[n,e]);i.useEffect(()=>{X()},[X]),i.useEffect(()=>{xe(d)},[xe,d]);async function fe(){if(!(!n||!d))try{W(!0),$(null);const B=await e(n,"mesh_status",{meshId:d});if((B==null?void 0:B.success)===!1){w(null),M(null),$((B==null?void 0:B.error)||"mesh_status failed");return}const z=Lu(B);if(z){const de=ju(z);w(de),M(z)}else w(null),M(null),$("mesh_status returned an unexpected payload.")}catch(B){w(null),M(null),$((B==null?void 0:B.message)||"Failed to load mesh graph")}finally{W(!1)}}i.useEffect(()=>{d&&(w(null),M(null),$(null),fe())},[d]);async function we(){var B;if(!(!n||!F.trim()))try{const z=await e(n,"create_mesh",{name:F.trim(),repoIdentity:E.trim()||void 0});z!=null&&z.success?(y(!1),P(""),G(""),await X(),m(((B=z.mesh)==null?void 0:B.id)||null)):S((z==null?void 0:z.error)||"Create failed")}catch(z){S((z==null?void 0:z.message)||"Create failed")}}async function be(B){if(!(!n||!confirm("Delete this mesh?")))try{await e(n,"delete_mesh",{meshId:B}),m(null),await X()}catch(z){S((z==null?void 0:z.message)||"Delete failed")}}async function Ce(){if(!(!n||!d||!he.trim()))try{const B=await e(n,"add_mesh_node",{meshId:d,workspace:he.trim(),providerPriority:ho(ue,o)});B!=null&&B.success?(ye(!1),ne(""),Se([]),await X(),await xe(d)):S((B==null?void 0:B.error)||"Add node failed")}catch(B){S((B==null?void 0:B.message)||"Add node failed")}}async function ee(B){var re;if(!n||!d)return;const z=Ja(ve),de=((re=mn.find(R=>R.value===z.sessionCleanupOnNodeRemove))==null?void 0:re.label)||"Preserve history and runtimes";if(confirm(`Remove this node?
97
97
 
98
- Node removal cleanup policy: ${de}`))try{await e(n,"remove_mesh_node",{meshId:d,nodeId:B}),A===B&&_(null),await X(),await xe(d)}catch(R){S((R==null?void 0:R.message)||"Remove node failed")}}async function me(B){if(!n||!d)return;const z={...Ja(ve),...B};try{p(!0),S(null);const de=await e(n,"update_mesh",{meshId:d,policy:z});if((de==null?void 0:de.success)===!1){S(de.error||"Policy update failed");return}await X()}catch(de){S((de==null?void 0:de.message)||"Policy update failed")}finally{p(!1)}}async function ie(B){if(!n||!d)return;const z=ho(f[B.id]||jn(B),o),de={...B.policy||{}};delete de.provider_priority,z.length?de.providerPriority=z:delete de.providerPriority;try{v(B.id),S(null);const re=await e(n,"update_mesh_node",{meshId:d,nodeId:B.id,policy:de});if((re==null?void 0:re.success)===!1){S(re.error||"Node policy update failed");return}await X()}catch(re){S((re==null?void 0:re.message)||"Node policy update failed")}finally{v(null)}}if(!n)return s.jsx(kr,{icon:s.jsx(as,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})});if(!ve)return s.jsxs(kr,{icon:s.jsx(as,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>y(!0),children:"+ Create Mesh"}),children:[x&&s.jsx(Os,{variant:"error",className:"mb-4",children:x}),C&&s.jsx(St,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Lt,{label:"Name",children:s.jsx(ga,{value:F,onChange:B=>P(B.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(Lt,{label:"Repo Identity (optional)",children:s.jsx(ga,{value:E,onChange:B=>G(B.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:we,disabled:!F.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(!1),children:"Cancel"})]})]})}),u?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):l.length===0?s.jsx(Dn,{icon:s.jsx(as,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:l.map(B=>s.jsxs("button",{className:"text-left w-full p-4 rounded-xl border border-border-subtle bg-bg-panel hover:border-accent-primary/40 transition-colors",onClick:()=>m(B.id),children:[s.jsx("div",{className:"font-semibold text-sm",children:B.name}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:B.repoIdentity||"No repo identity"}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[B.nodes.length," node(s)"]})]},B.id))})]});const pe=Ja(ve);return s.jsxs(kr,{icon:s.jsx(as,{}),title:ve.name,subtitle:ve.repoIdentity||"Repo Mesh",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(null),children:"← Back"}),s.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>be(ve.id),children:"Delete"})]}),children:[x&&s.jsx(Os,{variant:"error",className:"mb-4",children:x}),s.jsxs(St,{title:"Policy",description:"Coordinator safety defaults and node-removal session cleanup behavior for this local mesh.",children:[s.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[s.jsx(Lt,{label:"Checkpoint before task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:pe.requirePreTaskCheckpoint?"yes":"no",onChange:B=>me({requirePreTaskCheckpoint:B.target.value==="yes"}),disabled:b,children:[s.jsx("option",{value:"no",children:"No"}),s.jsx("option",{value:"yes",children:"Yes"})]})}),s.jsx(Lt,{label:"Checkpoint after task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:pe.requirePostTaskCheckpoint?"yes":"no",onChange:B=>me({requirePostTaskCheckpoint:B.target.value==="yes"}),disabled:b,children:[s.jsx("option",{value:"yes",children:"Yes"}),s.jsx("option",{value:"no",children:"No"})]})}),s.jsx(Lt,{label:"Push approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:pe.requireApprovalForPush?"required":"not_required",onChange:B=>me({requireApprovalForPush:B.target.value==="required"}),disabled:b,children:[s.jsx("option",{value:"required",children:"Require approval before push"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(Lt,{label:"Destructive git approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:pe.requireApprovalForDestructiveGit?"required":"not_required",onChange:B=>me({requireApprovalForDestructiveGit:B.target.value==="required"}),disabled:b,children:[s.jsx("option",{value:"required",children:"Require approval"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(Lt,{label:"Dirty workspace behavior",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:pe.dirtyWorkspaceBehavior||"warn",onChange:B=>me({dirtyWorkspaceBehavior:B.target.value}),disabled:b,children:[s.jsx("option",{value:"warn",children:"Warn and continue"}),s.jsx("option",{value:"block",children:"Block task"}),s.jsx("option",{value:"checkpoint_then_continue",children:"Checkpoint then continue"})]})}),s.jsx(Lt,{label:"Max parallel tasks",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:String(pe.maxParallelTasks??2),onChange:B=>me({maxParallelTasks:Number(B.target.value)}),disabled:b,children:[1,2,3,4,5,6,7,8].map(B=>s.jsx("option",{value:B,children:B},B))})})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(Lt,{label:"Node removal session cleanup",hint:"Separate transcript cleanup from runtime/process cleanup. Preserve is safest when completed work may need review.",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:pe.sessionCleanupOnNodeRemove||"preserve",onChange:B=>me({sessionCleanupOnNodeRemove:B.target.value}),disabled:b,children:mn.map(B=>s.jsx("option",{value:B.value,children:B.label},B.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((le=mn.find(B=>B.value===pe.sessionCleanupOnNodeRemove))==null?void 0:le.description)||mn[0].description})]}),b&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),s.jsxs(St,{title:"Visualization",description:"Live mesh topology: branches, worktrees, sessions, and orphan detection.",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500"}),"healthy"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-amber-500"}),"dirty"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-red-500"}),"error"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-gray-500"}),"offline"]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:fe,disabled:j,children:j?"Loading...":"Refresh Graph"})]}),H&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:H}),!N||!D?s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:j?"Loading graph...":"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon."}):s.jsx(_u,{graph:N,status:D,emptyMessage:"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon.",daemonId:n,sendDaemonCommand:e})]}),s.jsxs(St,{title:"Nodes",description:"Workspaces participating in this mesh.",children:[s.jsx("div",{className:"flex justify-end mb-3",children:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>ye(!0),children:"+ Add Node"})}),J&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:"Add Node"}),s.jsx("button",{onClick:()=>ye(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(wt,{size:16})})]}),s.jsx(Lt,{label:"Workspace Path",children:s.jsx(ga,{value:he,onChange:B=>ne(B.target.value),placeholder:"/Users/dev/projects/myapp",autoFocus:!0})}),s.jsx(Lt,{label:"Provider Priority",hint:"Order used when launching without an explicit provider. Empty means fail closed unless a provider is selected explicitly.",children:s.jsx(al,{value:ue,availableProviders:o,onChange:Se})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:Ce,disabled:!he.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>ye(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),ve.nodes.length===0?s.jsx(Dn,{icon:s.jsx(Ns,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:ve.nodes.map(B=>{const z=jn(B),de=Sw(B),re=Nw(B,I),R=Iw(B,r),q=A===B.id;return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary cursor-pointer transition-colors ${q?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`,role:"button",tabIndex:0,onClick:()=>_(q?null:B.id),onKeyDown:ce=>{(ce.key==="Enter"||ce.key===" ")&&(ce.preventDefault(),_(q?null:B.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"text-sm font-medium",children:B.workspace.split("/").pop()}),re.length>0&&s.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-orange-500/15 text-orange-300 border border-orange-500/25",children:[re.length," active task",re.length===1?"":"s"]})]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:B.workspace}),s.jsx("div",{className:"mt-3 max-w-2xl",onClick:ce=>ce.stopPropagation(),children:s.jsxs(Lt,{label:"Provider priority",hint:"Used when launches omit an explicit provider. Empty keeps fail-closed behavior until a provider is selected manually.",children:[s.jsx(al,{value:f[B.id]??z,availableProviders:o,onChange:ce=>T(Ne=>({...Ne,[B.id]:ce})),disabled:g===B.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:ce=>{ce.stopPropagation(),ie(B)},disabled:g===B.id,children:g===B.id?"Saving...":"Save policy"})}),s.jsxs("div",{className:"mt-2 text-[12px]",children:[s.jsx("span",{className:"text-text-muted",children:"Effective provider priority: "}),s.jsx("span",{className:de.configured?"text-text-primary font-mono":"text-amber-400",children:de.label}),de.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",de.launchBlockedMessage,")"]})]})]})})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:ce=>{ce.stopPropagation(),ee(B.id)},children:s.jsx(wt,{size:14})})]}),q&&s.jsxs("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Node ID:"})," ",s.jsx("span",{className:"font-mono",children:B.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:de.configured?"text-green-400":"text-amber-400",children:de.configured?"yes":"provider priority not configured"})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Repo root:"})," ",s.jsx("span",{className:"font-mono",children:B.repoRoot||B.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",R.length]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Branch / git:"})," not loaded in standalone list view"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Health:"})," ",re.length>0||R.length>0?"active":"idle/unknown"]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),re.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:re.map(ce=>s.jsx("li",{className:"font-mono",children:Cw(ce)},ce.id))})]}),R.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active sessions"}),s.jsx("ul",{className:"m-0 pl-4",children:R.map(ce=>s.jsxs("li",{className:"font-mono",children:[ce.provider," / ",ce.status," / ",ce.id]},ce.id))})]})]})]},B.id)})})]}),s.jsx(Tw,{meshId:ve.id,availableCliAgents:a})]})}function fi(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Aw(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=fi();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Ut(e,t){return await fetch(Aw(e),{credentials:"same-origin",...t})}function $u(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class _w{constructor(){Ze(this,"adapters",new Map);Ze(this,"states",new Map);Ze(this,"runtimeListeners",new Map);Ze(this,"screenshotCallbacks",new Map);Ze(this,"statusCallbacks",new Set)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r)}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}sendData(t,r){return!1}sendPtyInput(t,r,n){return!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,o,l){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:o,rows:l})}emitSessionOutput(t,r,n){!t||typeof r!="string"||!r||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(t,r){const n=this.runtimeListeners.get(t)||new Set;return n.add(r),this.runtimeListeners.set(t,n),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,r,n){if(!r)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`,window.location.origin);typeof(n==null?void 0:n.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(n.sinceSeq));const o=await Ut(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const l=await o.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof l.seq=="number"?l.seq:0,text:typeof l.text=="string"?l.text:"",truncated:!!l.truncated,cols:typeof l.cols=="number"?l.cols:void 0,rows:typeof l.rows=="number"?l.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Yt=new _w;function Lw(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=fi();return r?`${t}?token=${encodeURIComponent(r)}`:t}const pn=Lw(),ac=3e3,Rw=3e4;let Ot=null,Pw=0;const Wn=new Map;let ms=null,Ir=null;function oc(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function fr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function Dw(e){return e==="connected"?"connected":e}async function kn(e,t,r){const n=yd(e,r||{}),a=Ot;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++Pw}_${Date.now()}`;return new Promise((l,c)=>{const d=setTimeout(()=>{Wn.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);Wn.set(o,{resolve:m=>{clearTimeout(d),l(m)},reject:m=>{clearTimeout(d),c(m)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function No(e,t){const r=Ot;if(!r||r.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(t)),!0}catch{return!1}}function Ew(e,t,r){const n=Ot;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=yd(e,{sessionId:t,targetSessionId:t,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}class $w{constructor(t){Ze(this,"daemonId");Ze(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Ot==null?void 0:Ot.readyState)===WebSocket.OPEN}get connectionState(){return(Ot==null?void 0:Ot.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return kn(this.daemonId,t,r)}async sendInput(t,r){return kn(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,ms&&(clearInterval(ms),ms=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await kn(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(o=>o.blob());Yt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ms=setInterval(r,2e3)}stopScreenshots(t){ms&&(clearInterval(ms),ms=null)}}let Pt=null;function Bw(e){return(!Pt||Pt.daemonId!==e)&&(Pt=new $w(e)),Pt}function Ow({children:e}){const t=i.useRef(Mr()),r=Mr();t.current=r;const{setUserName:n}=cs(),a=i.useRef(n);a.current=n;const o=i.useRef(null),l=i.useRef(null),[,c]=i.useState("disconnected"),d=i.useCallback((p,g)=>{c(p),Ir==null||Ir(p,g)},[]),m=i.useRef(null),u=i.useRef(),h=i.useRef(ac),x=i.useRef(!0),S=i.useRef(!1),b=i.useRef("initial_connect");return i.useEffect(()=>{x.current=!0,S.current=!1;function p(){var f,T;if(!x.current||((f=m.current)==null?void 0:f.readyState)===WebSocket.OPEN||((T=m.current)==null?void 0:T.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${pn}...`),fr("connect_attempt",{url:pn,reason:b.current,delayMs:h.current});let v;try{v=new WebSocket(pn)}catch(I){console.error("[Standalone WS] Failed to create WebSocket:",I),g();return}m.current=v,v.onopen=()=>{if(!x.current){v.close();return}d("connected"),h.current=ac,fr("open",{url:pn,reason:b.current}),Qt.resubscribeAll({sendData:No}),console.log("[Standalone WS] Connected")},Ot=v,v.onmessage=I=>{var k,A;try{const _=JSON.parse(I.data);if((_.type==="command_result"||_.type==="error")&&_.requestId){const N=Wn.get(_.requestId);N&&(Wn.delete(_.requestId),_.type==="error"?N.reject(new Error(((k=_.data)==null?void 0:k.message)||"Command failed")):N.resolve(_.data));return}if(_.type==="session_output"){const N=_.sessionId||_.cliId||_.cliType;N&&Yt.emitSessionOutput(N,typeof _.data=="string"?_.data:"",typeof _.seq=="number"?_.seq:void 0);return}if(_.type==="runtime_snapshot"){Yt.emitRuntimeSnapshot(_.sessionId,typeof _.text=="string"?_.text:"",typeof _.seq=="number"?_.seq:0,!!_.truncated,typeof _.cols=="number"?_.cols:void 0,typeof _.rows=="number"?_.rows:void 0);return}if(_.type==="topic_update"){const N=_.update;N&&Qt.publish(N);return}if(_.type==="status"||_.type==="initial_state"){const N=_.data;if(!N)return;const{injectEntries:w,markLoaded:D,getIdes:M}=t.current,j=N.instanceId||"standalone",W=M().find(C=>C.id===j),H=Bw(j);Yt.register(j,H),Yt.setState(j,"connected"),d("connected",j),Yt.emitStatus(j,N);const $=Rn(N,{daemonId:j,existingDaemon:W,existingEntries:M()});oc("ws_status",{type:_.type,daemonId:j,sessions:(N.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(N.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),oc("entries",{daemonId:j,entries:$.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),$.length>0&&w($,{authoritativeDaemonIds:[j]}),D(),l.current!==j&&((A=o.current)==null||A.call(o),l.current=j,o.current=Qt.subscribe({sendData:No},j,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${j}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const y=t.current.getIdes(),F=y.find(E=>E.id===j),P=Rn(C.status,{daemonId:j,existingDaemon:F,existingEntries:y,timestamp:C.timestamp});P.length>0&&t.current.injectEntries(P,{authoritativeDaemonIds:[j]}),C.userName&&a.current&&a.current(C.userName)}))}}catch(_){console.error("[Standalone WS] Parse error:",_)}},v.onclose=I=>{x.current&&(Pt==null||Pt.stopScreenshots(),Pt&&Yt.setState(Pt.daemonId,"disconnected"),d("disconnected"),m.current=null,b.current=`close:${I.code}${I.wasClean?":clean":":unclean"}`,fr("close",{code:I.code,reason:I.reason||"",wasClean:I.wasClean}),g())},v.onerror=I=>{S.current||!x.current||(b.current="error",fr("error",{message:I instanceof Event?"event":String(I),readyState:v.readyState}),console.warn("[Standalone WS] Error, will reconnect:",I))}}function g(){if(!x.current)return;clearTimeout(u.current);const v=h.current;console.log(`[Standalone WS] Reconnecting in ${v}ms...`),fr("schedule_reconnect",{reason:b.current,delayMs:v}),u.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,Rw),p()},v)}return p(),()=>{var v;x.current=!1,S.current=!0,(v=o.current)==null||v.call(o),o.current=null,l.current=null,clearTimeout(u.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,Ot=null),Pt&&(Pt.stopScreenshots(),Yt.unregister(Pt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function Fw({children:e}){const[t,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(Ir=(l,c)=>{r(l),c&&a(c)},()=>{Ir=null}),[]);const o=i.useMemo(()=>{const l=t==="connected",c=Dw(t),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:t,isConnected:l,connectionStates:d}},[t,n]);return s.jsx(Fm,{connectionOverrides:o,children:s.jsx(Ow,{children:e})})}const Bu="adhdev_standalone_font_preferences",Ss={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},ra=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],Lr=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],Ww=new Set(ra.map(e=>e.id)),Kw=new Set(Lr.map(e=>e.id));function Vt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Sn("chat",t.chat),code:Sn("code",t.code),terminal:Sn("terminal",t.terminal)}}function Sn(e,t){const r=Ss[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",o=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?Ww:Kw).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Nn(e,t){var a;const r=Sn(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?ra:Lr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function Hw(e){const t=Vt(e),r=Nn("chat",t.chat),n=Nn("code",t.code),a=Nn("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function fs(e,t=document.documentElement){const r=Vt(e),n=Hw(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function Co(e){const t=Vt(e);try{localStorage.setItem(Bu,JSON.stringify(t))}catch{}return t}function Uw(){try{const e=localStorage.getItem(Bu);if(e)return Vt(JSON.parse(e))}catch{}return Ss}function zw(){return fs(Uw())}function xr(e,t){var n;const r=e==="chat"?ra:Lr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const Vw=[{id:"dashboard",path:"/dashboard",icon:s.jsx(xc,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(is,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(zs,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(Kn,{}),label:"Settings"}];function Gw({children:e}){const t=As(),r=To(),n=i.useMemo(()=>Vw.map(o=>({...o,active:r.pathname.startsWith(o.path),onSelect:()=>t(o.path)})),[r.pathname,t]),a=i.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Docs"}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(gc,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(yc,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(eb,{brand:({collapsed:o})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!o&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:o})=>o?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.81"]}),footerActions:({collapsed:o,toggleCollapsed:l})=>s.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":"mt-1"}`,onClick:l,title:o?"Expand sidebar":"Collapse sidebar",children:[s.jsx("span",{className:"nav-icon text-base",children:o?"›":"‹"}),!o&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const qw=[{icon:s.jsx(is,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(es,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(vc,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(_t,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(zs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(gc,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Yw=[{icon:s.jsx(rp,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(xc,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Hn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Xm,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(bc,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Qm,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Xw=[{feature:"Agent chat relay",selfhost:!0,cloud:!0},{feature:"Live IDE screenshots",selfhost:!0,cloud:!0},{feature:"Remote IDE control",selfhost:!0,cloud:!0},{feature:"Multi-IDE monitoring",selfhost:!0,cloud:!0},{feature:"Extension and CLI agents",selfhost:!0,cloud:!0},{feature:"Access from any network",selfhost:!1,cloud:!0},{feature:"WebRTC P2P streaming",selfhost:!1,cloud:!0},{feature:"Mobile push notifications",selfhost:!1,cloud:!0},{feature:"REST API and webhooks",selfhost:!1,cloud:!0},{feature:"Team collaboration",selfhost:!1,cloud:!0},{feature:"Multi-machine burrows",selfhost:!1,cloud:!0},{feature:"SSO, RBAC, audit logs",selfhost:!1,cloud:!0}];function Jw(){return s.jsxs(kr,{icon:s.jsx(yc,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.9.81"]}),children:[s.jsx(St,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),s.jsx(St,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:qw.map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(St,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:vd.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:jd.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:wd.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(St,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Yw.map(e=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(St,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),s.jsx("tbody",{children:Xw.map((e,t)=>s.jsxs("tr",{className:t%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),s.jsx(Dn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:"Cloud is optional, not required",description:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(pp,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Qa(e,t,r){return{...e,[t]:r}}function Za({surface:e,title:t,description:r,value:n,options:a,onChange:o}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:l=>{const c=l.target.value;o(c==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:c})},children:a.map(l=>s.jsx("option",{value:l.id,children:l.label},l.id))}),n.preset==="custom"&&s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:l=>o({preset:"custom",customFamily:l.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:Nn(e,n)})]})]})]})}function Qw({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:l,onResetToSaved:c,onResetToDefaults:d}){const m=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&s.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&s.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Za,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:ra,onChange:u=>o(Qa(e,"chat",u))}),s.jsx(Za,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Lr,onChange:u=>o(Qa(e,"code",u))}),s.jsx(Za,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Lr,onChange:u=>o(Qa(e,"terminal",u))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",xr("chat",e.chat.preset)," · Code: ",xr("code",e.code.preset)," · Terminal: ",xr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",xr("chat",Ss.chat.preset)," / ",xr("code",Ss.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:l,disabled:r||!m,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),s.jsx("button",{type:"button",onClick:c,disabled:r||!m,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),s.jsx("button",{type:"button",onClick:d,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function Zw(){const{ides:e}=cs(),t=e.find(X=>X.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=jt(),{userName:a}=cs(),[o,l]=i.useState(a||""),[c,d]=i.useState(null),[m,u]=i.useState(null),[h,x]=i.useState(Ss),[S,b]=i.useState(!1),[p,g]=i.useState(""),[v,f]=i.useState(""),[T,I]=i.useState("127.0.0.1"),[k,A]=i.useState(""),[_,N]=i.useState(""),[w,D]=i.useState(""),[M,j]=i.useState(""),[W,H]=i.useState(""),[$,C]=i.useState(!1),y=async()=>{const xe=await(await Ut("/auth/session")).json();d(xe)},F=async()=>{const xe=await(await Ut("/api/v1/standalone/preferences")).json();u(xe),I(xe.standaloneBindHost);const fe=Vt(xe.standaloneFontPreferences);x(fe),fs(fe),Co(fe)};i.useEffect(()=>{a!==void 0&&l(a)},[a]),i.useEffect(()=>{Promise.all([y(),F()]).catch(X=>{j(X instanceof Error?X.message:String(X))})},[]),i.useEffect(()=>{fs(h)},[h]);const P=X=>{const xe=X.target.value.trim();t!=null&&t.id&&xe!==a&&n(t.id,"set_user_name",{userName:xe}).catch(console.error)},[E,G]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),J=X=>{G(X);try{localStorage.setItem("adhdev_sound",X?"1":"0")}catch{}},ye=async()=>{g(""),f(""),b(!0);try{const X=Vt(h),xe=await Ut("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:X})}),fe=await xe.json();if(!xe.ok)throw new Error((fe==null?void 0:fe.error)||"Failed to save standalone font preferences");const we=Vt(fe.standaloneFontPreferences);u(fe),x(we),fs(we),Co(we),f("Standalone chat fonts saved for this self-hosted dashboard.")}catch(X){g(X instanceof Error?X.message:String(X))}finally{b(!1)}},he=()=>{const X=Vt(m==null?void 0:m.standaloneFontPreferences);g(""),f(""),x(X),fs(X)},ne=()=>{g(""),f(""),x(Ss),fs(Ss)},ue=async()=>{j(""),H(""),C(!0);try{const X=await Ut("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:T})}),xe=await X.json();if(!X.ok)throw new Error((xe==null?void 0:xe.error)||"Failed to save standalone network preference");u(xe),I(xe.standaloneBindHost),H(xe.standaloneBindHost==="0.0.0.0"?"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.":"Default standalone network mode set to localhost only. Restart standalone to apply it.")}catch(X){j(X instanceof Error?X.message:String(X))}finally{C(!1)}},Se=async()=>{if(j(""),H(""),_.trim().length<4){j("Password must be at least 4 characters.");return}if(_!==w){j("New password and confirmation do not match.");return}C(!0);try{const X=await Ut("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,newPassword:_})}),xe=await X.json();if(!X.ok)throw new Error((xe==null?void 0:xe.error)||"Failed to save password");d(xe),await F(),A(""),N(""),D(""),H(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),$u()}catch(X){j(X instanceof Error?X.message:String(X))}finally{C(!1)}},ve=async()=>{j(""),H(""),C(!0);try{const X=await Ut("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,clear:!0})}),xe=await X.json();if(!X.ok)throw new Error((xe==null?void 0:xe.error)||"Failed to clear password");d(xe),await F(),A(""),N(""),D(""),H("Standalone password disabled.")}catch(X){j(X instanceof Error?X.message:String(X))}finally{C(!1)}};return s.jsxs(kr,{icon:s.jsx(Kn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Os,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(c==null?void 0:c.publicHostWarning)&&s.jsx(Os,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),s.jsx(St,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:"Version"}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.81"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:c!=null&&c.hasPasswordAuth?"Password enabled":c!=null&&c.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(St,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:T==="127.0.0.1",onChange:()=>I("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:T==="0.0.0.0",onChange:()=>I("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:()=>{ue()},disabled:$,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:$?"Saving…":"Save default network mode"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(m==null?void 0:m.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(St,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:c!=null&&c.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),M&&s.jsx(Os,{variant:"error",children:M}),W&&s.jsx(Os,{variant:"success",children:W}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:c!=null&&c.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:k,onChange:X=>A(X.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:c!=null&&c.hasPasswordAuth?"New password":"New standalone password",value:_,onChange:X=>N(X.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:w,onChange:X=>D(X.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{Se()},disabled:$,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:$?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ve()},disabled:$,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),s.jsx(St,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(X=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${X.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:X.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:X.type})]},X.type))})}),s.jsx(St,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(cb,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(St,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(pb,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI."}),s.jsx(wb,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),s.jsx(Qw,{value:h,savedValue:Vt(m==null?void 0:m.standaloneFontPreferences),saving:S,error:p,notice:v,onChange:x,onSave:()=>{ye()},onResetToSaved:he,onResetToDefaults:ne})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),s.jsx(Sb,{})]})]})}),s.jsx(St,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(ob,{}),s.jsx(hs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(mp,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:J})]})}),s.jsx(St,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(Ym,{size:16,className:"text-text-secondary"})," Display Name"]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:o,onChange:X=>l(X.target.value),onBlur:P,onKeyDown:X=>{X.key==="Enter"&&X.currentTarget.blur()}})]})})})]})}Qx();yb();zw();const ej=hc({baseUrl:"",getToken:fi});function tj({children:e}){const[t,r]=i.useState(null),[n,a]=i.useState(!0),[o,l]=i.useState(""),[c,d]=i.useState(""),[m,u]=i.useState(!1),h=async()=>{a(!0),d("");try{const b=await(await Ut("/auth/session")).json();r(b)}catch(S){d(S instanceof Error?S.message:String(S))}finally{a(!1)}};i.useEffect(()=>{h()},[]),i.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let S=!1;return(async()=>{try{const b=await Ut("/api/v1/standalone/preferences");if(!b.ok)return;const p=await b.json();if(S)return;const g=Vt(p.standaloneFontPreferences);fs(g),Co(g)}catch{}})(),()=>{S=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const x=async S=>{S.preventDefault(),u(!0),d("");try{const b=await Ut("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),p=await b.json();if(!b.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),l(""),$u()}catch(b){d(b instanceof Error?b.message:String(b))}finally{u(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:x,children:[s.jsx("input",{type:"password",value:o,onChange:S=>l(S.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled:m||!o,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:m?"Signing in…":"Unlock dashboard"})]}):s.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),c&&s.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:c})]})}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",c||"unknown error"]})}function ic(){const{ides:e,initialLoaded:t}=cs();if(!t)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?s.jsx(so,{to:`/machines/${r.id}`,replace:!0}):s.jsx(so,{to:"/dashboard",replace:!0})}function sj(){const e=i.useMemo(()=>({sendCommand:kn,sendData:No,sendPtyInput:Ew}),[]);return s.jsx(Sm,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Hm,{client:ej,children:s.jsx(tj,{children:s.jsx(Fw,{children:s.jsx(zm,{value:e,children:s.jsx(Gw,{children:s.jsxs(Nm,{children:[s.jsx(rs,{path:"/dashboard",element:s.jsx(xv,{})}),s.jsx(rs,{path:"/machine",element:s.jsx(ic,{})}),s.jsx(rs,{path:"/machines/:id",element:s.jsx(jw,{})}),s.jsx(rs,{path:"/machines",element:s.jsx(ic,{})}),s.jsx(rs,{path:"/about",element:s.jsx(Jw,{})}),s.jsx(rs,{path:"/settings",element:s.jsx(Zw,{})}),s.jsx(rs,{path:"/mesh",element:s.jsx(Mw,{})}),s.jsx(rs,{path:"*",element:s.jsx(so,{to:"/dashboard",replace:!0})})]})})})})})})})}lx({connectionManager:Yt});Cm(document.getElementById("root")).render(s.jsx(sj,{}));
98
+ Node removal cleanup policy: ${de}`))try{await e(n,"remove_mesh_node",{meshId:d,nodeId:B}),A===B&&_(null),await X(),await xe(d)}catch(R){S((R==null?void 0:R.message)||"Remove node failed")}}async function me(B){if(!n||!d)return;const z={...Ja(ve),...B};try{p(!0),S(null);const de=await e(n,"update_mesh",{meshId:d,policy:z});if((de==null?void 0:de.success)===!1){S(de.error||"Policy update failed");return}await X()}catch(de){S((de==null?void 0:de.message)||"Policy update failed")}finally{p(!1)}}async function ie(B){if(!n||!d)return;const z=ho(f[B.id]||jn(B),o),de={...B.policy||{}};delete de.provider_priority,z.length?de.providerPriority=z:delete de.providerPriority;try{v(B.id),S(null);const re=await e(n,"update_mesh_node",{meshId:d,nodeId:B.id,policy:de});if((re==null?void 0:re.success)===!1){S(re.error||"Node policy update failed");return}await X()}catch(re){S((re==null?void 0:re.message)||"Node policy update failed")}finally{v(null)}}if(!n)return s.jsx(kr,{icon:s.jsx(as,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})});if(!ve)return s.jsxs(kr,{icon:s.jsx(as,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>y(!0),children:"+ Create Mesh"}),children:[x&&s.jsx(Os,{variant:"error",className:"mb-4",children:x}),C&&s.jsx(St,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Lt,{label:"Name",children:s.jsx(ga,{value:F,onChange:B=>P(B.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(Lt,{label:"Repo Identity (optional)",children:s.jsx(ga,{value:E,onChange:B=>G(B.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:we,disabled:!F.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(!1),children:"Cancel"})]})]})}),u?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):l.length===0?s.jsx(Dn,{icon:s.jsx(as,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:l.map(B=>s.jsxs("button",{className:"text-left w-full p-4 rounded-xl border border-border-subtle bg-bg-panel hover:border-accent-primary/40 transition-colors",onClick:()=>m(B.id),children:[s.jsx("div",{className:"font-semibold text-sm",children:B.name}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:B.repoIdentity||"No repo identity"}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[B.nodes.length," node(s)"]})]},B.id))})]});const pe=Ja(ve);return s.jsxs(kr,{icon:s.jsx(as,{}),title:ve.name,subtitle:ve.repoIdentity||"Repo Mesh",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(null),children:"← Back"}),s.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>be(ve.id),children:"Delete"})]}),children:[x&&s.jsx(Os,{variant:"error",className:"mb-4",children:x}),s.jsxs(St,{title:"Policy",description:"Coordinator safety defaults and node-removal session cleanup behavior for this local mesh.",children:[s.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[s.jsx(Lt,{label:"Checkpoint before task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:pe.requirePreTaskCheckpoint?"yes":"no",onChange:B=>me({requirePreTaskCheckpoint:B.target.value==="yes"}),disabled:b,children:[s.jsx("option",{value:"no",children:"No"}),s.jsx("option",{value:"yes",children:"Yes"})]})}),s.jsx(Lt,{label:"Checkpoint after task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:pe.requirePostTaskCheckpoint?"yes":"no",onChange:B=>me({requirePostTaskCheckpoint:B.target.value==="yes"}),disabled:b,children:[s.jsx("option",{value:"yes",children:"Yes"}),s.jsx("option",{value:"no",children:"No"})]})}),s.jsx(Lt,{label:"Push approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:pe.requireApprovalForPush?"required":"not_required",onChange:B=>me({requireApprovalForPush:B.target.value==="required"}),disabled:b,children:[s.jsx("option",{value:"required",children:"Require approval before push"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(Lt,{label:"Destructive git approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:pe.requireApprovalForDestructiveGit?"required":"not_required",onChange:B=>me({requireApprovalForDestructiveGit:B.target.value==="required"}),disabled:b,children:[s.jsx("option",{value:"required",children:"Require approval"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(Lt,{label:"Dirty workspace behavior",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:pe.dirtyWorkspaceBehavior||"warn",onChange:B=>me({dirtyWorkspaceBehavior:B.target.value}),disabled:b,children:[s.jsx("option",{value:"warn",children:"Warn and continue"}),s.jsx("option",{value:"block",children:"Block task"}),s.jsx("option",{value:"checkpoint_then_continue",children:"Checkpoint then continue"})]})}),s.jsx(Lt,{label:"Max parallel tasks",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:String(pe.maxParallelTasks??2),onChange:B=>me({maxParallelTasks:Number(B.target.value)}),disabled:b,children:[1,2,3,4,5,6,7,8].map(B=>s.jsx("option",{value:B,children:B},B))})})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(Lt,{label:"Node removal session cleanup",hint:"Separate transcript cleanup from runtime/process cleanup. Preserve is safest when completed work may need review.",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:pe.sessionCleanupOnNodeRemove||"preserve",onChange:B=>me({sessionCleanupOnNodeRemove:B.target.value}),disabled:b,children:mn.map(B=>s.jsx("option",{value:B.value,children:B.label},B.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((le=mn.find(B=>B.value===pe.sessionCleanupOnNodeRemove))==null?void 0:le.description)||mn[0].description})]}),b&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),s.jsxs(St,{title:"Visualization",description:"Live mesh topology: branches, worktrees, sessions, and orphan detection.",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500"}),"healthy"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-amber-500"}),"dirty"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-red-500"}),"error"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-gray-500"}),"offline"]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:fe,disabled:j,children:j?"Loading...":"Refresh Graph"})]}),H&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:H}),!N||!D?s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:j?"Loading graph...":"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon."}):s.jsx(_u,{graph:N,status:D,emptyMessage:"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon.",daemonId:n,sendDaemonCommand:e})]}),s.jsxs(St,{title:"Nodes",description:"Workspaces participating in this mesh.",children:[s.jsx("div",{className:"flex justify-end mb-3",children:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>ye(!0),children:"+ Add Node"})}),J&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:"Add Node"}),s.jsx("button",{onClick:()=>ye(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(wt,{size:16})})]}),s.jsx(Lt,{label:"Workspace Path",children:s.jsx(ga,{value:he,onChange:B=>ne(B.target.value),placeholder:"/Users/dev/projects/myapp",autoFocus:!0})}),s.jsx(Lt,{label:"Provider Priority",hint:"Order used when launching without an explicit provider. Empty means fail closed unless a provider is selected explicitly.",children:s.jsx(al,{value:ue,availableProviders:o,onChange:Se})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:Ce,disabled:!he.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>ye(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),ve.nodes.length===0?s.jsx(Dn,{icon:s.jsx(Ns,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:ve.nodes.map(B=>{const z=jn(B),de=Nw(B),re=Cw(B,I),R=Tw(B,r),q=A===B.id;return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary cursor-pointer transition-colors ${q?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`,role:"button",tabIndex:0,onClick:()=>_(q?null:B.id),onKeyDown:ce=>{(ce.key==="Enter"||ce.key===" ")&&(ce.preventDefault(),_(q?null:B.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"text-sm font-medium",children:B.workspace.split("/").pop()}),re.length>0&&s.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-orange-500/15 text-orange-300 border border-orange-500/25",children:[re.length," active task",re.length===1?"":"s"]})]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:B.workspace}),s.jsx("div",{className:"mt-3 max-w-2xl",onClick:ce=>ce.stopPropagation(),children:s.jsxs(Lt,{label:"Provider priority",hint:"Used when launches omit an explicit provider. Empty keeps fail-closed behavior until a provider is selected manually.",children:[s.jsx(al,{value:f[B.id]??z,availableProviders:o,onChange:ce=>T(Ne=>({...Ne,[B.id]:ce})),disabled:g===B.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:ce=>{ce.stopPropagation(),ie(B)},disabled:g===B.id,children:g===B.id?"Saving...":"Save policy"})}),s.jsxs("div",{className:"mt-2 text-[12px]",children:[s.jsx("span",{className:"text-text-muted",children:"Effective provider priority: "}),s.jsx("span",{className:de.configured?"text-text-primary font-mono":"text-amber-400",children:de.label}),de.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",de.launchBlockedMessage,")"]})]})]})})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:ce=>{ce.stopPropagation(),ee(B.id)},children:s.jsx(wt,{size:14})})]}),q&&s.jsxs("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Node ID:"})," ",s.jsx("span",{className:"font-mono",children:B.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:de.configured?"text-green-400":"text-amber-400",children:de.configured?"yes":"provider priority not configured"})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Repo root:"})," ",s.jsx("span",{className:"font-mono",children:B.repoRoot||B.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",R.length]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Branch / git:"})," not loaded in standalone list view"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Health:"})," ",re.length>0||R.length>0?"active":"idle/unknown"]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),re.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:re.map(ce=>s.jsx("li",{className:"font-mono",children:Iw(ce)},ce.id))})]}),R.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active sessions"}),s.jsx("ul",{className:"m-0 pl-4",children:R.map(ce=>s.jsxs("li",{className:"font-mono",children:[ce.provider," / ",ce.status," / ",ce.id]},ce.id))})]})]})]},B.id)})})]}),s.jsx(Mw,{meshId:ve.id,availableCliAgents:a})]})}function fi(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function _w(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=fi();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Ut(e,t){return await fetch(_w(e),{credentials:"same-origin",...t})}function $u(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class Lw{constructor(){Ze(this,"adapters",new Map);Ze(this,"states",new Map);Ze(this,"runtimeListeners",new Map);Ze(this,"screenshotCallbacks",new Map);Ze(this,"statusCallbacks",new Set)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r)}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}sendData(t,r){return!1}sendPtyInput(t,r,n){return!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,o,l){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:o,rows:l})}emitSessionOutput(t,r,n){!t||typeof r!="string"||!r||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(t,r){const n=this.runtimeListeners.get(t)||new Set;return n.add(r),this.runtimeListeners.set(t,n),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,r,n){if(!r)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`,window.location.origin);typeof(n==null?void 0:n.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(n.sinceSeq));const o=await Ut(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const l=await o.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof l.seq=="number"?l.seq:0,text:typeof l.text=="string"?l.text:"",truncated:!!l.truncated,cols:typeof l.cols=="number"?l.cols:void 0,rows:typeof l.rows=="number"?l.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Yt=new Lw;function Rw(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=fi();return r?`${t}?token=${encodeURIComponent(r)}`:t}const pn=Rw(),ac=3e3,Pw=3e4;let Ot=null,Dw=0;const Wn=new Map;let ms=null,Ir=null;function oc(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function fr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function Ew(e){return e==="connected"?"connected":e}async function kn(e,t,r){const n=yd(e,r||{}),a=Ot;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++Dw}_${Date.now()}`;return new Promise((l,c)=>{const d=setTimeout(()=>{Wn.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);Wn.set(o,{resolve:m=>{clearTimeout(d),l(m)},reject:m=>{clearTimeout(d),c(m)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function No(e,t){const r=Ot;if(!r||r.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(t)),!0}catch{return!1}}function $w(e,t,r){const n=Ot;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=yd(e,{sessionId:t,targetSessionId:t,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}class Bw{constructor(t){Ze(this,"daemonId");Ze(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Ot==null?void 0:Ot.readyState)===WebSocket.OPEN}get connectionState(){return(Ot==null?void 0:Ot.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return kn(this.daemonId,t,r)}async sendInput(t,r){return kn(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,ms&&(clearInterval(ms),ms=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await kn(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(o=>o.blob());Yt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ms=setInterval(r,2e3)}stopScreenshots(t){ms&&(clearInterval(ms),ms=null)}}let Pt=null;function Ow(e){return(!Pt||Pt.daemonId!==e)&&(Pt=new Bw(e)),Pt}function Fw({children:e}){const t=i.useRef(Mr()),r=Mr();t.current=r;const{setUserName:n}=cs(),a=i.useRef(n);a.current=n;const o=i.useRef(null),l=i.useRef(null),[,c]=i.useState("disconnected"),d=i.useCallback((p,g)=>{c(p),Ir==null||Ir(p,g)},[]),m=i.useRef(null),u=i.useRef(),h=i.useRef(ac),x=i.useRef(!0),S=i.useRef(!1),b=i.useRef("initial_connect");return i.useEffect(()=>{x.current=!0,S.current=!1;function p(){var f,T;if(!x.current||((f=m.current)==null?void 0:f.readyState)===WebSocket.OPEN||((T=m.current)==null?void 0:T.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${pn}...`),fr("connect_attempt",{url:pn,reason:b.current,delayMs:h.current});let v;try{v=new WebSocket(pn)}catch(I){console.error("[Standalone WS] Failed to create WebSocket:",I),g();return}m.current=v,v.onopen=()=>{if(!x.current){v.close();return}d("connected"),h.current=ac,fr("open",{url:pn,reason:b.current}),Qt.resubscribeAll({sendData:No}),console.log("[Standalone WS] Connected")},Ot=v,v.onmessage=I=>{var k,A;try{const _=JSON.parse(I.data);if((_.type==="command_result"||_.type==="error")&&_.requestId){const N=Wn.get(_.requestId);N&&(Wn.delete(_.requestId),_.type==="error"?N.reject(new Error(((k=_.data)==null?void 0:k.message)||"Command failed")):N.resolve(_.data));return}if(_.type==="session_output"){const N=_.sessionId||_.cliId||_.cliType;N&&Yt.emitSessionOutput(N,typeof _.data=="string"?_.data:"",typeof _.seq=="number"?_.seq:void 0);return}if(_.type==="runtime_snapshot"){Yt.emitRuntimeSnapshot(_.sessionId,typeof _.text=="string"?_.text:"",typeof _.seq=="number"?_.seq:0,!!_.truncated,typeof _.cols=="number"?_.cols:void 0,typeof _.rows=="number"?_.rows:void 0);return}if(_.type==="topic_update"){const N=_.update;N&&Qt.publish(N);return}if(_.type==="status"||_.type==="initial_state"){const N=_.data;if(!N)return;const{injectEntries:w,markLoaded:D,getIdes:M}=t.current,j=N.instanceId||"standalone",W=M().find(C=>C.id===j),H=Ow(j);Yt.register(j,H),Yt.setState(j,"connected"),d("connected",j),Yt.emitStatus(j,N);const $=Rn(N,{daemonId:j,existingDaemon:W,existingEntries:M()});oc("ws_status",{type:_.type,daemonId:j,sessions:(N.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(N.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),oc("entries",{daemonId:j,entries:$.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),$.length>0&&w($,{authoritativeDaemonIds:[j]}),D(),l.current!==j&&((A=o.current)==null||A.call(o),l.current=j,o.current=Qt.subscribe({sendData:No},j,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${j}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const y=t.current.getIdes(),F=y.find(E=>E.id===j),P=Rn(C.status,{daemonId:j,existingDaemon:F,existingEntries:y,timestamp:C.timestamp});P.length>0&&t.current.injectEntries(P,{authoritativeDaemonIds:[j]}),C.userName&&a.current&&a.current(C.userName)}))}}catch(_){console.error("[Standalone WS] Parse error:",_)}},v.onclose=I=>{x.current&&(Pt==null||Pt.stopScreenshots(),Pt&&Yt.setState(Pt.daemonId,"disconnected"),d("disconnected"),m.current=null,b.current=`close:${I.code}${I.wasClean?":clean":":unclean"}`,fr("close",{code:I.code,reason:I.reason||"",wasClean:I.wasClean}),g())},v.onerror=I=>{S.current||!x.current||(b.current="error",fr("error",{message:I instanceof Event?"event":String(I),readyState:v.readyState}),console.warn("[Standalone WS] Error, will reconnect:",I))}}function g(){if(!x.current)return;clearTimeout(u.current);const v=h.current;console.log(`[Standalone WS] Reconnecting in ${v}ms...`),fr("schedule_reconnect",{reason:b.current,delayMs:v}),u.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,Pw),p()},v)}return p(),()=>{var v;x.current=!1,S.current=!0,(v=o.current)==null||v.call(o),o.current=null,l.current=null,clearTimeout(u.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,Ot=null),Pt&&(Pt.stopScreenshots(),Yt.unregister(Pt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function Ww({children:e}){const[t,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(Ir=(l,c)=>{r(l),c&&a(c)},()=>{Ir=null}),[]);const o=i.useMemo(()=>{const l=t==="connected",c=Ew(t),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:t,isConnected:l,connectionStates:d}},[t,n]);return s.jsx(Fm,{connectionOverrides:o,children:s.jsx(Fw,{children:e})})}const Bu="adhdev_standalone_font_preferences",Ss={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},ra=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],Lr=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],Kw=new Set(ra.map(e=>e.id)),Hw=new Set(Lr.map(e=>e.id));function Vt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Sn("chat",t.chat),code:Sn("code",t.code),terminal:Sn("terminal",t.terminal)}}function Sn(e,t){const r=Ss[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",o=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?Kw:Hw).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Nn(e,t){var a;const r=Sn(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?ra:Lr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function Uw(e){const t=Vt(e),r=Nn("chat",t.chat),n=Nn("code",t.code),a=Nn("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function fs(e,t=document.documentElement){const r=Vt(e),n=Uw(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function Co(e){const t=Vt(e);try{localStorage.setItem(Bu,JSON.stringify(t))}catch{}return t}function zw(){try{const e=localStorage.getItem(Bu);if(e)return Vt(JSON.parse(e))}catch{}return Ss}function Vw(){return fs(zw())}function xr(e,t){var n;const r=e==="chat"?ra:Lr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const Gw=[{id:"dashboard",path:"/dashboard",icon:s.jsx(xc,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(is,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(zs,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(Kn,{}),label:"Settings"}];function qw({children:e}){const t=As(),r=To(),n=i.useMemo(()=>Gw.map(o=>({...o,active:r.pathname.startsWith(o.path),onSelect:()=>t(o.path)})),[r.pathname,t]),a=i.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Docs"}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(gc,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(yc,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(eb,{brand:({collapsed:o})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!o&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:o})=>o?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.81"]}),footerActions:({collapsed:o,toggleCollapsed:l})=>s.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":"mt-1"}`,onClick:l,title:o?"Expand sidebar":"Collapse sidebar",children:[s.jsx("span",{className:"nav-icon text-base",children:o?"›":"‹"}),!o&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const Yw=[{icon:s.jsx(is,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(es,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(vc,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(_t,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(zs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(gc,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Xw=[{icon:s.jsx(rp,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(xc,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Hn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Xm,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(bc,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Qm,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Jw=[{feature:"Agent chat relay",selfhost:!0,cloud:!0},{feature:"Live IDE screenshots",selfhost:!0,cloud:!0},{feature:"Remote IDE control",selfhost:!0,cloud:!0},{feature:"Multi-IDE monitoring",selfhost:!0,cloud:!0},{feature:"Extension and CLI agents",selfhost:!0,cloud:!0},{feature:"Access from any network",selfhost:!1,cloud:!0},{feature:"WebRTC P2P streaming",selfhost:!1,cloud:!0},{feature:"Mobile push notifications",selfhost:!1,cloud:!0},{feature:"REST API and webhooks",selfhost:!1,cloud:!0},{feature:"Team collaboration",selfhost:!1,cloud:!0},{feature:"Multi-machine burrows",selfhost:!1,cloud:!0},{feature:"SSO, RBAC, audit logs",selfhost:!1,cloud:!0}];function Qw(){return s.jsxs(kr,{icon:s.jsx(yc,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.9.81"]}),children:[s.jsx(St,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),s.jsx(St,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Yw.map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(St,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:vd.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:jd.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:wd.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(St,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Xw.map(e=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(St,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),s.jsx("tbody",{children:Jw.map((e,t)=>s.jsxs("tr",{className:t%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),s.jsx(Dn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:"Cloud is optional, not required",description:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(pp,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Qa(e,t,r){return{...e,[t]:r}}function Za({surface:e,title:t,description:r,value:n,options:a,onChange:o}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:l=>{const c=l.target.value;o(c==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:c})},children:a.map(l=>s.jsx("option",{value:l.id,children:l.label},l.id))}),n.preset==="custom"&&s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:l=>o({preset:"custom",customFamily:l.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:Nn(e,n)})]})]})]})}function Zw({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:l,onResetToSaved:c,onResetToDefaults:d}){const m=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&s.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&s.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Za,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:ra,onChange:u=>o(Qa(e,"chat",u))}),s.jsx(Za,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Lr,onChange:u=>o(Qa(e,"code",u))}),s.jsx(Za,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Lr,onChange:u=>o(Qa(e,"terminal",u))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",xr("chat",e.chat.preset)," · Code: ",xr("code",e.code.preset)," · Terminal: ",xr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",xr("chat",Ss.chat.preset)," / ",xr("code",Ss.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:l,disabled:r||!m,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),s.jsx("button",{type:"button",onClick:c,disabled:r||!m,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),s.jsx("button",{type:"button",onClick:d,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function ej(){const{ides:e}=cs(),t=e.find(X=>X.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=jt(),{userName:a}=cs(),[o,l]=i.useState(a||""),[c,d]=i.useState(null),[m,u]=i.useState(null),[h,x]=i.useState(Ss),[S,b]=i.useState(!1),[p,g]=i.useState(""),[v,f]=i.useState(""),[T,I]=i.useState("127.0.0.1"),[k,A]=i.useState(""),[_,N]=i.useState(""),[w,D]=i.useState(""),[M,j]=i.useState(""),[W,H]=i.useState(""),[$,C]=i.useState(!1),y=async()=>{const xe=await(await Ut("/auth/session")).json();d(xe)},F=async()=>{const xe=await(await Ut("/api/v1/standalone/preferences")).json();u(xe),I(xe.standaloneBindHost);const fe=Vt(xe.standaloneFontPreferences);x(fe),fs(fe),Co(fe)};i.useEffect(()=>{a!==void 0&&l(a)},[a]),i.useEffect(()=>{Promise.all([y(),F()]).catch(X=>{j(X instanceof Error?X.message:String(X))})},[]),i.useEffect(()=>{fs(h)},[h]);const P=X=>{const xe=X.target.value.trim();t!=null&&t.id&&xe!==a&&n(t.id,"set_user_name",{userName:xe}).catch(console.error)},[E,G]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),J=X=>{G(X);try{localStorage.setItem("adhdev_sound",X?"1":"0")}catch{}},ye=async()=>{g(""),f(""),b(!0);try{const X=Vt(h),xe=await Ut("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:X})}),fe=await xe.json();if(!xe.ok)throw new Error((fe==null?void 0:fe.error)||"Failed to save standalone font preferences");const we=Vt(fe.standaloneFontPreferences);u(fe),x(we),fs(we),Co(we),f("Standalone chat fonts saved for this self-hosted dashboard.")}catch(X){g(X instanceof Error?X.message:String(X))}finally{b(!1)}},he=()=>{const X=Vt(m==null?void 0:m.standaloneFontPreferences);g(""),f(""),x(X),fs(X)},ne=()=>{g(""),f(""),x(Ss),fs(Ss)},ue=async()=>{j(""),H(""),C(!0);try{const X=await Ut("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:T})}),xe=await X.json();if(!X.ok)throw new Error((xe==null?void 0:xe.error)||"Failed to save standalone network preference");u(xe),I(xe.standaloneBindHost),H(xe.standaloneBindHost==="0.0.0.0"?"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.":"Default standalone network mode set to localhost only. Restart standalone to apply it.")}catch(X){j(X instanceof Error?X.message:String(X))}finally{C(!1)}},Se=async()=>{if(j(""),H(""),_.trim().length<4){j("Password must be at least 4 characters.");return}if(_!==w){j("New password and confirmation do not match.");return}C(!0);try{const X=await Ut("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,newPassword:_})}),xe=await X.json();if(!X.ok)throw new Error((xe==null?void 0:xe.error)||"Failed to save password");d(xe),await F(),A(""),N(""),D(""),H(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),$u()}catch(X){j(X instanceof Error?X.message:String(X))}finally{C(!1)}},ve=async()=>{j(""),H(""),C(!0);try{const X=await Ut("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,clear:!0})}),xe=await X.json();if(!X.ok)throw new Error((xe==null?void 0:xe.error)||"Failed to clear password");d(xe),await F(),A(""),N(""),D(""),H("Standalone password disabled.")}catch(X){j(X instanceof Error?X.message:String(X))}finally{C(!1)}};return s.jsxs(kr,{icon:s.jsx(Kn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Os,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(c==null?void 0:c.publicHostWarning)&&s.jsx(Os,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),s.jsx(St,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:"Version"}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.81"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:c!=null&&c.hasPasswordAuth?"Password enabled":c!=null&&c.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(St,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:T==="127.0.0.1",onChange:()=>I("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:T==="0.0.0.0",onChange:()=>I("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:()=>{ue()},disabled:$,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:$?"Saving…":"Save default network mode"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(m==null?void 0:m.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(St,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:c!=null&&c.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),M&&s.jsx(Os,{variant:"error",children:M}),W&&s.jsx(Os,{variant:"success",children:W}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:c!=null&&c.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:k,onChange:X=>A(X.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:c!=null&&c.hasPasswordAuth?"New password":"New standalone password",value:_,onChange:X=>N(X.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:w,onChange:X=>D(X.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{Se()},disabled:$,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:$?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ve()},disabled:$,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),s.jsx(St,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(X=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${X.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:X.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:X.type})]},X.type))})}),s.jsx(St,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(cb,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(St,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(pb,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI."}),s.jsx(wb,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),s.jsx(Zw,{value:h,savedValue:Vt(m==null?void 0:m.standaloneFontPreferences),saving:S,error:p,notice:v,onChange:x,onSave:()=>{ye()},onResetToSaved:he,onResetToDefaults:ne})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),s.jsx(Sb,{})]})]})}),s.jsx(St,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(ob,{}),s.jsx(hs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(mp,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:J})]})}),s.jsx(St,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(Ym,{size:16,className:"text-text-secondary"})," Display Name"]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:o,onChange:X=>l(X.target.value),onBlur:P,onKeyDown:X=>{X.key==="Enter"&&X.currentTarget.blur()}})]})})})]})}Qx();yb();Vw();const tj=hc({baseUrl:"",getToken:fi});function sj({children:e}){const[t,r]=i.useState(null),[n,a]=i.useState(!0),[o,l]=i.useState(""),[c,d]=i.useState(""),[m,u]=i.useState(!1),h=async()=>{a(!0),d("");try{const b=await(await Ut("/auth/session")).json();r(b)}catch(S){d(S instanceof Error?S.message:String(S))}finally{a(!1)}};i.useEffect(()=>{h()},[]),i.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let S=!1;return(async()=>{try{const b=await Ut("/api/v1/standalone/preferences");if(!b.ok)return;const p=await b.json();if(S)return;const g=Vt(p.standaloneFontPreferences);fs(g),Co(g)}catch{}})(),()=>{S=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const x=async S=>{S.preventDefault(),u(!0),d("");try{const b=await Ut("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),p=await b.json();if(!b.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),l(""),$u()}catch(b){d(b instanceof Error?b.message:String(b))}finally{u(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:x,children:[s.jsx("input",{type:"password",value:o,onChange:S=>l(S.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled:m||!o,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:m?"Signing in…":"Unlock dashboard"})]}):s.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),c&&s.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:c})]})}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",c||"unknown error"]})}function ic(){const{ides:e,initialLoaded:t}=cs();if(!t)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?s.jsx(so,{to:`/machines/${r.id}`,replace:!0}):s.jsx(so,{to:"/dashboard",replace:!0})}function rj(){const e=i.useMemo(()=>({sendCommand:kn,sendData:No,sendPtyInput:$w}),[]);return s.jsx(Sm,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Hm,{client:tj,children:s.jsx(sj,{children:s.jsx(Ww,{children:s.jsx(zm,{value:e,children:s.jsx(qw,{children:s.jsxs(Nm,{children:[s.jsx(rs,{path:"/dashboard",element:s.jsx(bv,{})}),s.jsx(rs,{path:"/machine",element:s.jsx(ic,{})}),s.jsx(rs,{path:"/machines/:id",element:s.jsx(kw,{})}),s.jsx(rs,{path:"/machines",element:s.jsx(ic,{})}),s.jsx(rs,{path:"/about",element:s.jsx(Qw,{})}),s.jsx(rs,{path:"/settings",element:s.jsx(ej,{})}),s.jsx(rs,{path:"/mesh",element:s.jsx(Aw,{})}),s.jsx(rs,{path:"*",element:s.jsx(so,{to:"/dashboard",replace:!0})})]})})})})})})})}lx({connectionManager:Yt});Cm(document.getElementById("root")).render(s.jsx(rj,{}));