@adhdev/daemon-standalone 0.9.82-rc.72 → 0.9.82-rc.75

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
- `,V.style.top="52px",V.style.height="calc(100% - 52px)";const Fe=Re.querySelector("[data-adhdev-popout-focus]");Fe&&(Fe.onclick=()=>{window.focus()});const Ue=Re.querySelector("[data-adhdev-popout-dock]");Ue&&(Ue.disabled=!te,Ue.style.opacity=te?"1":"0.5",Ue.style.cursor=te?"pointer":"default",Ue.onclick=()=>{var Le;te&&Ne(te),(Le=H.defaultView)==null||Le.focus()})}},[U,Ne]),ae=i.useCallback(G=>{var se;const z=k.current,X=z==null?void 0:z.getPanel(G);if(!(!z||!X)){X.group.model.openPanel(X),X.api.setActive(),ie(G,"dockview-shortcut");try{const H=X.group.model.location;H.type==="popout"?H.getWindow().focus():Ta((se=X.group.element)==null?void 0:se.ownerDocument)}catch{}}},[ie]),ue=i.useCallback(G=>{const z=k.current,X=z==null?void 0:z.activePanel,se=(z==null?void 0:z.activeGroup)||(X==null?void 0:X.group);if(!z||!X||!se)return;const H=se.panels||[];if(H.length<=1)return;const V=H.findIndex(ke=>ke.id===X.id);if(V<0)return;const te=(V+G+H.length)%H.length,re=H[te];re&&(re.group.model.openPanel(re),re.api.setActive(),Bt(re.id)||ie(re.id,"dockview-shortcut"))},[ie]),oe=i.useCallback(G=>{var Fe;const z=k.current,X=(z==null?void 0:z.activeGroup)||((Fe=z==null?void 0:z.activePanel)==null?void 0:Fe.group);if(!z||!X)return;const se=z.groups||[],H=se.find(Ue=>Ue.id===X.id);if(!H)return;const V=H.element.getBoundingClientRect(),te=V.left+V.width/2,re=V.top+V.height/2,ke=(Ue,Le,Ze,et)=>Math.max(0,Math.min(Le,et)-Math.max(Ue,Ze)),Ee=Ue=>{const Le=Ue.element.getBoundingClientRect(),Ze=Le.left+Le.width/2,et=Le.top+Le.height/2;let gt=0,yt=0,dt=0,xt=!1;if(G==="left"?(xt=Ze<te,gt=Math.max(0,V.left-Le.right),yt=Math.abs(et-re),dt=ke(V.top,V.bottom,Le.top,Le.bottom)):G==="right"?(xt=Ze>te,gt=Math.max(0,Le.left-V.right),yt=Math.abs(et-re),dt=ke(V.top,V.bottom,Le.top,Le.bottom)):G==="above"?(xt=et<re,gt=Math.max(0,V.top-Le.bottom),yt=Math.abs(Ze-te),dt=ke(V.left,V.right,Le.left,Le.right)):(xt=et>re,gt=Math.max(0,Le.top-V.bottom),yt=Math.abs(Ze-te),dt=ke(V.left,V.right,Le.left,Le.right)),!xt)return Number.POSITIVE_INFINITY;const Ve=dt>0?0:120;return gt*3+yt+Ve};let Oe=null,Re=Number.POSITIVE_INFINITY;for(const Ue of se){if(Ue.id===H.id)continue;const Le=Ee(Ue);Number.isFinite(Le)&&(Le>=Re||(Re=Le,Oe=Ue))}return Oe||void 0},[]),de=i.useCallback(G=>{var se;const z=oe(G);if(!z)return;const X=z.activePanel||z.panels[0];X&&(z.model.openPanel(X),X.api.setActive(),Bt(X.id)||ie(X.id,"dockview-focus"),Ta((se=z.element)==null?void 0:se.ownerDocument))},[oe,ie]),Q=i.useCallback((G,z)=>{const X=k.current,se=X==null?void 0:X.activePanel,H=(X==null?void 0:X.activeGroup)||(se==null?void 0:se.group);if(!X||!se||!H)return;let V=oe(G);!V&&(z!=null&&z.createGroupIfMissing)&&(V=X.addGroup({referenceGroup:H,direction:G})),V&&(se.api.moveTo({group:V,position:"center"}),se.group.model.openPanel(se),se.api.setActive(),Bt(se.id)||ie(se.id,z!=null&&z.createGroupIfMissing?"dockview-split":"dockview-move"))},[oe,ie]),{isMac:ve,tabShortcuts:le,shortcutListening:pe,setShortcutListening:ne,saveShortcuts:Ie}=qd({sortedTabKeys:e.map(G=>G.tabKey),onFocus:me,onSelectTab:ae}),Ce=i.useCallback(()=>{var X;const G=k.current;if(!G)return;const z=G.activePanel;if(z){if(Bt(z.id)){const se=((X=z.params)==null?void 0:X.routeId)||z.id.slice(7),H=Wt(e,se);H!=null&&H.tabKey&&ne(H.tabKey);return}U.has(z.id)&&ne(z.id)}},[U,ae,ne,e]),_e=i.useCallback(G=>{const z=[];return G.metaKey&&z.push(ve?"⌘":"Meta"),G.ctrlKey&&z.push("Ctrl"),G.altKey&&z.push(ve?"⌥":"Alt"),G.shiftKey&&G.key.length!==1&&z.push(ve?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(G.key)?null:(z.push(Qd(G.key)),z.join("+"))},[ve]),K=i.useCallback(G=>{var z,X;switch(G){case"splitActiveTabRight":Q("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Q("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const se=xe();se&&fe(se);return}case"popoutActiveTab":{const se=xe();se&&je(se);return}case"dockActiveTab":{const se=xe();if(!se)return;q(se)?Ne(se):we(se)&&Se(se);return}case"focusLeftPane":de("left");return;case"focusRightPane":de("right");return;case"focusUpPane":de("above");return;case"focusDownPane":de("below");return;case"moveActiveTabToLeftPane":Q("left");return;case"moveActiveTabToRightPane":Q("right");return;case"moveActiveTabToUpPane":Q("above");return;case"moveActiveTabToDownPane":Q("below");return;case"selectPreviousGroupTab":ue(-1);return;case"selectNextGroupTab":ue(1);return;case"setActiveTabShortcut":Ce();return;case"hideCurrentTab":{const se=(X=(z=k.current)==null?void 0:z.activePanel)==null?void 0:X.id;se&&!Bt(se)&&ge(se);return}default:return}},[ue,Se,de,fe,xe,ge,we,q,Ne,Q,je,Ce]);i.useEffect(()=>{if(!C)return;const G=C.sourceDocument,z=G.defaultView??window,X=se=>{const H=G.querySelector("[data-dockview-tab-context-menu]");H&&H.contains(se.target)||I(null)};return z.addEventListener("mousedown",X,!0),z!==window&&window.addEventListener("mousedown",()=>I(null),!0),()=>{z.removeEventListener("mousedown",X,!0),z!==window&&window.removeEventListener("mousedown",()=>I(null),!0)}},[C]);const Me=i.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:U,hasDetachedConversationPanels:W,ides:r,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:g,liveSessionInboxState:S,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:ge,userName:m,scrollToBottomRequest:M,tabShortcuts:le,openTabContextMenu:({x:G,y:z,tabKey:X,sourceDocument:se})=>I({x:G,y:z,tabKey:X,sourceDocument:se??document}),popoutTab:je,moveTabBackToMain:Ne,isTabInPopout:q,floatTab:fe,isTabFloating:we}),[n,t,U,W,r,l,c,g,S,a,o,ge,m,M,le,je,Ne,q,fe,we]),Te=C?xy({isTabInPopout:q(C.tabKey),isTabFloating:we(C.tabKey),tabShortcut:le[C.tabKey],actionShortcuts:p}):[],He=i.useCallback(G=>{var se;const z=k.current;if((((se=z==null?void 0:z.activePanel)==null?void 0:se.id)??null)===G.id){G.group.model.openPanel(G);return}G.group.model.openPanel(G),G.api.setActive()},[]),Ge=i.useCallback((G,z="requested-tab")=>{if(!G)return!1;const X=k.current;if(!X)return!1;const se=X.getPanel(G);return se?(He(se),ie(G,z),f==null||f(),!0):!1},[He,f,ie]),Xe=i.useCallback(()=>{if(D.current)return!1;const G=Ge($.current,"stored-layout-restore");return G&&(D.current=!0),G},[Ge]),Ye=i.useCallback(()=>{var z;const G=k.current;G&&Vb(v,{activeTabId:((z=G.activePanel)==null?void 0:z.id)??null,layout:G.toJSON()})},[v]),tt=i.useCallback(()=>{Yb(v,R.current)},[v]),ct=i.useCallback(G=>{var se,H,V,te;const z=k.current;if(!z)return{kind:"grid"};const X=z.toJSON();for(const re of X.floatingGroups||[])if((H=(se=re.data)==null?void 0:se.views)!=null&&H.includes(G)&&re.position)return{kind:"floating",position:re.position};for(const re of X.popoutGroups||[])if((te=(V=re.data)==null?void 0:V.views)!=null&&te.includes(G))return{kind:"popout",position:re.position,popoutUrl:re.url};return{kind:"grid"}},[]),mt=i.useCallback(G=>{const z=k.current;if(!z)return;const X=z.getPanel(G),se=R.current[G];if(!X||!se||se.kind==="grid")return;if(X.group.model.location.type===se.kind){delete R.current[G],tt();return}if(se.kind==="floating"){z.addFloatingGroup(X,{x:se.position.left??24,y:se.position.top??24,width:se.position.width,height:se.position.height}),delete R.current[G],tt();return}delete R.current[G],tt()},[tt]);i.useEffect(()=>(x==null||x({setShortcutForActiveTab:Ce,restoreHiddenTabToSavedLocation:mt,activateConversationTab:ae,resetAllPanelsToMain:J,activatePreviousTabInGroup:()=>ue(-1),activateNextTabInGroup:()=>ue(1),floatActiveTab:()=>{const G=xe();G&&fe(G)},popoutActiveTab:()=>{const G=xe();G&&je(G)},dockActiveTab:()=>{const G=xe();G&&(q(G)?Ne(G):we(G)&&Se(G))},splitActiveTabRight:()=>Q("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Q("below",{createGroupIfMissing:!0}),focusLeftPane:()=>de("left"),focusRightPane:()=>de("right"),focusUpPane:()=>de("above"),focusDownPane:()=>de("below"),moveActiveTabToLeftPane:()=>Q("left"),moveActiveTabToRightPane:()=>Q("right"),moveActiveTabToUpPane:()=>Q("above"),moveActiveTabToDownPane:()=>Q("below")}),()=>x==null?void 0:x(null)),[ue,Se,fe,de,xe,we,q,Q,Ne,je,x,J,mt,ae,Ce]),i.useEffect(()=>()=>{var G;(G=B.current)==null||G.call(B),B.current=null},[]);const pt=i.useCallback(G=>{var X,se;k.current=G.api,(X=B.current)==null||X.call(B),B.current=null;const z=Gb(v);if($.current=(z==null?void 0:z.activeTabId)??null,z!=null&&z.layout&&G.api.fromJSON(z.layout,{reuseExistingPanels:!1}),N.current=kl({hasStoredLayout:!!(z!=null&&z.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),N.current||(Tl(G.api,e),Al(G.api,e,y)),G.api.totalPanels===0&&e.length>0){const H=Sy(G.api,e,b);if(H){const V=G.api.getPanel(H);V&&He(V)}}else!N.current&&!Ge(b)&&Xe();if(L.current=!0,G.api.onDidActivePanelChange(H=>{var te;if($.current=(H==null?void 0:H.id)??null,D.current=!0,he(),H&&Bt(H.id)){const re=((te=H.params)==null?void 0:te.routeId)||H.id.slice(7),ke=Wt(e,re);w((ke==null?void 0:ke.tabKey)??null),Ye();return}if(w((H==null?void 0:H.id)??null),Ye(),!H)return;const V=U.get(H.id);(V==null?void 0:V.streamSource)==="agent-stream"&&V.agentType&&A(V.routeId,$c(),{agentType:V.agentType,...V.sessionId&&{targetSessionId:V.sessionId}}).catch(()=>{})}),G.api.onDidLayoutChange(()=>{Ye(),he(),P(H=>H+1)}),vy()){const H=Re=>({clientX:Re.clientX,clientY:Re.clientY}),V=Re=>{const Fe=Re==null?void 0:Re.getBoundingClientRect();return Fe?{left:Fe.left,right:Fe.right,top:Fe.top,bottom:Fe.bottom}:null},te=Re=>{var Ue;const Fe=(Ue=j.current)==null?void 0:Ue.getBoundingClientRect();return Fe?Re.clientX<Fe.left||Re.clientX>Fe.right||Re.clientY<Fe.top||Re.clientY>Fe.bottom:!1},re=yy({detachDelayMs:eu,onDetach:({panelId:Re,clientX:Fe,clientY:Ue})=>{var dt,xt;const Le=G.api.getPanel(Re);if(!Le)return;try{if(Le.group.model.location.type!=="grid")return}catch{return}const Ze=(dt=j.current)==null?void 0:dt.getBoundingClientRect(),et=(xt=Le.group.element)==null?void 0:xt.getBoundingClientRect(),gt=Math.round(Math.min(Math.max((et==null?void 0:et.width)??600,360),720)),yt=Math.round(Math.min(Math.max((et==null?void 0:et.height)??500,260),640));G.api.addFloatingGroup(Le,{x:Ze?Math.max(0,Fe-Ze.left-32):void 0,y:Ze?Math.max(0,Ue-Ze.top-18):void 0,width:gt,height:yt}),Le.api.setActive(),Ye(),he(),P(Ve=>Ve+1)}}),ke=[G.api.onWillDragPanel(Re=>{if(!(Re.nativeEvent.defaultPrevented||Re.nativeEvent.shiftKey)){try{if(Re.panel.group.model.location.type!=="grid")return}catch{return}re.startDrag({panelId:Re.panel.id,selfPanelBounds:V(Re.panel.group.element),...H(Re.nativeEvent)})}}),G.api.onWillShowOverlay(Re=>{if(re.hasDetached()){Re.preventDefault();return}re.markDockTarget(H(Re.nativeEvent))}),G.api.onWillDrop(Re=>{if(re.hasDetached()){Re.preventDefault(),re.endDrag();return}re.markDockTarget(H(Re.nativeEvent))}),G.api.onDidDrop(()=>re.endDrag()),G.api.onUnhandledDragOverEvent(Re=>{re.isDragging()&&re.markSelfPanel(H(Re.nativeEvent))})],Ee=Re=>{if(!re.isDragging())return;const Fe=H(Re);te(Fe)&&re.markNonSelfPanel(Fe)},Oe=()=>re.endDrag();window.addEventListener("dragover",Ee,!0),window.addEventListener("drop",Oe,!0),window.addEventListener("dragend",Oe,!0),B.current=()=>{re.dispose();for(const Re of ke)Re.dispose();window.removeEventListener("dragover",Ee,!0),window.removeEventListener("drop",Oe,!0),window.removeEventListener("dragend",Oe,!0)}}G.api.onDidAddGroup(H=>{requestAnimationFrame(()=>{var V,te;try{const re=(V=H.element)==null?void 0:V.ownerDocument;if(!re||re===document)return;(te=re.getElementById("dv-popout-window"))==null||te.classList.add("adhdev-dockview");const ke=document.documentElement.getAttribute("data-theme");ke&&re.documentElement.setAttribute("data-theme",ke),re.body.className=document.body.className;const Ee=document.documentElement.getAttribute("style");Ee&&re.documentElement.setAttribute("style",Ee)}catch{}he(),P(re=>re+1)})}),w(((se=G.api.activePanel)==null?void 0:se.id)??null)},[He,Ge,U,r,d,v,w,Ye,b,y,A,he,e]);i.useLayoutEffect(()=>{const G=k.current;if(!G||!L.current||N.current&&kl({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;N.current&&(N.current=!1);const z=E.current,X=new Set(z),se=e.map(Oe=>Oe.tabKey),H=new Set(se),V=by({previousVisibleConversationCount:z.length,visibleConversationCount:e.length,ides:r});let te=!1;for(const Oe of z)H.has(Oe)||V||(R.current[Oe]=ct(Oe),te=!0);te&&tt(),V||(Tl(G,e),Al(G,e,y));const re=se.filter(Oe=>!X.has(Oe));let ke=!1;for(const Oe of re){const Re=G.getPanel(Oe),Fe=R.current[Oe];if(!Re||!Fe||Fe.kind==="grid")continue;if(Re.group.model.location.type===Fe.kind){delete R.current[Oe],ke=!0;continue}if(Fe.kind==="floating"){G.addFloatingGroup(Re,{x:Fe.position.left??24,y:Fe.position.top??24,width:Fe.position.width,height:Fe.position.height}),delete R.current[Oe],ke=!0;continue}}if(ke&&tt(),E.current=se,b&&Ge(b))return;!G.activePanel&&G.panels[0]&&He(G.panels[0]),!!(G.activePanel&&G.getPanel(G.activePanel.id))||Xe()},[He,Ge,Xe,r,d,tt,ct,b,y,e]),i.useEffect(()=>{L.current&&Ge(b)},[Ge,b]),i.useEffect(()=>{const G=X=>{const se=X.target;if(!se)return;const H=se.querySelector("[data-tab-key]")||se.closest("[data-tab-key]");if(H){const V=H.getAttribute("data-tab-key");if(V&&X.dataTransfer){const te=se.closest(".dv-tab")||H.closest(".dv-tab")||H;X.dataTransfer.effectAllowed="move",X.dataTransfer.setData("text/tab-key",V),te instanceof HTMLElement&&X.dataTransfer.setDragImage(te,Math.max(12,Math.round(te.clientWidth/2)),Math.max(10,Math.round(te.clientHeight/2)))}}};window.addEventListener("dragstart",G);const z=Ml(k.current);for(const X of z)X.addEventListener("dragstart",G);return()=>{window.removeEventListener("dragstart",G);for(const X of z)X.removeEventListener("dragstart",G)}},[O]),i.useEffect(()=>{var z;const G=(z=j.current)==null?void 0:z.querySelector(".adhdev-dockview");G instanceof HTMLElement&&Aa(G,T),ce(),he()},[he,ce,T]),i.useEffect(()=>{he()},[he]),i.useEffect(()=>{const G=z=>{if(z.defaultPrevented||pe)return;const X=_e(z);if(!X)return;const se=z.metaKey||z.ctrlKey||z.altKey;fo(z.target)&&!se||Bn(ve).setActiveTabShortcut!==X||(z.preventDefault(),z.stopPropagation(),Ce())};return window.addEventListener("keydown",G,!0),()=>window.removeEventListener("keydown",G,!0)},[_e,ve,pe,Ce]),i.useEffect(()=>{const G=j.current;if(!G)return;const z=X=>{var re,ke;if(!X.isTrusted)return;const se=(ke=(re=X.target)==null?void 0:re.closest)==null?void 0:ke.call(re,".dv-scrollable");if(!se)return;X.preventDefault(),X.stopPropagation();const H=Math.abs(X.deltaX),V=Math.abs(X.deltaY),te=H>V?X.deltaX:X.deltaY;se.dispatchEvent(new WheelEvent("wheel",{deltaY:te,deltaMode:X.deltaMode,bubbles:!1,cancelable:!0}))};return G.addEventListener("wheel",z,{passive:!1,capture:!0}),()=>G.removeEventListener("wheel",z,{capture:!0})},[]),i.useEffect(()=>{const G=Ml(k.current);if(G.length===0)return;const z=G.map(X=>{let se=[],H=null;const V=()=>{H!=null&&X.clearTimeout(H),H=null,se=[]},te=()=>{H!=null&&X.clearTimeout(H),H=X.setTimeout(()=>{H=null,se=[]},1200)},re=Ee=>{if(!Ee.ctrlKey&&!Ee.metaKey&&!Ee.altKey)return;const Oe=_e(Ee);if(!Oe)return;const Re=Vd();for(const[Fe,Ue]of Object.entries(Re))if(e.some(Le=>Le.tabKey===Fe)&&Ue===Oe){Ee.preventDefault(),ae(Fe);return}},ke=Ee=>{if(Ee.defaultPrevented||pe)return;const Oe=_e(Ee);if(!Oe)return;const Re=Ee.metaKey||Ee.ctrlKey||Ee.altKey;if(fo(Ee.target))return;const Fe=Bn(ve),Ue=Object.entries(Fe).filter(([Ve,Ht])=>!!Ht&&(Ve==="splitActiveTabRight"||Ve==="splitActiveTabDown"||Ve==="floatActiveTab"||Ve==="popoutActiveTab"||Ve==="dockActiveTab"||Ve==="focusLeftPane"||Ve==="focusRightPane"||Ve==="focusUpPane"||Ve==="focusDownPane"||Ve==="moveActiveTabToLeftPane"||Ve==="moveActiveTabToRightPane"||Ve==="moveActiveTabToUpPane"||Ve==="moveActiveTabToDownPane"||Ve==="selectPreviousGroupTab"||Ve==="selectNextGroupTab"||Ve==="setActiveTabShortcut"||Ve==="hideCurrentTab")),Le=Re?[Oe]:[...se.slice(-1),Oe].slice(-2),Ze=Le.join(" "),et=Le[Le.length-1],gt=Ue.find(([,Ve])=>Ve===Ze);if(gt){Ee.preventDefault(),V(),K(gt[0]);return}if(Ue.some(([,Ve])=>Ve.startsWith(`${Ze} `))){Ee.preventDefault(),se=Le,te();return}const dt=Ue.find(([,Ve])=>Ve===et);if(dt){Ee.preventDefault(),V(),K(dt[0]);return}if(Ue.some(([,Ve])=>Ve.startsWith(`${et} `))){Ee.preventDefault(),se=[et],te();return}V()};return X.addEventListener("keydown",re),X.addEventListener("keydown",ke),()=>{V(),X.removeEventListener("keydown",re),X.removeEventListener("keydown",ke)}});return()=>{for(const X of z)X()}},[_e,ve,O,ae,pe,K,e]);const F=T==="light"?qa:Ya,be=((qe=(Be=(Ae=k.current)==null?void 0:Ae.activePanel)==null?void 0:Be.group.element)==null?void 0:qe.ownerDocument)??document;return s.jsxs(tu.Provider,{value:Me,children:[s.jsx("div",{ref:j,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(sm,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:Ny,remote:Cy},defaultTabComponent:My,watermarkComponent:Iy,onReady:pt,singleTabMode:"default",tabAnimation:"smooth",theme:F,popoutUrl:"/popout.html"})}),C&&Nr.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:C.x,top:C.y},children:Te.map(G=>{if(G.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},G.id);let z=s.jsx(np,{size:13,className:"shrink-0 opacity-70"}),X=()=>{};switch(G.id){case"dockInWindow":case"dockBackToGrid":z=s.jsx(op,{size:13,className:"shrink-0 opacity-70"}),X=()=>{Se(C.tabKey),I(null)};break;case"moveBackToMain":z=s.jsx(rp,{size:13,className:"shrink-0 opacity-70"}),X=()=>{Ne(C.tabKey),I(null)};break;case"floatAsPanel":z=s.jsx(ap,{size:13,className:"shrink-0 opacity-70"}),X=()=>{fe(C.tabKey),I(null)};break;case"openInNewWindow":z=s.jsx(sp,{size:13,className:"shrink-0 opacity-70"}),X=()=>{je(C.tabKey),I(null)};break;case"setShortcut":X=se=>{se.stopPropagation(),ne(C.tabKey),I(null)};break;case"removeShortcut":z=s.jsx(jt,{size:13,className:"shrink-0 opacity-70"}),X=()=>{const se={...le};delete se[C.tabKey],Ie(se),I(null)};break;case"hideTab":z=s.jsx(No,{size:13,className:"shrink-0 opacity-70"}),X=()=>{ge(C.tabKey),I(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${G.tone==="muted"?"text-text-muted":""}`,onMouseDown:jy,onClick:X,children:[z,s.jsx("span",{className:"flex-1 min-w-0",children:G.label}),G.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:G.shortcut}):null]},G.id)})}),C.sourceDocument.body),pe&&Nr.createPortal(s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>ne(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:G=>G.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",ve?"⌘+1":"Ctrl+1",", ",ve?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),be.body)]})}const su="adhdev-recent-launch-args-v1",Ay=8;function ru(e){return String(e||"").trim().replace(/\s+/g," ")}function ri(e,t){return`${e.trim()}::${t.trim()}`}function ni(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(su)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function nu(e){if(!(typeof window>"u"))try{window.localStorage.setItem(su,JSON.stringify(e))}catch{}}function xo(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=ni().byKey[ri(r,n)])==null?void 0:o.items)||[]}function au(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=ru(r);if(!n||!a||!o)return;const l=ni(),c=ri(n,a),d=((u=l.byKey[c])==null?void 0:u.items)||[],m=[o,...d.filter(p=>p!==o)].slice(0,Ay);l.byKey[c]={items:m},nu(l)}function _y(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=ru(r);if(!n||!a||!o)return;const l=ni(),c=ri(n,a),m=(((u=l.byKey[c])==null?void 0:u.items)||[]).filter(p=>p!==o);m.length>0?l.byKey[c]={items:m}:delete l.byKey[c],nu(l)}function ou(e){return!e.hasLoadedInitialResults&&!e.isLoading}function gn({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 Ly({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 iu({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:l,onOpenHistory:c,onClearSelection:d}){const m=o?Ud(o):null,u=Ly({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(gn,{title:"Saved history",description:Uo(),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:yx()})]}),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 lu({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 Ry({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 _a(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>Is(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>Is(a,"acp"))?"acp":null}function sn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Py({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:l,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Ve,Ht;const u=Rr(),p=i.useMemo(()=>[...e].sort(Ro),[e]),[x,w]=i.useState(((Ve=p[0])==null?void 0:Ve.id)||""),g=i.useMemo(()=>p.find(Z=>Z.id===x)||p[0],[x,p]),h=i.useMemo(()=>((g==null?void 0:g.workspaces)||[]).map(Z=>({id:Z.id,path:Z.path,label:Z.label})),[g]),b=(g==null?void 0:g.defaultWorkspaceId)||null,[y,f]=i.useState("workspace"),[M,S]=i.useState(""),[v,T]=i.useState(""),[A,k]=i.useState([]),[j,B]=i.useState(""),[L,N]=i.useState(!1),[D,$]=i.useState(null),[E,C]=i.useState(""),[I,O]=i.useState(_a(p[0])),[P,R]=i.useState(""),[U,W]=i.useState(""),[me,ie]=i.useState([]),[ee,ce]=i.useState(""),[je,Ne]=i.useState([]),[q,ge]=i.useState(!1),[fe,we]=i.useState(!1),[xe,Se]=i.useState(""),[J,he]=i.useState(!1),[ae,ue]=i.useState(()=>Nt()),[oe,de]=i.useState(null),[Q,ve]=i.useState(!1),[le,pe]=i.useState(""),[ne,Ie]=i.useState(null),[Ce,_e]=i.useState(!1),[K,Me]=i.useState(""),[Te,He]=i.useState([]),[Ge,Xe]=i.useState(!1),[Ye,tt]=i.useState(""),[ct,mt]=i.useState(!1),pt=i.useRef(null),F=i.useRef(0);i.useEffect(()=>{var Z;!x&&((Z=p[0])!=null&&Z.id)&&w(p[0].id)},[x,p]),i.useEffect(()=>{!g||!(!g.workspaces||!g.availableProviders||!g.detectedIdes||!g.recentLaunches)||u(g.id,{minFreshMs:3e4}).catch(()=>{})},[u,g]);const be=i.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(Z=>Is(Z,"cli")),[g]),Ae=i.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(Z=>Is(Z,"acp")),[g]),Be=i.useMemo(()=>((g==null?void 0:g.detectedIdes)||[]).map(Z=>({id:Z.type,label:Z.name||Z.type,meta:Z.running?"Detected locally":"Available to open"})),[g]),qe=i.useMemo(()=>I==="cli"?be.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"CLI provider"})):I==="acp"?Ae.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"ACP provider"})):Be,[Ae,I,be,Be]),G=i.useMemo(()=>A.find(Z=>Z.id===j)||null,[A,j]),z=i.useMemo(()=>be.find(Z=>Z.type===P)||null,[be,P]),X=i.useMemo(()=>$d(z==null?void 0:z.meshCoordinator,{meshId:(G==null?void 0:G.id)||"",workspace:(G==null?void 0:G.workspace)||""}),[z,G]),se=ne||X,H=i.useCallback(async Z=>{N(!0),C("");try{const $e=await c(Z);k($e),B(_=>{var Y;return $e.some(ye=>ye.id===_)?_:((Y=$e[0])==null?void 0:Y.id)||""}),$(Z)}catch($e){k([]),B(""),$(Z),C($e instanceof Error?$e.message:"Could not load meshes")}finally{N(!1)}},[c]);i.useEffect(()=>{var $e;if(!g)return;if(pt.current!==g.id){pt.current=g.id,f("workspace"),S(b||(($e=h[0])==null?void 0:$e.id)||"__home__"),T(""),k([]),B(""),$(null),C(""),O(_a(g)),R(""),W(""),ce(""),Ne([]),we(!1),Se(""),ue(Nt()),pe(""),Ie(null);return}S(_=>{var Y;return _==="__custom__"||_==="__home__"||h.some(ye=>ye.id===_)?_:b||((Y=h[0])==null?void 0:Y.id)||"__home__"}),O(_=>_==="ide"&&Be.length>0||_==="cli"&&be.length>0||_==="acp"&&Ae.length>0?_:_a(g))},[Ae.length,be.length,b,Be.length,g,h]),i.useEffect(()=>{!g||y!=="mesh"||D===g.id||L||H(g.id)},[H,D,L,g,y]),i.useEffect(()=>{y==="mesh"&&I!=="cli"&&be.length>0&&O("cli")},[I,be.length,y]),i.useEffect(()=>{var Z;I&&(qe.some($e=>$e.id===P)||R(((Z=qe[0])==null?void 0:Z.id)||""))},[I,qe,P]),i.useEffect(()=>{Ie(null)},[g==null?void 0:g.id,j,P,y]);const V=i.useCallback(async(Z,$e)=>{const _=F.current+1;return F.current=_,ge(!0),Se(""),m(Z,$e).then(Y=>{F.current===_&&Ne(Y)}).catch(Y=>{F.current===_&&(Ne([]),Se(Y instanceof Error?Y.message:"Could not load saved sessions"))}).finally(()=>{F.current===_&&(ge(!1),we(!0))})},[m]),te=i.useCallback((Z,$e)=>{ie(xo(Z,$e))},[]);i.useEffect(()=>{F.current+=1,ce(""),ue(Nt()),!g||!P||I==="ide"?ie([]):te(g.id,P),we(!1),Ne([]),Se(""),ge(!1)},[I,te,V,g,P]),i.useEffect(()=>{if(!ee)return;const Z=je.find($e=>$e.providerSessionId===ee);Z!=null&&Z.canResume||ce("")},[je,ee]);const re=M==="__custom__"?v.trim():M==="__home__"?"":((Ht=h.find(Z=>Z.id===M))==null?void 0:Ht.path)||"",ke=i.useMemo(()=>g?t.filter(Z=>Z.id!==g.id&&Z.daemonId===g.id).map(Z=>Z.workspace):[],[t,g]),Ee=i.useMemo(()=>((g==null?void 0:g.recentLaunches)||[]).map(Z=>Z.workspace),[g]),Oe=i.useCallback(Z=>{const $e=String(Z.workspace||"").trim();if(!$e)return;const _=h.find(Y=>sn(Y.path)===sn($e));if(_){S(_.id),T("");return}S("__custom__"),T($e)},[h]),Re=i.useCallback(Z=>{const $e=String(Z.workspace||"").trim();if(!$e)return{workspaceId:null,workspacePath:null};const _=h.find(Y=>sn(Y.path)===sn($e));return _?{workspaceId:_.id,workspacePath:null}:{workspaceId:null,workspacePath:$e}},[h]),Fe=i.useMemo(()=>je.find(Z=>Z.providerSessionId===ee)||null,[je,ee]),Ue=i.useMemo(()=>{var $e;if(I!=="cli"||!g||!P)return null;const Z=(($e=be.find(_=>_.type===P))==null?void 0:$e.displayName)||P;return{routeId:g.id,daemonId:g.id,providerSessionId:ee||void 0,transport:"pty",mode:"chat",agentName:Z,agentType:P,status:"idle",title:Z,messages:[],ideType:P,workspaceName:re,workspacePath:re,displayPrimary:Z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${g.id}:${P}`,machineName:Lt(g,{fallbackId:g.id})}},[I,be,re,g,ee,P]),Le=i.useCallback(()=>{var $e;if(!g)return;S("__custom__"),_e(!0),tt("");const Z=Jn(g.platform,Xn(v.trim(),re,ke,Ee,g.defaultWorkspacePath,($e=h.find(_=>_.id===b))==null?void 0:$e.path,h.map(_=>_.path)));Xe(!0),n(g.id,Z).then(_=>{Me(_.path),T(_.path),He(_.directories)}).catch(_=>{tt(_ instanceof Error?_.message:"Could not load folder")}).finally(()=>Xe(!1))},[v,b,Ee,ke,n,re,g,h]),Ze=i.useCallback(Z=>{g&&(Xe(!0),tt(""),n(g.id,Z).then($e=>{Me($e.path),T($e.path),He($e.directories)}).catch($e=>{tt($e instanceof Error?$e.message:"Could not load folder")}).finally(()=>Xe(!1)))},[n,g]),et=i.useCallback(async()=>{if(!g||!re)return;mt(!0),pe("");const Z=await a(g.id,re);if(mt(!1),!Z.ok){pe(Z.error||"Could not save workspace");return}pe("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,re,g]),gt=i.useCallback(async()=>{if(!g)return;if(y==="mesh"){if(!j||!P)return;ve(!0),pe(""),Ie(null);const _=await d(g.id,j,P);if(ve(!1),!_.ok){if(_.code==="mesh_coordinator_manual_mcp_setup_required"&&_.manualSetup){Ie(_.manualSetup),pe("Manual MCP setup required before this provider can act as mesh coordinator.");return}pe(_.error||"Could not start mesh coordinator");return}r();return}if(!I||!P)return;ve(!0),pe("");const Z=U.trim()?U.trim().split(/\s+/).filter(Boolean):[],$e=I==="ide"?await o(g.id,P,{workspacePath:re||null}):await l(g.id,I,P,{workspaceId:M!=="__home__"&&M!=="__custom__"?M:null,workspacePath:M==="__custom__"&&re||null,resumeSessionId:I==="cli"&&ee?ee:null,cliArgs:Z});if(ve(!1),!$e.ok){pe($e.error||"Could not start session");return}I!=="ide"&&U.trim()&&(au(g.id,P,U),te(g.id,P)),r()},[I,U,te,r,o,d,l,re,g,j,ee,P,M,y]),yt=y==="mesh"?"Start mesh coordinator":I?rd(I,I==="cli"&&!!ee):"Start",dt=y==="mesh"?"Starting coordinator…":I?nd(I,I==="cli"&&!!ee):"Starting…",xt=p.length>5;return g?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(jt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[s.jsx(gn,{title:"Machine",children:xt?s.jsx("select",{"aria-label":"Machine",value:g.id,onChange:Z=>w(Z.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Q,children:p.map(Z=>s.jsx("option",{value:Z.id,children:Lt(Z,{fallbackId:Z.id})},Z.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:p.map(Z=>{const $e=Lt(Z,{fallbackId:Z.id}),_=g.id===Z.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${$e}`,"aria-pressed":_,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${_?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/60 text-text-secondary hover:bg-bg-secondary hover:text-text-primary"}`,onClick:()=>w(Z.id),disabled:Q,title:$e,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${Z.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:$e})]},Z.id)})})}),s.jsxs(gn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:y==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Le,disabled:Q,children:"Browse…"}):void 0,children:[s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":"Launch target type",children:[{id:"workspace",label:"Workspace",desc:"Normal session"},{id:"mesh",label:"Mesh",desc:"Coordinator session"}].map(Z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":y===Z.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${y===Z.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{f(Z.id),pe(""),Z.id==="mesh"&&g&&D!==g.id&&!L&&H(g.id)},disabled:Q,children:[s.jsx("div",{className:"text-sm font-semibold",children:Z.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:Z.desc})]},Z.id))}),y==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:M,onChange:Z=>{const $e=Z.target.value;S($e),$e==="__custom__"?Le():pe("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Q,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),h.map(Z=>s.jsxs("option",{value:Z.id,children:[Z.id===b?"⭐ ":"",zn(Z.path,Z.label)||Z.path]},Z.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:M==="__home__"?"Launch without a workspace.":re||"Select a workspace folder."}),M==="__custom__"&&re&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Le,disabled:Q,children:[s.jsx(Ss,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:et,disabled:Q||ct,children:ct?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[L&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!L&&E&&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:E}),!L&&!E&&A.length===0&&s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker."}),A.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:A.map(Z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":j===Z.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${j===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>B(Z.id),disabled:Q,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[Z.repoIdentity||"Repo mesh",typeof Z.nodesCount=="number"?` · ${Z.nodesCount} node${Z.nodesCount===1?"":"s"}`:""]}),Z.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",Z.workspace]})]},Z.id))}),G&&s.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),s.jsx(Ry,{workspaceMode:y,activeKind:I,cliEnabled:be.length>0,ideEnabled:Be.length>0,acpEnabled:Ae.length>0,busy:Q,onSelect:O}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:I==="ide"?"Choose IDE":I==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[qe.map(Z=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${P===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>R(Z.id),disabled:Q,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Z.meta})]},Z.id)),qe.length===0&&s.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),y==="mesh"&&se&&s.jsx(lu,{setup:se,providerName:(z==null?void 0:z.displayName)||(z==null?void 0:z.name)||P}),y!=="mesh"&&I!=="ide"&&s.jsxs(gn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:U,onChange:Z=>W(Z.target.value),placeholder:"Optional flags...",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Q}),me.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:me.map(Z=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>W(Z),disabled:Q,title:Z,children:Z},Z))})]}),y!=="mesh"&&I==="cli"&&s.jsx(iu,{busy:Q,savedSessionsLoading:q,savedSessionsError:xe,selectedSession:Fe,onRefresh:()=>{!g||!P||V(g.id,P)},onOpenHistory:()=>{!g||!P||(he(!0),ou({hasLoadedInitialResults:fe,isLoading:q})&&V(g.id,P))},onClearSelection:()=>ce("")}),le&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${le.includes("saved")||le.includes("requested")||le.includes("Manual MCP setup")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:le})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:r,disabled:Q,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:gt,disabled:Q||(y==="mesh"?!j||!P||I!=="cli"||L:!I||!P||M==="__custom__"&&!re),children:[s.jsx(Io,{size:14}),Q?dt:yt]})]})]})}),Ce&&s.jsx(Zn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:K,directories:Te,busy:Ge,error:Ye,onClose:()=>_e(!1),onNavigate:Ze,onConfirm:Z=>{T(Z),Me(Z),S("__custom__"),_e(!1)}}),J&&Ue&&s.jsx(Vo,{activeConv:Ue,ides:[],isCreatingChat:!1,isRefreshingHistory:q,savedSessions:je,isSavedSessionsLoading:q,isResumingSavedSessionId:oe,savedHistoryFilters:ae,missingWorkspaceResumePath:re||null,onSavedHistoryFiltersChange:ue,onClose:()=>he(!1),onNewChat:()=>{ce(""),he(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!g||!P||V(g.id,P)},onResumeSavedSession:Z=>{if(!g||!P||oe||!Z.canResume)return;const $e=Re(Z);ce(Z.providerSessionId),Oe(Z),de(Z.providerSessionId),he(!1),ve(!0),pe(""),l(g.id,"cli",P,{workspaceId:$e.workspaceId,workspacePath:$e.workspacePath,resumeSessionId:Z.providerSessionId}).then(_=>{if(!_.ok){pe(_.error||"Could not resume session");return}r()}).finally(()=>{ve(!1),de(_=>_===Z.providerSessionId?null:_)})}})]}):null}function cu(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 ai(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=cu(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 oi(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function du(e){var t;return!oi(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 rn(e){return[...new Set(e.filter(t=>!!t))]}function Dy(e){const t=e.nodes.find(l=>l.type==="defaultBranchNode")??null,r=(t==null?void 0:t.branch)??null,n=e.nodes.filter(l=>l.type!=="defaultBranchNode"&&l.type!=="submoduleNode"&&!l.isOrphan&&!!r&&l.branch===r),a=e.nodes.filter(l=>l.type!=="submoduleNode"&&!l.isOrphan),o=e.nodes.filter(l=>l.type!=="submoduleNode");return t||n.length>0?rn([t==null?void 0:t.id,...n.map(l=>l.id)]):a.length>0?rn(a.map(l=>l.id)):o.length>0?rn(o.map(l=>l.id)):rn(e.nodes.map(l=>l.id))}function uu(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 Ey(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${uu(e)}::${n}x${a}`}const $y={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"},By={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"},Oy={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"},Fy={default:"border-slate-300 bg-white text-slate-700 hover:bg-slate-50",info:"border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100",success:"border-emerald-300 bg-emerald-50 text-emerald-700 hover:bg-emerald-100"};function Zs(e){return e==="light"?{theme:e,isDark:!1,flowColorMode:"light",textPrimary:"text-slate-900",textSecondary:"text-slate-700",textMuted:"text-slate-500",graphShellClass:"relative w-full min-w-0 overflow-hidden rounded-2xl border border-slate-200 bg-[radial-gradient(circle_at_top,_rgba(14,165,233,0.16),_rgba(248,250,252,0.98)_42%,_rgba(255,255,255,1))]",graphStatChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-slate-700 shadow-sm",graphHintChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-[10px] text-slate-500 shadow-sm",graphControlsClass:"!bottom-4 !left-4 !shadow-md",graphBackgroundDotColor:"rgba(148, 163, 184, 0.34)",edgeLabelTextColor:"#334155",edgeLabelBackgroundColor:"rgba(255, 255, 255, 0.96)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.45)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[rgba(148,163,184,0.22)] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"flex h-[100dvh] w-full flex-col overflow-hidden bg-white md:h-[min(90vh,960px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-slate-200 md:bg-white/98 md:shadow-[0_28px_120px_rgba(148,163,184,0.28)]",dialogHeaderClass:"flex shrink-0 flex-col gap-3 border-b border-slate-200 bg-white/96 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-slate-900 md:text-xl",dialogKickerClass:"rounded-full border border-slate-300 bg-slate-50 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-600",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-500",dialogRefreshedChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1.5 text-xs text-slate-600",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-300 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",dialogBodyClass:"min-h-0 flex-1 overflow-y-auto bg-[linear-gradient(180deg,rgba(248,250,252,0.98),rgba(241,245,249,0.96))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-slate-300 bg-white/90 px-6 text-center text-sm text-slate-500",cardClass:"rounded-2xl border border-slate-200 bg-white/95 shadow-sm",cardHeaderClass:"border-b border-slate-200 px-4 py-3",cardTitleClass:"text-sm font-semibold text-slate-900",cardSubtitleClass:"mt-1 text-xs text-slate-500",rowClass:"flex items-start justify-between gap-3 border-b border-slate-200/80 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"text-slate-500",rowValueClass:"max-w-[65%] break-all text-right text-slate-800",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-slate-200 bg-white/95 p-4 shadow-md md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-slate-200 bg-white/95 p-4 text-xs text-slate-500 shadow-sm md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-900",panelCloseButtonClass:"text-xs text-slate-500 hover:text-slate-900",panelFieldRowClass:"flex justify-between gap-3 border-b border-slate-200/80 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-500",panelFieldValueClass:"break-all text-right font-medium text-slate-700",infoCalloutClass:"mt-1 rounded border border-sky-300 bg-sky-50 px-2 py-1.5 text-[10px] text-sky-700",badge:t=>By[t],actionButton:t=>Fy[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative w-full min-w-0 overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",graphStatChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-slate-200",graphHintChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-[10px] text-slate-300",graphControlsClass:"!bottom-4 !left-4 !shadow-lg",graphBackgroundDotColor:"rgba(148, 163, 184, 0.22)",edgeLabelTextColor:"#cbd5e1",edgeLabelBackgroundColor:"rgba(2, 6, 23, 0.86)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.2)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[#030617]/[0.58] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"flex h-[100dvh] w-full flex-col overflow-hidden bg-slate-950 md:h-[min(90vh,960px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-white/10 md:bg-slate-950/96 md:shadow-[0_28px_120px_rgba(2,6,23,0.46)]",dialogHeaderClass:"flex shrink-0 flex-col gap-3 border-b border-white/10 bg-slate-950/92 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-white md:text-xl",dialogKickerClass:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-300",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-400",dialogRefreshedChipClass:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 bg-white/6 text-slate-300 transition hover:bg-white/10 hover:text-white",dialogBodyClass:"min-h-0 flex-1 overflow-y-auto bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-white/10 bg-white/[0.03] px-6 text-center text-sm text-slate-400",cardClass:"rounded-2xl border border-white/10 bg-white/[0.04]",cardHeaderClass:"border-b border-white/10 px-4 py-3",cardTitleClass:"text-sm font-semibold text-white",cardSubtitleClass:"mt-1 text-xs text-slate-400",rowClass:"flex items-start justify-between gap-3 border-b border-white/5 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"text-slate-400",rowValueClass:"max-w-[65%] break-all text-right text-slate-100",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-white/10 bg-white/[0.04] p-4 shadow-lg md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-white/10 bg-white/[0.04] p-4 text-xs text-slate-400 md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-100",panelCloseButtonClass:"text-xs text-slate-400 hover:text-slate-100",panelFieldRowClass:"flex justify-between gap-3 border-b border-white/6 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-400",panelFieldValueClass:"break-all text-right font-medium text-slate-200",infoCalloutClass:"mt-1 rounded bg-blue-500/10 border border-blue-500/20 px-2 py-1.5 text-[10px] text-blue-300",badge:t=>$y[t],actionButton:t=>Oy[t]}}const It={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,columnGap:540,edgeLabelBuffer:180,defaultToContentGap:136,worktreeStackGap:82,parentToSubmoduleGap:48,submoduleStackGap:36,submoduleIndentX:72,placeholderTopOffset:0};function nn(e,t,r){const n=(e||"").trim();return n?Math.max(1,Math.min(r,Math.ceil(n.length/t))):0}function Wy(e){let t=1;return e.type==="submoduleNode"&&(t+=1),e.branch&&e.type!=="submoduleNode"&&(t+=1),e.submoduleCommit&&e.type==="submoduleNode"&&(t+=1),e.dirty&&(t+=1),e.outOfSync&&(t+=1),e.hasConflicts&&(t+=1),e.type!=="submoduleNode"&&e.upstream&&e.upstreamStatus!=="fresh"&&(t+=1),e.isOrphan&&(t+=1),t}function ii(e){return e.type==="submoduleNode"?It.submoduleCardWidth:It.worktreeCardWidth}function mu(e){var r;if(e.type==="defaultBranchNode")return e.nextStepHint||"Default branch anchor";if(e.type==="submoduleNode"){const n=[e.machineLabel?`parent ${e.machineLabel}`:null];return e.outOfSync?n.push("out of sync"):e.dirty?n.push("local changes"):n.push("synced"),n.filter(Boolean).join(" · ")}const t=[];if(e.upstream&&t.push(e.upstream),e.upstream&&e.upstreamStatus!=="fresh")t.push("upstream unverified");else{const n=cu(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 yn(e){const t=ii(e),r=e.type==="submoduleNode"?24:30,n=Math.ceil(Wy(e)/(e.type==="submoduleNode"?2:3)),a=nn(e.label,r,2),o=nn(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,r,2),l=nn(mu(e),r+4,3),c=ai(e),d=du(e)?oi(e):null,m=nn(d,Math.max(24,Math.floor(t/8)),4),u=52+a*18+o*14+(c?30:0)+n*24+Math.max(22,l*18)+(m>0?22+m*16:0),p=e.type==="submoduleNode"?It.minSubmoduleCardHeight:It.minWorktreeCardHeight;return Math.min(It.maxEstimatedCardHeight,Math.max(p,Math.ceil(u)))}function La(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 Hy(e){return e?Math.min(260,Math.max(72,e.length*7+26)):0}function Ky(e){const t=e.edges.reduce((r,n)=>Math.max(r,Hy(n.label)),0);return Math.max(It.columnGap,It.worktreeCardWidth+t+It.edgeLabelBuffer)}function an(e,t,r,n=!0){return{id:e.id,type:"meshNode",position:{x:t,y:r},graphNode:e,selected:!1,draggable:!1,selectable:n}}function on(e,t,r){return{id:e.id,x:t,y:r,width:ii(e),height:yn(e)}}function Uy(e,t){return{id:`${e.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:t.repoIdentity,branch:e.branch,upstream:null,upstreamStatus:null,machineLabel:null,health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],nextStepHint:"Waiting for worktree nodes to report live mesh status.",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{nodeId:`${e.id}__placeholder`,machineLabel:"",workspace:t.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}}function zy(e){const t=[...e.nodes].sort(La),r=t.find(b=>b.type==="defaultBranchNode")??null,n=new Map;for(const b of t){if(b.type!=="submoduleNode"||!b.parentNodeId)continue;const y=n.get(b.parentNodeId)??[];y.push(b),n.set(b.parentNodeId,y)}const a=t.filter(b=>b.id!==(r==null?void 0:r.id)&&b.type!=="submoduleNode"),o=new Map,l=[];for(const b of a){if(b.isOrphan||!b.branch){l.push(b);continue}const y=o.get(b.branch)??[];y.push(b),o.set(b.branch,y)}const c=[...o.entries()].sort(([b],[y])=>r!=null&&r.branch&&b===r.branch&&y!==r.branch?-1:r!=null&&r.branch&&y===r.branch&&b!==r.branch?1:b.localeCompare(y));l.length>0&&c.push(["__orphans__",[...l].sort(La)]),c.length===0&&c.push(["__nodes__",[]]);const d=[],m=[],u=c.length,p=Ky(e),x=Math.max(1,u-1)*p,w=r?0:96,g=r?yn(r):0,h=r?w+g+It.defaultToContentGap:0;if(r){const b=x/2;d.push(an(r,b,w)),m.push(on(r,b,w))}return c.forEach(([b,y],f)=>{const M=f*p,S=y.length>0?y:a.length>0?a:[];let v=h;if(S.forEach(T=>{const A=yn(T);d.push(an(T,M,v)),m.push(on(T,M,v));const k=[...n.get(T.id)??[]].sort(La);if(k.length>0){let j=v+A+It.parentToSubmoduleGap;k.forEach(B=>{const L=M+It.submoduleIndentX,N=yn(B);d.push(an(B,L,j)),m.push(on(B,L,j)),j+=N+It.submoduleStackGap}),v=j+It.worktreeStackGap-It.submoduleStackGap;return}v+=A+It.worktreeStackGap}),b==="__nodes__"&&a.length===0&&r){const T=Uy(r,e),A=h+It.placeholderTopOffset;d.push(an(T,M,A,!1)),m.push(on(T,M,A))}}),{nodes:d,bounds:m,columnGap:p}}const pu=i.createContext(Zs("dark"));function Gy(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=ai(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 Vy(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 qy(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 Yy(e){return e.replace(/_/g," ")}function Xy({data:e,selected:t}){const r=i.useContext(pu),n=e.graphNode,a=n.type==="defaultBranchNode",o=n.type==="submoduleNode",l=du(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=ai(n),u=mu(n),p=oi(n);return s.jsxs("div",{className:`${o?"w-[228px]":"w-[256px]"} rounded-2xl border px-4 py-3.5 backdrop-blur-sm transition-all ${Gy(n,t,r.isDark)}`,style:{width:ii(n)},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:qy(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] ${Vy(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:Yy(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&&p&&s.jsx("div",{className:`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${r.isDark?"border-cyan-400/15 bg-cyan-500/8 text-cyan-50/90":"border-sky-300 bg-sky-50 text-sky-700"}`,children:p}),s.jsx(ki,{type:"source",position:Si.Bottom,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const Jy={meshNode:Xy};function Qy(e,t=Zs("dark")){const n=zy(e).nodes.map(o=>({id:o.id,type:o.type,position:o.position,data:{graphNode:o.graphNode},selected:o.selected,draggable:o.draggable,selectable:o.selectable})),a=e.edges.map(o=>({id:o.id,source:o.source,target:o.target,label:o.label,type:o.type==="worktreeLink"||o.type==="submoduleLink"?"smoothstep":"bezier",animated:o.type==="orphanLink",markerEnd:o.direction==="directed"?{type:im.ArrowClosed,width:o.type==="submoduleLink"?16:18,height:o.type==="submoduleLink"?16:18,color:_l(o)}:void 0,style:{stroke:_l(o),strokeWidth:o.type==="orphanLink"?2.25:o.type==="submoduleLink"?1.7:o.type==="worktreeLink"?1.8:2,strokeDasharray:o.type==="orphanLink"?"5 4":o.type==="submoduleLink"?"4 3":void 0},labelStyle:{fill:t.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:t.edgeLabelBackgroundColor,fillOpacity:1,stroke:t.edgeLabelBorderColor},labelBgPadding:[6,4],labelBgBorderRadius:7}));return{nodes:n,edges:a}}function _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 Zy({data:e,viewportKey:t}){const r=lm(),n=cm(),a=i.useRef(null),o=i.useMemo(()=>uu(e),[e]),l=i.useMemo(()=>Dy(e),[e]);return i.useEffect(()=>{if(!r||e.nodes.length===0||a.current===t)return;let c=!1;const d=requestAnimationFrame(()=>{if(c)return;const m=l.length>0&&l.length<e.nodes.length;n.fitView({nodes:m?l.map(u=>({id:u})):void 0,padding:m?.24:.2,maxZoom:m?.98:.9,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(d)}},[e.nodes.length,l,o,r,n,t]),null}function e0({data:e,selectedNodeId:t=null,onNodeClick:r}){const{theme:n}=Qs(),a=i.useMemo(()=>Zs(n),[n]),o=i.useMemo(()=>Qy(e,a),[e,a]),l=i.useRef(null),[c,d]=i.useState({width:0,height:0}),m=i.useMemo(()=>Ey(e,c.width,c.height),[e,c.height,c.width]),u=i.useMemo(()=>o.nodes.map(p=>({...p,selected:p.id===t})),[o.nodes,t]);return i.useEffect(()=>{const p=l.current;if(!p)return;const x=()=>{const g=Math.max(0,Math.round(p.clientWidth)),h=Math.max(0,Math.round(p.clientHeight));d(b=>b.width===g&&b.height===h?b:{width:g,height:h})};x();const w=typeof ResizeObserver=="function"?new ResizeObserver(()=>x()):null;return w==null||w.observe(p),window.addEventListener("resize",x),()=>{w==null||w.disconnect(),window.removeEventListener("resize",x)}},[]),s.jsx(pu.Provider,{value:a,children:s.jsxs("div",{ref:l,className:a.graphShellClass,children:[s.jsxs("div",{className:`absolute inset-x-3 top-3 z-10 flex flex-wrap items-center justify-between gap-2 text-[11px] ${a.textSecondary}`,children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs("span",{className:a.graphStatChipClass,children:[e.stats.totalNodes," node",e.stats.totalNodes===1?"":"s"]}),s.jsxs("span",{className:a.graphStatChipClass,children:[e.stats.totalActiveSessions," active session",e.stats.totalActiveSessions===1?"":"s"]}),e.stats.orphanNodes>0&&s.jsxs("span",{className:a.isDark?"rounded-full border border-orange-400/25 bg-orange-500/12 px-3 py-1 text-orange-100":"rounded-full border border-orange-300 bg-orange-50 px-3 py-1 text-orange-700",children:[e.stats.orphanNodes," need attention"]})]}),s.jsx("div",{className:a.graphHintChipClass,children:"Focused on the main path first · drag or scroll to pan"})]}),s.jsx("div",{className:"h-[460px] w-full min-w-0 min-h-[460px] sm:h-[560px] xl:h-[680px]",children:s.jsxs(rm,{nodes:u,edges:o.edges,nodeTypes:Jy,minZoom:.25,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(p,x)=>r==null?void 0:r(x.data.graphNode),className:"h-full w-full",colorMode:a.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(Zy,{data:e,viewportKey:m}),s.jsx(nm,{className:a.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),s.jsx(am,{variant:om.Dots,gap:18,size:1.2,color:a.graphBackgroundDotColor})]})})]})})}function ft(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Pe(...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 Et(...e){for(const t of e)if(typeof t=="boolean")return t}function Ra(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function li(e){switch(e){case"fresh":return 30;case"no_upstream":return 4;case"unchecked":case void 0:return 0;case"stale":return-10;case"unavailable":return-15;default:return 0}}function t0(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 s0(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=ft(n),o=Pe(a.path),l=Pe(a.commit),c=Pe(a.repoPath,a.repo_root)??t0(t,o);return!o||!l||!c?null:{path:o,commit:l,repoPath:c,dirty:Et(a.dirty)??!1,outOfSync:Et(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:_t(a.lastCheckedAt,a.last_checked_at)??Date.now(),...Pe(a.error)?{error:Pe(a.error)}:{}}}).filter(n=>n!==null);return r.length>0?r:void 0}function r0(e){return Et(e.isGitRepo)!==void 0||!!Pe(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||_t(e.ahead,e.behind,e.staged,e.modified,e.untracked,e.deleted,e.renamed,e.lastCheckedAt,e.last_checked_at)!==void 0||Array.isArray(e.submodules)&&e.submodules.length>0}function vn(e,t,r){const n=Et(e.isGitRepo);if(!Object.keys(e).length||!r0(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(g=>typeof g=="string"):[],l=_t(e.conflicts)??o.length,c=Et(e.hasConflicts)??l>0,d=Pe(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,m=s0(e.submodules,d),u=Pe(e.upstreamStatus,e.upstream_status),p=_t(e.upstreamFetchedAt,e.upstream_fetched_at),x=Pe(e.upstreamFetchError,e.upstream_fetch_error),w=Pe(e.error);return{workspace:Pe(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:a,branch:Pe(e.branch)??null,headCommit:Pe(e.headCommit)??null,headMessage:Pe(e.headMessage)??null,upstream:Pe(e.upstream)??null,upstreamStatus:u??"unchecked",...p!==void 0?{upstreamFetchedAt:p}:{},...x?{upstreamFetchError:x}:{},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:c,conflictFiles:o,stashCount:_t(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??_t(e.lastCheckedAt,e.last_checked_at)??Date.now(),...m?{submodules:m}:{},...w?{error:w}:{}}}function n0(e){if(!e)return Number.NEGATIVE_INFINITY;let t=0;return e.isGitRepo===!0&&(t+=50),e.isGitRepo===!1&&(t-=10),e.branch&&(t+=20),e.headCommit&&(t+=20),e.upstream&&(t+=10),t+=li(e.upstreamStatus),typeof e.ahead=="number"&&(t+=2),typeof e.behind=="number"&&(t+=2),Array.isArray(e.submodules)&&e.submodules.length>0&&(t+=4+e.submodules.length),e.error&&(t-=20),t}function a0(e){const t=ft(e.lastGit??e.last_git),r=ft(t.result),n=ft(t.status),a=ft(r.status),o=ft(e.lastProbe??e.last_probe),l=ft(o.git),c=ft(l.result),d=ft(l.status),m=ft(c.status);let u=null;for(const p of[n,a,d,m]){const x=vn(p,e,{lastCheckedAt:Date.now()});if(!x)continue;const w=n0(x);(!u||w>u.score)&&(u={git:x,score:w})}return u==null?void 0:u.git}function o0(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 i0(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 On(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=o0(e);return t.outOfSync?"degraded":t.dirty||i0(e)?"dirty":"online"}function l0(e,t){const r=t?On(t):void 0;return!e||e==="unknown"?r:e}function c0(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=ft(o),c=Pe(l.sessionId,l.session_id,l.id);return c?{sessionId:c,...Pe(l.providerType,l.provider)?{providerType:Pe(l.providerType,l.provider)}:{},...Pe(l.state,l.status)?{state:Pe(l.state,l.status)}:{},...Pe(l.lifecycle)?{lifecycle:Pe(l.lifecycle)}:{},...Pe(l.surfaceKind,l.surface_kind)?{surfaceKind:Pe(l.surfaceKind,l.surface_kind)}:{},...Pe(l.recoveryState,l.recovery_state)?{recoveryState:Pe(l.recoveryState,l.recovery_state)}:{},...Pe(l.workspace)?{workspace:Pe(l.workspace)}:{},...Pe(l.title)?{title:Pe(l.title)}:{},...Pe(l.lastActivityAt,l.last_activity_at)?{lastActivityAt:Pe(l.lastActivityAt,l.last_activity_at)}:{},...Et(l.isCached,l.is_cached)!==void 0?{isCached:Et(l.isCached,l.is_cached)}:{}}:null}).filter(o=>o!==null);if(a.length>0)return a}const r=ft(e.activeSession??e.active_session),n=Pe(r.id,r.sessionId,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id);if(n)return[{sessionId:n,...Pe(r.providerType,r.provider)?{providerType:Pe(r.providerType,r.provider)}:{},...Pe(r.state,r.status)?{state:Pe(r.state,r.status)}:{}}]}function d0(e){const t=ft(e.connection);return Object.keys(t).length>0?t:void 0}function u0(e){const t=e==null?void 0:e.source,r=e==null?void 0:e.transport;return{...e,perspective:(e==null?void 0:e.perspective)??"selected_coordinator",source:t&&t!=="not_reported"?t:"mesh_peer_status",state:"connected",transport:r&&r!=="unknown"?r:"direct",reported:!0,reason:"Live peer git snapshot reported by the selected coordinator."}}function ci(e){var r;const t=e.git;return!!(t&&(t.isGitRepo===!0||t.isGitRepo===!1||t.branch||t.upstream||t.headCommit||typeof t.lastCheckedAt=="number"||(((r=t.submodules)==null?void 0:r.length)??0)>0))}function Ll(e){var n,a,o,l,c,d;let t=0;const r=e.git;return ci(e)&&(t+=80,(r==null?void 0:r.isGitRepo)===!0&&(t+=20),(r==null?void 0:r.isGitRepo)===!1&&(t+=5),r!=null&&r.branch&&(t+=20),r!=null&&r.upstream&&(t+=12),r!=null&&r.headCommit&&(t+=12),t+=li(r==null?void 0:r.upstreamStatus),typeof(r==null?void 0:r.lastCheckedAt)=="number"&&(t+=6),t+=(((n=r==null?void 0:r.submodules)==null?void 0:n.length)??0)*6),(a=e.branchConvergence)!=null&&a.status&&(t+=12),(((o=e.connection)==null?void 0:o.state)==="connected"||((l=e.connection)==null?void 0:l.state)==="self")&&(t+=8),((c=e.connection)==null?void 0:c.transport)==="direct"&&(t+=4),((d=e.connection)==null?void 0:d.source)==="mesh_peer_status"&&(t+=4),e.health==="online"&&(t+=4),e.health==="dirty"&&(t+=3),e.health==="degraded"&&(t+=2),e.launchReady&&(t+=2),e.gitProbePending&&(t-=40),e.error&&(t-=10),t}function m0(e,t){var g,h,b,y;const r=Ll(e),a=Ll(t)>r?t:e,o=a===t?e:t,l=a.git??o.git,c=(((g=a.providers)==null?void 0:g.length)??0)>0?a.providers:o.providers,d=(((h=a.activeSessions)==null?void 0:h.length)??0)>0?a.activeSessions:o.activeSessions,m=(((b=a.activeSessionDetails)==null?void 0:b.length)??0)>0?a.activeSessionDetails:o.activeSessionDetails,u=(((y=a.providerPriority)==null?void 0:y.length)??0)>0?a.providerPriority:o.providerPriority,p=a.connection??o.connection,x={...o,...a,machineLabel:a.machineLabel||o.machineLabel,workspace:a.workspace||o.workspace,...a.repoRoot||o.repoRoot?{repoRoot:a.repoRoot||o.repoRoot}:{},...a.daemonId||o.daemonId?{daemonId:a.daemonId||o.daemonId}:{},...a.machineId||o.machineId?{machineId:a.machineId||o.machineId}:{},...a.machineStatus||o.machineStatus?{machineStatus:a.machineStatus||o.machineStatus}:{},health:l&&(!a.health||a.health==="unknown")?On(l):a.health,providers:c??[],activeSessions:d??[],...m&&m.length>0?{activeSessionDetails:m}:{},...u&&u.length>0?{providerPriority:u}:{},...p?{connection:p}:{},...l?{git:l}:{}},w=ft(a.branchConvergence);return Object.keys(w).length>0?Object.assign(x,{branchConvergence:w}):delete x.branchConvergence,l&&(delete x.gitProbePending,delete x.error),x}function p0(e){const t=ft(e),r=Pe(t.nodeId,t.id);if(!r)return null;const n=ft(t.cachedStatus),a=a0(t),o=a?void 0:vn(ft(t.git),t)??vn(t,t),l=a??o,c=l?void 0:vn(ft(n.git),t),d=l??c,m=Pe(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),u=Pe(t.health),p=a?On(d):l0(u,l)||(d?On(d):void 0)||Pe(n.health)||m||Pe(t.status)||"unknown",w=(a?void 0:Pe(t.error))??(l?void 0:Pe(n.error)),g=c0(t),h=Ra(t.activeSessions),b=(g==null?void 0:g.map(k=>k.sessionId))??[],y=Ra(t.providerPriority),f=Et(t.gitProbePending,t.git_probe_pending),M=l?void 0:f,S=d0(t),v=ft(t.branchConvergence??t.branch_convergence),T=S==null?void 0:S.state,A=a&&(!(S!=null&&S.reported)||T==="unknown")?u0(S):S;return{nodeId:r,machineLabel:Pe(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:Pe(t.workspace,d==null?void 0:d.workspace)||"",...Pe(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:Pe(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},...Pe(t.daemonId,t.daemon_id)?{daemonId:Pe(t.daemonId,t.daemon_id)}:{},...Pe(t.machineId,t.machine_id)?{machineId:Pe(t.machineId,t.machine_id)}:{},...m?{machineStatus:m}:{},...Et(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Et(t.isLocalWorktree,t.is_local_worktree)}:{},...Pe(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:Pe(t.worktreeBranch,t.worktree_branch)}:{},health:p,...d?{git:d}:{},...M!==void 0?{gitProbePending:M}:{},providers:Ra(t.providers),activeSessions:h.length>0?h:b,...g&&g.length>0?{activeSessionDetails:g}:{},...y.length>0?{providerPriority:y}:{},...Et(t.launchReady)!==void 0?{launchReady:Et(t.launchReady)}:a?{launchReady:!0}:{},...Pe(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:Pe(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},...Pe(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:Pe(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...A?{connection:A}:{},...Object.keys(v).length>0?{branchConvergence:v}:{},...w?{error:w}:{}}}function hu(e){const t=new Map,r=[];for(const n of e){const a=t.get(n.nodeId);if(!a){t.set(n.nodeId,n),r.push(n);continue}const o=m0(a,n);t.set(n.nodeId,o);const l=r.findIndex(c=>c.nodeId===n.nodeId);l>=0&&(r[l]=o)}return r}function fu(e){return{...e,nodes:hu(e.nodes??[])}}function h0(e){var r;const t=e==null?void 0:e.git;return{nodeId:(e==null?void 0:e.nodeId)??null,chosenSource:t?"live_git":e!=null&&e.gitProbePending?"pending_git":"no_git",hasLiveGit:ci(e??{git:void 0}),branch:(t==null?void 0:t.branch)??null,upstream:(t==null?void 0:t.upstream)??null,headCommit:(t==null?void 0:t.headCommit)??null,submoduleCount:((r=t==null?void 0:t.submodules)==null?void 0:r.length)??0,pendingGit:(e==null?void 0:e.gitProbePending)===!0,connection:e!=null&&e.connection?{state:e.connection.state,transport:e.connection.transport,source:e.connection.source}:null}}function f0(e){const t=Pe(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(d=>p0(d)).filter(d=>d!==null):null;if(!t||!n)return null;const a=hu(n),o=Pe(e.meshName,e.mesh_name,e.name),l=Pe(e.repoIdentity,e.repo_identity),c=Pe(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!o||!l||!c?null:{...e,meshId:t,meshName:o,repoIdentity:l,refreshedAt:c,nodes:a}}function x0(e){var o;let t=0;const r=ft(e.sourceOfTruth),n=ft(r.directPeerTruth);Pe(r.currentStatus)==="live_git_and_session_probes"&&(t+=100),r.coordinatorOwnsLiveTruth===!0&&(t+=25),n.satisfied===!0&&(t+=15);for(const l of e.nodes){const c=l.git;if(!c){l.gitProbePending&&(t-=8);continue}t+=10,c.isGitRepo===!0&&(t+=5),c.isGitRepo===!1&&(t+=1),c.branch&&(t+=4),c.upstream&&(t+=3),c.headCommit&&(t+=3),t+=li(c.upstreamStatus),typeof c.ahead=="number"&&(t+=1),typeof c.behind=="number"&&(t+=1),typeof c.lastCheckedAt=="number"&&(t+=2),t+=(((o=c.submodules)==null?void 0:o.length)??0)*2}return t}function Rl(e){let t=null;for(const r of e){const n=f0(ft(r));if(!n)continue;const a=x0(n);(!t||a>t.score)&&(t={status:n,score:a})}return(t==null?void 0:t.status)??null}function xu(e){const r=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,n=Rl([r==null?void 0:r.status,r]);return n||Rl([e==null?void 0:e.status,e])}const b0=5*60*1e3;function g0(e){return ci(e)}function bu(e){var t;return g0(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function y0(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function gu(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function yu(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function di(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function v0(e){return di(e)?"degraded":yu(e)?"dirty":"online"}function w0(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function Pl(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)=>Pl(r)>Pl(t)?r:t)}function j0(e){var o,l,c,d,m;const t=new Map,r=new Map;for(const u of e){const p=(l=(o=u.git)==null?void 0:o.branch)==null?void 0:l.trim();p&&(r.set(p,(r.get(p)??0)+1),(c=u.git)!=null&&c.upstream&&t.set(p,(t.get(p)??0)+1))}const n=[...t.entries()].sort((u,p)=>{if(p[1]!==u[1])return p[1]-u[1];const x=["main","master","develop","dev"],w=x.indexOf(u[0]),g=x.indexOf(p[0]);return w!==-1||g!==-1?w===-1?1:g===-1?-1:w-g:u[0].localeCompare(p[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((m=[...r.entries()].sort((u,p)=>p[1]-u[1])[0])==null?void 0:m[0])??null}function k0(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 Dl(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 S0(e){return e.reduce((t,r)=>Dl(r.status)>Dl(t.status)?r:t)}function N0(e){const t=e.branchConvergenceSummary;if(Array.isArray(t==null?void 0:t.followUps))return t.followUps;const r=e.followUps;return Array.isArray(r)?r:(t==null?void 0:t.needsFollowUp)===!1||(t==null?void 0:t.unresolvedCount)===0?[]:null}function C0(e,t){return e.type!=="submoduleNode"&&e.branch===t&&e.ahead===0&&e.behind===0&&!e.dirty&&!e.hasConflicts&&(!e.upstreamStatus||e.upstreamStatus==="fresh")&&e.snapshotCompleteness==="complete"}function I0(e,t){var r,n;return{status:"merged_to_main",needsConvergence:!1,reason:"clean_default_branch_aggregate",nextStep:null,branch:e,defaultBranch:e,upstream:((r=t.find(a=>a.upstream))==null?void 0:r.upstream)??null,upstreamStatus:((n=t.find(a=>a.upstreamStatus))==null?void 0:n.upstreamStatus)??null,ahead:0,behind:0,dirty:!1,hasConflicts:!1}}function M0(e,t){if(bu(e))return null;const r=e.branchConvergence;if(!r||typeof r!="object")return null;const n=r.status;if(!n||!["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"].includes(n))return null;const a=e.git,o=gu(a)||yu(a),l=!!(a!=null&&a.hasConflicts)||di(a),c=(a==null?void 0:a.ahead)??0,d=(a==null?void 0:a.behind)??0,m=(a==null?void 0:a.branch)??null,u=(a==null?void 0:a.upstream)??null,p=(a==null?void 0:a.upstreamStatus)??null,x=r.defaultBranch??t??null;return{status:n,needsConvergence:r.needsConvergence??n!=="merged_to_main",reason:r.reason??"provided_by_coordinator",nextStep:r.nextStep??null,branch:r.branch??m,defaultBranch:x,upstream:r.upstream??u,upstreamStatus:r.upstreamStatus??p,ahead:r.ahead??c,behind:r.behind??d,dirty:r.dirty??o,hasConflicts:r.hasConflicts??l}}function T0(e,t){const r=M0(e,t);return r?{...r,defaultBranch:r.defaultBranch??t}:null}function A0(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function _0(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(bu(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const p=t.health==="online"||t.machineStatus==="online"||((d=t.connection)==null?void 0:d.state)==="connected"||((m=t.connection)==null?void 0:m.state)==="self";return a.push(p?`${o} is online but no peer git snapshot is visible yet.`:`${o} has no peer git snapshot visible yet.`),{snapshotCompleteness:"missing_git",snapshotWarnings:a}}const c=new Set((l.submodules??[]).map(p=>p.path));if(r.size>0){const p=[...r].filter(x=>!c.has(x));p.length>0&&a.push(`${o} is missing submodule visibility for ${p.join(", ")} even though another peer reported it.`)}return((u=t.connection)==null?void 0:u.state)!=="self"&&n!==null&&typeof l.lastCheckedAt=="number"&&n-l.lastCheckedAt>b0&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(p=>p.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(p=>p.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function L0(e){var L;const t=fu(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??j0(t.nodes),a=y0(t.refreshedAt),o=new Set(t.nodes.flatMap(N=>{var D;return(((D=N.git)==null?void 0:D.submodules)??[]).map($=>$.path)})),l=[],c=[],d=[],m=new Map;for(const N of t.nodes){const D=N.git,$=(D==null?void 0:D.branch)??null,E=v0(D),C=gu(D)||E==="dirty",I=k0(N,n),O=T0(N,n),P=_0({nodeStatus:N,expectedSubmodulePaths:o,refreshedAtMs:a}),R={id:N.nodeId,type:I.length>0?"orphanNode":"worktreeNode",label:N.machineLabel||N.nodeId.slice(0,8),workspace:N.workspace,branch:$,upstream:(D==null?void 0:D.upstream)??null,upstreamStatus:(D==null?void 0:D.upstreamStatus)??null,machineLabel:N.machineLabel||null,health:Pa([N.health,E]),ahead:(D==null?void 0:D.ahead)??0,behind:(D==null?void 0:D.behind)??0,dirty:C,dirtyFiles:w0(D),hasConflicts:(D==null?void 0:D.hasConflicts)??!1,activeSessionCount:((L=N.activeSessions)==null?void 0:L.length)??0,activeSessions:N.activeSessions??[],providers:N.providers??[],isOrphan:I.length>0,orphanReasons:I,error:N.error,nextStepHint:P.snapshotWarnings[0]??I[0]??(O==null?void 0:O.nextStep)??void 0,parentNodeId:null,submodulePath:null,submoduleCommit:(D==null?void 0:D.headCommit)??null,outOfSync:di(D),snapshotCompleteness:P.snapshotCompleteness,snapshotWarnings:P.snapshotWarnings,branchConvergence:O,source:N};if(l.push(R),$){const U=m.get($)??[];U.push(R.id),m.set($,U)}for(const U of(D==null?void 0:D.submodules)??[]){const W=`${R.id}::submodule::${U.path}`,me=U.path.split("/").filter(Boolean).pop()||U.path;l.push({id:W,type:"submoduleNode",label:me,workspace:U.repoPath,branch:null,upstream:null,upstreamStatus:null,machineLabel:R.machineLabel,health:A0(U),ahead:0,behind:0,dirty:U.dirty,dirtyFiles:U.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],error:U.error,nextStepHint:U.error||(U.outOfSync?`${U.path} is out of sync with the parent checkout`:U.dirty?`${U.path} has local changes`:`${U.path} is in sync with the parent checkout`),parentNodeId:R.id,submodulePath:U.path,submoduleCommit:U.commit,outOfSync:U.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:R.id,parentWorkspace:N.workspace,submodule:U}}),c.push({id:`${R.id}--${W}`,source:R.id,target:W,type:"submoduleLink",label:U.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const u=n?`__branch_${n}`:null;if(u&&n){const D=(m.get(n)??[]).map(R=>l.find(U=>U.id===R)).filter(Boolean),$=D.map(R=>R.branchConvergence).filter(Boolean),E=N0(t),C=D.length>0&&D.every(R=>C0(R,n)),I=(E==null?void 0:E.length)===0&&C?I0(n,D):$.length>0?S0($):null,O=(E==null?void 0:E.length)===0&&C?0:$.filter(R=>R.needsConvergence).length,P={id:u,type:"defaultBranchNode",label:n,workspace:t.repoIdentity,branch:n,upstream:null,upstreamStatus:null,machineLabel:"default branch",health:Pa(D.map(R=>R.health)),ahead:0,behind:0,dirty:D.some(R=>R.dirty),dirtyFiles:D.reduce((R,U)=>R+U.dirtyFiles,0),hasConflicts:D.some(R=>R.hasConflicts),activeSessionCount:D.reduce((R,U)=>R+U.activeSessionCount,0),activeSessions:D.flatMap(R=>R.activeSessions),providers:[...new Set(D.flatMap(R=>R.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:O>0?`${O} workspace(s) on ${n} still need follow-up`:D.length>0?`${D.length} workspace(s) currently on ${n}`:"No workspaces currently checked out to the default branch",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:I,source:{nodeId:u,machineLabel:n,workspace:t.repoIdentity,health:Pa(D.map(R=>R.health)),providers:[],activeSessions:[]}};l.push(P);for(const R of l)if(!(R.id===u||R.type==="submoduleNode")){if(R.branch===n){c.push({id:`${u}--${R.id}`,source:u,target:R.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(R.branch){c.push({id:`${u}--${R.id}`,source:u,target:R.id,type:R.isOrphan?"orphanLink":"parentBranch",label:R.branch,direction:"undirected"});continue}R.isOrphan&&c.push({id:`${u}--${R.id}`,source:u,target:R.id,type:"orphanLink",label:"detached",direction:"undirected"})}}for(const[N,D]of m){if(D.length<2)continue;const $=D.map(E=>l.find(C=>C.id===E)).filter(Boolean);$.sort((E,C)=>E.label.localeCompare(C.label));for(let E=1;E<$.length;E+=1)c.push({id:`wt_${$[E-1].id}--${$[E].id}`,source:$[E-1].id,target:$[E].id,type:"worktreeLink",label:E===1?`${N} peers`:void 0,direction:"undirected"})}const p=l.filter(N=>N.type!=="defaultBranchNode"),x=p.filter(N=>N.isOrphan).length,w=p.filter(N=>N.hasConflicts).length,g=p.filter(N=>N.health==="offline").length,h=p.filter(N=>N.type==="submoduleNode"&&N.outOfSync).length,b=p.filter(N=>{var D;return N.type!=="submoduleNode"&&((D=N.branchConvergence)==null?void 0:D.needsConvergence)}).length,y=p.filter(N=>{var D;return((D=N.branchConvergence)==null?void 0:D.status)==="blocked_review"}).length,f=p.filter(N=>{var D;return((D=N.branchConvergence)==null?void 0:D.status)==="pushed_feature_branch_needs_merge"}).length,M=p.filter(N=>{var D;return((D=N.branchConvergence)==null?void 0:D.status)==="cleanup_candidate"}).length,S=p.filter(N=>{var D;return((D=N.branchConvergence)==null?void 0:D.status)==="not_mergeable"}).length,v=p.filter(N=>N.snapshotWarnings.length>0).length,T=p.filter(N=>N.snapshotCompleteness==="pending_git").length,A=p.filter(N=>N.snapshotCompleteness==="missing_git").length,k=p.filter(N=>N.snapshotCompleteness==="missing_submodule_report").length,j=p.filter(N=>N.snapshotCompleteness==="stale").length,B=[T>0?`${T} node(s) are still waiting for a live peer git snapshot`:null,A>0?`${A} node(s) have no visible peer git snapshot`:null,k>0?`${k} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,j>0?`${j} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return b>0&&d.push(`${b} workspace(s) still need follow-up before the mesh is converged`),x>0&&d.push(`${x} workspace(s) need attention before safe coordination`),y>0&&d.push(`${y} workspace(s) are blocked on branch convergence or upstream sync`),f>0&&d.push(`${f} clean feature branch workspace(s) still need merge follow-up`),M>0&&d.push(`${M} worktree workspace(s) are ready for refine / cleanup`),S>0&&d.push(`${S} workspace(s) have local changes or conflicts blocking convergence`),w>0&&d.push(`${w} workspace(s) report merge conflicts`),g>0&&d.push(`${g} node(s) are currently offline`),h>0&&d.push(`${h} submodule(s) are out of sync with their parent checkout`),d.push(...B),n||d.push("Could not infer a default branch from live mesh status"),{meshId:t.meshId,meshName:t.meshName,repoIdentity:t.repoIdentity,refreshedAt:t.refreshedAt,nodes:l,edges:c,stats:{totalNodes:p.length,onlineNodes:p.filter(N=>N.health==="online").length,dirtyNodes:p.filter(N=>N.dirty).length,orphanNodes:x,errorNodes:p.filter(N=>!!N.error||N.outOfSync).length,offlineNodes:g,followUpNodes:b,blockedReviewNodes:y,mergeReadyNodes:f,cleanupCandidateNodes:M,notMergeableNodes:S,incompleteSnapshotNodes:v,missingGitSnapshotNodes:A,missingSubmoduleSnapshotNodes:k,staleGitSnapshotNodes:j,totalActiveSessions:p.reduce((N,D)=>N+D.activeSessionCount,0)},warnings:d,snapshotWarnings:B}}const R0={recentFailures:0},ui=i.createContext(Zs("dark"));function nt({label:e,tone:t="default"}){const r=i.useContext(ui);return s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${r.badge(t)}`,children:e})}function ss({label:e,value:t}){const r=i.useContext(ui);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 P0(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 D0(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 E0(e){if(!e)return"default";if(e.state==="self")return"info";if(e.transport==="direct"&&e.state==="connected")return"good";if(e.transport==="relay"&&e.state==="connected")return"info";switch(e.state){case"connected":return"good";case"connecting":return"warn";case"disconnected":case"failed":case"closed":return"danger";default:return"default"}}function $0(e){return e?e.state==="self"?"mesh self":e.transport==="direct"&&e.state==="connected"?"mesh direct":e.transport==="relay"&&e.state==="connected"?"mesh relay":!e.reported&&e.source==="not_reported"?"mesh unknown / not reported":`mesh ${e.state}`:"mesh unknown"}function B0(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 El(e){return e?e.slice(0,7):null}function O0(e,t){var o,l,c;const r=El((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?[El(a.commit),a.message].filter(Boolean).join(" · "):null}function F0(e,t){const r=O0(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function W0(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 H0(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 K0(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":$0(e.connection)}function U0(e){var r;const t=e.source;return t!=null&&t.kind?t.kind:((r=t==null?void 0:t.connection)==null?void 0:r.source)??"mesh_status"}function z0(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function vu({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null}){var I,O,P,R,U;const{theme:a}=Qs(),o=i.useMemo(()=>Zs(a),[a]),l=i.useMemo(()=>fu(e),[e]),c=i.useMemo(()=>L0(l),[l]),[d,m]=i.useState(null),[u,p]=i.useState(null),[x,w]=i.useState({}),g=i.useMemo(()=>new Map(l.nodes.map(W=>[W.nodeId,W])),[l.nodes]),h=i.useMemo(()=>new Map(c.nodes.map(W=>[W.id,W])),[c.nodes]),b=((I=l.queue)==null?void 0:I.summary)??null,y=((O=l.ledger)==null?void 0:O.summary)??R0,f=i.useMemo(()=>B0(l),[l]),M=i.useMemo(()=>{const W=new Map;for(const me of f){const ie=me.session.state||me.session.lifecycle||"unknown";W.set(ie,(W.get(ie)??0)+1)}return[...W.entries()].sort((me,ie)=>ie[1]-me[1])},[f]);i.useEffect(()=>{d&&(h.has(d)||(m(null),p(W=>!W||"nodeId"in W&&W.nodeId===d?null:W)))},[h,d]);const S=d?g.get(d)??null:null,v=z0(c,d);i.useEffect(()=>{var W,me,ie;if(d)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:l.meshId,selectedNodeId:d,canonicalNode:h0(S),graphNode:v?{id:v.id,branch:v.branch,upstream:v.upstream,headCommit:v.submoduleCommit,submoduleCount:((me=(W=S==null?void 0:S.git)==null?void 0:W.submodules)==null?void 0:me.length)??0,snapshotCompleteness:v.snapshotCompleteness,snapshotWarnings:v.snapshotWarnings,branchConvergence:((ie=v.branchConvergence)==null?void 0:ie.status)??null}:null})}catch{}},[l.meshId,v,d,S]);const T=(u==null?void 0:u.kind)==="session"?f.find(W=>W.nodeId===u.nodeId&&W.session.sessionId===u.sessionId)??null:null,A=i.useMemo(()=>f.filter(W=>W.nodeId===d),[d,f]),k=H0({coordinatorDaemonId:r,selectedNodeStatus:S,selectedSessionEntry:T}),j=(k==null?void 0:k.workspace)??null,B=j?x[j]??null:null,L=F0(S,(B==null?void 0:B.entries)??[]),N=i.useCallback(()=>{m(null),p(null)},[]);i.useEffect(()=>{if(!v)return;const W=me=>{me.key==="Escape"&&N()};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[N,v]),i.useEffect(()=>{if(!k||!n)return;const{daemonId:W,workspace:me}=k,ie=x[me];if(ie!=null&&ie.loading||ie&&(ie.entries.length>0||ie.error))return;let ee=!1;return w(ce=>{var je;return{...ce,[me]:{loading:!0,error:null,entries:((je=ce[me])==null?void 0:je.entries)??[]}}}),n(W,"git_log",{workspace:me,limit:5}).then(ce=>{ee||w(je=>({...je,[me]:{loading:!1,error:null,entries:W0(ce)}}))}).catch(ce=>{ee||w(je=>({...je,[me]:{loading:!1,error:ce instanceof Error?ce.message:"git_log failed",entries:[]}}))}),()=>{ee=!0}},[x,k,n]);const D=[...c.warnings??[],...l.nodes.filter(W=>W.machineStatus&&W.machineStatus!=="online").map(W=>`${W.machineLabel}: ${W.machineStatus}`)],$=c.stats.incompleteSnapshotNodes>0,E=c.stats.followUpNodes>0?`${c.stats.followUpNodes} need follow-up`:$?"mesh visibility incomplete":"mesh converged",C=c.stats.followUpNodes>0?"danger":$?"warn":"good";return s.jsx(ui.Provider,{value:o,children:s.jsx("div",{className:"flex min-h-0 flex-col gap-4",children:s.jsx("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-4",children:s.jsxs("div",{className:`${o.cardClass} relative min-h-0 flex-1 rounded-[28px] p-3 sm:p-4`,style:{minHeight:420},children:[s.jsxs("div",{className:`absolute inset-x-4 top-4 z-30 flex max-h-[42dvh] flex-wrap items-start justify-between gap-3 overflow-y-auto rounded-2xl px-3.5 py-3 backdrop-blur-xl sm:static sm:mb-3 sm:max-h-none sm:overflow-visible sm:backdrop-blur-none ${o.isDark?"border border-white/10 bg-slate-950/85 sm:bg-slate-950/45":"border border-slate-200 bg-white/95 shadow-lg shadow-slate-900/10 sm:bg-white/95 sm:shadow-sm"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-wrap gap-2 text-xs ${o.textSecondary}`,children:[s.jsx(nt,{label:E,tone:C}),c.stats.blockedReviewNodes>0&&s.jsx(nt,{label:`${c.stats.blockedReviewNodes} blocked review`,tone:"danger"}),c.stats.notMergeableNodes>0&&s.jsx(nt,{label:`${c.stats.notMergeableNodes} not mergeable`,tone:"danger"}),c.stats.mergeReadyNodes>0&&s.jsx(nt,{label:`${c.stats.mergeReadyNodes} need merge`,tone:"warn"}),c.stats.cleanupCandidateNodes>0&&s.jsx(nt,{label:`${c.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),c.stats.offlineNodes>0&&s.jsx(nt,{label:`${c.stats.offlineNodes} offline`,tone:"danger"}),c.stats.incompleteSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),c.stats.missingGitSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),c.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),c.stats.staleGitSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((b==null?void 0:b.active)??0)>0&&s.jsx(nt,{label:`${(b==null?void 0:b.active)??0} active queue`,tone:"info"}),s.jsx(nt,{label:`${c.stats.totalNodes} nodes`,tone:"default"}),c.stats.totalActiveSessions>0&&s.jsx(nt,{label:`${c.stats.totalActiveSessions} active sessions`,tone:"info"})]}),s.jsxs("details",{className:`max-w-full rounded-xl px-3 py-2 text-xs ${o.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${o.textSecondary} [&::-webkit-details-marker]:hidden`,children:"Legend & secondary details"}),s.jsxs("div",{className:"mt-3 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(nt,{label:`${c.stats.dirtyNodes} dirty`,tone:c.stats.dirtyNodes>0?"warn":"good"}),s.jsx(nt,{label:`${c.stats.orphanNodes} orphan`,tone:c.stats.orphanNodes>0?"warn":"good"}),s.jsx(nt,{label:`${y.recentFailures} recent failures`,tone:y.recentFailures>0?"danger":"good"}),M.length===0?s.jsx(nt,{label:"no session metadata"}):M.slice(0,2).map(([W,me])=>s.jsx(nt,{label:`${me} ${W}`,tone:D0(W)},W))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(nt,{label:"Anchor = default branch",tone:"info"}),s.jsx(nt,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(nt,{label:"Submodule link = child checkout",tone:"warn"})]}),D.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:D.map(W=>s.jsx("span",{className:o.isDark?"rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1 text-xs text-amber-100":"rounded-full border border-amber-300 bg-amber-50 px-3 py-1 text-xs text-amber-700",children:W},W))}),s.jsx("div",{className:`text-xs ${o.textMuted}`,children:"Click a node only when you want drill-down details. The graph itself now carries the convergence state."})]})]})]}),c.nodes.length>0?s.jsx(e0,{data:c,selectedNodeId:d,onNodeClick:W=>{if((u==null?void 0:u.kind)==="node"&&d===W.id){m(null),p(null);return}m(W.id),p({kind:"node",nodeId:W.id})}}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:t}),v&&(u==null?void 0:u.kind)==="node"&&s.jsx("div",{className:"absolute inset-x-3 bottom-3 top-20 z-20 flex items-end justify-center p-2 sm:inset-5 sm:top-24 sm:items-start sm:justify-end",onClick:N,role:"presentation",children:s.jsxs("section",{role:"dialog","aria-modal":"false","aria-label":"Selected node",className:o.isDark?"max-h-[min(72vh,540px)] w-full max-w-[min(28rem,calc(100vw-2.5rem))] overflow-y-auto rounded-2xl border border-white/12 bg-slate-950/96 p-4 shadow-2xl shadow-black/40 backdrop-blur-xl":"max-h-[min(72vh,540px)] w-full max-w-[min(28rem,calc(100vw-2.5rem))] overflow-y-auto rounded-2xl border border-slate-200 bg-white/96 p-4 shadow-2xl shadow-slate-900/15 backdrop-blur-xl",onClick:W=>W.stopPropagation(),children:[s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${o.textPrimary}`,children:v.label}),s.jsx("div",{className:`mt-1 font-mono text-[11px] ${o.textMuted}`,children:v.id.slice(0,16)})]}),s.jsx("button",{type:"button",onClick:N,className:o.isDark?"rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-xs text-slate-200 transition hover:bg-white/[0.08]":"rounded-full border border-slate-200 bg-white px-2.5 py-1 text-xs text-slate-600 transition hover:bg-slate-50",children:"Close"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[s.jsx(nt,{label:(S==null?void 0:S.health)??v.health,tone:P0((S==null?void 0:S.health)??v.health)}),v.branch&&s.jsx(nt,{label:v.branch,tone:"default"}),v.ahead>0&&s.jsx(nt,{label:`ahead ${v.ahead}`,tone:"warn"}),v.behind>0&&s.jsx(nt,{label:`behind ${v.behind}`,tone:"warn"}),v.dirtyFiles>0&&s.jsx(nt,{label:`${v.dirtyFiles} dirty`,tone:"warn"}),(S==null?void 0:S.connection)&&s.jsx(nt,{label:K0(S),tone:E0(S.connection)}),A.length>0&&s.jsx(nt,{label:`${A.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[s.jsx(ss,{label:"Workspace",value:(S==null?void 0:S.workspace)??v.workspace}),s.jsx(ss,{label:"Branch",value:v.branch??"unknown"}),s.jsx(ss,{label:"HEAD",value:L??(S!=null&&S.gitProbePending?"Pending live git probe":"not reported")}),s.jsx(ss,{label:"Upstream",value:v.upstream??"none"}),s.jsx(ss,{label:"Dirty/ahead/behind",value:`${v.dirtyFiles} dirty · ↑${v.ahead}/↓${v.behind}`}),s.jsx(ss,{label:"Source",value:String(((P=S==null?void 0:S.connection)==null?void 0:P.source)??U0(v))}),s.jsx(ss,{label:"Transport",value:((R=S==null?void 0:S.connection)==null?void 0:R.transport)??"unknown"}),s.jsx(ss,{label:"Sessions",value:A.length>0?A.map(W=>W.session.state||W.session.lifecycle||"unknown").join(", "):"none active"})]}),v.snapshotWarnings.length>0&&s.jsxs("div",{className:o.isDark?"mt-3 rounded-xl border border-amber-400/20 bg-amber-500/10 p-3 text-xs text-amber-100":"mt-3 rounded-xl border border-amber-300 bg-amber-50 p-3 text-xs text-amber-800",children:[s.jsx("div",{className:"font-medium",children:"Key warning"}),s.jsx("div",{className:"mt-1",children:v.snapshotWarnings[0]})]}),((U=v.branchConvergence)==null?void 0:U.nextStep)&&s.jsxs("div",{className:o.isDark?"mt-3 rounded-xl border border-sky-400/20 bg-sky-500/10 p-3 text-xs text-sky-100":"mt-3 rounded-xl border border-sky-300 bg-sky-50 p-3 text-xs text-sky-800",children:[s.jsx("div",{className:"font-medium",children:"Follow-up"}),s.jsx("div",{className:"mt-1",children:v.branchConvergence.nextStep})]})]})})]})})})})}function G0({activeConv:e,sendDaemonCommand:t,onClose:r}){var v;const n=typeof((v=e.settings)==null?void 0:v.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null,a=e.daemonId??null,o=Ed(),{theme:l}=Qs(),c=i.useMemo(()=>Zs(l),[l]),[d,m]=i.useState(null),[u,p]=i.useState(!1),[x,w]=i.useState(null),[g,h]=i.useState(null),b=i.useRef(!1);i.useEffect(()=>{b.current=d!==null},[d]);const y=i.useCallback(async(T=!1)=>{if(!a||!n){w("This coordinator does not expose a live mesh id."),m(null);return}p(!b.current),w(null);try{const A=o!=null&&o.loadMeshStatus?await o.loadMeshStatus(a,n,{refresh:T}):await t(a,"mesh_status",{meshId:n,refresh:T}),k=xu(A);if(!k){w("mesh_status returned an unexpected payload.");return}m(k),h(k.refreshedAt||new Date().toISOString())}catch(A){w(A instanceof Error?A.message:"Failed to load live mesh status")}finally{p(!1)}},[a,n,o,t]);i.useEffect(()=>{y(!1)},[y]),i.useEffect(()=>{const T=A=>{A.key==="Escape"&&r()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[r]);const f=(d==null?void 0:d.meshName)||n||"Repo Mesh",M=g?new Date(g).toLocaleTimeString():null,S=i.useMemo(()=>u?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[u]);return s.jsx("div",{className:c.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:c.dialogShellClass,onClick:T=>T.stopPropagation(),children:[s.jsxs("div",{className:c.dialogHeaderClass,children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-400/20 bg-sky-500/12 text-sky-200 shadow-[0_12px_30px_rgba(14,165,233,0.18)]",children:s.jsx(ns,{size:18})}),s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("h2",{className:c.dialogTitleClass,children:f}),s.jsx("span",{className:c.dialogKickerClass,children:"Mesh observability"})]}),s.jsxs("p",{className:c.dialogSubtitleClass,children:[ut(e),e.workspaceName?` · ${e.workspaceName}`:"",d!=null&&d.repoIdentity?` · ${d.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[M&&s.jsxs("span",{className:c.dialogRefreshedChipClass,children:["Refreshed ",M]}),s.jsx("button",{type:"button",onClick:()=>{y(!0)},disabled:u,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:u?"Refreshing…":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:c.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:s.jsx(jt,{size:16})})]})]}),x&&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:x}),s.jsx("div",{className:c.dialogBodyClass,children:d?s.jsx(vu,{status:d,emptyMessage:S,daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:c.dialogEmptyClass,children:S})})]})})}function V0(e,t){const{sendCommand:r}=kt(),[n,a]=i.useState(null),[o,l]=i.useState(!1);i.useEffect(()=>{if(!e||!t){a(null);return}l(!0),r(e,"git_remote_url",{workspace:t}).then(d=>{const m=(d==null?void 0:d.result)??d;a(typeof(m==null?void 0:m.remoteUrl)=="string"?m.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>l(!1))},[e,t,r]);const c=q0(n);return{remoteUrl:n,githubUrl:c,loading:o}}function q0(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 wu=5e3;function Y0(e){return`git:${e}`}function X0({workspace:e,includeDiffSummary:t=!1,intervalMs:r=wu}){return{type:"subscribe",topic:"workspace.git",key:Y0(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 J0(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 Q0(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 Da(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"&&Da(t.binary)&&Da(t.truncated)&&Da(t.staged)}function ev(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 tv({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=wu}){const{sendCommand:o,sendData:l}=kt(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[m,u]=i.useState(null),[p,x]=i.useState(null),[w,g]=i.useState(!1),[h,b]=i.useState(null),y=i.useCallback(async()=>{if(!(!d||!e||!c)){g(!0),b(null);try{const M=J0(await o(e,"git_status",{workspace:c}));if(M.error){u(null),x(null),b(M.error);return}if(u(M.status),!n){x(null);return}const S=Q0(await o(e,"git_diff_summary",{workspace:c}));if(S.error){x(null),b(S.error);return}x(S.diffSummary)}catch(M){b(Ms(M,"Git status request failed"))}finally{g(!1)}}},[d,e,n,o,c]),f=i.useMemo(()=>c?X0({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return i.useEffect(()=>{if(!d||!e||!c||!f){u(null),x(null),g(!1),b(null);return}const M=l?Jt.subscribe({sendData:l},e,f,S=>{var v,T;S.workspace===c&&(u(S.status),x(S.diffSummary??null),b(((v=S.status)==null?void 0:v.error)||((T=S.diffSummary)==null?void 0:T.error)||null),g(!1))},{retryIntervalMs:1e3}):null;return y(),()=>{M==null||M()}},[d,e,y,f,l,c]),{status:m,diffSummary:p,loading:w,error:h,refresh:y}}const sv={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},rv={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 $l(e){return e.split("/").pop()??e}function nv(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function av({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=sv[o.status]??"?",d=rv[o.status]??"text-zinc-400",m=nv(o.path),u=$l(o.path),p=o.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${l?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(o),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:o.status,children:c}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&s.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),s.jsx("span",{className:"text-text-primary",children:u}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",$l(o.oldPath)]}),p]}),!o.binary&&(o.insertions>0||o.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",o.insertions]}),o.insertions>0&&o.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),o.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",o.deletions]})]}),o.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${o.path}-${o.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function ov(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 iv({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)=>ov(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 lv(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 ju({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=kt(),{status:a,diffSummary:o,loading:l,error:c,refresh:d}=tv({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=i.useState(null),[p,x]=i.useState(null),[w,g]=i.useState(""),[h,b]=i.useState(!1),[y,f]=i.useState(!1),[M,S]=i.useState(null),[v,T]=i.useState(null),{githubUrl:A}=V0(e,t),k=i.useCallback(async $=>{if(!((m==null?void 0:m.path)===$.path&&!m.loading)){u({path:$.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const E=await n(e,"git_diff_file",{workspace:t,path:$.path,staged:$.staged}),C=ev(E);if(C.error||!C.diff){u({path:$.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C.error??"Failed to load diff"});return}u({path:$.path,diff:C.diff.diff,binary:C.diff.binary??!1,truncated:C.diff.truncated??!1,loading:!1,error:null})}catch(E){const C=E instanceof Error?E.message:"Failed to load diff";u({path:$.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C})}}},[e,n,m,t]),j=i.useCallback($=>{g(""),b(!1),S(null),T(null),x($)},[]),B=i.useCallback(()=>{x(null),S(null),f(!1)},[]),L=i.useCallback(async()=>{var $,E,C;if(p){f(!0),S(null);try{let I;p==="checkpoint"?I=await n(e,"git_checkpoint",{workspace:t,message:w,includeUntracked:h}):p==="stash"?I=await n(e,"git_stash_push",{workspace:t,message:w,includeUntracked:h}):p==="stash_pop"?I=await n(e,"git_stash_pop",{workspace:t}):p==="checkout_files"&&m&&(I=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const O=(I==null?void 0:I.result)??I;if((O==null?void 0:O.success)===!1||O!=null&&O.error){S((O==null?void 0:O.error)??"Action failed"),f(!1);return}p==="checkpoint"?T(`Checkpoint created: ${((E=($=O==null?void 0:O.checkpoint)==null?void 0:$.commit)==null?void 0:E.slice(0,7))??"done"}`):p==="stash"?T(`Stashed as ${((C=O==null?void 0:O.stash)==null?void 0:C.stashRef)??"stash@{0}"}`):p==="stash_pop"?T("Stash restored"):(T("File reverted"),u(null)),x(null),await d()}catch(I){S(I instanceof Error?I.message:"Action failed")}finally{f(!1)}}},[p,n,e,t,w,h,m,d]),N=!!(a!=null&&a.hasConflicts),D=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:$=>{$.target===$.currentTarget&&r()},children:s.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),A&&s.jsx("a",{href:`${A}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-sky-400 underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:d,disabled:l,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),s.jsx("button",{onClick:r,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(jt,{className:"h-4 w-4"})})]}),a&&s.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[a.headCommit&&s.jsxs("span",{title:a.headMessage??void 0,children:[s.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&s.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&s.jsxs("span",{className:"text-orange-400",children:["↑",a.ahead," ahead"]}),a.behind>0&&s.jsxs("span",{className:"text-orange-400",children:["↓",a.behind," behind"]}),a.staged>0&&s.jsxs("span",{className:"text-emerald-400",children:[a.staged," staged"]}),a.modified>0&&s.jsxs("span",{children:[a.modified," modified"]}),a.untracked>0&&s.jsxs("span",{children:[a.untracked," untracked"]}),a.deleted>0&&s.jsxs("span",{className:"text-red-400",children:[a.deleted," deleted"]}),a.stashCount>0&&s.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&s.jsx("span",{className:"font-bold text-red-400",children:"conflicts"}),D===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(av,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:k}),!l&&!o&&!c&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:m?s.jsx(iv,{diff:m.diff,binary:m.binary,truncated:m.truncated,loading:m.loading,error:m.error,className:"h-full"}):s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),v&&s.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-emerald-500/10 px-4 py-2 text-xs text-emerald-400 flex items-center justify-between",children:[s.jsx("span",{children:v}),s.jsx("button",{onClick:()=>T(null),className:"ml-2 text-emerald-400 hover:text-text-primary",children:"×"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[s.jsx("button",{onClick:()=>j("checkpoint"),disabled:N,title:N?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),s.jsx("button",{onClick:()=>j("stash"),disabled:N,title:N?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),s.jsx("button",{onClick:()=>j("stash_pop"),disabled:N||!(a!=null&&a.stashCount),title:N?"Resolve conflicts before restoring a stash":a!=null&&a.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),s.jsx("button",{onClick:()=>j("checkout_files"),disabled:!m,title:m?`Revert changes to ${m.path}`:"Select a file to revert",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkout selected"}),o&&o.files.length>0&&s.jsx("button",{onClick:()=>{const $=lv((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText($),T("Copied to clipboard"),setTimeout(()=>T(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),p&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[p==="checkpoint"&&"Create checkpoint commit",p==="stash"&&"Stash changes",p==="stash_pop"&&"Restore latest stash?",p==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(p==="checkpoint"||p==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:w,onChange:$=>g($.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:h,onChange:$=>b($.target.checked)}),"Include untracked files"]})]}),M&&s.jsx("p",{className:"text-xs text-red-400",children:M}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:B,disabled:y,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),s.jsx("button",{onClick:L,disabled:y||(p==="checkpoint"||p==="stash")&&!w.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:y?"Working…":"Confirm"})]})]})})]})})}function cv({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=i.useState(!1),[o,l]=i.useState(!1),[c,d]=i.useState(!1),[m,u]=i.useState(!1),[p,x]=i.useState(!1),[w,g]=i.useState("quickstart"),[h,b]=i.useState("workspace"),y=i.useMemo(()=>!t&&!e,[t,e]),f=i.useCallback(k=>{a(k),k&&l(!1)},[]),M=i.useCallback(k=>{l(k),k&&a(!1)},[]),S=i.useCallback(()=>{g(r===0?"quickstart":"shortcuts"),b("workspace"),d(!0),a(!1),l(!1)},[r]),v=i.useCallback(()=>{d(!1)},[]),T=i.useCallback(()=>{u(!0)},[]),A=i.useCallback(()=>{u(!1)},[]);return i.useEffect(()=>{if(!y){x(!1);return}x(!0);const k=window.setTimeout(()=>{x(!1)},1e4);return()=>window.clearTimeout(k)},[y]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:m,guideNudgeVisible:p,guideTab:w,shortcutSection:h,isDesktopDashboard:y,setGuideTab:g,setShortcutSection:b,handleInboxOpenChange:f,handleHiddenOpenChange:M,handleOpenShortcutHelp:S,closeShortcutHelp:v,openNewSession:T,closeNewSession:A}}function dv(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 uv(e){return e instanceof Error?e.message:String(e||"")}function mv(e){const t=uv(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function pv({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:l,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:p,ides:x,actionLogs:w,sendDaemonCommand:g,setActionLogs:h,setCliViewModeOverrides:b,isStandalone:y,initialDataLoaded:f,userName:M,requestedMobileTabKey:S,onRequestedMobileTabConsumed:v,requestedMachineId:T,onRequestedMachineConsumed:A,requestedMobileSection:k,onRequestedMobileSectionConsumed:j,containerRef:B,isSplitMode:L,numGroups:N,groupSizes:D,groupedConvs:$,clearedTabs:E,focusedGroup:C,focusGroup:I,moveTabToGroup:O,splitTabRelative:P,closeGroup:R,handleResizeStart:U,groupActiveTabIds:W,setGroupActiveTab:me,groupTabOrders:ie,setGroupTabOrder:ee,toggleHiddenTab:ce,visibleConversations:je,requestedDesktopTabKey:Ne,onRequestedDesktopTabConsumed:q,onDesktopActiveTabChange:ge,onRequestScrollToBottom:fe,onHideConversation:we,onShowHiddenConversation:xe,onShowAllHiddenConversations:Se,scrollToBottomRequest:J,machineEntries:he,layoutProfile:ae,onBrowseMachineDirectory:ue,onSaveMachineWorkspace:oe,onLaunchMachineIde:de,onLaunchMachineProvider:Q,onListMachineMeshes:ve,onLaunchMeshCoordinator:le,onListMachineSavedSessions:pe,notifications:ne,notificationUnreadCount:Ie,liveSessionInboxState:Ce,onMarkNotificationRead:_e,onMarkNotificationUnread:K,onDeleteNotification:Me}){const Te=St.useRef(null),{inboxOpen:He,hiddenOpen:Ge,shortcutHelpOpen:Xe,newSessionOpen:Ye,guideNudgeVisible:tt,guideTab:ct,shortcutSection:mt,isDesktopDashboard:pt,setGuideTab:F,setShortcutSection:be,handleInboxOpenChange:Ae,handleHiddenOpenChange:Be,handleOpenShortcutHelp:qe,closeShortcutHelp:G,openNewSession:z,closeNewSession:X}=cv({isMobile:t,showMobileChatMode:e,visibleConversationCount:je.length}),[se,H]=St.useState(null),[V,te]=St.useState(null),re=St.useCallback((_,Y)=>{H({daemonId:_,workspace:Y})},[]),ke=St.useCallback(_=>{te(_)},[]),Ee=St.useCallback(_=>{var Y;Nr.flushSync(()=>{xe(_)}),(Y=Te.current)==null||Y.restoreHiddenTabToSavedLocation(_.tabKey)},[xe]),Oe=St.useCallback(_=>{var ye;const Y=u.find(We=>no(We,_))||p.find(We=>no(We,_));Y&&(p.some(We=>We.tabKey===Y.tabKey)&&Ee(Y),ge(Y.tabKey),(ye=Te.current)==null||ye.activateConversationTab(Y.tabKey),fe(Y.tabKey,"notification-open")),_e(_.id),Ae(!1)},[Ee,p,u,ge,_e,fe]),Re=St.useCallback(()=>{var Y;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Y=Te.current)==null||Y.resetAllPanelsToMain(),Be(!1))},[Be]),Fe=St.useCallback(async _=>{var Ke;if(!r)return;const Y=(Ke=r.modalButtons)==null?void 0:Ke[_];if(!Y)return;const ye=Us(r);if(!ye)return;const We=Y.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),De=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(We);try{await g(ye,"resolve_action",{button:Y,action:De?"approve":"reject",buttonIndex:_,...fs(r)})}catch(rt){mv(rt)||console.error("[Shortcut approval] Failed:",rt)}},[r,g]),{isMac:Ue,actionDefinitions:Le,actionShortcuts:Ze,shortcutListening:et,shortcutListeningDraft:gt,setShortcutListening:yt,setShortcutListeningDraft:dt,saveShortcuts:xt}=fy({enabled:pt&&!Xe,onTrigger:_=>{var Y,ye,We,De,Ke,rt,Tt,bt,es,Er,$r,Br,Or,Fr,Wr,Hr;if(_==="openShortcutHelp"){qe();return}if(_==="openNewSession"){z();return}if(_==="hideCurrentTab"){r&&we(r);return}if(_==="toggleHiddenTabs"){Be(!Ge);return}if(_==="openHistoryForActiveTab"){r&&!st(r)&&o(r);return}if(_==="openRemoteForActiveTab"){r&&!at(r)&&!st(r)&&l(r);return}if(_==="splitActiveTabRight"){(Y=Te.current)==null||Y.splitActiveTabRight();return}if(_==="splitActiveTabDown"){(ye=Te.current)==null||ye.splitActiveTabDown();return}if(_==="floatActiveTab"){(We=Te.current)==null||We.floatActiveTab();return}if(_==="popoutActiveTab"){(De=Te.current)==null||De.popoutActiveTab();return}if(_==="dockActiveTab"){(Ke=Te.current)==null||Ke.dockActiveTab();return}if(_==="focusLeftPane"){(rt=Te.current)==null||rt.focusLeftPane();return}if(_==="focusRightPane"){(Tt=Te.current)==null||Tt.focusRightPane();return}if(_==="focusUpPane"){(bt=Te.current)==null||bt.focusUpPane();return}if(_==="focusDownPane"){(es=Te.current)==null||es.focusDownPane();return}if(_==="moveActiveTabToLeftPane"){(Er=Te.current)==null||Er.moveActiveTabToLeftPane();return}if(_==="moveActiveTabToRightPane"){($r=Te.current)==null||$r.moveActiveTabToRightPane();return}if(_==="moveActiveTabToUpPane"){(Br=Te.current)==null||Br.moveActiveTabToUpPane();return}if(_==="moveActiveTabToDownPane"){(Or=Te.current)==null||Or.moveActiveTabToDownPane();return}if(_==="triggerPrimaryApprovalAction"){Fe(0);return}if(_==="triggerSecondaryApprovalAction"){Fe(1);return}if(_==="triggerTertiaryApprovalAction"){Fe(2);return}if(_==="setActiveTabShortcut"){(Fr=Te.current)==null||Fr.setShortcutForActiveTab();return}if(_==="selectPreviousGroupTab"){(Wr=Te.current)==null||Wr.activatePreviousTabInGroup();return}if(_==="selectNextGroupTab"){(Hr=Te.current)==null||Hr.activateNextTabInGroup();return}!r||!at(r)||st(r)||_==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),Ve=St.useCallback(()=>{G(),yt(null),dt([])},[G,yt,dt]),Ht=St.useMemo(()=>mt==="all"?Le:Le.filter(_=>dv(_)===mt),[Le,mt]),Z=St.useCallback(()=>{const _=Object.fromEntries(Le.map(Y=>[Y.id,""]));xt(_)},[Le,xt]),$e=St.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const _=Object.fromEntries(Le.map(Y=>[Y.id,Y.defaultShortcut]));xt(_)},[Le,xt]);return St.useEffect(()=>{const _=Y=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Y.metaKey&&Y.key.toLowerCase()==="w":Y.ctrlKey&&Y.key.toLowerCase()==="w")&&(Y.preventDefault(),r&&we&&we(r))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[r,we]),St.useEffect(()=>{if(!Xe||et)return;const _=Y=>{Y.key==="Escape"&&(Y.preventDefault(),Ve())};return window.addEventListener("keydown",_,!0),()=>window.removeEventListener("keydown",_,!0)},[Ve,Xe,et]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(px,{activeConv:r,wsStatus:n,isConnected:a,conversations:je,hiddenConversations:p,onOpenHistory:o,onHideConversation:we,onShowConversation:Ee,onShowAllHidden:Se,onResetPanelsToMain:Re,notifications:ne,notificationUnreadCount:Ie,onOpenNotification:Oe,onMarkNotificationRead:_e,onMarkNotificationUnread:K,onDeleteNotification:Me,inboxOpen:He,onInboxOpenChange:Ae,hiddenOpen:Ge,onHiddenOpenChange:Be,onOpenNewSession:t?void 0:z,onOpenDashboardGuide:qe,guideNudgeVisible:tt,actionShortcuts:Ze,onOpenRemote:()=>{!r||at(r)||st(r)||l(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:re,onOpenMeshGraph:ke}),e?s.jsx(ry,{conversations:u,hiddenConversations:p,ides:x,actionLogs:w,sendDaemonCommand:g,setActionLogs:h,setCliViewModeOverrides:b,isStandalone:y,userName:M,requestedActiveTabKey:S,onRequestedActiveTabConsumed:v,requestedMachineId:T,onRequestedMachineConsumed:A,requestedMobileSection:k,onRequestedMobileSectionConsumed:j,onOpenHistory:o,onOpenRemote:l,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Se,onHideConversation:we,onOpenMeshGraph:ke,onOpenNewSession:z,liveSessionInboxState:Ce}):t?s.jsx(uy,{containerRef:B,isSplitMode:L,numGroups:N,groupSizes:D,groupedConvs:$,clearedTabs:E,ides:x,actionLogs:w,sendDaemonCommand:g,setActionLogs:h,isStandalone:y,hasRegisteredMachines:he.length>0,userName:M,focusedGroup:C,focusGroup:I,moveTabToGroup:O,splitTabRelative:P,closeGroup:R,handleResizeStart:U,groupActiveTabIds:W,setGroupActiveTab:me,groupTabOrders:ie,setGroupTabOrder:ee,toggleHiddenTab:ce,onOpenNewSession:z,allowTabShortcuts:!1,liveSessionInboxState:Ce}):s.jsx(Ty,{visibleConversations:je,clearedTabs:E,ides:x,actionLogs:w,sendDaemonCommand:g,setActionLogs:h,isStandalone:y,hasRegisteredMachines:he.length>0,initialDataLoaded:f,userName:M,toggleHiddenTab:ce,actionShortcuts:Ze,registerActionHandlers:_=>{Te.current=_},onActiveTabChange:ge,requestedActiveTabKey:Ne,onRequestedActiveTabConsumed:q,onRequestScrollToBottom:fe,scrollToBottomRequest:J,onOpenNewSession:z,liveSessionInboxState:Ce,layoutProfile:ae}),Ye&&s.jsx(Py,{machines:he,ides:x,onClose:X,onBrowseDirectory:ue,onSaveWorkspace:oe,onLaunchIde:de,onLaunchProvider:Q,onListMeshes:ve,onLaunchMeshCoordinator:le,onListSavedSessions:pe}),V&&s.jsx(G0,{activeConv:V,sendDaemonCommand:g,onClose:()=>te(null)}),se&&s.jsx(ju,{daemonId:se.daemonId,workspace:se.workspace,onClose:()=>H(null)}),Xe&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:Ve,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",onClick:_=>_.stopPropagation(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:Ve,"aria-label":"Close dashboard guide",children:s.jsx(jt,{size:14})})]}),s.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(_=>s.jsx("button",{type:"button",className:`btn btn-sm ${ct===_.id?"btn-primary":"btn-secondary"}`,onClick:()=>F(_.id),children:_.label},_.id))}),ct==="overview"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Ue?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),ct==="quickstart"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),ct==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(_=>s.jsx("button",{type:"button",className:`btn btn-sm ${mt===_.id?"btn-primary":"btn-secondary"}`,onClick:()=>be(_.id),children:_.label},_.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Z,children:"Disable all"}),s.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:$e,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Ht.map(_=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${et===_.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:_.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:_.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:_.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:et===_.id?gt.length>0?`${gt.join(" ")} ...`:"Listening...":Ze[_.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{yt(_.id),dt([])},children:et===_.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Y={...Ze};Y[_.id]="",xt(Y)},children:"Disable"})]})]})},_.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Ue?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",", or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs."]})]})]})})]})}const Ea=[{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 hv({onClose:e}){const[t,r]=i.useState(0),n=Ea[t],a=t===Ea.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:o=>{o.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(jt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Ea.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
+ `,V.style.top="52px",V.style.height="calc(100% - 52px)";const Fe=Re.querySelector("[data-adhdev-popout-focus]");Fe&&(Fe.onclick=()=>{window.focus()});const Ue=Re.querySelector("[data-adhdev-popout-dock]");Ue&&(Ue.disabled=!te,Ue.style.opacity=te?"1":"0.5",Ue.style.cursor=te?"pointer":"default",Ue.onclick=()=>{var Le;te&&Ne(te),(Le=H.defaultView)==null||Le.focus()})}},[U,Ne]),ae=i.useCallback(G=>{var se;const z=k.current,X=z==null?void 0:z.getPanel(G);if(!(!z||!X)){X.group.model.openPanel(X),X.api.setActive(),ie(G,"dockview-shortcut");try{const H=X.group.model.location;H.type==="popout"?H.getWindow().focus():Ta((se=X.group.element)==null?void 0:se.ownerDocument)}catch{}}},[ie]),ue=i.useCallback(G=>{const z=k.current,X=z==null?void 0:z.activePanel,se=(z==null?void 0:z.activeGroup)||(X==null?void 0:X.group);if(!z||!X||!se)return;const H=se.panels||[];if(H.length<=1)return;const V=H.findIndex(ke=>ke.id===X.id);if(V<0)return;const te=(V+G+H.length)%H.length,re=H[te];re&&(re.group.model.openPanel(re),re.api.setActive(),Bt(re.id)||ie(re.id,"dockview-shortcut"))},[ie]),oe=i.useCallback(G=>{var Fe;const z=k.current,X=(z==null?void 0:z.activeGroup)||((Fe=z==null?void 0:z.activePanel)==null?void 0:Fe.group);if(!z||!X)return;const se=z.groups||[],H=se.find(Ue=>Ue.id===X.id);if(!H)return;const V=H.element.getBoundingClientRect(),te=V.left+V.width/2,re=V.top+V.height/2,ke=(Ue,Le,Ze,et)=>Math.max(0,Math.min(Le,et)-Math.max(Ue,Ze)),Ee=Ue=>{const Le=Ue.element.getBoundingClientRect(),Ze=Le.left+Le.width/2,et=Le.top+Le.height/2;let gt=0,yt=0,dt=0,xt=!1;if(G==="left"?(xt=Ze<te,gt=Math.max(0,V.left-Le.right),yt=Math.abs(et-re),dt=ke(V.top,V.bottom,Le.top,Le.bottom)):G==="right"?(xt=Ze>te,gt=Math.max(0,Le.left-V.right),yt=Math.abs(et-re),dt=ke(V.top,V.bottom,Le.top,Le.bottom)):G==="above"?(xt=et<re,gt=Math.max(0,V.top-Le.bottom),yt=Math.abs(Ze-te),dt=ke(V.left,V.right,Le.left,Le.right)):(xt=et>re,gt=Math.max(0,Le.top-V.bottom),yt=Math.abs(Ze-te),dt=ke(V.left,V.right,Le.left,Le.right)),!xt)return Number.POSITIVE_INFINITY;const Ve=dt>0?0:120;return gt*3+yt+Ve};let Oe=null,Re=Number.POSITIVE_INFINITY;for(const Ue of se){if(Ue.id===H.id)continue;const Le=Ee(Ue);Number.isFinite(Le)&&(Le>=Re||(Re=Le,Oe=Ue))}return Oe||void 0},[]),de=i.useCallback(G=>{var se;const z=oe(G);if(!z)return;const X=z.activePanel||z.panels[0];X&&(z.model.openPanel(X),X.api.setActive(),Bt(X.id)||ie(X.id,"dockview-focus"),Ta((se=z.element)==null?void 0:se.ownerDocument))},[oe,ie]),Q=i.useCallback((G,z)=>{const X=k.current,se=X==null?void 0:X.activePanel,H=(X==null?void 0:X.activeGroup)||(se==null?void 0:se.group);if(!X||!se||!H)return;let V=oe(G);!V&&(z!=null&&z.createGroupIfMissing)&&(V=X.addGroup({referenceGroup:H,direction:G})),V&&(se.api.moveTo({group:V,position:"center"}),se.group.model.openPanel(se),se.api.setActive(),Bt(se.id)||ie(se.id,z!=null&&z.createGroupIfMissing?"dockview-split":"dockview-move"))},[oe,ie]),{isMac:ve,tabShortcuts:le,shortcutListening:pe,setShortcutListening:ne,saveShortcuts:Ie}=qd({sortedTabKeys:e.map(G=>G.tabKey),onFocus:me,onSelectTab:ae}),Ce=i.useCallback(()=>{var X;const G=k.current;if(!G)return;const z=G.activePanel;if(z){if(Bt(z.id)){const se=((X=z.params)==null?void 0:X.routeId)||z.id.slice(7),H=Wt(e,se);H!=null&&H.tabKey&&ne(H.tabKey);return}U.has(z.id)&&ne(z.id)}},[U,ae,ne,e]),_e=i.useCallback(G=>{const z=[];return G.metaKey&&z.push(ve?"⌘":"Meta"),G.ctrlKey&&z.push("Ctrl"),G.altKey&&z.push(ve?"⌥":"Alt"),G.shiftKey&&G.key.length!==1&&z.push(ve?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(G.key)?null:(z.push(Qd(G.key)),z.join("+"))},[ve]),K=i.useCallback(G=>{var z,X;switch(G){case"splitActiveTabRight":Q("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Q("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const se=xe();se&&fe(se);return}case"popoutActiveTab":{const se=xe();se&&je(se);return}case"dockActiveTab":{const se=xe();if(!se)return;q(se)?Ne(se):we(se)&&Se(se);return}case"focusLeftPane":de("left");return;case"focusRightPane":de("right");return;case"focusUpPane":de("above");return;case"focusDownPane":de("below");return;case"moveActiveTabToLeftPane":Q("left");return;case"moveActiveTabToRightPane":Q("right");return;case"moveActiveTabToUpPane":Q("above");return;case"moveActiveTabToDownPane":Q("below");return;case"selectPreviousGroupTab":ue(-1);return;case"selectNextGroupTab":ue(1);return;case"setActiveTabShortcut":Ce();return;case"hideCurrentTab":{const se=(X=(z=k.current)==null?void 0:z.activePanel)==null?void 0:X.id;se&&!Bt(se)&&ge(se);return}default:return}},[ue,Se,de,fe,xe,ge,we,q,Ne,Q,je,Ce]);i.useEffect(()=>{if(!C)return;const G=C.sourceDocument,z=G.defaultView??window,X=se=>{const H=G.querySelector("[data-dockview-tab-context-menu]");H&&H.contains(se.target)||I(null)};return z.addEventListener("mousedown",X,!0),z!==window&&window.addEventListener("mousedown",()=>I(null),!0),()=>{z.removeEventListener("mousedown",X,!0),z!==window&&window.removeEventListener("mousedown",()=>I(null),!0)}},[C]);const Me=i.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:U,hasDetachedConversationPanels:W,ides:r,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:g,liveSessionInboxState:S,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:ge,userName:m,scrollToBottomRequest:M,tabShortcuts:le,openTabContextMenu:({x:G,y:z,tabKey:X,sourceDocument:se})=>I({x:G,y:z,tabKey:X,sourceDocument:se??document}),popoutTab:je,moveTabBackToMain:Ne,isTabInPopout:q,floatTab:fe,isTabFloating:we}),[n,t,U,W,r,l,c,g,S,a,o,ge,m,M,le,je,Ne,q,fe,we]),Te=C?xy({isTabInPopout:q(C.tabKey),isTabFloating:we(C.tabKey),tabShortcut:le[C.tabKey],actionShortcuts:p}):[],He=i.useCallback(G=>{var se;const z=k.current;if((((se=z==null?void 0:z.activePanel)==null?void 0:se.id)??null)===G.id){G.group.model.openPanel(G);return}G.group.model.openPanel(G),G.api.setActive()},[]),Ge=i.useCallback((G,z="requested-tab")=>{if(!G)return!1;const X=k.current;if(!X)return!1;const se=X.getPanel(G);return se?(He(se),ie(G,z),f==null||f(),!0):!1},[He,f,ie]),Xe=i.useCallback(()=>{if(D.current)return!1;const G=Ge($.current,"stored-layout-restore");return G&&(D.current=!0),G},[Ge]),Ye=i.useCallback(()=>{var z;const G=k.current;G&&Vb(v,{activeTabId:((z=G.activePanel)==null?void 0:z.id)??null,layout:G.toJSON()})},[v]),tt=i.useCallback(()=>{Yb(v,R.current)},[v]),ct=i.useCallback(G=>{var se,H,V,te;const z=k.current;if(!z)return{kind:"grid"};const X=z.toJSON();for(const re of X.floatingGroups||[])if((H=(se=re.data)==null?void 0:se.views)!=null&&H.includes(G)&&re.position)return{kind:"floating",position:re.position};for(const re of X.popoutGroups||[])if((te=(V=re.data)==null?void 0:V.views)!=null&&te.includes(G))return{kind:"popout",position:re.position,popoutUrl:re.url};return{kind:"grid"}},[]),mt=i.useCallback(G=>{const z=k.current;if(!z)return;const X=z.getPanel(G),se=R.current[G];if(!X||!se||se.kind==="grid")return;if(X.group.model.location.type===se.kind){delete R.current[G],tt();return}if(se.kind==="floating"){z.addFloatingGroup(X,{x:se.position.left??24,y:se.position.top??24,width:se.position.width,height:se.position.height}),delete R.current[G],tt();return}delete R.current[G],tt()},[tt]);i.useEffect(()=>(x==null||x({setShortcutForActiveTab:Ce,restoreHiddenTabToSavedLocation:mt,activateConversationTab:ae,resetAllPanelsToMain:J,activatePreviousTabInGroup:()=>ue(-1),activateNextTabInGroup:()=>ue(1),floatActiveTab:()=>{const G=xe();G&&fe(G)},popoutActiveTab:()=>{const G=xe();G&&je(G)},dockActiveTab:()=>{const G=xe();G&&(q(G)?Ne(G):we(G)&&Se(G))},splitActiveTabRight:()=>Q("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Q("below",{createGroupIfMissing:!0}),focusLeftPane:()=>de("left"),focusRightPane:()=>de("right"),focusUpPane:()=>de("above"),focusDownPane:()=>de("below"),moveActiveTabToLeftPane:()=>Q("left"),moveActiveTabToRightPane:()=>Q("right"),moveActiveTabToUpPane:()=>Q("above"),moveActiveTabToDownPane:()=>Q("below")}),()=>x==null?void 0:x(null)),[ue,Se,fe,de,xe,we,q,Q,Ne,je,x,J,mt,ae,Ce]),i.useEffect(()=>()=>{var G;(G=B.current)==null||G.call(B),B.current=null},[]);const pt=i.useCallback(G=>{var X,se;k.current=G.api,(X=B.current)==null||X.call(B),B.current=null;const z=Gb(v);if($.current=(z==null?void 0:z.activeTabId)??null,z!=null&&z.layout&&G.api.fromJSON(z.layout,{reuseExistingPanels:!1}),N.current=kl({hasStoredLayout:!!(z!=null&&z.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),N.current||(Tl(G.api,e),Al(G.api,e,y)),G.api.totalPanels===0&&e.length>0){const H=Sy(G.api,e,b);if(H){const V=G.api.getPanel(H);V&&He(V)}}else!N.current&&!Ge(b)&&Xe();if(L.current=!0,G.api.onDidActivePanelChange(H=>{var te;if($.current=(H==null?void 0:H.id)??null,D.current=!0,he(),H&&Bt(H.id)){const re=((te=H.params)==null?void 0:te.routeId)||H.id.slice(7),ke=Wt(e,re);w((ke==null?void 0:ke.tabKey)??null),Ye();return}if(w((H==null?void 0:H.id)??null),Ye(),!H)return;const V=U.get(H.id);(V==null?void 0:V.streamSource)==="agent-stream"&&V.agentType&&A(V.routeId,$c(),{agentType:V.agentType,...V.sessionId&&{targetSessionId:V.sessionId}}).catch(()=>{})}),G.api.onDidLayoutChange(()=>{Ye(),he(),P(H=>H+1)}),vy()){const H=Re=>({clientX:Re.clientX,clientY:Re.clientY}),V=Re=>{const Fe=Re==null?void 0:Re.getBoundingClientRect();return Fe?{left:Fe.left,right:Fe.right,top:Fe.top,bottom:Fe.bottom}:null},te=Re=>{var Ue;const Fe=(Ue=j.current)==null?void 0:Ue.getBoundingClientRect();return Fe?Re.clientX<Fe.left||Re.clientX>Fe.right||Re.clientY<Fe.top||Re.clientY>Fe.bottom:!1},re=yy({detachDelayMs:eu,onDetach:({panelId:Re,clientX:Fe,clientY:Ue})=>{var dt,xt;const Le=G.api.getPanel(Re);if(!Le)return;try{if(Le.group.model.location.type!=="grid")return}catch{return}const Ze=(dt=j.current)==null?void 0:dt.getBoundingClientRect(),et=(xt=Le.group.element)==null?void 0:xt.getBoundingClientRect(),gt=Math.round(Math.min(Math.max((et==null?void 0:et.width)??600,360),720)),yt=Math.round(Math.min(Math.max((et==null?void 0:et.height)??500,260),640));G.api.addFloatingGroup(Le,{x:Ze?Math.max(0,Fe-Ze.left-32):void 0,y:Ze?Math.max(0,Ue-Ze.top-18):void 0,width:gt,height:yt}),Le.api.setActive(),Ye(),he(),P(Ve=>Ve+1)}}),ke=[G.api.onWillDragPanel(Re=>{if(!(Re.nativeEvent.defaultPrevented||Re.nativeEvent.shiftKey)){try{if(Re.panel.group.model.location.type!=="grid")return}catch{return}re.startDrag({panelId:Re.panel.id,selfPanelBounds:V(Re.panel.group.element),...H(Re.nativeEvent)})}}),G.api.onWillShowOverlay(Re=>{if(re.hasDetached()){Re.preventDefault();return}re.markDockTarget(H(Re.nativeEvent))}),G.api.onWillDrop(Re=>{if(re.hasDetached()){Re.preventDefault(),re.endDrag();return}re.markDockTarget(H(Re.nativeEvent))}),G.api.onDidDrop(()=>re.endDrag()),G.api.onUnhandledDragOverEvent(Re=>{re.isDragging()&&re.markSelfPanel(H(Re.nativeEvent))})],Ee=Re=>{if(!re.isDragging())return;const Fe=H(Re);te(Fe)&&re.markNonSelfPanel(Fe)},Oe=()=>re.endDrag();window.addEventListener("dragover",Ee,!0),window.addEventListener("drop",Oe,!0),window.addEventListener("dragend",Oe,!0),B.current=()=>{re.dispose();for(const Re of ke)Re.dispose();window.removeEventListener("dragover",Ee,!0),window.removeEventListener("drop",Oe,!0),window.removeEventListener("dragend",Oe,!0)}}G.api.onDidAddGroup(H=>{requestAnimationFrame(()=>{var V,te;try{const re=(V=H.element)==null?void 0:V.ownerDocument;if(!re||re===document)return;(te=re.getElementById("dv-popout-window"))==null||te.classList.add("adhdev-dockview");const ke=document.documentElement.getAttribute("data-theme");ke&&re.documentElement.setAttribute("data-theme",ke),re.body.className=document.body.className;const Ee=document.documentElement.getAttribute("style");Ee&&re.documentElement.setAttribute("style",Ee)}catch{}he(),P(re=>re+1)})}),w(((se=G.api.activePanel)==null?void 0:se.id)??null)},[He,Ge,U,r,d,v,w,Ye,b,y,A,he,e]);i.useLayoutEffect(()=>{const G=k.current;if(!G||!L.current||N.current&&kl({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;N.current&&(N.current=!1);const z=E.current,X=new Set(z),se=e.map(Oe=>Oe.tabKey),H=new Set(se),V=by({previousVisibleConversationCount:z.length,visibleConversationCount:e.length,ides:r});let te=!1;for(const Oe of z)H.has(Oe)||V||(R.current[Oe]=ct(Oe),te=!0);te&&tt(),V||(Tl(G,e),Al(G,e,y));const re=se.filter(Oe=>!X.has(Oe));let ke=!1;for(const Oe of re){const Re=G.getPanel(Oe),Fe=R.current[Oe];if(!Re||!Fe||Fe.kind==="grid")continue;if(Re.group.model.location.type===Fe.kind){delete R.current[Oe],ke=!0;continue}if(Fe.kind==="floating"){G.addFloatingGroup(Re,{x:Fe.position.left??24,y:Fe.position.top??24,width:Fe.position.width,height:Fe.position.height}),delete R.current[Oe],ke=!0;continue}}if(ke&&tt(),E.current=se,b&&Ge(b))return;!G.activePanel&&G.panels[0]&&He(G.panels[0]),!!(G.activePanel&&G.getPanel(G.activePanel.id))||Xe()},[He,Ge,Xe,r,d,tt,ct,b,y,e]),i.useEffect(()=>{L.current&&Ge(b)},[Ge,b]),i.useEffect(()=>{const G=X=>{const se=X.target;if(!se)return;const H=se.querySelector("[data-tab-key]")||se.closest("[data-tab-key]");if(H){const V=H.getAttribute("data-tab-key");if(V&&X.dataTransfer){const te=se.closest(".dv-tab")||H.closest(".dv-tab")||H;X.dataTransfer.effectAllowed="move",X.dataTransfer.setData("text/tab-key",V),te instanceof HTMLElement&&X.dataTransfer.setDragImage(te,Math.max(12,Math.round(te.clientWidth/2)),Math.max(10,Math.round(te.clientHeight/2)))}}};window.addEventListener("dragstart",G);const z=Ml(k.current);for(const X of z)X.addEventListener("dragstart",G);return()=>{window.removeEventListener("dragstart",G);for(const X of z)X.removeEventListener("dragstart",G)}},[O]),i.useEffect(()=>{var z;const G=(z=j.current)==null?void 0:z.querySelector(".adhdev-dockview");G instanceof HTMLElement&&Aa(G,T),ce(),he()},[he,ce,T]),i.useEffect(()=>{he()},[he]),i.useEffect(()=>{const G=z=>{if(z.defaultPrevented||pe)return;const X=_e(z);if(!X)return;const se=z.metaKey||z.ctrlKey||z.altKey;fo(z.target)&&!se||Bn(ve).setActiveTabShortcut!==X||(z.preventDefault(),z.stopPropagation(),Ce())};return window.addEventListener("keydown",G,!0),()=>window.removeEventListener("keydown",G,!0)},[_e,ve,pe,Ce]),i.useEffect(()=>{const G=j.current;if(!G)return;const z=X=>{var re,ke;if(!X.isTrusted)return;const se=(ke=(re=X.target)==null?void 0:re.closest)==null?void 0:ke.call(re,".dv-scrollable");if(!se)return;X.preventDefault(),X.stopPropagation();const H=Math.abs(X.deltaX),V=Math.abs(X.deltaY),te=H>V?X.deltaX:X.deltaY;se.dispatchEvent(new WheelEvent("wheel",{deltaY:te,deltaMode:X.deltaMode,bubbles:!1,cancelable:!0}))};return G.addEventListener("wheel",z,{passive:!1,capture:!0}),()=>G.removeEventListener("wheel",z,{capture:!0})},[]),i.useEffect(()=>{const G=Ml(k.current);if(G.length===0)return;const z=G.map(X=>{let se=[],H=null;const V=()=>{H!=null&&X.clearTimeout(H),H=null,se=[]},te=()=>{H!=null&&X.clearTimeout(H),H=X.setTimeout(()=>{H=null,se=[]},1200)},re=Ee=>{if(!Ee.ctrlKey&&!Ee.metaKey&&!Ee.altKey)return;const Oe=_e(Ee);if(!Oe)return;const Re=Vd();for(const[Fe,Ue]of Object.entries(Re))if(e.some(Le=>Le.tabKey===Fe)&&Ue===Oe){Ee.preventDefault(),ae(Fe);return}},ke=Ee=>{if(Ee.defaultPrevented||pe)return;const Oe=_e(Ee);if(!Oe)return;const Re=Ee.metaKey||Ee.ctrlKey||Ee.altKey;if(fo(Ee.target))return;const Fe=Bn(ve),Ue=Object.entries(Fe).filter(([Ve,Ht])=>!!Ht&&(Ve==="splitActiveTabRight"||Ve==="splitActiveTabDown"||Ve==="floatActiveTab"||Ve==="popoutActiveTab"||Ve==="dockActiveTab"||Ve==="focusLeftPane"||Ve==="focusRightPane"||Ve==="focusUpPane"||Ve==="focusDownPane"||Ve==="moveActiveTabToLeftPane"||Ve==="moveActiveTabToRightPane"||Ve==="moveActiveTabToUpPane"||Ve==="moveActiveTabToDownPane"||Ve==="selectPreviousGroupTab"||Ve==="selectNextGroupTab"||Ve==="setActiveTabShortcut"||Ve==="hideCurrentTab")),Le=Re?[Oe]:[...se.slice(-1),Oe].slice(-2),Ze=Le.join(" "),et=Le[Le.length-1],gt=Ue.find(([,Ve])=>Ve===Ze);if(gt){Ee.preventDefault(),V(),K(gt[0]);return}if(Ue.some(([,Ve])=>Ve.startsWith(`${Ze} `))){Ee.preventDefault(),se=Le,te();return}const dt=Ue.find(([,Ve])=>Ve===et);if(dt){Ee.preventDefault(),V(),K(dt[0]);return}if(Ue.some(([,Ve])=>Ve.startsWith(`${et} `))){Ee.preventDefault(),se=[et],te();return}V()};return X.addEventListener("keydown",re),X.addEventListener("keydown",ke),()=>{V(),X.removeEventListener("keydown",re),X.removeEventListener("keydown",ke)}});return()=>{for(const X of z)X()}},[_e,ve,O,ae,pe,K,e]);const F=T==="light"?qa:Ya,be=((qe=(Be=(Ae=k.current)==null?void 0:Ae.activePanel)==null?void 0:Be.group.element)==null?void 0:qe.ownerDocument)??document;return s.jsxs(tu.Provider,{value:Me,children:[s.jsx("div",{ref:j,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(sm,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:Ny,remote:Cy},defaultTabComponent:My,watermarkComponent:Iy,onReady:pt,singleTabMode:"default",tabAnimation:"smooth",theme:F,popoutUrl:"/popout.html"})}),C&&Nr.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:C.x,top:C.y},children:Te.map(G=>{if(G.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},G.id);let z=s.jsx(np,{size:13,className:"shrink-0 opacity-70"}),X=()=>{};switch(G.id){case"dockInWindow":case"dockBackToGrid":z=s.jsx(op,{size:13,className:"shrink-0 opacity-70"}),X=()=>{Se(C.tabKey),I(null)};break;case"moveBackToMain":z=s.jsx(rp,{size:13,className:"shrink-0 opacity-70"}),X=()=>{Ne(C.tabKey),I(null)};break;case"floatAsPanel":z=s.jsx(ap,{size:13,className:"shrink-0 opacity-70"}),X=()=>{fe(C.tabKey),I(null)};break;case"openInNewWindow":z=s.jsx(sp,{size:13,className:"shrink-0 opacity-70"}),X=()=>{je(C.tabKey),I(null)};break;case"setShortcut":X=se=>{se.stopPropagation(),ne(C.tabKey),I(null)};break;case"removeShortcut":z=s.jsx(jt,{size:13,className:"shrink-0 opacity-70"}),X=()=>{const se={...le};delete se[C.tabKey],Ie(se),I(null)};break;case"hideTab":z=s.jsx(No,{size:13,className:"shrink-0 opacity-70"}),X=()=>{ge(C.tabKey),I(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${G.tone==="muted"?"text-text-muted":""}`,onMouseDown:jy,onClick:X,children:[z,s.jsx("span",{className:"flex-1 min-w-0",children:G.label}),G.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:G.shortcut}):null]},G.id)})}),C.sourceDocument.body),pe&&Nr.createPortal(s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>ne(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:G=>G.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",ve?"⌘+1":"Ctrl+1",", ",ve?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),be.body)]})}const su="adhdev-recent-launch-args-v1",Ay=8;function ru(e){return String(e||"").trim().replace(/\s+/g," ")}function ri(e,t){return`${e.trim()}::${t.trim()}`}function ni(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(su)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function nu(e){if(!(typeof window>"u"))try{window.localStorage.setItem(su,JSON.stringify(e))}catch{}}function xo(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=ni().byKey[ri(r,n)])==null?void 0:o.items)||[]}function au(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=ru(r);if(!n||!a||!o)return;const l=ni(),c=ri(n,a),d=((u=l.byKey[c])==null?void 0:u.items)||[],m=[o,...d.filter(p=>p!==o)].slice(0,Ay);l.byKey[c]={items:m},nu(l)}function _y(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=ru(r);if(!n||!a||!o)return;const l=ni(),c=ri(n,a),m=(((u=l.byKey[c])==null?void 0:u.items)||[]).filter(p=>p!==o);m.length>0?l.byKey[c]={items:m}:delete l.byKey[c],nu(l)}function ou(e){return!e.hasLoadedInitialResults&&!e.isLoading}function gn({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 Ly({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 iu({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:l,onOpenHistory:c,onClearSelection:d}){const m=o?Ud(o):null,u=Ly({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(gn,{title:"Saved history",description:Uo(),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:yx()})]}),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 lu({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 Ry({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 _a(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>Is(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>Is(a,"acp"))?"acp":null}function sn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Py({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:l,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Ve,Ht;const u=Rr(),p=i.useMemo(()=>[...e].sort(Ro),[e]),[x,w]=i.useState(((Ve=p[0])==null?void 0:Ve.id)||""),g=i.useMemo(()=>p.find(Z=>Z.id===x)||p[0],[x,p]),h=i.useMemo(()=>((g==null?void 0:g.workspaces)||[]).map(Z=>({id:Z.id,path:Z.path,label:Z.label})),[g]),b=(g==null?void 0:g.defaultWorkspaceId)||null,[y,f]=i.useState("workspace"),[M,S]=i.useState(""),[v,T]=i.useState(""),[A,k]=i.useState([]),[j,B]=i.useState(""),[L,N]=i.useState(!1),[D,$]=i.useState(null),[E,C]=i.useState(""),[I,O]=i.useState(_a(p[0])),[P,R]=i.useState(""),[U,W]=i.useState(""),[me,ie]=i.useState([]),[ee,ce]=i.useState(""),[je,Ne]=i.useState([]),[q,ge]=i.useState(!1),[fe,we]=i.useState(!1),[xe,Se]=i.useState(""),[J,he]=i.useState(!1),[ae,ue]=i.useState(()=>Nt()),[oe,de]=i.useState(null),[Q,ve]=i.useState(!1),[le,pe]=i.useState(""),[ne,Ie]=i.useState(null),[Ce,_e]=i.useState(!1),[K,Me]=i.useState(""),[Te,He]=i.useState([]),[Ge,Xe]=i.useState(!1),[Ye,tt]=i.useState(""),[ct,mt]=i.useState(!1),pt=i.useRef(null),F=i.useRef(0);i.useEffect(()=>{var Z;!x&&((Z=p[0])!=null&&Z.id)&&w(p[0].id)},[x,p]),i.useEffect(()=>{!g||!(!g.workspaces||!g.availableProviders||!g.detectedIdes||!g.recentLaunches)||u(g.id,{minFreshMs:3e4}).catch(()=>{})},[u,g]);const be=i.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(Z=>Is(Z,"cli")),[g]),Ae=i.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(Z=>Is(Z,"acp")),[g]),Be=i.useMemo(()=>((g==null?void 0:g.detectedIdes)||[]).map(Z=>({id:Z.type,label:Z.name||Z.type,meta:Z.running?"Detected locally":"Available to open"})),[g]),qe=i.useMemo(()=>I==="cli"?be.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"CLI provider"})):I==="acp"?Ae.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"ACP provider"})):Be,[Ae,I,be,Be]),G=i.useMemo(()=>A.find(Z=>Z.id===j)||null,[A,j]),z=i.useMemo(()=>be.find(Z=>Z.type===P)||null,[be,P]),X=i.useMemo(()=>$d(z==null?void 0:z.meshCoordinator,{meshId:(G==null?void 0:G.id)||"",workspace:(G==null?void 0:G.workspace)||""}),[z,G]),se=ne||X,H=i.useCallback(async Z=>{N(!0),C("");try{const $e=await c(Z);k($e),B(_=>{var Y;return $e.some(ye=>ye.id===_)?_:((Y=$e[0])==null?void 0:Y.id)||""}),$(Z)}catch($e){k([]),B(""),$(Z),C($e instanceof Error?$e.message:"Could not load meshes")}finally{N(!1)}},[c]);i.useEffect(()=>{var $e;if(!g)return;if(pt.current!==g.id){pt.current=g.id,f("workspace"),S(b||(($e=h[0])==null?void 0:$e.id)||"__home__"),T(""),k([]),B(""),$(null),C(""),O(_a(g)),R(""),W(""),ce(""),Ne([]),we(!1),Se(""),ue(Nt()),pe(""),Ie(null);return}S(_=>{var Y;return _==="__custom__"||_==="__home__"||h.some(ye=>ye.id===_)?_:b||((Y=h[0])==null?void 0:Y.id)||"__home__"}),O(_=>_==="ide"&&Be.length>0||_==="cli"&&be.length>0||_==="acp"&&Ae.length>0?_:_a(g))},[Ae.length,be.length,b,Be.length,g,h]),i.useEffect(()=>{!g||y!=="mesh"||D===g.id||L||H(g.id)},[H,D,L,g,y]),i.useEffect(()=>{y==="mesh"&&I!=="cli"&&be.length>0&&O("cli")},[I,be.length,y]),i.useEffect(()=>{var Z;I&&(qe.some($e=>$e.id===P)||R(((Z=qe[0])==null?void 0:Z.id)||""))},[I,qe,P]),i.useEffect(()=>{Ie(null)},[g==null?void 0:g.id,j,P,y]);const V=i.useCallback(async(Z,$e)=>{const _=F.current+1;return F.current=_,ge(!0),Se(""),m(Z,$e).then(Y=>{F.current===_&&Ne(Y)}).catch(Y=>{F.current===_&&(Ne([]),Se(Y instanceof Error?Y.message:"Could not load saved sessions"))}).finally(()=>{F.current===_&&(ge(!1),we(!0))})},[m]),te=i.useCallback((Z,$e)=>{ie(xo(Z,$e))},[]);i.useEffect(()=>{F.current+=1,ce(""),ue(Nt()),!g||!P||I==="ide"?ie([]):te(g.id,P),we(!1),Ne([]),Se(""),ge(!1)},[I,te,V,g,P]),i.useEffect(()=>{if(!ee)return;const Z=je.find($e=>$e.providerSessionId===ee);Z!=null&&Z.canResume||ce("")},[je,ee]);const re=M==="__custom__"?v.trim():M==="__home__"?"":((Ht=h.find(Z=>Z.id===M))==null?void 0:Ht.path)||"",ke=i.useMemo(()=>g?t.filter(Z=>Z.id!==g.id&&Z.daemonId===g.id).map(Z=>Z.workspace):[],[t,g]),Ee=i.useMemo(()=>((g==null?void 0:g.recentLaunches)||[]).map(Z=>Z.workspace),[g]),Oe=i.useCallback(Z=>{const $e=String(Z.workspace||"").trim();if(!$e)return;const _=h.find(Y=>sn(Y.path)===sn($e));if(_){S(_.id),T("");return}S("__custom__"),T($e)},[h]),Re=i.useCallback(Z=>{const $e=String(Z.workspace||"").trim();if(!$e)return{workspaceId:null,workspacePath:null};const _=h.find(Y=>sn(Y.path)===sn($e));return _?{workspaceId:_.id,workspacePath:null}:{workspaceId:null,workspacePath:$e}},[h]),Fe=i.useMemo(()=>je.find(Z=>Z.providerSessionId===ee)||null,[je,ee]),Ue=i.useMemo(()=>{var $e;if(I!=="cli"||!g||!P)return null;const Z=(($e=be.find(_=>_.type===P))==null?void 0:$e.displayName)||P;return{routeId:g.id,daemonId:g.id,providerSessionId:ee||void 0,transport:"pty",mode:"chat",agentName:Z,agentType:P,status:"idle",title:Z,messages:[],ideType:P,workspaceName:re,workspacePath:re,displayPrimary:Z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${g.id}:${P}`,machineName:Lt(g,{fallbackId:g.id})}},[I,be,re,g,ee,P]),Le=i.useCallback(()=>{var $e;if(!g)return;S("__custom__"),_e(!0),tt("");const Z=Jn(g.platform,Xn(v.trim(),re,ke,Ee,g.defaultWorkspacePath,($e=h.find(_=>_.id===b))==null?void 0:$e.path,h.map(_=>_.path)));Xe(!0),n(g.id,Z).then(_=>{Me(_.path),T(_.path),He(_.directories)}).catch(_=>{tt(_ instanceof Error?_.message:"Could not load folder")}).finally(()=>Xe(!1))},[v,b,Ee,ke,n,re,g,h]),Ze=i.useCallback(Z=>{g&&(Xe(!0),tt(""),n(g.id,Z).then($e=>{Me($e.path),T($e.path),He($e.directories)}).catch($e=>{tt($e instanceof Error?$e.message:"Could not load folder")}).finally(()=>Xe(!1)))},[n,g]),et=i.useCallback(async()=>{if(!g||!re)return;mt(!0),pe("");const Z=await a(g.id,re);if(mt(!1),!Z.ok){pe(Z.error||"Could not save workspace");return}pe("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,re,g]),gt=i.useCallback(async()=>{if(!g)return;if(y==="mesh"){if(!j||!P)return;ve(!0),pe(""),Ie(null);const _=await d(g.id,j,P);if(ve(!1),!_.ok){if(_.code==="mesh_coordinator_manual_mcp_setup_required"&&_.manualSetup){Ie(_.manualSetup),pe("Manual MCP setup required before this provider can act as mesh coordinator.");return}pe(_.error||"Could not start mesh coordinator");return}r();return}if(!I||!P)return;ve(!0),pe("");const Z=U.trim()?U.trim().split(/\s+/).filter(Boolean):[],$e=I==="ide"?await o(g.id,P,{workspacePath:re||null}):await l(g.id,I,P,{workspaceId:M!=="__home__"&&M!=="__custom__"?M:null,workspacePath:M==="__custom__"&&re||null,resumeSessionId:I==="cli"&&ee?ee:null,cliArgs:Z});if(ve(!1),!$e.ok){pe($e.error||"Could not start session");return}I!=="ide"&&U.trim()&&(au(g.id,P,U),te(g.id,P)),r()},[I,U,te,r,o,d,l,re,g,j,ee,P,M,y]),yt=y==="mesh"?"Start mesh coordinator":I?rd(I,I==="cli"&&!!ee):"Start",dt=y==="mesh"?"Starting coordinator…":I?nd(I,I==="cli"&&!!ee):"Starting…",xt=p.length>5;return g?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(jt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[s.jsx(gn,{title:"Machine",children:xt?s.jsx("select",{"aria-label":"Machine",value:g.id,onChange:Z=>w(Z.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Q,children:p.map(Z=>s.jsx("option",{value:Z.id,children:Lt(Z,{fallbackId:Z.id})},Z.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:p.map(Z=>{const $e=Lt(Z,{fallbackId:Z.id}),_=g.id===Z.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${$e}`,"aria-pressed":_,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${_?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/60 text-text-secondary hover:bg-bg-secondary hover:text-text-primary"}`,onClick:()=>w(Z.id),disabled:Q,title:$e,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${Z.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:$e})]},Z.id)})})}),s.jsxs(gn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:y==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Le,disabled:Q,children:"Browse…"}):void 0,children:[s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":"Launch target type",children:[{id:"workspace",label:"Workspace",desc:"Normal session"},{id:"mesh",label:"Mesh",desc:"Coordinator session"}].map(Z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":y===Z.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${y===Z.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{f(Z.id),pe(""),Z.id==="mesh"&&g&&D!==g.id&&!L&&H(g.id)},disabled:Q,children:[s.jsx("div",{className:"text-sm font-semibold",children:Z.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:Z.desc})]},Z.id))}),y==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:M,onChange:Z=>{const $e=Z.target.value;S($e),$e==="__custom__"?Le():pe("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Q,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),h.map(Z=>s.jsxs("option",{value:Z.id,children:[Z.id===b?"⭐ ":"",zn(Z.path,Z.label)||Z.path]},Z.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:M==="__home__"?"Launch without a workspace.":re||"Select a workspace folder."}),M==="__custom__"&&re&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Le,disabled:Q,children:[s.jsx(Ss,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:et,disabled:Q||ct,children:ct?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[L&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!L&&E&&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:E}),!L&&!E&&A.length===0&&s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker."}),A.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:A.map(Z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":j===Z.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${j===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>B(Z.id),disabled:Q,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[Z.repoIdentity||"Repo mesh",typeof Z.nodesCount=="number"?` · ${Z.nodesCount} node${Z.nodesCount===1?"":"s"}`:""]}),Z.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",Z.workspace]})]},Z.id))}),G&&s.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),s.jsx(Ry,{workspaceMode:y,activeKind:I,cliEnabled:be.length>0,ideEnabled:Be.length>0,acpEnabled:Ae.length>0,busy:Q,onSelect:O}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:I==="ide"?"Choose IDE":I==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[qe.map(Z=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${P===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>R(Z.id),disabled:Q,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Z.meta})]},Z.id)),qe.length===0&&s.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),y==="mesh"&&se&&s.jsx(lu,{setup:se,providerName:(z==null?void 0:z.displayName)||(z==null?void 0:z.name)||P}),y!=="mesh"&&I!=="ide"&&s.jsxs(gn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:U,onChange:Z=>W(Z.target.value),placeholder:"Optional flags...",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Q}),me.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:me.map(Z=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>W(Z),disabled:Q,title:Z,children:Z},Z))})]}),y!=="mesh"&&I==="cli"&&s.jsx(iu,{busy:Q,savedSessionsLoading:q,savedSessionsError:xe,selectedSession:Fe,onRefresh:()=>{!g||!P||V(g.id,P)},onOpenHistory:()=>{!g||!P||(he(!0),ou({hasLoadedInitialResults:fe,isLoading:q})&&V(g.id,P))},onClearSelection:()=>ce("")}),le&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${le.includes("saved")||le.includes("requested")||le.includes("Manual MCP setup")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:le})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:r,disabled:Q,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:gt,disabled:Q||(y==="mesh"?!j||!P||I!=="cli"||L:!I||!P||M==="__custom__"&&!re),children:[s.jsx(Io,{size:14}),Q?dt:yt]})]})]})}),Ce&&s.jsx(Zn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:K,directories:Te,busy:Ge,error:Ye,onClose:()=>_e(!1),onNavigate:Ze,onConfirm:Z=>{T(Z),Me(Z),S("__custom__"),_e(!1)}}),J&&Ue&&s.jsx(Vo,{activeConv:Ue,ides:[],isCreatingChat:!1,isRefreshingHistory:q,savedSessions:je,isSavedSessionsLoading:q,isResumingSavedSessionId:oe,savedHistoryFilters:ae,missingWorkspaceResumePath:re||null,onSavedHistoryFiltersChange:ue,onClose:()=>he(!1),onNewChat:()=>{ce(""),he(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!g||!P||V(g.id,P)},onResumeSavedSession:Z=>{if(!g||!P||oe||!Z.canResume)return;const $e=Re(Z);ce(Z.providerSessionId),Oe(Z),de(Z.providerSessionId),he(!1),ve(!0),pe(""),l(g.id,"cli",P,{workspaceId:$e.workspaceId,workspacePath:$e.workspacePath,resumeSessionId:Z.providerSessionId}).then(_=>{if(!_.ok){pe(_.error||"Could not resume session");return}r()}).finally(()=>{ve(!1),de(_=>_===Z.providerSessionId?null:_)})}})]}):null}function cu(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 ai(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=cu(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 oi(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function du(e){var t;return!oi(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 rn(e){return[...new Set(e.filter(t=>!!t))]}function Dy(e){const t=e.nodes.find(l=>l.type==="defaultBranchNode")??null,r=(t==null?void 0:t.branch)??null,n=e.nodes.filter(l=>l.type!=="defaultBranchNode"&&l.type!=="submoduleNode"&&!l.isOrphan&&!!r&&l.branch===r),a=e.nodes.filter(l=>l.type!=="submoduleNode"&&!l.isOrphan),o=e.nodes.filter(l=>l.type!=="submoduleNode");return t||n.length>0?rn([t==null?void 0:t.id,...n.map(l=>l.id)]):a.length>0?rn(a.map(l=>l.id)):o.length>0?rn(o.map(l=>l.id)):rn(e.nodes.map(l=>l.id))}function uu(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 Ey(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${uu(e)}::${n}x${a}`}const $y={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"},By={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"},Oy={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"},Fy={default:"border-slate-300 bg-white text-slate-700 hover:bg-slate-50",info:"border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100",success:"border-emerald-300 bg-emerald-50 text-emerald-700 hover:bg-emerald-100"};function Zs(e){return e==="light"?{theme:e,isDark:!1,flowColorMode:"light",textPrimary:"text-slate-900",textSecondary:"text-slate-700",textMuted:"text-slate-500",graphShellClass:"relative w-full min-w-0 overflow-hidden rounded-2xl border border-slate-200 bg-[radial-gradient(circle_at_top,_rgba(14,165,233,0.16),_rgba(248,250,252,0.98)_42%,_rgba(255,255,255,1))]",graphStatChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-slate-700 shadow-sm",graphHintChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-[10px] text-slate-500 shadow-sm",graphControlsClass:"!bottom-4 !left-4 !shadow-md",graphBackgroundDotColor:"rgba(148, 163, 184, 0.34)",edgeLabelTextColor:"#334155",edgeLabelBackgroundColor:"rgba(255, 255, 255, 0.96)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.45)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[rgba(148,163,184,0.22)] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"flex h-[100dvh] w-full flex-col overflow-hidden bg-white md:h-[min(90vh,960px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-slate-200 md:bg-white/98 md:shadow-[0_28px_120px_rgba(148,163,184,0.28)]",dialogHeaderClass:"flex shrink-0 flex-col gap-3 border-b border-slate-200 bg-white/96 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-slate-900 md:text-xl",dialogKickerClass:"rounded-full border border-slate-300 bg-slate-50 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-600",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-500",dialogRefreshedChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1.5 text-xs text-slate-600",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-300 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",dialogBodyClass:"min-h-0 flex-1 overflow-y-auto bg-[linear-gradient(180deg,rgba(248,250,252,0.98),rgba(241,245,249,0.96))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-slate-300 bg-white/90 px-6 text-center text-sm text-slate-500",cardClass:"rounded-2xl border border-slate-200 bg-white/95 shadow-sm",cardHeaderClass:"border-b border-slate-200 px-4 py-3",cardTitleClass:"text-sm font-semibold text-slate-900",cardSubtitleClass:"mt-1 text-xs text-slate-500",rowClass:"flex items-start justify-between gap-3 border-b border-slate-200/80 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"text-slate-500",rowValueClass:"max-w-[65%] break-all text-right text-slate-800",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-slate-200 bg-white/95 p-4 shadow-md md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-slate-200 bg-white/95 p-4 text-xs text-slate-500 shadow-sm md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-900",panelCloseButtonClass:"text-xs text-slate-500 hover:text-slate-900",panelFieldRowClass:"flex justify-between gap-3 border-b border-slate-200/80 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-500",panelFieldValueClass:"break-all text-right font-medium text-slate-700",infoCalloutClass:"mt-1 rounded border border-sky-300 bg-sky-50 px-2 py-1.5 text-[10px] text-sky-700",badge:t=>By[t],actionButton:t=>Fy[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative w-full min-w-0 overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",graphStatChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-slate-200",graphHintChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-[10px] text-slate-300",graphControlsClass:"!bottom-4 !left-4 !shadow-lg",graphBackgroundDotColor:"rgba(148, 163, 184, 0.22)",edgeLabelTextColor:"#cbd5e1",edgeLabelBackgroundColor:"rgba(2, 6, 23, 0.86)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.2)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[#030617]/[0.58] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"flex h-[100dvh] w-full flex-col overflow-hidden bg-slate-950 md:h-[min(90vh,960px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-white/10 md:bg-slate-950/96 md:shadow-[0_28px_120px_rgba(2,6,23,0.46)]",dialogHeaderClass:"flex shrink-0 flex-col gap-3 border-b border-white/10 bg-slate-950/92 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-white md:text-xl",dialogKickerClass:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-300",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-400",dialogRefreshedChipClass:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 bg-white/6 text-slate-300 transition hover:bg-white/10 hover:text-white",dialogBodyClass:"min-h-0 flex-1 overflow-y-auto bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-white/10 bg-white/[0.03] px-6 text-center text-sm text-slate-400",cardClass:"rounded-2xl border border-white/10 bg-white/[0.04]",cardHeaderClass:"border-b border-white/10 px-4 py-3",cardTitleClass:"text-sm font-semibold text-white",cardSubtitleClass:"mt-1 text-xs text-slate-400",rowClass:"flex items-start justify-between gap-3 border-b border-white/5 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"text-slate-400",rowValueClass:"max-w-[65%] break-all text-right text-slate-100",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-white/10 bg-white/[0.04] p-4 shadow-lg md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-white/10 bg-white/[0.04] p-4 text-xs text-slate-400 md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-100",panelCloseButtonClass:"text-xs text-slate-400 hover:text-slate-100",panelFieldRowClass:"flex justify-between gap-3 border-b border-white/6 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-400",panelFieldValueClass:"break-all text-right font-medium text-slate-200",infoCalloutClass:"mt-1 rounded bg-blue-500/10 border border-blue-500/20 px-2 py-1.5 text-[10px] text-blue-300",badge:t=>$y[t],actionButton:t=>Oy[t]}}const It={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,columnGap:540,edgeLabelBuffer:180,defaultToContentGap:136,worktreeStackGap:82,parentToSubmoduleGap:48,submoduleStackGap:36,submoduleIndentX:72,placeholderTopOffset:0};function nn(e,t,r){const n=(e||"").trim();return n?Math.max(1,Math.min(r,Math.ceil(n.length/t))):0}function Wy(e){let t=1;return e.type==="submoduleNode"&&(t+=1),e.branch&&e.type!=="submoduleNode"&&(t+=1),e.submoduleCommit&&e.type==="submoduleNode"&&(t+=1),e.dirty&&(t+=1),e.outOfSync&&(t+=1),e.hasConflicts&&(t+=1),e.type!=="submoduleNode"&&e.upstream&&e.upstreamStatus!=="fresh"&&(t+=1),e.isOrphan&&(t+=1),t}function ii(e){return e.type==="submoduleNode"?It.submoduleCardWidth:It.worktreeCardWidth}function mu(e){var r;if(e.type==="defaultBranchNode")return e.nextStepHint||"Default branch anchor";if(e.type==="submoduleNode"){const n=[e.machineLabel?`parent ${e.machineLabel}`:null];return e.outOfSync?n.push("out of sync"):e.dirty?n.push("local changes"):n.push("synced"),n.filter(Boolean).join(" · ")}const t=[];if(e.upstream&&t.push(e.upstream),e.upstream&&e.upstreamStatus!=="fresh")t.push("upstream unverified");else{const n=cu(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 yn(e){const t=ii(e),r=e.type==="submoduleNode"?24:30,n=Math.ceil(Wy(e)/(e.type==="submoduleNode"?2:3)),a=nn(e.label,r,2),o=nn(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,r,2),l=nn(mu(e),r+4,3),c=ai(e),d=du(e)?oi(e):null,m=nn(d,Math.max(24,Math.floor(t/8)),4),u=52+a*18+o*14+(c?30:0)+n*24+Math.max(22,l*18)+(m>0?22+m*16:0),p=e.type==="submoduleNode"?It.minSubmoduleCardHeight:It.minWorktreeCardHeight;return Math.min(It.maxEstimatedCardHeight,Math.max(p,Math.ceil(u)))}function La(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 Hy(e){return e?Math.min(260,Math.max(72,e.length*7+26)):0}function Ky(e){const t=e.edges.reduce((r,n)=>Math.max(r,Hy(n.label)),0);return Math.max(It.columnGap,It.worktreeCardWidth+t+It.edgeLabelBuffer)}function an(e,t,r,n=!0){return{id:e.id,type:"meshNode",position:{x:t,y:r},graphNode:e,selected:!1,draggable:!1,selectable:n}}function on(e,t,r){return{id:e.id,x:t,y:r,width:ii(e),height:yn(e)}}function Uy(e,t){return{id:`${e.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:t.repoIdentity,branch:e.branch,upstream:null,upstreamStatus:null,machineLabel:null,health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],nextStepHint:"Waiting for worktree nodes to report live mesh status.",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{nodeId:`${e.id}__placeholder`,machineLabel:"",workspace:t.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}}function zy(e){const t=[...e.nodes].sort(La),r=t.find(b=>b.type==="defaultBranchNode")??null,n=new Map;for(const b of t){if(b.type!=="submoduleNode"||!b.parentNodeId)continue;const y=n.get(b.parentNodeId)??[];y.push(b),n.set(b.parentNodeId,y)}const a=t.filter(b=>b.id!==(r==null?void 0:r.id)&&b.type!=="submoduleNode"),o=new Map,l=[];for(const b of a){if(b.isOrphan||!b.branch){l.push(b);continue}const y=o.get(b.branch)??[];y.push(b),o.set(b.branch,y)}const c=[...o.entries()].sort(([b],[y])=>r!=null&&r.branch&&b===r.branch&&y!==r.branch?-1:r!=null&&r.branch&&y===r.branch&&b!==r.branch?1:b.localeCompare(y));l.length>0&&c.push(["__orphans__",[...l].sort(La)]),c.length===0&&c.push(["__nodes__",[]]);const d=[],m=[],u=c.length,p=Ky(e),x=Math.max(1,u-1)*p,w=r?0:96,g=r?yn(r):0,h=r?w+g+It.defaultToContentGap:0;if(r){const b=x/2;d.push(an(r,b,w)),m.push(on(r,b,w))}return c.forEach(([b,y],f)=>{const M=f*p,S=y.length>0?y:a.length>0?a:[];let v=h;if(S.forEach(T=>{const A=yn(T);d.push(an(T,M,v)),m.push(on(T,M,v));const k=[...n.get(T.id)??[]].sort(La);if(k.length>0){let j=v+A+It.parentToSubmoduleGap;k.forEach(B=>{const L=M+It.submoduleIndentX,N=yn(B);d.push(an(B,L,j)),m.push(on(B,L,j)),j+=N+It.submoduleStackGap}),v=j+It.worktreeStackGap-It.submoduleStackGap;return}v+=A+It.worktreeStackGap}),b==="__nodes__"&&a.length===0&&r){const T=Uy(r,e),A=h+It.placeholderTopOffset;d.push(an(T,M,A,!1)),m.push(on(T,M,A))}}),{nodes:d,bounds:m,columnGap:p}}const pu=i.createContext(Zs("dark"));function Gy(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=ai(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 Vy(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 qy(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 Yy(e){return e.replace(/_/g," ")}function Xy({data:e,selected:t}){const r=i.useContext(pu),n=e.graphNode,a=n.type==="defaultBranchNode",o=n.type==="submoduleNode",l=du(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=ai(n),u=mu(n),p=oi(n);return s.jsxs("div",{className:`${o?"w-[228px]":"w-[256px]"} rounded-2xl border px-4 py-3.5 backdrop-blur-sm transition-all ${Gy(n,t,r.isDark)}`,style:{width:ii(n)},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:qy(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] ${Vy(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:Yy(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&&p&&s.jsx("div",{className:`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${r.isDark?"border-cyan-400/15 bg-cyan-500/8 text-cyan-50/90":"border-sky-300 bg-sky-50 text-sky-700"}`,children:p}),s.jsx(ki,{type:"source",position:Si.Bottom,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const Jy={meshNode:Xy};function Qy(e,t=Zs("dark")){const n=zy(e).nodes.map(o=>({id:o.id,type:o.type,position:o.position,data:{graphNode:o.graphNode},selected:o.selected,draggable:o.draggable,selectable:o.selectable})),a=e.edges.map(o=>({id:o.id,source:o.source,target:o.target,label:o.label,type:o.type==="worktreeLink"||o.type==="submoduleLink"?"smoothstep":"bezier",animated:o.type==="orphanLink",markerEnd:o.direction==="directed"?{type:im.ArrowClosed,width:o.type==="submoduleLink"?16:18,height:o.type==="submoduleLink"?16:18,color:_l(o)}:void 0,style:{stroke:_l(o),strokeWidth:o.type==="orphanLink"?2.25:o.type==="submoduleLink"?1.7:o.type==="worktreeLink"?1.8:2,strokeDasharray:o.type==="orphanLink"?"5 4":o.type==="submoduleLink"?"4 3":void 0},labelStyle:{fill:t.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:t.edgeLabelBackgroundColor,fillOpacity:1,stroke:t.edgeLabelBorderColor},labelBgPadding:[6,4],labelBgBorderRadius:7}));return{nodes:n,edges:a}}function _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 Zy({data:e,viewportKey:t}){const r=lm(),n=cm(),a=i.useRef(null),o=i.useMemo(()=>uu(e),[e]),l=i.useMemo(()=>Dy(e),[e]);return i.useEffect(()=>{if(!r||e.nodes.length===0||a.current===t)return;let c=!1;const d=requestAnimationFrame(()=>{if(c)return;const m=l.length>0&&l.length<e.nodes.length;n.fitView({nodes:m?l.map(u=>({id:u})):void 0,padding:m?.24:.2,maxZoom:m?.98:.9,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(d)}},[e.nodes.length,l,o,r,n,t]),null}function e0({data:e,selectedNodeId:t=null,onNodeClick:r}){const{theme:n}=Qs(),a=i.useMemo(()=>Zs(n),[n]),o=i.useMemo(()=>Qy(e,a),[e,a]),l=i.useRef(null),[c,d]=i.useState({width:0,height:0}),m=i.useMemo(()=>Ey(e,c.width,c.height),[e,c.height,c.width]),u=i.useMemo(()=>o.nodes.map(p=>({...p,selected:p.id===t})),[o.nodes,t]);return i.useEffect(()=>{const p=l.current;if(!p)return;const x=()=>{const g=Math.max(0,Math.round(p.clientWidth)),h=Math.max(0,Math.round(p.clientHeight));d(b=>b.width===g&&b.height===h?b:{width:g,height:h})};x();const w=typeof ResizeObserver=="function"?new ResizeObserver(()=>x()):null;return w==null||w.observe(p),window.addEventListener("resize",x),()=>{w==null||w.disconnect(),window.removeEventListener("resize",x)}},[]),s.jsx(pu.Provider,{value:a,children:s.jsxs("div",{ref:l,className:a.graphShellClass,children:[s.jsxs("div",{className:`absolute inset-x-3 top-3 z-10 flex flex-wrap items-center justify-between gap-2 text-[11px] ${a.textSecondary}`,children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs("span",{className:a.graphStatChipClass,children:[e.stats.totalNodes," node",e.stats.totalNodes===1?"":"s"]}),s.jsxs("span",{className:a.graphStatChipClass,children:[e.stats.totalActiveSessions," active session",e.stats.totalActiveSessions===1?"":"s"]}),e.stats.orphanNodes>0&&s.jsxs("span",{className:a.isDark?"rounded-full border border-orange-400/25 bg-orange-500/12 px-3 py-1 text-orange-100":"rounded-full border border-orange-300 bg-orange-50 px-3 py-1 text-orange-700",children:[e.stats.orphanNodes," need attention"]})]}),s.jsx("div",{className:a.graphHintChipClass,children:"Focused on the main path first · drag or scroll to pan"})]}),s.jsx("div",{className:"h-[460px] w-full min-w-0 min-h-[460px] sm:h-[560px] xl:h-[680px]",children:s.jsxs(rm,{nodes:u,edges:o.edges,nodeTypes:Jy,minZoom:.25,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(p,x)=>r==null?void 0:r(x.data.graphNode),className:"h-full w-full",colorMode:a.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(Zy,{data:e,viewportKey:m}),s.jsx(nm,{className:a.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),s.jsx(am,{variant:om.Dots,gap:18,size:1.2,color:a.graphBackgroundDotColor})]})})]})})}function ft(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Pe(...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 Et(...e){for(const t of e)if(typeof t=="boolean")return t}function Ra(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function li(e){switch(e){case"fresh":return 30;case"no_upstream":return 4;case"unchecked":case void 0:return 0;case"stale":return-10;case"unavailable":return-15;default:return 0}}function t0(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 s0(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=ft(n),o=Pe(a.path),l=Pe(a.commit),c=Pe(a.repoPath,a.repo_root)??t0(t,o);return!o||!l||!c?null:{path:o,commit:l,repoPath:c,dirty:Et(a.dirty)??!1,outOfSync:Et(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:_t(a.lastCheckedAt,a.last_checked_at)??Date.now(),...Pe(a.error)?{error:Pe(a.error)}:{}}}).filter(n=>n!==null);return r.length>0?r:void 0}function r0(e){return Et(e.isGitRepo)!==void 0||!!Pe(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||_t(e.ahead,e.behind,e.staged,e.modified,e.untracked,e.deleted,e.renamed,e.lastCheckedAt,e.last_checked_at)!==void 0||Array.isArray(e.submodules)&&e.submodules.length>0}function vn(e,t,r){const n=Et(e.isGitRepo);if(!Object.keys(e).length||!r0(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(g=>typeof g=="string"):[],l=_t(e.conflicts)??o.length,c=Et(e.hasConflicts)??l>0,d=Pe(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,m=s0(e.submodules,d),u=Pe(e.upstreamStatus,e.upstream_status),p=_t(e.upstreamFetchedAt,e.upstream_fetched_at),x=Pe(e.upstreamFetchError,e.upstream_fetch_error),w=Pe(e.error);return{workspace:Pe(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:a,branch:Pe(e.branch)??null,headCommit:Pe(e.headCommit)??null,headMessage:Pe(e.headMessage)??null,upstream:Pe(e.upstream)??null,upstreamStatus:u??"unchecked",...p!==void 0?{upstreamFetchedAt:p}:{},...x?{upstreamFetchError:x}:{},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:c,conflictFiles:o,stashCount:_t(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??_t(e.lastCheckedAt,e.last_checked_at)??Date.now(),...m?{submodules:m}:{},...w?{error:w}:{}}}function n0(e){if(!e)return Number.NEGATIVE_INFINITY;let t=0;return e.isGitRepo===!0&&(t+=50),e.isGitRepo===!1&&(t-=10),e.branch&&(t+=20),e.headCommit&&(t+=20),e.upstream&&(t+=10),t+=li(e.upstreamStatus),typeof e.ahead=="number"&&(t+=2),typeof e.behind=="number"&&(t+=2),Array.isArray(e.submodules)&&e.submodules.length>0&&(t+=4+e.submodules.length),e.error&&(t-=20),t}function a0(e){const t=ft(e.lastGit??e.last_git),r=ft(t.result),n=ft(t.status),a=ft(r.status),o=ft(e.lastProbe??e.last_probe),l=ft(o.git),c=ft(l.result),d=ft(l.status),m=ft(c.status);let u=null;for(const p of[n,a,d,m]){const x=vn(p,e,{lastCheckedAt:Date.now()});if(!x)continue;const w=n0(x);(!u||w>u.score)&&(u={git:x,score:w})}return u==null?void 0:u.git}function o0(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 i0(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 On(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=o0(e);return t.outOfSync?"degraded":t.dirty||i0(e)?"dirty":"online"}function l0(e,t){const r=t?On(t):void 0;return!e||e==="unknown"?r:e}function c0(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=ft(o),c=Pe(l.sessionId,l.session_id,l.id);return c?{sessionId:c,...Pe(l.providerType,l.provider)?{providerType:Pe(l.providerType,l.provider)}:{},...Pe(l.state,l.status)?{state:Pe(l.state,l.status)}:{},...Pe(l.lifecycle)?{lifecycle:Pe(l.lifecycle)}:{},...Pe(l.surfaceKind,l.surface_kind)?{surfaceKind:Pe(l.surfaceKind,l.surface_kind)}:{},...Pe(l.recoveryState,l.recovery_state)?{recoveryState:Pe(l.recoveryState,l.recovery_state)}:{},...Pe(l.workspace)?{workspace:Pe(l.workspace)}:{},...Pe(l.title)?{title:Pe(l.title)}:{},...Pe(l.lastActivityAt,l.last_activity_at)?{lastActivityAt:Pe(l.lastActivityAt,l.last_activity_at)}:{},...Et(l.isCached,l.is_cached)!==void 0?{isCached:Et(l.isCached,l.is_cached)}:{}}:null}).filter(o=>o!==null);if(a.length>0)return a}const r=ft(e.activeSession??e.active_session),n=Pe(r.id,r.sessionId,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id);if(n)return[{sessionId:n,...Pe(r.providerType,r.provider)?{providerType:Pe(r.providerType,r.provider)}:{},...Pe(r.state,r.status)?{state:Pe(r.state,r.status)}:{}}]}function d0(e){const t=ft(e.connection);return Object.keys(t).length>0?t:void 0}function u0(e){const t=e==null?void 0:e.source,r=e==null?void 0:e.transport;return{...e,perspective:(e==null?void 0:e.perspective)??"selected_coordinator",source:t&&t!=="not_reported"?t:"mesh_peer_status",state:"connected",transport:r&&r!=="unknown"?r:"direct",reported:!0,reason:"Live peer git snapshot reported by the selected coordinator."}}function ci(e){var r;const t=e.git;return!!(t&&(t.isGitRepo===!0||t.isGitRepo===!1||t.branch||t.upstream||t.headCommit||typeof t.lastCheckedAt=="number"||(((r=t.submodules)==null?void 0:r.length)??0)>0))}function Ll(e){var n,a,o,l,c,d;let t=0;const r=e.git;return ci(e)&&(t+=80,(r==null?void 0:r.isGitRepo)===!0&&(t+=20),(r==null?void 0:r.isGitRepo)===!1&&(t+=5),r!=null&&r.branch&&(t+=20),r!=null&&r.upstream&&(t+=12),r!=null&&r.headCommit&&(t+=12),t+=li(r==null?void 0:r.upstreamStatus),typeof(r==null?void 0:r.lastCheckedAt)=="number"&&(t+=6),t+=(((n=r==null?void 0:r.submodules)==null?void 0:n.length)??0)*6),(a=e.branchConvergence)!=null&&a.status&&(t+=12),(((o=e.connection)==null?void 0:o.state)==="connected"||((l=e.connection)==null?void 0:l.state)==="self")&&(t+=8),((c=e.connection)==null?void 0:c.transport)==="direct"&&(t+=4),((d=e.connection)==null?void 0:d.source)==="mesh_peer_status"&&(t+=4),e.health==="online"&&(t+=4),e.health==="dirty"&&(t+=3),e.health==="degraded"&&(t+=2),e.launchReady&&(t+=2),e.gitProbePending&&(t-=40),e.error&&(t-=10),t}function m0(e,t){var g,h,b,y;const r=Ll(e),a=Ll(t)>r?t:e,o=a===t?e:t,l=a.git??o.git,c=(((g=a.providers)==null?void 0:g.length)??0)>0?a.providers:o.providers,d=(((h=a.activeSessions)==null?void 0:h.length)??0)>0?a.activeSessions:o.activeSessions,m=(((b=a.activeSessionDetails)==null?void 0:b.length)??0)>0?a.activeSessionDetails:o.activeSessionDetails,u=(((y=a.providerPriority)==null?void 0:y.length)??0)>0?a.providerPriority:o.providerPriority,p=a.connection??o.connection,x={...o,...a,machineLabel:a.machineLabel||o.machineLabel,workspace:a.workspace||o.workspace,...a.repoRoot||o.repoRoot?{repoRoot:a.repoRoot||o.repoRoot}:{},...a.daemonId||o.daemonId?{daemonId:a.daemonId||o.daemonId}:{},...a.machineId||o.machineId?{machineId:a.machineId||o.machineId}:{},...a.machineStatus||o.machineStatus?{machineStatus:a.machineStatus||o.machineStatus}:{},health:l&&(!a.health||a.health==="unknown")?On(l):a.health,providers:c??[],activeSessions:d??[],...m&&m.length>0?{activeSessionDetails:m}:{},...u&&u.length>0?{providerPriority:u}:{},...p?{connection:p}:{},...l?{git:l}:{}},w=ft(a.branchConvergence);return Object.keys(w).length>0?Object.assign(x,{branchConvergence:w}):delete x.branchConvergence,l&&(delete x.gitProbePending,delete x.error),x}function p0(e){const t=ft(e),r=Pe(t.nodeId,t.id);if(!r)return null;const n=ft(t.cachedStatus),a=a0(t),o=a?void 0:vn(ft(t.git),t)??vn(t,t),l=a??o,c=l?void 0:vn(ft(n.git),t),d=l??c,m=Pe(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),u=Pe(t.health),p=a?On(d):l0(u,l)||(d?On(d):void 0)||Pe(n.health)||m||Pe(t.status)||"unknown",w=(a?void 0:Pe(t.error))??(l?void 0:Pe(n.error)),g=c0(t),h=Ra(t.activeSessions),b=(g==null?void 0:g.map(k=>k.sessionId))??[],y=Ra(t.providerPriority),f=Et(t.gitProbePending,t.git_probe_pending),M=l?void 0:f,S=d0(t),v=ft(t.branchConvergence??t.branch_convergence),T=S==null?void 0:S.state,A=a&&(!(S!=null&&S.reported)||T==="unknown")?u0(S):S;return{nodeId:r,machineLabel:Pe(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:Pe(t.workspace,d==null?void 0:d.workspace)||"",...Pe(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:Pe(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},...Pe(t.daemonId,t.daemon_id)?{daemonId:Pe(t.daemonId,t.daemon_id)}:{},...Pe(t.machineId,t.machine_id)?{machineId:Pe(t.machineId,t.machine_id)}:{},...m?{machineStatus:m}:{},...Et(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Et(t.isLocalWorktree,t.is_local_worktree)}:{},...Pe(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:Pe(t.worktreeBranch,t.worktree_branch)}:{},health:p,...d?{git:d}:{},...M!==void 0?{gitProbePending:M}:{},providers:Ra(t.providers),activeSessions:h.length>0?h:b,...g&&g.length>0?{activeSessionDetails:g}:{},...y.length>0?{providerPriority:y}:{},...Et(t.launchReady)!==void 0?{launchReady:Et(t.launchReady)}:a?{launchReady:!0}:{},...Pe(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:Pe(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},...Pe(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:Pe(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...A?{connection:A}:{},...Object.keys(v).length>0?{branchConvergence:v}:{},...w?{error:w}:{}}}function hu(e){const t=new Map,r=[];for(const n of e){const a=t.get(n.nodeId);if(!a){t.set(n.nodeId,n),r.push(n);continue}const o=m0(a,n);t.set(n.nodeId,o);const l=r.findIndex(c=>c.nodeId===n.nodeId);l>=0&&(r[l]=o)}return r}function fu(e){return{...e,nodes:hu(e.nodes??[])}}function h0(e){var r;const t=e==null?void 0:e.git;return{nodeId:(e==null?void 0:e.nodeId)??null,chosenSource:t?"live_git":e!=null&&e.gitProbePending?"pending_git":"no_git",hasLiveGit:ci(e??{git:void 0}),branch:(t==null?void 0:t.branch)??null,upstream:(t==null?void 0:t.upstream)??null,headCommit:(t==null?void 0:t.headCommit)??null,submoduleCount:((r=t==null?void 0:t.submodules)==null?void 0:r.length)??0,pendingGit:(e==null?void 0:e.gitProbePending)===!0,connection:e!=null&&e.connection?{state:e.connection.state,transport:e.connection.transport,source:e.connection.source}:null}}function f0(e){const t=Pe(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(d=>p0(d)).filter(d=>d!==null):null;if(!t||!n)return null;const a=hu(n),o=Pe(e.meshName,e.mesh_name,e.name),l=Pe(e.repoIdentity,e.repo_identity),c=Pe(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!o||!l||!c?null:{...e,meshId:t,meshName:o,repoIdentity:l,refreshedAt:c,nodes:a}}function x0(e){var o;let t=0;const r=ft(e.sourceOfTruth),n=ft(r.directPeerTruth);Pe(r.currentStatus)==="live_git_and_session_probes"&&(t+=100),r.coordinatorOwnsLiveTruth===!0&&(t+=25),n.satisfied===!0&&(t+=15);for(const l of e.nodes){const c=l.git;if(!c){l.gitProbePending&&(t-=8);continue}t+=10,c.isGitRepo===!0&&(t+=5),c.isGitRepo===!1&&(t+=1),c.branch&&(t+=4),c.upstream&&(t+=3),c.headCommit&&(t+=3),t+=li(c.upstreamStatus),typeof c.ahead=="number"&&(t+=1),typeof c.behind=="number"&&(t+=1),typeof c.lastCheckedAt=="number"&&(t+=2),t+=(((o=c.submodules)==null?void 0:o.length)??0)*2}return t}function Rl(e){let t=null;for(const r of e){const n=f0(ft(r));if(!n)continue;const a=x0(n);(!t||a>t.score)&&(t={status:n,score:a})}return(t==null?void 0:t.status)??null}function xu(e){const r=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,n=Rl([r==null?void 0:r.status,r]);return n||Rl([e==null?void 0:e.status,e])}const b0=5*60*1e3;function g0(e){return ci(e)}function bu(e){var t;return g0(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function y0(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function gu(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function yu(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function di(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function v0(e){return di(e)?"degraded":yu(e)?"dirty":"online"}function w0(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function Pl(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)=>Pl(r)>Pl(t)?r:t)}function j0(e){var o,l,c,d,m;const t=new Map,r=new Map;for(const u of e){const p=(l=(o=u.git)==null?void 0:o.branch)==null?void 0:l.trim();p&&(r.set(p,(r.get(p)??0)+1),(c=u.git)!=null&&c.upstream&&t.set(p,(t.get(p)??0)+1))}const n=[...t.entries()].sort((u,p)=>{if(p[1]!==u[1])return p[1]-u[1];const x=["main","master","develop","dev"],w=x.indexOf(u[0]),g=x.indexOf(p[0]);return w!==-1||g!==-1?w===-1?1:g===-1?-1:w-g:u[0].localeCompare(p[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((m=[...r.entries()].sort((u,p)=>p[1]-u[1])[0])==null?void 0:m[0])??null}function k0(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 Dl(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 S0(e){return e.reduce((t,r)=>Dl(r.status)>Dl(t.status)?r:t)}function N0(e){const t=e.branchConvergenceSummary;if(Array.isArray(t==null?void 0:t.followUps))return t.followUps;const r=e.followUps;return Array.isArray(r)?r:(t==null?void 0:t.needsFollowUp)===!1||(t==null?void 0:t.unresolvedCount)===0?[]:null}function C0(e){var a,o,l;const t=e.sourceOfTruth,r=[],n=(a=t==null?void 0:t.fallback)==null?void 0:a.warning;return typeof n=="string"&&n.trim()&&r.push(n.trim()),(t==null?void 0:t.currentStatus)==="bootstrap_inventory_fallback"&&((o=t.directPeerTruth)==null?void 0:o.required)===!0&&((l=t.directPeerTruth)==null?void 0:l.satisfied)!==!0&&!r.some(c=>c.includes("direct mesh truth"))&&r.push("Direct mesh truth is not confirmed yet; this graph is drawn from setup inventory only."),r}function I0(e,t){return e.type!=="submoduleNode"&&e.branch===t&&e.ahead===0&&e.behind===0&&!e.dirty&&!e.hasConflicts&&(!e.upstreamStatus||e.upstreamStatus==="fresh")&&e.snapshotCompleteness==="complete"}function M0(e,t){var r,n;return{status:"merged_to_main",needsConvergence:!1,reason:"clean_default_branch_aggregate",nextStep:null,branch:e,defaultBranch:e,upstream:((r=t.find(a=>a.upstream))==null?void 0:r.upstream)??null,upstreamStatus:((n=t.find(a=>a.upstreamStatus))==null?void 0:n.upstreamStatus)??null,ahead:0,behind:0,dirty:!1,hasConflicts:!1}}function T0(e,t){if(bu(e))return null;const r=e.branchConvergence;if(!r||typeof r!="object")return null;const n=r.status;if(!n||!["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"].includes(n))return null;const a=e.git,o=gu(a)||yu(a),l=!!(a!=null&&a.hasConflicts)||di(a),c=(a==null?void 0:a.ahead)??0,d=(a==null?void 0:a.behind)??0,m=(a==null?void 0:a.branch)??null,u=(a==null?void 0:a.upstream)??null,p=(a==null?void 0:a.upstreamStatus)??null,x=r.defaultBranch??t??null;return{status:n,needsConvergence:r.needsConvergence??n!=="merged_to_main",reason:r.reason??"provided_by_coordinator",nextStep:r.nextStep??null,branch:r.branch??m,defaultBranch:x,upstream:r.upstream??u,upstreamStatus:r.upstreamStatus??p,ahead:r.ahead??c,behind:r.behind??d,dirty:r.dirty??o,hasConflicts:r.hasConflicts??l}}function A0(e,t){const r=T0(e,t);return r?{...r,defaultBranch:r.defaultBranch??t}:null}function _0(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function L0(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(bu(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const p=t.health==="online"||t.machineStatus==="online"||((d=t.connection)==null?void 0:d.state)==="connected"||((m=t.connection)==null?void 0:m.state)==="self";return a.push(p?`${o} is online but no peer git snapshot is visible yet.`:`${o} has no peer git snapshot visible yet.`),{snapshotCompleteness:"missing_git",snapshotWarnings:a}}const c=new Set((l.submodules??[]).map(p=>p.path));if(r.size>0){const p=[...r].filter(x=>!c.has(x));p.length>0&&a.push(`${o} is missing submodule visibility for ${p.join(", ")} even though another peer reported it.`)}return((u=t.connection)==null?void 0:u.state)!=="self"&&n!==null&&typeof l.lastCheckedAt=="number"&&n-l.lastCheckedAt>b0&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(p=>p.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(p=>p.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function R0(e){var L;const t=fu(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??j0(t.nodes),a=y0(t.refreshedAt),o=new Set(t.nodes.flatMap(N=>{var D;return(((D=N.git)==null?void 0:D.submodules)??[]).map($=>$.path)})),l=[],c=[],d=C0(t),m=new Map;for(const N of t.nodes){const D=N.git,$=(D==null?void 0:D.branch)??null,E=v0(D),C=gu(D)||E==="dirty",I=k0(N,n),O=A0(N,n),P=L0({nodeStatus:N,expectedSubmodulePaths:o,refreshedAtMs:a}),R={id:N.nodeId,type:I.length>0?"orphanNode":"worktreeNode",label:N.machineLabel||N.nodeId.slice(0,8),workspace:N.workspace,branch:$,upstream:(D==null?void 0:D.upstream)??null,upstreamStatus:(D==null?void 0:D.upstreamStatus)??null,machineLabel:N.machineLabel||null,health:Pa([N.health,E]),ahead:(D==null?void 0:D.ahead)??0,behind:(D==null?void 0:D.behind)??0,dirty:C,dirtyFiles:w0(D),hasConflicts:(D==null?void 0:D.hasConflicts)??!1,activeSessionCount:((L=N.activeSessions)==null?void 0:L.length)??0,activeSessions:N.activeSessions??[],providers:N.providers??[],isOrphan:I.length>0,orphanReasons:I,error:N.error,nextStepHint:P.snapshotWarnings[0]??I[0]??(O==null?void 0:O.nextStep)??void 0,parentNodeId:null,submodulePath:null,submoduleCommit:(D==null?void 0:D.headCommit)??null,outOfSync:di(D),snapshotCompleteness:P.snapshotCompleteness,snapshotWarnings:P.snapshotWarnings,branchConvergence:O,source:N};if(l.push(R),$){const U=m.get($)??[];U.push(R.id),m.set($,U)}for(const U of(D==null?void 0:D.submodules)??[]){const W=`${R.id}::submodule::${U.path}`,me=U.path.split("/").filter(Boolean).pop()||U.path;l.push({id:W,type:"submoduleNode",label:me,workspace:U.repoPath,branch:null,upstream:null,upstreamStatus:null,machineLabel:R.machineLabel,health:_0(U),ahead:0,behind:0,dirty:U.dirty,dirtyFiles:U.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],error:U.error,nextStepHint:U.error||(U.outOfSync?`${U.path} is out of sync with the parent checkout`:U.dirty?`${U.path} has local changes`:`${U.path} is in sync with the parent checkout`),parentNodeId:R.id,submodulePath:U.path,submoduleCommit:U.commit,outOfSync:U.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:R.id,parentWorkspace:N.workspace,submodule:U}}),c.push({id:`${R.id}--${W}`,source:R.id,target:W,type:"submoduleLink",label:U.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const u=n?`__branch_${n}`:null;if(u&&n){const D=(m.get(n)??[]).map(R=>l.find(U=>U.id===R)).filter(Boolean),$=D.map(R=>R.branchConvergence).filter(Boolean),E=N0(t),C=D.length>0&&D.every(R=>I0(R,n)),I=(E==null?void 0:E.length)===0&&C?M0(n,D):$.length>0?S0($):null,O=(E==null?void 0:E.length)===0&&C?0:$.filter(R=>R.needsConvergence).length,P={id:u,type:"defaultBranchNode",label:n,workspace:t.repoIdentity,branch:n,upstream:null,upstreamStatus:null,machineLabel:"default branch",health:Pa(D.map(R=>R.health)),ahead:0,behind:0,dirty:D.some(R=>R.dirty),dirtyFiles:D.reduce((R,U)=>R+U.dirtyFiles,0),hasConflicts:D.some(R=>R.hasConflicts),activeSessionCount:D.reduce((R,U)=>R+U.activeSessionCount,0),activeSessions:D.flatMap(R=>R.activeSessions),providers:[...new Set(D.flatMap(R=>R.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:O>0?`${O} workspace(s) on ${n} still need follow-up`:D.length>0?`${D.length} workspace(s) currently on ${n}`:"No workspaces currently checked out to the default branch",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:I,source:{nodeId:u,machineLabel:n,workspace:t.repoIdentity,health:Pa(D.map(R=>R.health)),providers:[],activeSessions:[]}};l.push(P);for(const R of l)if(!(R.id===u||R.type==="submoduleNode")){if(R.branch===n){c.push({id:`${u}--${R.id}`,source:u,target:R.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(R.branch){c.push({id:`${u}--${R.id}`,source:u,target:R.id,type:R.isOrphan?"orphanLink":"parentBranch",label:R.branch,direction:"undirected"});continue}R.isOrphan&&c.push({id:`${u}--${R.id}`,source:u,target:R.id,type:"orphanLink",label:"detached",direction:"undirected"})}}for(const[N,D]of m){if(D.length<2)continue;const $=D.map(E=>l.find(C=>C.id===E)).filter(Boolean);$.sort((E,C)=>E.label.localeCompare(C.label));for(let E=1;E<$.length;E+=1)c.push({id:`wt_${$[E-1].id}--${$[E].id}`,source:$[E-1].id,target:$[E].id,type:"worktreeLink",label:E===1?`${N} peers`:void 0,direction:"undirected"})}const p=l.filter(N=>N.type!=="defaultBranchNode"),x=p.filter(N=>N.isOrphan).length,w=p.filter(N=>N.hasConflicts).length,g=p.filter(N=>N.health==="offline").length,h=p.filter(N=>N.type==="submoduleNode"&&N.outOfSync).length,b=p.filter(N=>{var D;return N.type!=="submoduleNode"&&((D=N.branchConvergence)==null?void 0:D.needsConvergence)}).length,y=p.filter(N=>{var D;return((D=N.branchConvergence)==null?void 0:D.status)==="blocked_review"}).length,f=p.filter(N=>{var D;return((D=N.branchConvergence)==null?void 0:D.status)==="pushed_feature_branch_needs_merge"}).length,M=p.filter(N=>{var D;return((D=N.branchConvergence)==null?void 0:D.status)==="cleanup_candidate"}).length,S=p.filter(N=>{var D;return((D=N.branchConvergence)==null?void 0:D.status)==="not_mergeable"}).length,v=p.filter(N=>N.snapshotWarnings.length>0).length,T=p.filter(N=>N.snapshotCompleteness==="pending_git").length,A=p.filter(N=>N.snapshotCompleteness==="missing_git").length,k=p.filter(N=>N.snapshotCompleteness==="missing_submodule_report").length,j=p.filter(N=>N.snapshotCompleteness==="stale").length,B=[T>0?`${T} node(s) are still waiting for a live peer git snapshot`:null,A>0?`${A} node(s) have no visible peer git snapshot`:null,k>0?`${k} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,j>0?`${j} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return b>0&&d.push(`${b} workspace(s) still need follow-up before the mesh is converged`),x>0&&d.push(`${x} workspace(s) need attention before safe coordination`),y>0&&d.push(`${y} workspace(s) are blocked on branch convergence or upstream sync`),f>0&&d.push(`${f} clean feature branch workspace(s) still need merge follow-up`),M>0&&d.push(`${M} worktree workspace(s) are ready for refine / cleanup`),S>0&&d.push(`${S} workspace(s) have local changes or conflicts blocking convergence`),w>0&&d.push(`${w} workspace(s) report merge conflicts`),g>0&&d.push(`${g} node(s) are currently offline`),h>0&&d.push(`${h} submodule(s) are out of sync with their parent checkout`),d.push(...B),n||d.push("Could not infer a default branch from live mesh status"),{meshId:t.meshId,meshName:t.meshName,repoIdentity:t.repoIdentity,refreshedAt:t.refreshedAt,nodes:l,edges:c,stats:{totalNodes:p.length,onlineNodes:p.filter(N=>N.health==="online").length,dirtyNodes:p.filter(N=>N.dirty).length,orphanNodes:x,errorNodes:p.filter(N=>!!N.error||N.outOfSync).length,offlineNodes:g,followUpNodes:b,blockedReviewNodes:y,mergeReadyNodes:f,cleanupCandidateNodes:M,notMergeableNodes:S,incompleteSnapshotNodes:v,missingGitSnapshotNodes:A,missingSubmoduleSnapshotNodes:k,staleGitSnapshotNodes:j,totalActiveSessions:p.reduce((N,D)=>N+D.activeSessionCount,0)},warnings:d,snapshotWarnings:B}}const P0={recentFailures:0},ui=i.createContext(Zs("dark"));function nt({label:e,tone:t="default"}){const r=i.useContext(ui);return s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${r.badge(t)}`,children:e})}function ss({label:e,value:t}){const r=i.useContext(ui);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 D0(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 E0(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 $0(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 B0(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 O0(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 El(e){return e?e.slice(0,7):null}function F0(e,t){var o,l,c;const r=El((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?[El(a.commit),a.message].filter(Boolean).join(" · "):null}function W0(e,t){const r=F0(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function H0(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 K0(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 U0(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":B0(e.connection)}function z0(e){var r;const t=e.source;return t!=null&&t.kind?t.kind:((r=t==null?void 0:t.connection)==null?void 0:r.source)??"mesh_status"}function G0(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function vu({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null}){var I,O,P,R,U;const{theme:a}=Qs(),o=i.useMemo(()=>Zs(a),[a]),l=i.useMemo(()=>fu(e),[e]),c=i.useMemo(()=>R0(l),[l]),[d,m]=i.useState(null),[u,p]=i.useState(null),[x,w]=i.useState({}),g=i.useMemo(()=>new Map(l.nodes.map(W=>[W.nodeId,W])),[l.nodes]),h=i.useMemo(()=>new Map(c.nodes.map(W=>[W.id,W])),[c.nodes]),b=((I=l.queue)==null?void 0:I.summary)??null,y=((O=l.ledger)==null?void 0:O.summary)??P0,f=i.useMemo(()=>O0(l),[l]),M=i.useMemo(()=>{const W=new Map;for(const me of f){const ie=me.session.state||me.session.lifecycle||"unknown";W.set(ie,(W.get(ie)??0)+1)}return[...W.entries()].sort((me,ie)=>ie[1]-me[1])},[f]);i.useEffect(()=>{d&&(h.has(d)||(m(null),p(W=>!W||"nodeId"in W&&W.nodeId===d?null:W)))},[h,d]);const S=d?g.get(d)??null:null,v=G0(c,d);i.useEffect(()=>{var W,me,ie;if(d)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:l.meshId,selectedNodeId:d,canonicalNode:h0(S),graphNode:v?{id:v.id,branch:v.branch,upstream:v.upstream,headCommit:v.submoduleCommit,submoduleCount:((me=(W=S==null?void 0:S.git)==null?void 0:W.submodules)==null?void 0:me.length)??0,snapshotCompleteness:v.snapshotCompleteness,snapshotWarnings:v.snapshotWarnings,branchConvergence:((ie=v.branchConvergence)==null?void 0:ie.status)??null}:null})}catch{}},[l.meshId,v,d,S]);const T=(u==null?void 0:u.kind)==="session"?f.find(W=>W.nodeId===u.nodeId&&W.session.sessionId===u.sessionId)??null:null,A=i.useMemo(()=>f.filter(W=>W.nodeId===d),[d,f]),k=K0({coordinatorDaemonId:r,selectedNodeStatus:S,selectedSessionEntry:T}),j=(k==null?void 0:k.workspace)??null,B=j?x[j]??null:null,L=W0(S,(B==null?void 0:B.entries)??[]),N=i.useCallback(()=>{m(null),p(null)},[]);i.useEffect(()=>{if(!v)return;const W=me=>{me.key==="Escape"&&N()};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[N,v]),i.useEffect(()=>{if(!k||!n)return;const{daemonId:W,workspace:me}=k,ie=x[me];if(ie!=null&&ie.loading||ie&&(ie.entries.length>0||ie.error))return;let ee=!1;return w(ce=>{var je;return{...ce,[me]:{loading:!0,error:null,entries:((je=ce[me])==null?void 0:je.entries)??[]}}}),n(W,"git_log",{workspace:me,limit:5}).then(ce=>{ee||w(je=>({...je,[me]:{loading:!1,error:null,entries:H0(ce)}}))}).catch(ce=>{ee||w(je=>({...je,[me]:{loading:!1,error:ce instanceof Error?ce.message:"git_log failed",entries:[]}}))}),()=>{ee=!0}},[x,k,n]);const D=[...c.warnings??[],...l.nodes.filter(W=>W.machineStatus&&W.machineStatus!=="online").map(W=>`${W.machineLabel}: ${W.machineStatus}`)],$=c.stats.incompleteSnapshotNodes>0,E=c.stats.followUpNodes>0?`${c.stats.followUpNodes} need follow-up`:$?"mesh visibility incomplete":"mesh converged",C=c.stats.followUpNodes>0?"danger":$?"warn":"good";return s.jsx(ui.Provider,{value:o,children:s.jsx("div",{className:"flex min-h-0 flex-col gap-4",children:s.jsx("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-4",children:s.jsxs("div",{className:`${o.cardClass} relative min-h-0 flex-1 rounded-[28px] p-3 sm:p-4`,style:{minHeight:420},children:[s.jsxs("div",{className:`absolute inset-x-4 top-4 z-30 flex max-h-[42dvh] flex-wrap items-start justify-between gap-3 overflow-y-auto rounded-2xl px-3.5 py-3 backdrop-blur-xl sm:static sm:mb-3 sm:max-h-none sm:overflow-visible sm:backdrop-blur-none ${o.isDark?"border border-white/10 bg-slate-950/85 sm:bg-slate-950/45":"border border-slate-200 bg-white/95 shadow-lg shadow-slate-900/10 sm:bg-white/95 sm:shadow-sm"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-wrap gap-2 text-xs ${o.textSecondary}`,children:[s.jsx(nt,{label:E,tone:C}),c.stats.blockedReviewNodes>0&&s.jsx(nt,{label:`${c.stats.blockedReviewNodes} blocked review`,tone:"danger"}),c.stats.notMergeableNodes>0&&s.jsx(nt,{label:`${c.stats.notMergeableNodes} not mergeable`,tone:"danger"}),c.stats.mergeReadyNodes>0&&s.jsx(nt,{label:`${c.stats.mergeReadyNodes} need merge`,tone:"warn"}),c.stats.cleanupCandidateNodes>0&&s.jsx(nt,{label:`${c.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),c.stats.offlineNodes>0&&s.jsx(nt,{label:`${c.stats.offlineNodes} offline`,tone:"danger"}),c.stats.incompleteSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),c.stats.missingGitSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),c.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),c.stats.staleGitSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((b==null?void 0:b.active)??0)>0&&s.jsx(nt,{label:`${(b==null?void 0:b.active)??0} active queue`,tone:"info"}),s.jsx(nt,{label:`${c.stats.totalNodes} nodes`,tone:"default"}),c.stats.totalActiveSessions>0&&s.jsx(nt,{label:`${c.stats.totalActiveSessions} active sessions`,tone:"info"})]}),s.jsxs("details",{className:`max-w-full rounded-xl px-3 py-2 text-xs ${o.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${o.textSecondary} [&::-webkit-details-marker]:hidden`,children:"Legend & secondary details"}),s.jsxs("div",{className:"mt-3 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(nt,{label:`${c.stats.dirtyNodes} dirty`,tone:c.stats.dirtyNodes>0?"warn":"good"}),s.jsx(nt,{label:`${c.stats.orphanNodes} orphan`,tone:c.stats.orphanNodes>0?"warn":"good"}),s.jsx(nt,{label:`${y.recentFailures} recent failures`,tone:y.recentFailures>0?"danger":"good"}),M.length===0?s.jsx(nt,{label:"no session metadata"}):M.slice(0,2).map(([W,me])=>s.jsx(nt,{label:`${me} ${W}`,tone:E0(W)},W))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(nt,{label:"Anchor = default branch",tone:"info"}),s.jsx(nt,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(nt,{label:"Submodule link = child checkout",tone:"warn"})]}),D.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:D.map(W=>s.jsx("span",{className:o.isDark?"rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1 text-xs text-amber-100":"rounded-full border border-amber-300 bg-amber-50 px-3 py-1 text-xs text-amber-700",children:W},W))}),s.jsx("div",{className:`text-xs ${o.textMuted}`,children:"Click a node only when you want drill-down details. The graph itself now carries the convergence state."})]})]})]}),c.nodes.length>0?s.jsx(e0,{data:c,selectedNodeId:d,onNodeClick:W=>{if((u==null?void 0:u.kind)==="node"&&d===W.id){m(null),p(null);return}m(W.id),p({kind:"node",nodeId:W.id})}}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:t}),v&&(u==null?void 0:u.kind)==="node"&&s.jsx("div",{className:"absolute inset-x-3 bottom-3 top-20 z-20 flex items-end justify-center p-2 sm:inset-5 sm:top-24 sm:items-start sm:justify-end",onClick:N,role:"presentation",children:s.jsxs("section",{role:"dialog","aria-modal":"false","aria-label":"Selected node",className:o.isDark?"max-h-[min(72vh,540px)] w-full max-w-[min(28rem,calc(100vw-2.5rem))] overflow-y-auto rounded-2xl border border-white/12 bg-slate-950/96 p-4 shadow-2xl shadow-black/40 backdrop-blur-xl":"max-h-[min(72vh,540px)] w-full max-w-[min(28rem,calc(100vw-2.5rem))] overflow-y-auto rounded-2xl border border-slate-200 bg-white/96 p-4 shadow-2xl shadow-slate-900/15 backdrop-blur-xl",onClick:W=>W.stopPropagation(),children:[s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${o.textPrimary}`,children:v.label}),s.jsx("div",{className:`mt-1 font-mono text-[11px] ${o.textMuted}`,children:v.id.slice(0,16)})]}),s.jsx("button",{type:"button",onClick:N,className:o.isDark?"rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-xs text-slate-200 transition hover:bg-white/[0.08]":"rounded-full border border-slate-200 bg-white px-2.5 py-1 text-xs text-slate-600 transition hover:bg-slate-50",children:"Close"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[s.jsx(nt,{label:(S==null?void 0:S.health)??v.health,tone:D0((S==null?void 0:S.health)??v.health)}),v.branch&&s.jsx(nt,{label:v.branch,tone:"default"}),v.ahead>0&&s.jsx(nt,{label:`ahead ${v.ahead}`,tone:"warn"}),v.behind>0&&s.jsx(nt,{label:`behind ${v.behind}`,tone:"warn"}),v.dirtyFiles>0&&s.jsx(nt,{label:`${v.dirtyFiles} dirty`,tone:"warn"}),(S==null?void 0:S.connection)&&s.jsx(nt,{label:U0(S),tone:$0(S.connection)}),A.length>0&&s.jsx(nt,{label:`${A.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[s.jsx(ss,{label:"Workspace",value:(S==null?void 0:S.workspace)??v.workspace}),s.jsx(ss,{label:"Branch",value:v.branch??"unknown"}),s.jsx(ss,{label:"HEAD",value:L??(S!=null&&S.gitProbePending?"Pending live git probe":"not reported")}),s.jsx(ss,{label:"Upstream",value:v.upstream??"none"}),s.jsx(ss,{label:"Dirty/ahead/behind",value:`${v.dirtyFiles} dirty · ↑${v.ahead}/↓${v.behind}`}),s.jsx(ss,{label:"Source",value:String(((P=S==null?void 0:S.connection)==null?void 0:P.source)??z0(v))}),s.jsx(ss,{label:"Transport",value:((R=S==null?void 0:S.connection)==null?void 0:R.transport)??"unknown"}),s.jsx(ss,{label:"Sessions",value:A.length>0?A.map(W=>W.session.state||W.session.lifecycle||"unknown").join(", "):"none active"})]}),v.snapshotWarnings.length>0&&s.jsxs("div",{className:o.isDark?"mt-3 rounded-xl border border-amber-400/20 bg-amber-500/10 p-3 text-xs text-amber-100":"mt-3 rounded-xl border border-amber-300 bg-amber-50 p-3 text-xs text-amber-800",children:[s.jsx("div",{className:"font-medium",children:"Key warning"}),s.jsx("div",{className:"mt-1",children:v.snapshotWarnings[0]})]}),((U=v.branchConvergence)==null?void 0:U.nextStep)&&s.jsxs("div",{className:o.isDark?"mt-3 rounded-xl border border-sky-400/20 bg-sky-500/10 p-3 text-xs text-sky-100":"mt-3 rounded-xl border border-sky-300 bg-sky-50 p-3 text-xs text-sky-800",children:[s.jsx("div",{className:"font-medium",children:"Follow-up"}),s.jsx("div",{className:"mt-1",children:v.branchConvergence.nextStep})]})]})})]})})})})}function V0({activeConv:e,sendDaemonCommand:t,onClose:r}){var v;const n=typeof((v=e.settings)==null?void 0:v.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null,a=e.daemonId??null,o=Ed(),{theme:l}=Qs(),c=i.useMemo(()=>Zs(l),[l]),[d,m]=i.useState(null),[u,p]=i.useState(!1),[x,w]=i.useState(null),[g,h]=i.useState(null),b=i.useRef(!1);i.useEffect(()=>{b.current=d!==null},[d]);const y=i.useCallback(async(T=!1)=>{if(!a||!n){w("This coordinator does not expose a live mesh id."),m(null);return}p(!b.current),w(null);try{const A=o!=null&&o.loadMeshStatus?await o.loadMeshStatus(a,n,{refresh:T}):await t(a,"mesh_status",{meshId:n,refresh:T}),k=xu(A);if(!k){w("mesh_status returned an unexpected payload.");return}m(k),h(k.refreshedAt||new Date().toISOString())}catch(A){w(A instanceof Error?A.message:"Failed to load live mesh status")}finally{p(!1)}},[a,n,o,t]);i.useEffect(()=>{y(!1)},[y]),i.useEffect(()=>{const T=A=>{A.key==="Escape"&&r()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[r]);const f=(d==null?void 0:d.meshName)||n||"Repo Mesh",M=g?new Date(g).toLocaleTimeString():null,S=i.useMemo(()=>u?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[u]);return s.jsx("div",{className:c.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:c.dialogShellClass,onClick:T=>T.stopPropagation(),children:[s.jsxs("div",{className:c.dialogHeaderClass,children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-400/20 bg-sky-500/12 text-sky-200 shadow-[0_12px_30px_rgba(14,165,233,0.18)]",children:s.jsx(ns,{size:18})}),s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("h2",{className:c.dialogTitleClass,children:f}),s.jsx("span",{className:c.dialogKickerClass,children:"Mesh observability"})]}),s.jsxs("p",{className:c.dialogSubtitleClass,children:[ut(e),e.workspaceName?` · ${e.workspaceName}`:"",d!=null&&d.repoIdentity?` · ${d.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[M&&s.jsxs("span",{className:c.dialogRefreshedChipClass,children:["Refreshed ",M]}),s.jsx("button",{type:"button",onClick:()=>{y(!0)},disabled:u,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:u?"Refreshing…":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:c.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:s.jsx(jt,{size:16})})]})]}),x&&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:x}),s.jsx("div",{className:c.dialogBodyClass,children:d?s.jsx(vu,{status:d,emptyMessage:S,daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:c.dialogEmptyClass,children:S})})]})})}function q0(e,t){const{sendCommand:r}=kt(),[n,a]=i.useState(null),[o,l]=i.useState(!1);i.useEffect(()=>{if(!e||!t){a(null);return}l(!0),r(e,"git_remote_url",{workspace:t}).then(d=>{const m=(d==null?void 0:d.result)??d;a(typeof(m==null?void 0:m.remoteUrl)=="string"?m.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>l(!1))},[e,t,r]);const c=Y0(n);return{remoteUrl:n,githubUrl:c,loading:o}}function Y0(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 wu=5e3;function X0(e){return`git:${e}`}function J0({workspace:e,includeDiffSummary:t=!1,intervalMs:r=wu}){return{type:"subscribe",topic:"workspace.git",key:X0(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 Q0(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 Da(e){return e===void 0||typeof e=="boolean"}function ev(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Da(t.binary)&&Da(t.truncated)&&Da(t.staged)}function tv(e){const t=mi(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Ms(t,"Git file diff request failed")}:ev(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 sv({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=wu}){const{sendCommand:o,sendData:l}=kt(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[m,u]=i.useState(null),[p,x]=i.useState(null),[w,g]=i.useState(!1),[h,b]=i.useState(null),y=i.useCallback(async()=>{if(!(!d||!e||!c)){g(!0),b(null);try{const M=Q0(await o(e,"git_status",{workspace:c}));if(M.error){u(null),x(null),b(M.error);return}if(u(M.status),!n){x(null);return}const S=Z0(await o(e,"git_diff_summary",{workspace:c}));if(S.error){x(null),b(S.error);return}x(S.diffSummary)}catch(M){b(Ms(M,"Git status request failed"))}finally{g(!1)}}},[d,e,n,o,c]),f=i.useMemo(()=>c?J0({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return i.useEffect(()=>{if(!d||!e||!c||!f){u(null),x(null),g(!1),b(null);return}const M=l?Jt.subscribe({sendData:l},e,f,S=>{var v,T;S.workspace===c&&(u(S.status),x(S.diffSummary??null),b(((v=S.status)==null?void 0:v.error)||((T=S.diffSummary)==null?void 0:T.error)||null),g(!1))},{retryIntervalMs:1e3}):null;return y(),()=>{M==null||M()}},[d,e,y,f,l,c]),{status:m,diffSummary:p,loading:w,error:h,refresh:y}}const rv={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},nv={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 $l(e){return e.split("/").pop()??e}function av(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function ov({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=rv[o.status]??"?",d=nv[o.status]??"text-zinc-400",m=av(o.path),u=$l(o.path),p=o.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${l?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(o),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:o.status,children:c}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&s.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),s.jsx("span",{className:"text-text-primary",children:u}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",$l(o.oldPath)]}),p]}),!o.binary&&(o.insertions>0||o.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",o.insertions]}),o.insertions>0&&o.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),o.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",o.deletions]})]}),o.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${o.path}-${o.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function iv(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 lv({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)=>iv(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 cv(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 ju({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=kt(),{status:a,diffSummary:o,loading:l,error:c,refresh:d}=sv({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=i.useState(null),[p,x]=i.useState(null),[w,g]=i.useState(""),[h,b]=i.useState(!1),[y,f]=i.useState(!1),[M,S]=i.useState(null),[v,T]=i.useState(null),{githubUrl:A}=q0(e,t),k=i.useCallback(async $=>{if(!((m==null?void 0:m.path)===$.path&&!m.loading)){u({path:$.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const E=await n(e,"git_diff_file",{workspace:t,path:$.path,staged:$.staged}),C=tv(E);if(C.error||!C.diff){u({path:$.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C.error??"Failed to load diff"});return}u({path:$.path,diff:C.diff.diff,binary:C.diff.binary??!1,truncated:C.diff.truncated??!1,loading:!1,error:null})}catch(E){const C=E instanceof Error?E.message:"Failed to load diff";u({path:$.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C})}}},[e,n,m,t]),j=i.useCallback($=>{g(""),b(!1),S(null),T(null),x($)},[]),B=i.useCallback(()=>{x(null),S(null),f(!1)},[]),L=i.useCallback(async()=>{var $,E,C;if(p){f(!0),S(null);try{let I;p==="checkpoint"?I=await n(e,"git_checkpoint",{workspace:t,message:w,includeUntracked:h}):p==="stash"?I=await n(e,"git_stash_push",{workspace:t,message:w,includeUntracked:h}):p==="stash_pop"?I=await n(e,"git_stash_pop",{workspace:t}):p==="checkout_files"&&m&&(I=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const O=(I==null?void 0:I.result)??I;if((O==null?void 0:O.success)===!1||O!=null&&O.error){S((O==null?void 0:O.error)??"Action failed"),f(!1);return}p==="checkpoint"?T(`Checkpoint created: ${((E=($=O==null?void 0:O.checkpoint)==null?void 0:$.commit)==null?void 0:E.slice(0,7))??"done"}`):p==="stash"?T(`Stashed as ${((C=O==null?void 0:O.stash)==null?void 0:C.stashRef)??"stash@{0}"}`):p==="stash_pop"?T("Stash restored"):(T("File reverted"),u(null)),x(null),await d()}catch(I){S(I instanceof Error?I.message:"Action failed")}finally{f(!1)}}},[p,n,e,t,w,h,m,d]),N=!!(a!=null&&a.hasConflicts),D=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:$=>{$.target===$.currentTarget&&r()},children:s.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),A&&s.jsx("a",{href:`${A}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-sky-400 underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:d,disabled:l,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),s.jsx("button",{onClick:r,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(jt,{className:"h-4 w-4"})})]}),a&&s.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[a.headCommit&&s.jsxs("span",{title:a.headMessage??void 0,children:[s.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&s.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&s.jsxs("span",{className:"text-orange-400",children:["↑",a.ahead," ahead"]}),a.behind>0&&s.jsxs("span",{className:"text-orange-400",children:["↓",a.behind," behind"]}),a.staged>0&&s.jsxs("span",{className:"text-emerald-400",children:[a.staged," staged"]}),a.modified>0&&s.jsxs("span",{children:[a.modified," modified"]}),a.untracked>0&&s.jsxs("span",{children:[a.untracked," untracked"]}),a.deleted>0&&s.jsxs("span",{className:"text-red-400",children:[a.deleted," deleted"]}),a.stashCount>0&&s.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&s.jsx("span",{className:"font-bold text-red-400",children:"conflicts"}),D===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(ov,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:k}),!l&&!o&&!c&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:m?s.jsx(lv,{diff:m.diff,binary:m.binary,truncated:m.truncated,loading:m.loading,error:m.error,className:"h-full"}):s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),v&&s.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-emerald-500/10 px-4 py-2 text-xs text-emerald-400 flex items-center justify-between",children:[s.jsx("span",{children:v}),s.jsx("button",{onClick:()=>T(null),className:"ml-2 text-emerald-400 hover:text-text-primary",children:"×"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[s.jsx("button",{onClick:()=>j("checkpoint"),disabled:N,title:N?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),s.jsx("button",{onClick:()=>j("stash"),disabled:N,title:N?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),s.jsx("button",{onClick:()=>j("stash_pop"),disabled:N||!(a!=null&&a.stashCount),title:N?"Resolve conflicts before restoring a stash":a!=null&&a.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),s.jsx("button",{onClick:()=>j("checkout_files"),disabled:!m,title:m?`Revert changes to ${m.path}`:"Select a file to revert",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkout selected"}),o&&o.files.length>0&&s.jsx("button",{onClick:()=>{const $=cv((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText($),T("Copied to clipboard"),setTimeout(()=>T(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),p&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[p==="checkpoint"&&"Create checkpoint commit",p==="stash"&&"Stash changes",p==="stash_pop"&&"Restore latest stash?",p==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(p==="checkpoint"||p==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:w,onChange:$=>g($.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:h,onChange:$=>b($.target.checked)}),"Include untracked files"]})]}),M&&s.jsx("p",{className:"text-xs text-red-400",children:M}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:B,disabled:y,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),s.jsx("button",{onClick:L,disabled:y||(p==="checkpoint"||p==="stash")&&!w.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:y?"Working…":"Confirm"})]})]})})]})})}function dv({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=i.useState(!1),[o,l]=i.useState(!1),[c,d]=i.useState(!1),[m,u]=i.useState(!1),[p,x]=i.useState(!1),[w,g]=i.useState("quickstart"),[h,b]=i.useState("workspace"),y=i.useMemo(()=>!t&&!e,[t,e]),f=i.useCallback(k=>{a(k),k&&l(!1)},[]),M=i.useCallback(k=>{l(k),k&&a(!1)},[]),S=i.useCallback(()=>{g(r===0?"quickstart":"shortcuts"),b("workspace"),d(!0),a(!1),l(!1)},[r]),v=i.useCallback(()=>{d(!1)},[]),T=i.useCallback(()=>{u(!0)},[]),A=i.useCallback(()=>{u(!1)},[]);return i.useEffect(()=>{if(!y){x(!1);return}x(!0);const k=window.setTimeout(()=>{x(!1)},1e4);return()=>window.clearTimeout(k)},[y]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:m,guideNudgeVisible:p,guideTab:w,shortcutSection:h,isDesktopDashboard:y,setGuideTab:g,setShortcutSection:b,handleInboxOpenChange:f,handleHiddenOpenChange:M,handleOpenShortcutHelp:S,closeShortcutHelp:v,openNewSession:T,closeNewSession:A}}function uv(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 mv(e){return e instanceof Error?e.message:String(e||"")}function pv(e){const t=mv(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function hv({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:l,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:p,ides:x,actionLogs:w,sendDaemonCommand:g,setActionLogs:h,setCliViewModeOverrides:b,isStandalone:y,initialDataLoaded:f,userName:M,requestedMobileTabKey:S,onRequestedMobileTabConsumed:v,requestedMachineId:T,onRequestedMachineConsumed:A,requestedMobileSection:k,onRequestedMobileSectionConsumed:j,containerRef:B,isSplitMode:L,numGroups:N,groupSizes:D,groupedConvs:$,clearedTabs:E,focusedGroup:C,focusGroup:I,moveTabToGroup:O,splitTabRelative:P,closeGroup:R,handleResizeStart:U,groupActiveTabIds:W,setGroupActiveTab:me,groupTabOrders:ie,setGroupTabOrder:ee,toggleHiddenTab:ce,visibleConversations:je,requestedDesktopTabKey:Ne,onRequestedDesktopTabConsumed:q,onDesktopActiveTabChange:ge,onRequestScrollToBottom:fe,onHideConversation:we,onShowHiddenConversation:xe,onShowAllHiddenConversations:Se,scrollToBottomRequest:J,machineEntries:he,layoutProfile:ae,onBrowseMachineDirectory:ue,onSaveMachineWorkspace:oe,onLaunchMachineIde:de,onLaunchMachineProvider:Q,onListMachineMeshes:ve,onLaunchMeshCoordinator:le,onListMachineSavedSessions:pe,notifications:ne,notificationUnreadCount:Ie,liveSessionInboxState:Ce,onMarkNotificationRead:_e,onMarkNotificationUnread:K,onDeleteNotification:Me}){const Te=St.useRef(null),{inboxOpen:He,hiddenOpen:Ge,shortcutHelpOpen:Xe,newSessionOpen:Ye,guideNudgeVisible:tt,guideTab:ct,shortcutSection:mt,isDesktopDashboard:pt,setGuideTab:F,setShortcutSection:be,handleInboxOpenChange:Ae,handleHiddenOpenChange:Be,handleOpenShortcutHelp:qe,closeShortcutHelp:G,openNewSession:z,closeNewSession:X}=dv({isMobile:t,showMobileChatMode:e,visibleConversationCount:je.length}),[se,H]=St.useState(null),[V,te]=St.useState(null),re=St.useCallback((_,Y)=>{H({daemonId:_,workspace:Y})},[]),ke=St.useCallback(_=>{te(_)},[]),Ee=St.useCallback(_=>{var Y;Nr.flushSync(()=>{xe(_)}),(Y=Te.current)==null||Y.restoreHiddenTabToSavedLocation(_.tabKey)},[xe]),Oe=St.useCallback(_=>{var ye;const Y=u.find(We=>no(We,_))||p.find(We=>no(We,_));Y&&(p.some(We=>We.tabKey===Y.tabKey)&&Ee(Y),ge(Y.tabKey),(ye=Te.current)==null||ye.activateConversationTab(Y.tabKey),fe(Y.tabKey,"notification-open")),_e(_.id),Ae(!1)},[Ee,p,u,ge,_e,fe]),Re=St.useCallback(()=>{var Y;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Y=Te.current)==null||Y.resetAllPanelsToMain(),Be(!1))},[Be]),Fe=St.useCallback(async _=>{var Ke;if(!r)return;const Y=(Ke=r.modalButtons)==null?void 0:Ke[_];if(!Y)return;const ye=Us(r);if(!ye)return;const We=Y.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),De=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(We);try{await g(ye,"resolve_action",{button:Y,action:De?"approve":"reject",buttonIndex:_,...fs(r)})}catch(rt){pv(rt)||console.error("[Shortcut approval] Failed:",rt)}},[r,g]),{isMac:Ue,actionDefinitions:Le,actionShortcuts:Ze,shortcutListening:et,shortcutListeningDraft:gt,setShortcutListening:yt,setShortcutListeningDraft:dt,saveShortcuts:xt}=fy({enabled:pt&&!Xe,onTrigger:_=>{var Y,ye,We,De,Ke,rt,Tt,bt,es,Er,$r,Br,Or,Fr,Wr,Hr;if(_==="openShortcutHelp"){qe();return}if(_==="openNewSession"){z();return}if(_==="hideCurrentTab"){r&&we(r);return}if(_==="toggleHiddenTabs"){Be(!Ge);return}if(_==="openHistoryForActiveTab"){r&&!st(r)&&o(r);return}if(_==="openRemoteForActiveTab"){r&&!at(r)&&!st(r)&&l(r);return}if(_==="splitActiveTabRight"){(Y=Te.current)==null||Y.splitActiveTabRight();return}if(_==="splitActiveTabDown"){(ye=Te.current)==null||ye.splitActiveTabDown();return}if(_==="floatActiveTab"){(We=Te.current)==null||We.floatActiveTab();return}if(_==="popoutActiveTab"){(De=Te.current)==null||De.popoutActiveTab();return}if(_==="dockActiveTab"){(Ke=Te.current)==null||Ke.dockActiveTab();return}if(_==="focusLeftPane"){(rt=Te.current)==null||rt.focusLeftPane();return}if(_==="focusRightPane"){(Tt=Te.current)==null||Tt.focusRightPane();return}if(_==="focusUpPane"){(bt=Te.current)==null||bt.focusUpPane();return}if(_==="focusDownPane"){(es=Te.current)==null||es.focusDownPane();return}if(_==="moveActiveTabToLeftPane"){(Er=Te.current)==null||Er.moveActiveTabToLeftPane();return}if(_==="moveActiveTabToRightPane"){($r=Te.current)==null||$r.moveActiveTabToRightPane();return}if(_==="moveActiveTabToUpPane"){(Br=Te.current)==null||Br.moveActiveTabToUpPane();return}if(_==="moveActiveTabToDownPane"){(Or=Te.current)==null||Or.moveActiveTabToDownPane();return}if(_==="triggerPrimaryApprovalAction"){Fe(0);return}if(_==="triggerSecondaryApprovalAction"){Fe(1);return}if(_==="triggerTertiaryApprovalAction"){Fe(2);return}if(_==="setActiveTabShortcut"){(Fr=Te.current)==null||Fr.setShortcutForActiveTab();return}if(_==="selectPreviousGroupTab"){(Wr=Te.current)==null||Wr.activatePreviousTabInGroup();return}if(_==="selectNextGroupTab"){(Hr=Te.current)==null||Hr.activateNextTabInGroup();return}!r||!at(r)||st(r)||_==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),Ve=St.useCallback(()=>{G(),yt(null),dt([])},[G,yt,dt]),Ht=St.useMemo(()=>mt==="all"?Le:Le.filter(_=>uv(_)===mt),[Le,mt]),Z=St.useCallback(()=>{const _=Object.fromEntries(Le.map(Y=>[Y.id,""]));xt(_)},[Le,xt]),$e=St.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const _=Object.fromEntries(Le.map(Y=>[Y.id,Y.defaultShortcut]));xt(_)},[Le,xt]);return St.useEffect(()=>{const _=Y=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Y.metaKey&&Y.key.toLowerCase()==="w":Y.ctrlKey&&Y.key.toLowerCase()==="w")&&(Y.preventDefault(),r&&we&&we(r))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[r,we]),St.useEffect(()=>{if(!Xe||et)return;const _=Y=>{Y.key==="Escape"&&(Y.preventDefault(),Ve())};return window.addEventListener("keydown",_,!0),()=>window.removeEventListener("keydown",_,!0)},[Ve,Xe,et]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(px,{activeConv:r,wsStatus:n,isConnected:a,conversations:je,hiddenConversations:p,onOpenHistory:o,onHideConversation:we,onShowConversation:Ee,onShowAllHidden:Se,onResetPanelsToMain:Re,notifications:ne,notificationUnreadCount:Ie,onOpenNotification:Oe,onMarkNotificationRead:_e,onMarkNotificationUnread:K,onDeleteNotification:Me,inboxOpen:He,onInboxOpenChange:Ae,hiddenOpen:Ge,onHiddenOpenChange:Be,onOpenNewSession:t?void 0:z,onOpenDashboardGuide:qe,guideNudgeVisible:tt,actionShortcuts:Ze,onOpenRemote:()=>{!r||at(r)||st(r)||l(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:re,onOpenMeshGraph:ke}),e?s.jsx(ry,{conversations:u,hiddenConversations:p,ides:x,actionLogs:w,sendDaemonCommand:g,setActionLogs:h,setCliViewModeOverrides:b,isStandalone:y,userName:M,requestedActiveTabKey:S,onRequestedActiveTabConsumed:v,requestedMachineId:T,onRequestedMachineConsumed:A,requestedMobileSection:k,onRequestedMobileSectionConsumed:j,onOpenHistory:o,onOpenRemote:l,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Se,onHideConversation:we,onOpenMeshGraph:ke,onOpenNewSession:z,liveSessionInboxState:Ce}):t?s.jsx(uy,{containerRef:B,isSplitMode:L,numGroups:N,groupSizes:D,groupedConvs:$,clearedTabs:E,ides:x,actionLogs:w,sendDaemonCommand:g,setActionLogs:h,isStandalone:y,hasRegisteredMachines:he.length>0,userName:M,focusedGroup:C,focusGroup:I,moveTabToGroup:O,splitTabRelative:P,closeGroup:R,handleResizeStart:U,groupActiveTabIds:W,setGroupActiveTab:me,groupTabOrders:ie,setGroupTabOrder:ee,toggleHiddenTab:ce,onOpenNewSession:z,allowTabShortcuts:!1,liveSessionInboxState:Ce}):s.jsx(Ty,{visibleConversations:je,clearedTabs:E,ides:x,actionLogs:w,sendDaemonCommand:g,setActionLogs:h,isStandalone:y,hasRegisteredMachines:he.length>0,initialDataLoaded:f,userName:M,toggleHiddenTab:ce,actionShortcuts:Ze,registerActionHandlers:_=>{Te.current=_},onActiveTabChange:ge,requestedActiveTabKey:Ne,onRequestedActiveTabConsumed:q,onRequestScrollToBottom:fe,scrollToBottomRequest:J,onOpenNewSession:z,liveSessionInboxState:Ce,layoutProfile:ae}),Ye&&s.jsx(Py,{machines:he,ides:x,onClose:X,onBrowseDirectory:ue,onSaveWorkspace:oe,onLaunchIde:de,onLaunchProvider:Q,onListMeshes:ve,onLaunchMeshCoordinator:le,onListSavedSessions:pe}),V&&s.jsx(V0,{activeConv:V,sendDaemonCommand:g,onClose:()=>te(null)}),se&&s.jsx(ju,{daemonId:se.daemonId,workspace:se.workspace,onClose:()=>H(null)}),Xe&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:Ve,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",onClick:_=>_.stopPropagation(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:Ve,"aria-label":"Close dashboard guide",children:s.jsx(jt,{size:14})})]}),s.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(_=>s.jsx("button",{type:"button",className:`btn btn-sm ${ct===_.id?"btn-primary":"btn-secondary"}`,onClick:()=>F(_.id),children:_.label},_.id))}),ct==="overview"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Ue?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),ct==="quickstart"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),ct==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(_=>s.jsx("button",{type:"button",className:`btn btn-sm ${mt===_.id?"btn-primary":"btn-secondary"}`,onClick:()=>be(_.id),children:_.label},_.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Z,children:"Disable all"}),s.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:$e,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Ht.map(_=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${et===_.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:_.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:_.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:_.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:et===_.id?gt.length>0?`${gt.join(" ")} ...`:"Listening...":Ze[_.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{yt(_.id),dt([])},children:et===_.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Y={...Ze};Y[_.id]="",xt(Y)},children:"Disable"})]})]})},_.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Ue?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",", or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs."]})]})]})})]})}const Ea=[{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 fv({onClose:e}){const[t,r]=i.useState(0),n=Ea[t],a=t===Ea.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:o=>{o.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(jt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Ea.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 fv({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 xv({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,l]=i.useState(()=>a||"native"),c=i.useMemo(()=>od(t),[t]),d=i.useMemo(()=>e?qo(e,{machineNames:c,connectionStates:r,defaultConnectionState:"new"}):[],[e,c,r]),m=i.useMemo(()=>d.find(h=>h.streamSource==="native"),[d]),u=i.useMemo(()=>d.filter(h=>h.streamSource==="agent-stream"),[d]),p=i.useMemo(()=>e?Wt(d,e.id):null,[d,e]);i.useEffect(()=>{a&&l(a)},[a]),i.useEffect(()=>{if(a||!p)return;const h=p.streamSource==="native"?"native":p.tabKey;!h||o===h||o==="native"&&l(h)},[o,p,a]),i.useEffect(()=>{var h;o!=="native"&&(u.some(b=>b.tabKey===o)||l(((h=u[0])==null?void 0:h.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(h=>h.tabKey===o)||p||m||u[0],[o,m,p,u]),w=i.useMemo(()=>u.map(h=>({tabKey:h.tabKey,title:Zc(h)||n,status:h.status})),[u,n]),g=i.useCallback(h=>{if(h)return d.find(b=>no(b,{sessionId:h,routeId:h,tabKey:h,providerSessionId:h}))},[d]);return{activeChatTab:o,setActiveChatTab:l,activeConv:x,conversations:d,extensionTabs:w,hasExtensions:w.length>0,resolveConversationByTarget:g}}function bv({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:l,isStandalone:c,userName:d,onOpenHistory:m,onConversationChange:u,onClose:p}){const[x,w]=i.useState("split"),[g,h]=i.useState(()=>is(e)?"native":e.tabKey),b=i.useRef(null),y=i.useMemo(()=>t||r.find(I=>I.id===e.routeId),[e.routeId,t,r]),f=i.useMemo(()=>lt((y==null?void 0:y.type)||""),[y==null?void 0:y.type]),{conversations:M,extensionTabs:S,hasExtensions:v}=xv({ideData:y,allIdes:r,connectionStates:n,ideName:f||"IDE",preferredTabKey:is(e)?void 0:e.tabKey}),T=i.useMemo(()=>y?Wt(M,y.id):null,[y,M]);i.useEffect(()=>{const I=b.current,O={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(b.current=O,!(I&&I.routeId===O.routeId&&I.tabKey===O.tabKey&&I.streamSource===O.streamSource)){if(is(e)){h("native");return}h(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),i.useEffect(()=>{if(g==="native"){if(M.some(I=>I.streamSource==="native"))return;(T==null?void 0:T.streamSource)==="agent-stream"&&h(T.tabKey);return}if(!M.some(I=>I.tabKey===g)){if((T==null?void 0:T.streamSource)==="agent-stream"){h(T.tabKey);return}h("native")}},[M,g,T]);const A=i.useMemo(()=>g==="native"?M.find(I=>I.streamSource==="native")||e:M.find(I=>I.tabKey===g)||e,[e,M,g]),k=yd(A),j=i.useMemo(()=>k.status||k.modalMessage||k.modalButtons?{...A,...k.status?{status:k.status}:{},...k.modalMessage!==void 0?{modalMessage:k.modalMessage}:{},...k.modalButtons!==void 0?{modalButtons:k.modalButtons}:{}}:A,[A,k]),B=Lr(j),L=Vn({sendDaemonCommand:o,activeConv:j,setActionLogs:l,isStandalone:c}),{connScreenshot:N,screenshotUsage:D,handleRemoteAction:$}=Yd({doId:B,targetSessionId:Ec(j),connState:j.connectionState||"new",viewMode:x}),E=i.useMemo(()=>a.filter(I=>I.routeId===j.tabKey),[a,j.tabKey]);i.useEffect(()=>{u==null||u(j)},[j,u]),i.useEffect(()=>{const I=O=>{O.key==="Escape"&&p()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[p]);const C=i.useCallback(I=>{I.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:p,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(Rt,{size:16})}),s.jsx("span",{className:"truncate",children:Eo(A)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:p,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(I=>{const O=x===I;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${O?"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:()=>w(I),title:I==="split"?"Split view":"Remote only",children:I==="split"?s.jsx(Um,{size:15}):s.jsx(Rt,{size:15})},I)})}),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(A),title:"Chat History",children:[s.jsx(So,{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:p,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(fv,{hasExtensions:v,ideName:f||"IDE",activeChatTab:g,extensionTabs:S,onSelectTab:h}),s.jsx(jc,{activeConv:j,onModalButton:L.handleModalButton}),s.jsx(oo,{activeConv:j,ideEntry:y,showMetaChips:!1,handleSendChat:L.handleSendChat,isSendingChat:L.isSendingChat,sendFeedbackMessage:L.sendFeedbackMessage,handleFocusAgent:L.handleFocusAgent,isFocusingAgent:L.isFocusingAgent,actionLogs:E,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(vc,{addLog:()=>{},connState:j.connectionState||"new",connScreenshot:N,screenshotUsage:D,transportType:j.transport,onAction:$})})]})]})})}function gv({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=sx(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 yv({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o}){var l;return s.jsxs(s.Fragment,{children:[s.jsx(ix,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(Vo,{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(bv,{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(gv,{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(ad,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),o.open&&s.jsx(hv,{onClose:o.onClose})]})}function vv({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(Ar,{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=Lt(l,{fallbackId:l.id}),d=n[l.id],m=l.version||l.daemonVersion||"unknown",u=l.versionUpdateRequired===!0,x=Rd(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(jt,{size:16})})]})}function wv(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function jv(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 kv(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>jv(t)).map(t=>t.id)}}function Sv(){var yi,vi,wi,ji;const{sendCommand:e}=kt(),t=Rr(),r=gd(),n=wo(),a=Ys(),[o,l]=dm(),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,p=Yc(),x=p.ides||[],w=p.initialLoaded??!0,{updateRouteChats:g,setToasts:h}=p,[b,y]=i.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),f=p.toasts||[],M=p.wsStatus||"connected",S=p.isConnected??!0,v=p.connectionStates||{},T=p.showReconnected||!1,{layoutProfile:A,groupAssignments:k,updateGroupAssignments:j,focusedGroup:B,updateFocusedGroup:L,focusGroup:N,groupActiveTabIds:D,updateGroupActiveTabIds:$,setGroupActiveTab:E,groupTabOrders:C,updateGroupTabOrders:I,setGroupTabOrder:O,groupSizes:P,updateGroupSizes:R,isMobile:U,hasHydratedStoredLayout:W,hydrateStoredLayout:me,focusConversationTab:ie}=Qb(),[ee,ce]=i.useState(()=>Jo());i.useEffect(()=>db(ce),[]);const je=i.useMemo(()=>wv({isMobile:U,mobileViewMode:ee}),[U,ee]),[Ne,q]=i.useState([]),[ge,fe]=i.useState({}),[we,xe]=i.useState({});_r("Dashboard",{ideCount:x.length,toastCount:f.length,focusedGroup:B,groupCount:Object.keys(k).length,actionLogCount:Ne.length});const Se=i.useMemo(()=>x.filter(Je=>Je.type==="adhdev-daemon").sort(Ro),[x]),J=Se[0],he=!!J;i.useEffect(()=>{const{metadataDaemonIds:Je,runtimeDaemonIds:$t}=kv(Se);for(const er of Je)t(er,{minFreshMs:3e4}).catch(()=>{});for(const er of $t)r(er,{minFreshMs:3e4}).catch(()=>{})},[t,r,Se]);const ae=(J==null?void 0:J.terminalBackend)||null,ue=J?Lt(J,{fallbackId:J.id}):null,oe=(J==null?void 0:J.id)||null,de=i.useMemo(()=>Sb(x,ge),[x,ge]),{hiddenTabs:Q,autoHiddenTabs:ve,autoHideTarget:le,hideTarget:pe,toggleTarget:ne,showTarget:Ie,showAllTabs:Ce}=kb(),{conversations:_e,visibleConversations:K,visibleTabKeys:Me,resolveConversationBySessionId:Te,resolveConversationByTarget:He}=$b({ides:de,connectionStates:v,clearedTabs:we,hiddenTabs:Q}),Ge=i.useMemo(()=>new Map(_e.map(Je=>[Je.tabKey,Je])),[_e]),Xe=i.useMemo(()=>jb(_e,Q,ve),[_e,Q,ve]);i.useEffect(()=>{for(const Je of Xe)le(Je)},[Xe,le]),Rf(K,je),i.useEffect(()=>{Object.keys(ge).length!==0&&fe(Je=>Nb(Je,x))},[x,ge]);const Ye=i.useMemo(()=>Fp(x),[x]),{notifications:tt,unreadCount:ct}=hg({conversations:_e,liveSessionInboxState:Ye}),{handleMarkDashboardNotificationRead:mt,handleMarkDashboardNotificationUnread:pt,handleDeleteDashboardNotification:F}=fg({notifications:tt,sendDaemonCommand:e}),{containerRef:be,normalizedGroupAssignments:Ae,numGroups:Be,isSplitMode:qe,groupedConvs:G,moveTabToGroup:z,closeGroup:X,handleResizeStart:se,splitTabRelative:H}=ag({groupAssignments:k,updateGroupAssignments:j,updateFocusedGroup:L,updateGroupActiveTabIds:$,updateGroupTabOrders:I,groupSizes:P,updateGroupSizes:R,isMobile:U,visibleConversations:K,visibleTabKeys:Me}),{activeConv:V,openDesktopConversation:te,requestScrollToBottom:re,scrollToBottomRequest:ke,setDesktopActiveTab:Ee}=Tg({isMobile:U,conversations:_e,visibleConversations:K,groupActiveTabIds:D,focusedGroup:B,groupedConvs:G,setSearchParams:l});Lg({activeConv:V,isMobile:U,liveSessionInboxState:Ye,sendDaemonCommand:e});const{requestedDesktopTabKey:Oe,requestedMobileTabKey:Re,consumeRequestedActiveTab:Fe}=Bb({isMobile:U,urlActiveTab:c,resolveConversationBySessionId:Te,setSearchParams:l}),{remoteDialogConv:Ue,remoteDialogIdeEntry:Le,remoteDialogActiveConv:Ze,setRemoteDialogActiveConv:et,openRemoteDialog:gt,closeRemoteDialog:yt,cliStopDialogOpen:dt,cliStopTargetConv:xt,requestCliStop:Ve,cancelCliStop:Ht,confirmCliStop:Z}=Dg({isMobile:U,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:Oe,conversations:_e,ides:x,resolveConversationByTarget:He,activeConv:V,sendDaemonCommand:e}),{historyModalOpen:$e,openHistoryModal:_,closeHistoryModal:Y,historyTargetConv:ye,isSavedSessionHistoryTarget:We,isHistoryCreatingChat:De,isHistoryRefreshingHistory:Ke,handleHistorySwitchSession:rt,handleHistoryNewChat:Tt,handleHistoryRefresh:bt,savedHistorySessions:es,savedHistoryFilters:Er,setSavedHistoryFilters:$r,missingWorkspaceResumePath:Br,isSavedHistoryLoading:Or,resumingSavedHistorySessionId:Fr,handleRefreshSavedHistory:Wr,handleResumeSavedHistorySession:Hr}=Rg({activeConv:V,remoteDialogConv:Ue,remoteDialogActiveConv:Ze,ides:x,sendDaemonCommand:e,updateRouteChats:g,setToasts:h,setClearedTabs:xe,setSearchParams:l}),Mu=i.useMemo(()=>K,[K]),Kr=U&&ee==="chat",Tu=i.useMemo(()=>_e.filter(Je=>Yn(Q,Je)),[_e,Q]),xi=i.useCallback(Je=>{const $t=new URLSearchParams(o);$t.set("activeTab",Je),l($t,{replace:!0})},[o,l]),{trackPendingLaunch:Au}=Ng({ides:x,conversations:_e,onOpenSession:xi}),{handleBrowseMachineDirectory:_u,handleSaveMachineWorkspace:Lu,handleLaunchMachineIde:Ru,handleLaunchMachineProvider:Pu,handleListMachineMeshes:Du,handleLaunchMeshCoordinator:Eu,handleListMachineSavedSessions:$u,setActiveCliViewMode:Bu}=Cg({sendDaemonCommand:e,trackPendingLaunch:Au,onOpenSession:xi,activeConv:V,ides:x,setCliViewModeOverrides:fe});Cb({visibleConversations:K,clearedTabs:we,setClearedTabs:xe,setActionLogs:q}),Ob({ides:x,sendDaemonCommand:e,setToasts:h,resolveConversationByTarget:He});const{isRefreshingHistory:Ou,handleRefreshHistory:Fu}=Ld({sendDaemonCommand:e,activeConv:V,chats:(ji=x.find(Je=>Je.id===(V==null?void 0:V.routeId)))==null?void 0:ji.chats,updateRouteChats:g,setToasts:h,setClearedTabs:xe});eg({urlActiveTab:U&&!Kr?c:null,conversations:_e,resolveConversationBySessionId:Te,normalizedGroupAssignments:Ae,hasHydratedStoredLayout:U&&!Kr?W:!0,hydrateStoredLayout:U&&!Kr?me:()=>{},focusConversationTab:ie,setSearchParams:l,historyModalOpen:$e,activeConv:V,isRefreshingHistory:Ou,ides:x,handleRefreshHistory:Fu});const Wu=i.useMemo(()=>!V||!at(V)||st(V)?null:Js(V),[V]),{versionMismatchDaemons:Hu,hasRequiredVersionDaemons:bi,targetVersion:Ku,versionBannerDismissed:Uu,setVersionBannerDismissed:zu,upgradingDaemons:Gu,handleBannerUpgrade:Vu}=ig({ides:x,sendDaemonCommand:e}),gi=i.useCallback(Je=>{Ie(Je),te(Je)},[te,Ie]),qu=i.useCallback(Je=>{pe(Je)},[pe]);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(lx,{terminalBackend:ae,isStandalone:he,machineLabel:ue,machineKey:oe}),(!Uu||bi)&&s.jsx(vv,{daemons:Hu,targetVersion:Ku,required:bi,upgradingDaemons:Gu,onUpgrade:Vu,onDismiss:()=>zu(!0)}),s.jsx(pv,{showMobileChatMode:Kr,isMobile:U,activeConv:V,wsStatus:M,isConnected:S,onOpenHistory:Je=>{Je&&et(Je),_()},onOpenRemote:gt,onStopCli:Ve,activeCliViewMode:Wu,onSetActiveCliViewMode:Bu,mobileChatConversations:Mu,ides:x,actionLogs:Ne,sendDaemonCommand:e,setActionLogs:q,setCliViewModeOverrides:fe,isStandalone:he,initialDataLoaded:w,userName:p.userName,requestedMobileTabKey:Re,onRequestedMobileTabConsumed:Fe,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:be,isSplitMode:qe,numGroups:Be,groupSizes:P,groupedConvs:G,clearedTabs:we,focusedGroup:B,focusGroup:N,moveTabToGroup:z,splitTabRelative:H,closeGroup:X,handleResizeStart:se,groupActiveTabIds:D,setGroupActiveTab:E,groupTabOrders:C,setGroupTabOrder:O,toggleHiddenTab:Je=>ne(Ge.get(Je)||{tabKey:Je}),visibleConversations:K,hiddenConversations:Tu,requestedDesktopTabKey:Oe,onRequestedDesktopTabConsumed:Fe,onDesktopActiveTabChange:Ee,onRequestScrollToBottom:re,onHideConversation:qu,onShowHiddenConversation:gi,onShowAllHiddenConversations:Ce,scrollToBottomRequest:ke,machineEntries:Se,layoutProfile:A,onBrowseMachineDirectory:_u,onSaveMachineWorkspace:Lu,onLaunchMachineIde:Ru,onLaunchMachineProvider:Pu,onListMachineMeshes:Du,onLaunchMeshCoordinator:Eu,onListMachineSavedSessions:$u,notifications:tt,notificationUnreadCount:ct,liveSessionInboxState:Ye,onMarkNotificationRead:mt,onMarkNotificationUnread:pt,onDeleteNotification:F}),s.jsx("style",{children:`
69
+ `})]})}function xv({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 bv({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,l]=i.useState(()=>a||"native"),c=i.useMemo(()=>od(t),[t]),d=i.useMemo(()=>e?qo(e,{machineNames:c,connectionStates:r,defaultConnectionState:"new"}):[],[e,c,r]),m=i.useMemo(()=>d.find(h=>h.streamSource==="native"),[d]),u=i.useMemo(()=>d.filter(h=>h.streamSource==="agent-stream"),[d]),p=i.useMemo(()=>e?Wt(d,e.id):null,[d,e]);i.useEffect(()=>{a&&l(a)},[a]),i.useEffect(()=>{if(a||!p)return;const h=p.streamSource==="native"?"native":p.tabKey;!h||o===h||o==="native"&&l(h)},[o,p,a]),i.useEffect(()=>{var h;o!=="native"&&(u.some(b=>b.tabKey===o)||l(((h=u[0])==null?void 0:h.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(h=>h.tabKey===o)||p||m||u[0],[o,m,p,u]),w=i.useMemo(()=>u.map(h=>({tabKey:h.tabKey,title:Zc(h)||n,status:h.status})),[u,n]),g=i.useCallback(h=>{if(h)return d.find(b=>no(b,{sessionId:h,routeId:h,tabKey:h,providerSessionId:h}))},[d]);return{activeChatTab:o,setActiveChatTab:l,activeConv:x,conversations:d,extensionTabs:w,hasExtensions:w.length>0,resolveConversationByTarget:g}}function gv({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:l,isStandalone:c,userName:d,onOpenHistory:m,onConversationChange:u,onClose:p}){const[x,w]=i.useState("split"),[g,h]=i.useState(()=>is(e)?"native":e.tabKey),b=i.useRef(null),y=i.useMemo(()=>t||r.find(I=>I.id===e.routeId),[e.routeId,t,r]),f=i.useMemo(()=>lt((y==null?void 0:y.type)||""),[y==null?void 0:y.type]),{conversations:M,extensionTabs:S,hasExtensions:v}=bv({ideData:y,allIdes:r,connectionStates:n,ideName:f||"IDE",preferredTabKey:is(e)?void 0:e.tabKey}),T=i.useMemo(()=>y?Wt(M,y.id):null,[y,M]);i.useEffect(()=>{const I=b.current,O={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(b.current=O,!(I&&I.routeId===O.routeId&&I.tabKey===O.tabKey&&I.streamSource===O.streamSource)){if(is(e)){h("native");return}h(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),i.useEffect(()=>{if(g==="native"){if(M.some(I=>I.streamSource==="native"))return;(T==null?void 0:T.streamSource)==="agent-stream"&&h(T.tabKey);return}if(!M.some(I=>I.tabKey===g)){if((T==null?void 0:T.streamSource)==="agent-stream"){h(T.tabKey);return}h("native")}},[M,g,T]);const A=i.useMemo(()=>g==="native"?M.find(I=>I.streamSource==="native")||e:M.find(I=>I.tabKey===g)||e,[e,M,g]),k=yd(A),j=i.useMemo(()=>k.status||k.modalMessage||k.modalButtons?{...A,...k.status?{status:k.status}:{},...k.modalMessage!==void 0?{modalMessage:k.modalMessage}:{},...k.modalButtons!==void 0?{modalButtons:k.modalButtons}:{}}:A,[A,k]),B=Lr(j),L=Vn({sendDaemonCommand:o,activeConv:j,setActionLogs:l,isStandalone:c}),{connScreenshot:N,screenshotUsage:D,handleRemoteAction:$}=Yd({doId:B,targetSessionId:Ec(j),connState:j.connectionState||"new",viewMode:x}),E=i.useMemo(()=>a.filter(I=>I.routeId===j.tabKey),[a,j.tabKey]);i.useEffect(()=>{u==null||u(j)},[j,u]),i.useEffect(()=>{const I=O=>{O.key==="Escape"&&p()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[p]);const C=i.useCallback(I=>{I.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:p,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(Rt,{size:16})}),s.jsx("span",{className:"truncate",children:Eo(A)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:p,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(I=>{const O=x===I;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${O?"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:()=>w(I),title:I==="split"?"Split view":"Remote only",children:I==="split"?s.jsx(Um,{size:15}):s.jsx(Rt,{size:15})},I)})}),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(A),title:"Chat History",children:[s.jsx(So,{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:p,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(xv,{hasExtensions:v,ideName:f||"IDE",activeChatTab:g,extensionTabs:S,onSelectTab:h}),s.jsx(jc,{activeConv:j,onModalButton:L.handleModalButton}),s.jsx(oo,{activeConv:j,ideEntry:y,showMetaChips:!1,handleSendChat:L.handleSendChat,isSendingChat:L.isSendingChat,sendFeedbackMessage:L.sendFeedbackMessage,handleFocusAgent:L.handleFocusAgent,isFocusingAgent:L.isFocusingAgent,actionLogs:E,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(vc,{addLog:()=>{},connState:j.connectionState||"new",connScreenshot:N,screenshotUsage:D,transportType:j.transport,onAction:$})})]})]})})}function yv({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=sx(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 vv({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o}){var l;return s.jsxs(s.Fragment,{children:[s.jsx(ix,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(Vo,{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(gv,{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(yv,{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(ad,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),o.open&&s.jsx(fv,{onClose:o.onClose})]})}function wv({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(Ar,{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=Lt(l,{fallbackId:l.id}),d=n[l.id],m=l.version||l.daemonVersion||"unknown",u=l.versionUpdateRequired===!0,x=Rd(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(jt,{size:16})})]})}function jv(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function kv(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 Sv(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>kv(t)).map(t=>t.id)}}function Nv(){var yi,vi,wi,ji;const{sendCommand:e}=kt(),t=Rr(),r=gd(),n=wo(),a=Ys(),[o,l]=dm(),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,p=Yc(),x=p.ides||[],w=p.initialLoaded??!0,{updateRouteChats:g,setToasts:h}=p,[b,y]=i.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),f=p.toasts||[],M=p.wsStatus||"connected",S=p.isConnected??!0,v=p.connectionStates||{},T=p.showReconnected||!1,{layoutProfile:A,groupAssignments:k,updateGroupAssignments:j,focusedGroup:B,updateFocusedGroup:L,focusGroup:N,groupActiveTabIds:D,updateGroupActiveTabIds:$,setGroupActiveTab:E,groupTabOrders:C,updateGroupTabOrders:I,setGroupTabOrder:O,groupSizes:P,updateGroupSizes:R,isMobile:U,hasHydratedStoredLayout:W,hydrateStoredLayout:me,focusConversationTab:ie}=Qb(),[ee,ce]=i.useState(()=>Jo());i.useEffect(()=>db(ce),[]);const je=i.useMemo(()=>jv({isMobile:U,mobileViewMode:ee}),[U,ee]),[Ne,q]=i.useState([]),[ge,fe]=i.useState({}),[we,xe]=i.useState({});_r("Dashboard",{ideCount:x.length,toastCount:f.length,focusedGroup:B,groupCount:Object.keys(k).length,actionLogCount:Ne.length});const Se=i.useMemo(()=>x.filter(Je=>Je.type==="adhdev-daemon").sort(Ro),[x]),J=Se[0],he=!!J;i.useEffect(()=>{const{metadataDaemonIds:Je,runtimeDaemonIds:$t}=Sv(Se);for(const er of Je)t(er,{minFreshMs:3e4}).catch(()=>{});for(const er of $t)r(er,{minFreshMs:3e4}).catch(()=>{})},[t,r,Se]);const ae=(J==null?void 0:J.terminalBackend)||null,ue=J?Lt(J,{fallbackId:J.id}):null,oe=(J==null?void 0:J.id)||null,de=i.useMemo(()=>Sb(x,ge),[x,ge]),{hiddenTabs:Q,autoHiddenTabs:ve,autoHideTarget:le,hideTarget:pe,toggleTarget:ne,showTarget:Ie,showAllTabs:Ce}=kb(),{conversations:_e,visibleConversations:K,visibleTabKeys:Me,resolveConversationBySessionId:Te,resolveConversationByTarget:He}=$b({ides:de,connectionStates:v,clearedTabs:we,hiddenTabs:Q}),Ge=i.useMemo(()=>new Map(_e.map(Je=>[Je.tabKey,Je])),[_e]),Xe=i.useMemo(()=>jb(_e,Q,ve),[_e,Q,ve]);i.useEffect(()=>{for(const Je of Xe)le(Je)},[Xe,le]),Rf(K,je),i.useEffect(()=>{Object.keys(ge).length!==0&&fe(Je=>Nb(Je,x))},[x,ge]);const Ye=i.useMemo(()=>Fp(x),[x]),{notifications:tt,unreadCount:ct}=hg({conversations:_e,liveSessionInboxState:Ye}),{handleMarkDashboardNotificationRead:mt,handleMarkDashboardNotificationUnread:pt,handleDeleteDashboardNotification:F}=fg({notifications:tt,sendDaemonCommand:e}),{containerRef:be,normalizedGroupAssignments:Ae,numGroups:Be,isSplitMode:qe,groupedConvs:G,moveTabToGroup:z,closeGroup:X,handleResizeStart:se,splitTabRelative:H}=ag({groupAssignments:k,updateGroupAssignments:j,updateFocusedGroup:L,updateGroupActiveTabIds:$,updateGroupTabOrders:I,groupSizes:P,updateGroupSizes:R,isMobile:U,visibleConversations:K,visibleTabKeys:Me}),{activeConv:V,openDesktopConversation:te,requestScrollToBottom:re,scrollToBottomRequest:ke,setDesktopActiveTab:Ee}=Tg({isMobile:U,conversations:_e,visibleConversations:K,groupActiveTabIds:D,focusedGroup:B,groupedConvs:G,setSearchParams:l});Lg({activeConv:V,isMobile:U,liveSessionInboxState:Ye,sendDaemonCommand:e});const{requestedDesktopTabKey:Oe,requestedMobileTabKey:Re,consumeRequestedActiveTab:Fe}=Bb({isMobile:U,urlActiveTab:c,resolveConversationBySessionId:Te,setSearchParams:l}),{remoteDialogConv:Ue,remoteDialogIdeEntry:Le,remoteDialogActiveConv:Ze,setRemoteDialogActiveConv:et,openRemoteDialog:gt,closeRemoteDialog:yt,cliStopDialogOpen:dt,cliStopTargetConv:xt,requestCliStop:Ve,cancelCliStop:Ht,confirmCliStop:Z}=Dg({isMobile:U,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:Oe,conversations:_e,ides:x,resolveConversationByTarget:He,activeConv:V,sendDaemonCommand:e}),{historyModalOpen:$e,openHistoryModal:_,closeHistoryModal:Y,historyTargetConv:ye,isSavedSessionHistoryTarget:We,isHistoryCreatingChat:De,isHistoryRefreshingHistory:Ke,handleHistorySwitchSession:rt,handleHistoryNewChat:Tt,handleHistoryRefresh:bt,savedHistorySessions:es,savedHistoryFilters:Er,setSavedHistoryFilters:$r,missingWorkspaceResumePath:Br,isSavedHistoryLoading:Or,resumingSavedHistorySessionId:Fr,handleRefreshSavedHistory:Wr,handleResumeSavedHistorySession:Hr}=Rg({activeConv:V,remoteDialogConv:Ue,remoteDialogActiveConv:Ze,ides:x,sendDaemonCommand:e,updateRouteChats:g,setToasts:h,setClearedTabs:xe,setSearchParams:l}),Mu=i.useMemo(()=>K,[K]),Kr=U&&ee==="chat",Tu=i.useMemo(()=>_e.filter(Je=>Yn(Q,Je)),[_e,Q]),xi=i.useCallback(Je=>{const $t=new URLSearchParams(o);$t.set("activeTab",Je),l($t,{replace:!0})},[o,l]),{trackPendingLaunch:Au}=Ng({ides:x,conversations:_e,onOpenSession:xi}),{handleBrowseMachineDirectory:_u,handleSaveMachineWorkspace:Lu,handleLaunchMachineIde:Ru,handleLaunchMachineProvider:Pu,handleListMachineMeshes:Du,handleLaunchMeshCoordinator:Eu,handleListMachineSavedSessions:$u,setActiveCliViewMode:Bu}=Cg({sendDaemonCommand:e,trackPendingLaunch:Au,onOpenSession:xi,activeConv:V,ides:x,setCliViewModeOverrides:fe});Cb({visibleConversations:K,clearedTabs:we,setClearedTabs:xe,setActionLogs:q}),Ob({ides:x,sendDaemonCommand:e,setToasts:h,resolveConversationByTarget:He});const{isRefreshingHistory:Ou,handleRefreshHistory:Fu}=Ld({sendDaemonCommand:e,activeConv:V,chats:(ji=x.find(Je=>Je.id===(V==null?void 0:V.routeId)))==null?void 0:ji.chats,updateRouteChats:g,setToasts:h,setClearedTabs:xe});eg({urlActiveTab:U&&!Kr?c:null,conversations:_e,resolveConversationBySessionId:Te,normalizedGroupAssignments:Ae,hasHydratedStoredLayout:U&&!Kr?W:!0,hydrateStoredLayout:U&&!Kr?me:()=>{},focusConversationTab:ie,setSearchParams:l,historyModalOpen:$e,activeConv:V,isRefreshingHistory:Ou,ides:x,handleRefreshHistory:Fu});const Wu=i.useMemo(()=>!V||!at(V)||st(V)?null:Js(V),[V]),{versionMismatchDaemons:Hu,hasRequiredVersionDaemons:bi,targetVersion:Ku,versionBannerDismissed:Uu,setVersionBannerDismissed:zu,upgradingDaemons:Gu,handleBannerUpgrade:Vu}=ig({ides:x,sendDaemonCommand:e}),gi=i.useCallback(Je=>{Ie(Je),te(Je)},[te,Ie]),qu=i.useCallback(Je=>{pe(Je)},[pe]);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(lx,{terminalBackend:ae,isStandalone:he,machineLabel:ue,machineKey:oe}),(!Uu||bi)&&s.jsx(wv,{daemons:Hu,targetVersion:Ku,required:bi,upgradingDaemons:Gu,onUpgrade:Vu,onDismiss:()=>zu(!0)}),s.jsx(hv,{showMobileChatMode:Kr,isMobile:U,activeConv:V,wsStatus:M,isConnected:S,onOpenHistory:Je=>{Je&&et(Je),_()},onOpenRemote:gt,onStopCli:Ve,activeCliViewMode:Wu,onSetActiveCliViewMode:Bu,mobileChatConversations:Mu,ides:x,actionLogs:Ne,sendDaemonCommand:e,setActionLogs:q,setCliViewModeOverrides:fe,isStandalone:he,initialDataLoaded:w,userName:p.userName,requestedMobileTabKey:Re,onRequestedMobileTabConsumed:Fe,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:be,isSplitMode:qe,numGroups:Be,groupSizes:P,groupedConvs:G,clearedTabs:we,focusedGroup:B,focusGroup:N,moveTabToGroup:z,splitTabRelative:H,closeGroup:X,handleResizeStart:se,groupActiveTabIds:D,setGroupActiveTab:E,groupTabOrders:C,setGroupTabOrder:O,toggleHiddenTab:Je=>ne(Ge.get(Je)||{tabKey:Je}),visibleConversations:K,hiddenConversations:Tu,requestedDesktopTabKey:Oe,onRequestedDesktopTabConsumed:Fe,onDesktopActiveTabChange:Ee,onRequestScrollToBottom:re,onHideConversation:qu,onShowHiddenConversation:gi,onShowAllHiddenConversations:Ce,scrollToBottomRequest:ke,machineEntries:Se,layoutProfile:A,onBrowseMachineDirectory:_u,onSaveMachineWorkspace:Lu,onLaunchMachineIde:Ru,onLaunchMachineProvider:Pu,onListMachineMeshes:Du,onLaunchMeshCoordinator:Eu,onListMachineSavedSessions:$u,notifications:tt,notificationUnreadCount:ct,liveSessionInboxState:Ye,onMarkNotificationRead:mt,onMarkNotificationUnread:pt,onDeleteNotification:F}),s.jsx("style",{children:`
70
70
  body { overflow: hidden; overscroll-behavior: none; }
71
- `}),s.jsx(yv,{historyModal:{open:$e,targetConv:ye,ides:x,isCreatingChat:De,isRefreshingHistory:We?!1:Ke,savedSessions:es,savedHistoryFilters:Er,missingWorkspaceResumePath:Br||null,onSavedHistoryFiltersChange:$r,isSavedSessionsLoading:Or,isResumingSavedSessionId:Fr,onClose:Y,onNewChat:Tt,onSwitchSession:rt,onRefreshHistory:We?Wr:bt,onResumeSavedSession:Hr},remoteDialog:{conversation:Ue,ideEntry:Le,ides:x,connectionStates:v,actionLogs:Ne,sendDaemonCommand:e,setActionLogs:q,isStandalone:he,userName:p.userName,onOpenHistory:Je=>{Je&&et(Je),_()},onConversationChange:et,onClose:yt},cliStopDialog:{open:dt,targetConv:xt,onCancel:Ht,onStopNow:async()=>{await Z("hard")},onSaveAndStop:async()=>{await Z("save")}},connectionBanner:{wsStatus:M,showReconnected:T,loginUrl:p.connectionLoginUrl,onReconnect:p.retryServerConnection},toastOverlay:{toasts:f,onDismiss:Je=>h($t=>$t.filter(er=>er.id!==Je)),onClick:Je=>{if(Je.targetKey){const $t=He(Je.targetKey);$t&&(ie($t.tabKey,Ae),gi($t),re($t.tabKey,"toast-open"))}}},onboarding:{open:b,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}y(!1)}}})]})}function Nv({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),[p,x]=i.useState(!1),[w,g]=i.useState(null),[h,b]=i.useState(!1),[y,f]=i.useState(""),M=i.useRef(null),S=i.useCallback(P=>{M.current=P},[]),v=i.useCallback((P,R,U=!1)=>{l(W=>[...W.slice(-100),{timestamp:Date.now(),level:P,message:R}]),setTimeout(()=>{var W;return(W=a.current)==null?void 0:W.scrollIntoView({behavior:"smooth"})},100),U&&ot.showToast(R,P==="error"||P==="warn"?"warning":"success")},[a]),T=i.useCallback(P=>{const R=P instanceof Error?P.message:String(P||"");return R.includes("P2P command timeout")||R.includes("P2P not connected")||R.includes("P2P not available")},[]),A=i.useCallback(async(P,R)=>{var U;if(!e||c)return!1;d(P),v("info",`Launching ${lt(P)}${R!=null&&R.workspace?` in ${R.workspace}`:""}...`);try{const W={ideType:P,enableCdp:!0};(U=R==null?void 0:R.workspace)!=null&&U.trim()?W.workspace=R.workspace.trim():R!=null&&R.useDefaultWorkspace&&(W.useDefaultWorkspace=!0);const me=await r(e,"launch_ide",W);return v(me!=null&&me.success?"info":"error",me!=null&&me.success?`${lt(P)} launched`:`Failed: ${me==null?void 0:me.error}`,!0),!!(me!=null&&me.success)}catch(W){return v("error",`Launch error: ${W.message}`,!0),!1}finally{d(null)}},[e,c,v,r]),k=i.useCallback(async P=>{if(!e)return{success:!1};const{cliType:R,dir:U,workspaceId:W,useDefaultWorkspace:me,useHome:ie,argsStr:ee,model:ce,resumeSessionId:je}=P;if(!R)return v("warn","Select a CLI or ACP provider first",!0),{success:!1};const Ne=ee?ee.split(/\s+/).filter(Boolean):void 0,q=(U==null?void 0:U.trim())||(W?"(saved id)":me?"(default workspace)":ie?"(home)":"");v("info",`Launching ${R}${q?` in ${q}`:""}${ce?` (model: ${ce})`:""}...`),u(R);try{const ge={cliType:R,cliArgs:Ne,initialModel:ce||void 0};U!=null&&U.trim()?ge.dir=U.trim():W?ge.workspaceId=W:me?ge.useDefaultWorkspace=!0:ie&&(ge.useHome=!0),je&&(ge.resumeSessionId=je);const fe=await r(e,"launch_cli",ge),we=(fe==null?void 0:fe.result)||fe;return fe!=null&&fe.success?(v("info",`${R} launched`,!0),(we==null?void 0:we.launchSource)==="home"?v("info","📂 Running in home directory (explicit choice)"):(we==null?void 0:we.launchSource)==="defaultWorkspace"&&v("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:we==null?void 0:we.sessionId}):(v("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"&&g({cliType:R,argsStr:ee,model:ce}),{success:!1,sessionId:we==null?void 0:we.sessionId})}catch(ge){return T(ge)?(v("warn",`${R} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(v("error",`Launch error: ${ge.message}`,!0),{success:!1})}finally{u(null)}},[e,v,T,r]),j=i.useCallback(async(P,R,U,W)=>e?P?R.trim()?k({cliType:P,dir:R,argsStr:U,model:W}):(g({cliType:P,argsStr:U,model:W}),{success:!1}):(v("warn","Select a provider",!0),{success:!1}):{success:!1},[e,v,k]),B=i.useCallback(async(P,R,U)=>{if(e&&window.confirm(`Stop ${P}?
71
+ `}),s.jsx(vv,{historyModal:{open:$e,targetConv:ye,ides:x,isCreatingChat:De,isRefreshingHistory:We?!1:Ke,savedSessions:es,savedHistoryFilters:Er,missingWorkspaceResumePath:Br||null,onSavedHistoryFiltersChange:$r,isSavedSessionsLoading:Or,isResumingSavedSessionId:Fr,onClose:Y,onNewChat:Tt,onSwitchSession:rt,onRefreshHistory:We?Wr:bt,onResumeSavedSession:Hr},remoteDialog:{conversation:Ue,ideEntry:Le,ides:x,connectionStates:v,actionLogs:Ne,sendDaemonCommand:e,setActionLogs:q,isStandalone:he,userName:p.userName,onOpenHistory:Je=>{Je&&et(Je),_()},onConversationChange:et,onClose:yt},cliStopDialog:{open:dt,targetConv:xt,onCancel:Ht,onStopNow:async()=>{await Z("hard")},onSaveAndStop:async()=>{await Z("save")}},connectionBanner:{wsStatus:M,showReconnected:T,loginUrl:p.connectionLoginUrl,onReconnect:p.retryServerConnection},toastOverlay:{toasts:f,onDismiss:Je=>h($t=>$t.filter(er=>er.id!==Je)),onClick:Je=>{if(Je.targetKey){const $t=He(Je.targetKey);$t&&(ie($t.tabKey,Ae),gi($t),re($t.tabKey,"toast-open"))}}},onboarding:{open:b,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}y(!1)}}})]})}function Cv({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),[p,x]=i.useState(!1),[w,g]=i.useState(null),[h,b]=i.useState(!1),[y,f]=i.useState(""),M=i.useRef(null),S=i.useCallback(P=>{M.current=P},[]),v=i.useCallback((P,R,U=!1)=>{l(W=>[...W.slice(-100),{timestamp:Date.now(),level:P,message:R}]),setTimeout(()=>{var W;return(W=a.current)==null?void 0:W.scrollIntoView({behavior:"smooth"})},100),U&&ot.showToast(R,P==="error"||P==="warn"?"warning":"success")},[a]),T=i.useCallback(P=>{const R=P instanceof Error?P.message:String(P||"");return R.includes("P2P command timeout")||R.includes("P2P not connected")||R.includes("P2P not available")},[]),A=i.useCallback(async(P,R)=>{var U;if(!e||c)return!1;d(P),v("info",`Launching ${lt(P)}${R!=null&&R.workspace?` in ${R.workspace}`:""}...`);try{const W={ideType:P,enableCdp:!0};(U=R==null?void 0:R.workspace)!=null&&U.trim()?W.workspace=R.workspace.trim():R!=null&&R.useDefaultWorkspace&&(W.useDefaultWorkspace=!0);const me=await r(e,"launch_ide",W);return v(me!=null&&me.success?"info":"error",me!=null&&me.success?`${lt(P)} launched`:`Failed: ${me==null?void 0:me.error}`,!0),!!(me!=null&&me.success)}catch(W){return v("error",`Launch error: ${W.message}`,!0),!1}finally{d(null)}},[e,c,v,r]),k=i.useCallback(async P=>{if(!e)return{success:!1};const{cliType:R,dir:U,workspaceId:W,useDefaultWorkspace:me,useHome:ie,argsStr:ee,model:ce,resumeSessionId:je}=P;if(!R)return v("warn","Select a CLI or ACP provider first",!0),{success:!1};const Ne=ee?ee.split(/\s+/).filter(Boolean):void 0,q=(U==null?void 0:U.trim())||(W?"(saved id)":me?"(default workspace)":ie?"(home)":"");v("info",`Launching ${R}${q?` in ${q}`:""}${ce?` (model: ${ce})`:""}...`),u(R);try{const ge={cliType:R,cliArgs:Ne,initialModel:ce||void 0};U!=null&&U.trim()?ge.dir=U.trim():W?ge.workspaceId=W:me?ge.useDefaultWorkspace=!0:ie&&(ge.useHome=!0),je&&(ge.resumeSessionId=je);const fe=await r(e,"launch_cli",ge),we=(fe==null?void 0:fe.result)||fe;return fe!=null&&fe.success?(v("info",`${R} launched`,!0),(we==null?void 0:we.launchSource)==="home"?v("info","📂 Running in home directory (explicit choice)"):(we==null?void 0:we.launchSource)==="defaultWorkspace"&&v("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:we==null?void 0:we.sessionId}):(v("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"&&g({cliType:R,argsStr:ee,model:ce}),{success:!1,sessionId:we==null?void 0:we.sessionId})}catch(ge){return T(ge)?(v("warn",`${R} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(v("error",`Launch error: ${ge.message}`,!0),{success:!1})}finally{u(null)}},[e,v,T,r]),j=i.useCallback(async(P,R,U,W)=>e?P?R.trim()?k({cliType:P,dir:R,argsStr:U,model:W}):(g({cliType:P,argsStr:U,model:W}),{success:!1}):(v("warn","Select a provider",!0),{success:!1}):{success:!1},[e,v,k]),B=i.useCallback(async(P,R,U)=>{if(e&&window.confirm(`Stop ${P}?
72
72
  This will terminate the process.`))try{const W=await r(e,"stop_cli",{cliType:P,dir:R,targetSessionId:U});W!=null&&W.success?v("info",`${P} stopped`,!0):v("error",`Stop failed: ${(W==null?void 0:W.error)||"Unknown error"}`,!0)}catch(W){v("error",`Stop failed: ${W.message}`,!0)}},[e,v,r]),L=i.useCallback(async P=>{try{await r(P.daemonId,"restart_ide",{ideType:P.type}),v("info",`${lt(P.type)} restart initiated`,!0)}catch(R){v("error",`Restart failed: ${R.message}`,!0)}},[v,r]),N=i.useCallback(async P=>{if(window.confirm(`Stop ${lt(P.type)}?
73
- This will disconnect CDP and optionally kill the process.`))try{const R=await r(P.daemonId,"stop_ide",{ideType:P.type,killProcess:!0});R!=null&&R.success?v("info",`${lt(P.type)} stopped`,!0):v("error",`Stop failed: ${(R==null?void 0:R.error)||"Unknown error"}`,!0)}catch(R){v("error",`Stop failed: ${R.message}`,!0)}},[v,r]),D=i.useCallback(async()=>{if(e)try{const P=await r(e,"detect_ides",{});v("info",`Found ${((P==null?void 0:P.result)||[]).length} IDE(s)`,!0)}catch(P){v("error",`Detection failed: ${P.message}`,!0)}},[e,v,r]),$=i.useCallback(async P=>{if(!e||!P.trim())return!1;x(!0);try{const R=await r(e,"workspace_add",{path:P.trim()});return R!=null&&R.success?(v("info",`Workspace added: ${P.trim()}`),!0):(v("error",(R==null?void 0:R.error)||"workspace_add failed"),!1)}catch(R){return v("error",R.message),!1}finally{x(!1)}},[e,v,r]),E=i.useCallback(async P=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){x(!0);try{const R=await r(e,"workspace_remove",{id:P});R!=null&&R.success?v("info","Workspace removed",!0):v("error",(R==null?void 0:R.error)||"workspace_remove failed",!0)}catch(R){v("error",R.message,!0)}finally{x(!1)}}},[e,v,r]),C=i.useCallback(async P=>{var R;if(e){x(!0);try{const U=await r(e,"workspace_set_default",P===null?{clear:!0}:{id:P});if(U!=null&&U.success){v("info",P?"Default workspace updated":"Default workspace cleared",!0);const W=typeof U.defaultWorkspacePath=="string"?U.defaultWorkspacePath:"";W&&((R=M.current)==null||R.call(M,W))}else v("error",(U==null?void 0:U.error)||"workspace_set_default failed",!0)}catch(U){v("error",U.message,!0)}finally{x(!1)}}},[e,v,r]),I=i.useCallback(async P=>{var U;if(!e||!P.trim())return;const R=P.trim();x(!0);try{const W=await r(e,"workspace_set_default",{path:R});W!=null&&W.success?(v("info","Default workspace set from history"),(U=M.current)==null||U.call(M,R)):v("error",(W==null?void 0:W.error)||"Could not set default (path missing on disk?)")}catch(W){v("error",W.message)}finally{x(!1)}},[e,v,r]),O=i.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:y}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:y})}catch(P){v("warn",`Live nickname updated, but account sync failed: ${P.message}`)}v("info",`Nickname set to "${y||"(cleared)"}"`),b(!1)}catch(P){v("error",`Failed: ${P.message}`)}},[e,y,t,v,n,r]);return{logs:o,launchingIde:c,launchingAgentType:m,workspaceBusy:p,launchPick:w,setLaunchPick:g,editingNickname:h,setEditingNickname:b,nicknameInput:y,setNicknameInput:f,addLog:v,handleLaunchIde:A,runLaunchCliCore:k,handleLaunchCli:j,handleStopCli:B,handleRestartIde:L,handleStopIde:N,handleDetectIdes:D,handleWorkspaceAdd:$,handleWorkspaceRemove:E,handleWorkspaceSetDefault:C,handleWorkspaceResumePath:I,handleSaveNickname:O,setOnDefaultWorkspaceChanged:S}}function Cv({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:l}){var L;const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:m,handleWorkspaceSetDefault:u}=o,[p,x]=i.useState(!1),[w,g]=i.useState(""),[h,b]=i.useState([]),[y,f]=i.useState(!1),[M,S]=i.useState(""),v=i.useCallback(async N=>{f(!0),S("");try{const D=await Qn(l,e,N);g(D.path),b(D.directories)}catch(D){S(D instanceof Error?D.message:"Could not load folder")}finally{f(!1)}},[e,l]),T=i.useCallback(()=>{x(!0);const N=[...r.map($=>$.workspace),...n.map($=>$.workspace),...a.map($=>$.workspace)],D=Jn(t.platform,Xn(N,t.defaultWorkspacePath,(t.workspaces||[]).map($=>$.path)));v(D)},[a,n,r,v,t.defaultWorkspacePath,t.platform,t.workspaces]),A=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,k=t.availableMem??t.freeMem??t.totalMem,j=A&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-k)/t.totalMem*100))):0,B=((L=t.loadavg)==null?void 0:L[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(zr,{icon:s.jsx(uc,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?Gp(t.uptime):"Waiting…"}),s.jsx(zr,{icon:s.jsx(Rt,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(zr,{icon:s.jsx(Co,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(zr,{icon:s.jsx(Gm,{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:A?Math.min(Math.round(B/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:A?`${B.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(Bi,{value:j,max:100,label:"Memory",color:"#3b82f6",detail:A?`${ca(t.totalMem-k)} / ${ca(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${ca(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(Ss,{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:N=>void u(N.target.value===""?null:N.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(N=>s.jsx("option",{value:N.id,children:N.label||N.path},N.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:T,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(N=>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:[N.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:zn(N.path,N.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:N.path,children:N.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void m(N.id),children:"Remove"})]},N.id))})]}),p&&s.jsx(Zn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:w,directories:h,busy:y,error:M,confirmLabel:"Add workspace",onClose:()=>x(!1),onNavigate:N=>{v(N)},onConfirm:N=>{(async()=>{if(!N)return;await d(N)&&x(!1)})()}})]})}function Iv(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 Mv(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 $a(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 Bl(e){if(!e||typeof e!="object")return null;if($a(e))return e;const t=e,r=t.result;return $a(r)?r:$a(t.sourceConfig)?t.sourceConfig:null}function Tv(e){const t=e.trim();return t||null}const Ol=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Av=[{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 _v({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,p]=i.useState(""),[x,w]=i.useState([]),[g,h]=i.useState(""),b=i.useRef(null),y=i.useRef(null),f=k=>{m(j=>j.includes(k)?j.filter(B=>B!==k):[...j,k])},M=()=>m([...Ol]),S=()=>m([]);i.useEffect(()=>{var k;(k=b.current)==null||k.scrollIntoView({behavior:"smooth"})},[x]),i.useEffect(()=>()=>{y.current&&clearInterval(y.current)},[]);const v=i.useCallback(()=>{y.current&&clearInterval(y.current),y.current=setInterval(async()=>{try{const k=await r(e,"provider_auto_fix_status",{providerType:t.type});(k==null?void 0:k.running)===!1&&a==="running"&&(o("done"),w(j=>[...j,`
73
+ This will disconnect CDP and optionally kill the process.`))try{const R=await r(P.daemonId,"stop_ide",{ideType:P.type,killProcess:!0});R!=null&&R.success?v("info",`${lt(P.type)} stopped`,!0):v("error",`Stop failed: ${(R==null?void 0:R.error)||"Unknown error"}`,!0)}catch(R){v("error",`Stop failed: ${R.message}`,!0)}},[v,r]),D=i.useCallback(async()=>{if(e)try{const P=await r(e,"detect_ides",{});v("info",`Found ${((P==null?void 0:P.result)||[]).length} IDE(s)`,!0)}catch(P){v("error",`Detection failed: ${P.message}`,!0)}},[e,v,r]),$=i.useCallback(async P=>{if(!e||!P.trim())return!1;x(!0);try{const R=await r(e,"workspace_add",{path:P.trim()});return R!=null&&R.success?(v("info",`Workspace added: ${P.trim()}`),!0):(v("error",(R==null?void 0:R.error)||"workspace_add failed"),!1)}catch(R){return v("error",R.message),!1}finally{x(!1)}},[e,v,r]),E=i.useCallback(async P=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){x(!0);try{const R=await r(e,"workspace_remove",{id:P});R!=null&&R.success?v("info","Workspace removed",!0):v("error",(R==null?void 0:R.error)||"workspace_remove failed",!0)}catch(R){v("error",R.message,!0)}finally{x(!1)}}},[e,v,r]),C=i.useCallback(async P=>{var R;if(e){x(!0);try{const U=await r(e,"workspace_set_default",P===null?{clear:!0}:{id:P});if(U!=null&&U.success){v("info",P?"Default workspace updated":"Default workspace cleared",!0);const W=typeof U.defaultWorkspacePath=="string"?U.defaultWorkspacePath:"";W&&((R=M.current)==null||R.call(M,W))}else v("error",(U==null?void 0:U.error)||"workspace_set_default failed",!0)}catch(U){v("error",U.message,!0)}finally{x(!1)}}},[e,v,r]),I=i.useCallback(async P=>{var U;if(!e||!P.trim())return;const R=P.trim();x(!0);try{const W=await r(e,"workspace_set_default",{path:R});W!=null&&W.success?(v("info","Default workspace set from history"),(U=M.current)==null||U.call(M,R)):v("error",(W==null?void 0:W.error)||"Could not set default (path missing on disk?)")}catch(W){v("error",W.message)}finally{x(!1)}},[e,v,r]),O=i.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:y}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:y})}catch(P){v("warn",`Live nickname updated, but account sync failed: ${P.message}`)}v("info",`Nickname set to "${y||"(cleared)"}"`),b(!1)}catch(P){v("error",`Failed: ${P.message}`)}},[e,y,t,v,n,r]);return{logs:o,launchingIde:c,launchingAgentType:m,workspaceBusy:p,launchPick:w,setLaunchPick:g,editingNickname:h,setEditingNickname:b,nicknameInput:y,setNicknameInput:f,addLog:v,handleLaunchIde:A,runLaunchCliCore:k,handleLaunchCli:j,handleStopCli:B,handleRestartIde:L,handleStopIde:N,handleDetectIdes:D,handleWorkspaceAdd:$,handleWorkspaceRemove:E,handleWorkspaceSetDefault:C,handleWorkspaceResumePath:I,handleSaveNickname:O,setOnDefaultWorkspaceChanged:S}}function Iv({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:l}){var L;const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:m,handleWorkspaceSetDefault:u}=o,[p,x]=i.useState(!1),[w,g]=i.useState(""),[h,b]=i.useState([]),[y,f]=i.useState(!1),[M,S]=i.useState(""),v=i.useCallback(async N=>{f(!0),S("");try{const D=await Qn(l,e,N);g(D.path),b(D.directories)}catch(D){S(D instanceof Error?D.message:"Could not load folder")}finally{f(!1)}},[e,l]),T=i.useCallback(()=>{x(!0);const N=[...r.map($=>$.workspace),...n.map($=>$.workspace),...a.map($=>$.workspace)],D=Jn(t.platform,Xn(N,t.defaultWorkspacePath,(t.workspaces||[]).map($=>$.path)));v(D)},[a,n,r,v,t.defaultWorkspacePath,t.platform,t.workspaces]),A=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,k=t.availableMem??t.freeMem??t.totalMem,j=A&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-k)/t.totalMem*100))):0,B=((L=t.loadavg)==null?void 0:L[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(zr,{icon:s.jsx(uc,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?Gp(t.uptime):"Waiting…"}),s.jsx(zr,{icon:s.jsx(Rt,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(zr,{icon:s.jsx(Co,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(zr,{icon:s.jsx(Gm,{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:A?Math.min(Math.round(B/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:A?`${B.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(Bi,{value:j,max:100,label:"Memory",color:"#3b82f6",detail:A?`${ca(t.totalMem-k)} / ${ca(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${ca(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(Ss,{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:N=>void u(N.target.value===""?null:N.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(N=>s.jsx("option",{value:N.id,children:N.label||N.path},N.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:T,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(N=>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:[N.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:zn(N.path,N.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:N.path,children:N.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void m(N.id),children:"Remove"})]},N.id))})]}),p&&s.jsx(Zn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:w,directories:h,busy:y,error:M,confirmLabel:"Add workspace",onClose:()=>x(!1),onNavigate:N=>{v(N)},onConfirm:N=>{(async()=>{if(!N)return;await d(N)&&x(!1)})()}})]})}function Mv(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 Tv(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 $a(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 Bl(e){if(!e||typeof e!="object")return null;if($a(e))return e;const t=e,r=t.result;return $a(r)?r:$a(t.sourceConfig)?t.sourceConfig:null}function Av(e){const t=e.trim();return t||null}const Ol=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],_v=[{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 Lv({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,p]=i.useState(""),[x,w]=i.useState([]),[g,h]=i.useState(""),b=i.useRef(null),y=i.useRef(null),f=k=>{m(j=>j.includes(k)?j.filter(B=>B!==k):[...j,k])},M=()=>m([...Ol]),S=()=>m([]);i.useEffect(()=>{var k;(k=b.current)==null||k.scrollIntoView({behavior:"smooth"})},[x]),i.useEffect(()=>()=>{y.current&&clearInterval(y.current)},[]);const v=i.useCallback(()=>{y.current&&clearInterval(y.current),y.current=setInterval(async()=>{try{const k=await r(e,"provider_auto_fix_status",{providerType:t.type});(k==null?void 0:k.running)===!1&&a==="running"&&(o("done"),w(j=>[...j,`
74
74
  ✅ Auto-fix completed!`]),y.current&&clearInterval(y.current))}catch{}},3e3)},[e,t.type,r,a]),T=async()=>{if(d.length!==0){o("running"),w(["🚀 Starting auto-fix...",`Agent: ${l}`,`Scripts: ${d.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),h("");try{const k=await r(e,"provider_auto_fix",{providerType:t.type,functions:d,agent:l,...u?{comment:u}:{}});k!=null&&k.success&&(k!=null&&k.started||k!=null&&k.running)?(w(j=>[...j,"✅ Agent started. Monitoring progress..."]),v()):(o("error"),h((k==null?void 0:k.error)||"Failed to start auto-fix"))}catch(k){o("error"),h((k==null?void 0:k.message)||"Connection failed")}}},A=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:t.type}),w(k=>[...k,`
75
- ⚠️ Auto-fix cancelled.`]),o("done"),y.current&&clearInterval(y.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:k=>k.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:Av.map(k=>s.jsxs("button",{onClick:()=>c(k.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:l===k.value?k.color+"66":"var(--border-subtle)",background:l===k.value?k.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:l===k.value?k.color:"var(--text-primary)"},children:k.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:k.desc})]},k.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:M,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:S,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Ol.map(k=>s.jsxs("button",{onClick:()=>f(k),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(k)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(k)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(k)?"#a78bfa":"var(--text-secondary)"},children:[d.includes(k)?"☑ ":"☐ ",k]},k))})]}),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:k=>p(k.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((k,j)=>s.jsx("div",{className:k.startsWith("✅")?"text-green-400":"",style:k.startsWith("❌")||k.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:k},j)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:b})]}),g&&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:g})]})]}),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:T,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:A,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"),w([]),h("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Lv({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var v;const o=t.filter(T=>T.category==="ide"),[l,c]=i.useState(((v=o[0])==null?void 0:v.type)||""),[d,m]=i.useState(""),[u,p]=i.useState(""),[x,w]=i.useState(!1),[g,h]=i.useState(""),[b,y]=i.useState(!1),f=T=>{const A=T.toLowerCase().replace(/[^a-z0-9-]/g,"");m(A),(!u||u===M(d))&&p(M(A))},M=T=>T.split("-").map(A=>A.charAt(0).toUpperCase()+A.slice(1)).join(" "),S=async()=>{if(!(!d||!u||!l)){w(!0),h("");try{const T=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:l});T!=null&&T.success||T!=null&&T.created?(y(!0),a==null||a(d)):h((T==null?void 0:T.error)||"Failed to create provider")}catch(T){h((T==null?void 0:T.message)||"Connection failed")}w(!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:T=>T.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:b?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(T=>s.jsxs("button",{onClick:()=>c(T.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:l===T.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:l===T.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:T.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:l===T.type?"#a78bfa":"var(--text-secondary)"},children:T.displayName})]},T.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:T=>f(T.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:T=>p(T.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"})]}),g&&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:g})]})}),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:b?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:S,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 Fl(e){return e==="cli"||e==="acp"}function Rv(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 Pv(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 Wl(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 Dv({machineId:e,providers:t,sendDaemonCommand:r}){var $;const[n,a]=i.useState([]),[o,l]=i.useState(!1),[c,d]=i.useState(null),[m,u]=i.useState("all"),[p,x]=i.useState(null),[w,g]=i.useState(!1),[h,b]=i.useState(null),[y,f]=i.useState("normal"),[M,S]=i.useState(""),[v,T]=i.useState(!1),A=i.useCallback(async()=>{if(e)try{const E=await r(e,"get_provider_source_config",{}),C=Bl(E);C&&(b(C),f(C.sourceMode),S(C.explicitProviderDir||""))}catch{}},[e,r]),k=i.useCallback(async()=>{if(e){l(!0);try{const E=await r(e,"get_provider_settings",{}),C=Iv(E);if(C){const I=Mv(C,t,{filterSchema:O=>O.filter(P=>P.key!=="enabled")});I.sort((O,P)=>O.category.localeCompare(P.category)||O.displayName.localeCompare(P.displayName)),a(I)}}catch{}l(!1)}},[e,t,r]);i.useEffect(()=>{n.length===0&&k(),h||A()},[]);const j=async(E,C,I)=>{d(`${E}.${C}`),a(O=>O.map(P=>P.type===E?{...P,values:{...P.values,[C]:I}}:P));try{const O=await r(e,"set_provider_setting",{providerType:E,key:C,value:I});O!=null&&O.success||k()}catch{k()}d(null)},B=async(E,C)=>{await j(E,"enabled",C),await k()},L=async E=>{d(`${E}.detect`);try{await r(e,"detect_provider",{providerType:E})}finally{await k(),d(null)}},N=async E=>{await j(E,"executablePath",""),await j(E,"executableArgs",""),await k()},D=async()=>{T(!0);try{const E=await r(e,"set_provider_source_config",{providerSourceMode:y,providerDir:Tv(M)}),C=Bl(E);C?(b(C),f(C.sourceMode),S(C.explicitProviderDir||"")):await A(),await k()}catch{await A()}T(!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(E=>s.jsx("button",{onClick:()=>u(E),className:`machine-btn text-[10px] px-2 py-0.5 ${m===E?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:E.toUpperCase()},E))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>g(!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:k,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:A,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:y,onChange:E=>f(E.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:M,onChange:E=>S(E.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void D(),disabled:v,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:v?"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:"})," ",(h==null?void 0:h.userDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(h==null?void 0:h.upstreamDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",(($=h==null?void 0:h.providerRoots)==null?void 0:$.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(E=>E.category===m).length>1&&(()=>{const E=n.filter(P=>P.category===m),C=new Map;for(const P of E)for(const R of P.schema){if(R.type!=="boolean")continue;const U=C.get(R.key),W=!!(P.values[R.key]??R.default);U?(U.onCount+=W?1:0,U.total+=1):C.set(R.key,{label:R.label||R.key,onCount:W?1:0,total:1})}const I=[...C.entries()].filter(([,P])=>P.total===E.length);if(I.length===0)return null;const O=async(P,R)=>{for(const U of E)await j(U.type,P,R)};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 (",E.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:I.map(([P,R])=>{const U=R.onCount===R.total,W=R.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:R.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",R.onCount,"/",R.total,")"]}),s.jsx("button",{onClick:()=>void O(P,!0),disabled:U,className:`machine-btn text-[9px] px-1.5 py-px ${U?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void O(P,!1),disabled:W,className:`machine-btn text-[9px] px-1.5 py-px ${W?"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(E=>m==="all"||E.category===m).map(E=>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:E.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:E.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:E.category==="acp"?"rgba(139,92,246,0.08)":E.category==="cli"?"rgba(59,130,246,0.08)":E.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:E.category==="acp"?"#a78bfa":E.category==="cli"?"#60a5fa":E.category==="ide"?"#86efac":"var(--status-warning)"},children:E.category}),Fl(E.category)&&(()=>{const C=t.find(P=>P.type===E.type),I=(C==null?void 0:C.enabled)===!0||E.values.enabled===!0,O=(C==null?void 0:C.machineStatus)||(I?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${Pv(O)}`,children:Rv(O)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void B(E.type,!I),disabled:c===`${E.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${I?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:I?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void L(E.type),disabled:!I||c===`${E.type}.detect`,title:I?"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 ${I?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void N(E.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),E.category==="ide"&&s.jsx("button",{onClick:()=>x(t.find(C=>C.type===E.type)||{type:E.type,name:E.displayName,displayName:E.displayName,icon:E.icon,category:E.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"})]}),Fl(E.category)&&(()=>{const C=t.find(I=>I.type===E.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:"})," ",Wl(C==null?void 0:C.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",Wl(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:E.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===`${E.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:()=>j(E.type,C.key,!(E.values[C.key]??C.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:E.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:E.values[C.key]??C.default?21:3}})}):C.type==="number"?s.jsx("input",{type:"number",value:Number(E.values[C.key]??C.default??0)||0,min:C.min,max:C.max,onChange:I=>{const O=parseInt(I.target.value)||0;C.min!==void 0&&O<C.min||C.max!==void 0&&O>C.max||j(E.type,C.key,O)},className:"machine-input w-20 text-center text-[11px]"}):C.type==="select"&&C.options?s.jsx("select",{value:String(E.values[C.key]??C.default??""),onChange:I=>j(E.type,C.key,I.target.value),className:"machine-input text-[11px]",children:C.options.map(I=>s.jsx("option",{value:I,children:I},I))}):s.jsx("input",{type:"text",value:String(E.values[C.key]??C.default??""),onBlur:I=>j(E.type,C.key,I.target.value),className:"machine-input w-[120px] text-[11px]"})})]},C.key))})]},E.type))}),p&&s.jsx(_v,{machineId:e,provider:p,sendDaemonCommand:r,onClose:()=>x(null)}),w&&s.jsx(Lv,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>g(!1),onCreated:()=>{g(!1),k()}})]})}const Ev=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function $v({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function Bv(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function Ov(e){return e.trim().toLowerCase()}function ta(e,t){const r=Ov(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 qs(e,t=220){const r=pi(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function Fv(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 Wv(e,t){return e.filter(r=>ta([r.level,r.message],t))}function Hl(e){return`${e.timestamp}:${e.level}:${e.message}`}function Hv(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const l of e.entries)n.set(Hl(l),l);for(const l of t.entries)n.set(Hl(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 Kv(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 Uv(e,t){return e.split(`
76
- `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>ta([r],t))}function zv(e,t){return e.filter(r=>ta([r.level,r.category,r.stage,r.interactionId,pi(r.payload)],t))}function Gv(e,t){return e.filter(r=>ta([r.kind,r.topic,r.interactionId,pi(r.payload)],t))}function Kl(e){return e==="warn"||e==="error"}function Vv({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=>Kl(a.level)).length+r.filter(a=>Kl(a.level)).length}}function qv({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"),y.current&&clearInterval(y.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:k=>k.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:_v.map(k=>s.jsxs("button",{onClick:()=>c(k.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:l===k.value?k.color+"66":"var(--border-subtle)",background:l===k.value?k.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:l===k.value?k.color:"var(--text-primary)"},children:k.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:k.desc})]},k.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:M,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:S,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Ol.map(k=>s.jsxs("button",{onClick:()=>f(k),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(k)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(k)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(k)?"#a78bfa":"var(--text-secondary)"},children:[d.includes(k)?"☑ ":"☐ ",k]},k))})]}),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:k=>p(k.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((k,j)=>s.jsx("div",{className:k.startsWith("✅")?"text-green-400":"",style:k.startsWith("❌")||k.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:k},j)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:b})]}),g&&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:g})]})]}),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:T,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:A,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"),w([]),h("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Rv({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var v;const o=t.filter(T=>T.category==="ide"),[l,c]=i.useState(((v=o[0])==null?void 0:v.type)||""),[d,m]=i.useState(""),[u,p]=i.useState(""),[x,w]=i.useState(!1),[g,h]=i.useState(""),[b,y]=i.useState(!1),f=T=>{const A=T.toLowerCase().replace(/[^a-z0-9-]/g,"");m(A),(!u||u===M(d))&&p(M(A))},M=T=>T.split("-").map(A=>A.charAt(0).toUpperCase()+A.slice(1)).join(" "),S=async()=>{if(!(!d||!u||!l)){w(!0),h("");try{const T=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:l});T!=null&&T.success||T!=null&&T.created?(y(!0),a==null||a(d)):h((T==null?void 0:T.error)||"Failed to create provider")}catch(T){h((T==null?void 0:T.message)||"Connection failed")}w(!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:T=>T.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:b?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(T=>s.jsxs("button",{onClick:()=>c(T.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:l===T.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:l===T.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:T.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:l===T.type?"#a78bfa":"var(--text-secondary)"},children:T.displayName})]},T.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:T=>f(T.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:T=>p(T.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"})]}),g&&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:g})]})}),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:b?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:S,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 Fl(e){return e==="cli"||e==="acp"}function Pv(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 Dv(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 Wl(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 Ev({machineId:e,providers:t,sendDaemonCommand:r}){var $;const[n,a]=i.useState([]),[o,l]=i.useState(!1),[c,d]=i.useState(null),[m,u]=i.useState("all"),[p,x]=i.useState(null),[w,g]=i.useState(!1),[h,b]=i.useState(null),[y,f]=i.useState("normal"),[M,S]=i.useState(""),[v,T]=i.useState(!1),A=i.useCallback(async()=>{if(e)try{const E=await r(e,"get_provider_source_config",{}),C=Bl(E);C&&(b(C),f(C.sourceMode),S(C.explicitProviderDir||""))}catch{}},[e,r]),k=i.useCallback(async()=>{if(e){l(!0);try{const E=await r(e,"get_provider_settings",{}),C=Mv(E);if(C){const I=Tv(C,t,{filterSchema:O=>O.filter(P=>P.key!=="enabled")});I.sort((O,P)=>O.category.localeCompare(P.category)||O.displayName.localeCompare(P.displayName)),a(I)}}catch{}l(!1)}},[e,t,r]);i.useEffect(()=>{n.length===0&&k(),h||A()},[]);const j=async(E,C,I)=>{d(`${E}.${C}`),a(O=>O.map(P=>P.type===E?{...P,values:{...P.values,[C]:I}}:P));try{const O=await r(e,"set_provider_setting",{providerType:E,key:C,value:I});O!=null&&O.success||k()}catch{k()}d(null)},B=async(E,C)=>{await j(E,"enabled",C),await k()},L=async E=>{d(`${E}.detect`);try{await r(e,"detect_provider",{providerType:E})}finally{await k(),d(null)}},N=async E=>{await j(E,"executablePath",""),await j(E,"executableArgs",""),await k()},D=async()=>{T(!0);try{const E=await r(e,"set_provider_source_config",{providerSourceMode:y,providerDir:Av(M)}),C=Bl(E);C?(b(C),f(C.sourceMode),S(C.explicitProviderDir||"")):await A(),await k()}catch{await A()}T(!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(E=>s.jsx("button",{onClick:()=>u(E),className:`machine-btn text-[10px] px-2 py-0.5 ${m===E?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:E.toUpperCase()},E))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>g(!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:k,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:A,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:y,onChange:E=>f(E.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:M,onChange:E=>S(E.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void D(),disabled:v,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:v?"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:"})," ",(h==null?void 0:h.userDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(h==null?void 0:h.upstreamDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",(($=h==null?void 0:h.providerRoots)==null?void 0:$.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(E=>E.category===m).length>1&&(()=>{const E=n.filter(P=>P.category===m),C=new Map;for(const P of E)for(const R of P.schema){if(R.type!=="boolean")continue;const U=C.get(R.key),W=!!(P.values[R.key]??R.default);U?(U.onCount+=W?1:0,U.total+=1):C.set(R.key,{label:R.label||R.key,onCount:W?1:0,total:1})}const I=[...C.entries()].filter(([,P])=>P.total===E.length);if(I.length===0)return null;const O=async(P,R)=>{for(const U of E)await j(U.type,P,R)};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 (",E.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:I.map(([P,R])=>{const U=R.onCount===R.total,W=R.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:R.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",R.onCount,"/",R.total,")"]}),s.jsx("button",{onClick:()=>void O(P,!0),disabled:U,className:`machine-btn text-[9px] px-1.5 py-px ${U?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void O(P,!1),disabled:W,className:`machine-btn text-[9px] px-1.5 py-px ${W?"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(E=>m==="all"||E.category===m).map(E=>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:E.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:E.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:E.category==="acp"?"rgba(139,92,246,0.08)":E.category==="cli"?"rgba(59,130,246,0.08)":E.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:E.category==="acp"?"#a78bfa":E.category==="cli"?"#60a5fa":E.category==="ide"?"#86efac":"var(--status-warning)"},children:E.category}),Fl(E.category)&&(()=>{const C=t.find(P=>P.type===E.type),I=(C==null?void 0:C.enabled)===!0||E.values.enabled===!0,O=(C==null?void 0:C.machineStatus)||(I?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${Dv(O)}`,children:Pv(O)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void B(E.type,!I),disabled:c===`${E.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${I?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:I?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void L(E.type),disabled:!I||c===`${E.type}.detect`,title:I?"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 ${I?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void N(E.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),E.category==="ide"&&s.jsx("button",{onClick:()=>x(t.find(C=>C.type===E.type)||{type:E.type,name:E.displayName,displayName:E.displayName,icon:E.icon,category:E.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"})]}),Fl(E.category)&&(()=>{const C=t.find(I=>I.type===E.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:"})," ",Wl(C==null?void 0:C.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",Wl(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:E.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===`${E.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:()=>j(E.type,C.key,!(E.values[C.key]??C.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:E.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:E.values[C.key]??C.default?21:3}})}):C.type==="number"?s.jsx("input",{type:"number",value:Number(E.values[C.key]??C.default??0)||0,min:C.min,max:C.max,onChange:I=>{const O=parseInt(I.target.value)||0;C.min!==void 0&&O<C.min||C.max!==void 0&&O>C.max||j(E.type,C.key,O)},className:"machine-input w-20 text-center text-[11px]"}):C.type==="select"&&C.options?s.jsx("select",{value:String(E.values[C.key]??C.default??""),onChange:I=>j(E.type,C.key,I.target.value),className:"machine-input text-[11px]",children:C.options.map(I=>s.jsx("option",{value:I,children:I},I))}):s.jsx("input",{type:"text",value:String(E.values[C.key]??C.default??""),onBlur:I=>j(E.type,C.key,I.target.value),className:"machine-input w-[120px] text-[11px]"})})]},C.key))})]},E.type))}),p&&s.jsx(Lv,{machineId:e,provider:p,sendDaemonCommand:r,onClose:()=>x(null)}),w&&s.jsx(Rv,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>g(!1),onCreated:()=>{g(!1),k()}})]})}const $v=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Bv({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function Ov(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function Fv(e){return e.trim().toLowerCase()}function ta(e,t){const r=Fv(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 qs(e,t=220){const r=pi(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function Wv(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 Hv(e,t){return e.filter(r=>ta([r.level,r.message],t))}function Hl(e){return`${e.timestamp}:${e.level}:${e.message}`}function Kv(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const l of e.entries)n.set(Hl(l),l);for(const l of t.entries)n.set(Hl(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 Uv(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 zv(e,t){return e.split(`
76
+ `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>ta([r],t))}function Gv(e,t){return e.filter(r=>ta([r.level,r.category,r.stage,r.interactionId,pi(r.payload)],t))}function Vv(e,t){return e.filter(r=>ta([r.kind,r.topic,r.interactionId,pi(r.payload)],t))}function Kl(e){return e==="warn"||e==="error"}function qv({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=>Kl(a.level)).length+r.filter(a=>Kl(a.level)).length}}function Yv({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} ${qs(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}`:""} ${qs(o.payload,500)}`.trim())].join(`
80
80
  `)),a.join(`
81
81
 
82
- `)}function Yv({machineId:e,sendDaemonCommand:t}){const[r,n]=i.useState([]),[a,o]=i.useState("empty"),[l,c]=i.useState(""),[d,m]=i.useState([]),[u,p]=i.useState([]),[x,w]=i.useState(null),[g,h]=i.useState(!0),[b,y]=i.useState("info"),[f,M]=i.useState("all"),[S,v]=i.useState(!0),[T,A]=i.useState(!0),[k,j]=i.useState(""),[B,L]=i.useState(""),[N,D]=i.useState(0),$=i.useRef(0),E=i.useRef(0),C=i.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),I=i.useRef([]),O=i.useCallback(()=>{const ee={entries:[],kind:"empty",rawText:"",lastTs:0};C.current=ee,$.current=0,n([]),c(""),o("empty"),v(!0)},[]),P=i.useCallback(()=>{I.current=[],E.current=0,m([]),A(!0)},[]),R=i.useCallback(ee=>{ee!==b&&(O(),y(ee))},[b,O]),U=i.useCallback(ee=>{M(ce=>ce===ee?ce:ee)},[]),W=i.useCallback(()=>{O(),P(),p([]),w(null),j(""),L(""),Fs.clear()},[O,P]),me=i.useCallback(()=>{D(ee=>ee+1)},[]),ie=i.useCallback(async()=>{if(!e)return;const ee=$.current,ce=E.current,[je,Ne]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:b,since:ee}),t(e,"get_debug_trace",$v({count:120,since:ce,category:f}))]);if(je.status==="fulfilled"){const q=je.value,ge=(q==null?void 0:q.result)||q,fe=Fv(ge),we=Hv(C.current,fe,300);C.current=we,$.current=we.lastTs,v(!1),j((q==null?void 0:q.success)===!1?String((q==null?void 0:q.error)||"Could not load daemon logs"):""),o(we.kind),c(we.rawText),n(we.entries)}else v(!1),j(je.reason instanceof Error?je.reason.message:"Could not load daemon logs");if(Ne.status==="fulfilled"){const q=Ne.value,ge=(q==null?void 0:q.result)||q;if((q==null?void 0:q.success)===!1)L(String((q==null?void 0:q.error)||"Could not load daemon trace"));else if(Array.isArray(ge==null?void 0:ge.trace)){const fe=ge.trace,we=Kv(I.current,fe,120),xe=fe.reduce((Se,J)=>Math.max(Se,Number(J.ts||0)),ce);I.current=we,xe>ce&&(E.current=xe),L(""),m(we)}else L("");A(!1)}else A(!1),L(Ne.reason instanceof Error?Ne.reason.message:"Could not load daemon trace");p(Fs.list({limit:120})),w(Date.now())},[b,e,t,f]);return i.useEffect(()=>{P()},[P,f]),i.useEffect(()=>{if(!e||(ie(),!g))return;const ee=setInterval(()=>{ie()},3e3);return()=>clearInterval(ee)},[g,ie,e,N]),{daemonLogs:r,daemonLogKind:a,daemonRawText:l,debugTrace:d,webEvents:u,lastUpdatedAt:x,autoRefresh:g,logLevel:b,traceCategory:f,daemonLoading:S,traceLoading:T,daemonFetchError:k,traceFetchError:B,setAutoRefresh:h,setLogLevel:R,setTraceCategory:U,refresh:me,clear:W}}function Xv({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 Ul(e){return e==="warn"||e==="error"}function Jv(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 Qv(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 zl(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function Zv(e){const t=qs(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function ew(e){const t=qs(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function tw({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:ew(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:Qv(o,l),severity:Jv(o),message:o,raw:o})}),a.sort((o,l)=>o.ts!==l.ts?o.ts-l.ts:zl(o.source)-zl(l.source))}function sw(e){return`${e.source}:${e.severity}:${e.message}`}function rw(e){const t=e.filter(n=>Ul(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!Ul(n.severity))continue;const a=sw(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 nw(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Gl(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${nw(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function aw({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 Xv({machineId:e,sendDaemonCommand:t}){const[r,n]=i.useState([]),[a,o]=i.useState("empty"),[l,c]=i.useState(""),[d,m]=i.useState([]),[u,p]=i.useState([]),[x,w]=i.useState(null),[g,h]=i.useState(!0),[b,y]=i.useState("info"),[f,M]=i.useState("all"),[S,v]=i.useState(!0),[T,A]=i.useState(!0),[k,j]=i.useState(""),[B,L]=i.useState(""),[N,D]=i.useState(0),$=i.useRef(0),E=i.useRef(0),C=i.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),I=i.useRef([]),O=i.useCallback(()=>{const ee={entries:[],kind:"empty",rawText:"",lastTs:0};C.current=ee,$.current=0,n([]),c(""),o("empty"),v(!0)},[]),P=i.useCallback(()=>{I.current=[],E.current=0,m([]),A(!0)},[]),R=i.useCallback(ee=>{ee!==b&&(O(),y(ee))},[b,O]),U=i.useCallback(ee=>{M(ce=>ce===ee?ce:ee)},[]),W=i.useCallback(()=>{O(),P(),p([]),w(null),j(""),L(""),Fs.clear()},[O,P]),me=i.useCallback(()=>{D(ee=>ee+1)},[]),ie=i.useCallback(async()=>{if(!e)return;const ee=$.current,ce=E.current,[je,Ne]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:b,since:ee}),t(e,"get_debug_trace",Bv({count:120,since:ce,category:f}))]);if(je.status==="fulfilled"){const q=je.value,ge=(q==null?void 0:q.result)||q,fe=Wv(ge),we=Kv(C.current,fe,300);C.current=we,$.current=we.lastTs,v(!1),j((q==null?void 0:q.success)===!1?String((q==null?void 0:q.error)||"Could not load daemon logs"):""),o(we.kind),c(we.rawText),n(we.entries)}else v(!1),j(je.reason instanceof Error?je.reason.message:"Could not load daemon logs");if(Ne.status==="fulfilled"){const q=Ne.value,ge=(q==null?void 0:q.result)||q;if((q==null?void 0:q.success)===!1)L(String((q==null?void 0:q.error)||"Could not load daemon trace"));else if(Array.isArray(ge==null?void 0:ge.trace)){const fe=ge.trace,we=Uv(I.current,fe,120),xe=fe.reduce((Se,J)=>Math.max(Se,Number(J.ts||0)),ce);I.current=we,xe>ce&&(E.current=xe),L(""),m(we)}else L("");A(!1)}else A(!1),L(Ne.reason instanceof Error?Ne.reason.message:"Could not load daemon trace");p(Fs.list({limit:120})),w(Date.now())},[b,e,t,f]);return i.useEffect(()=>{P()},[P,f]),i.useEffect(()=>{if(!e||(ie(),!g))return;const ee=setInterval(()=>{ie()},3e3);return()=>clearInterval(ee)},[g,ie,e,N]),{daemonLogs:r,daemonLogKind:a,daemonRawText:l,debugTrace:d,webEvents:u,lastUpdatedAt:x,autoRefresh:g,logLevel:b,traceCategory:f,daemonLoading:S,traceLoading:T,daemonFetchError:k,traceFetchError:B,setAutoRefresh:h,setLogLevel:R,setTraceCategory:U,refresh:me,clear:W}}function Jv({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 Ul(e){return e==="warn"||e==="error"}function Qv(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 zl(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function ew(e){const t=qs(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function tw(e){const t=qs(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function sw({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:tw(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:ew(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:Qv(o),message:o,raw:o})}),a.sort((o,l)=>o.ts!==l.ts?o.ts-l.ts:zl(o.source)-zl(l.source))}function rw(e){return`${e.source}:${e.severity}:${e.message}`}function nw(e){const t=e.filter(n=>Ul(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!Ul(n.severity))continue;const a=rw(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 aw(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Gl(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${aw(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function ow({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]",Gl(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(Gl):["No diagnostic events captured."]].join(`
87
87
  `)),a.join(`
88
88
 
89
- `)}function ow(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function iw(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function lw({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:l,searchQuery:c,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:p}){const x=Bv(n,o),w=Wv(e,c),g=Uv(t,c),h=zv(x,c),b=Gv(a,c),y=ow(w,l),f=l==="all"?g:[],M=iw(h,l),S=l==="issues"?[]:b,v=Vv({daemonLogs:w,daemonRawLines:g,trace:h,webEvents:b}),T=tw({daemonLogs:y,daemonRawLines:f,trace:M,webEvents:S}),A=rw(T),k=Xv({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:p,daemonLogKind:r,daemonLogsCount:w.length,daemonRawLineCount:g.length,traceCount:h.length,webEventCount:b.length});return{filteredDaemonLogs:w,filteredDaemonRawLines:g,filteredTraceEntries:h,filteredWebEvents:b,visibleDaemonLogs:y,visibleDaemonRawLines:f,visibleTraceEntries:M,visibleWebEvents:S,quickFilterCounts:v,diagnosticEvents:T,diagnosticsSummary:A,sourceStates:k}}function cw(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function ku(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function bo(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 Ba(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 dw({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${bo(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:ku(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 uw({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(p=>s.jsx("button",{type:"button",onClick:()=>a(p.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===p.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:p.label},p.id))}),s.jsx("input",{value:r,onChange:p=>o(p.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 mw({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:Ev.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 pw({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:l,traceFetchError:c}){var u,p;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((p=e.latestIssue)==null?void 0:p.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 ${Ba(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 ${Ba(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:ku(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 ${Ba(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: ",cw(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 hw({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 fw({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(dw,{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,p)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${p}`)),e.daemonLogKind!=="text"&&a.map((u,p)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${bo(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-${p}`))]})]}),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 ${bo(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:qs(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:qs(u.payload,360)||"No payload"})]},u.id))]})]})]})}function xw({machineId:e,sendDaemonCommand:t}){const r=Yv({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),p=i.useMemo(()=>lw({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&&p.diagnosticEvents.length>0){const g=u.current?"smooth":"instant";setTimeout(()=>{var h;(h=m.current)==null||h.scrollIntoView({behavior:g}),u.current=!0},50)}},[p.diagnosticEvents.length,r.autoRefresh]);const x=i.useCallback(async()=>{var h;const g=qv({daemonLogs:p.visibleDaemonLogs,daemonRawLines:p.visibleDaemonRawLines,trace:p.visibleTraceEntries,webEvents:p.visibleWebEvents});if(!g.trim()){ot.showToast("No visible logs to copy.","info");return}try{await((h=navigator.clipboard)==null?void 0:h.writeText(g)),ot.showToast("Copied visible logs to clipboard.","success")}catch(b){ot.showToast(b instanceof Error?b.message:"Could not copy visible logs","warning")}},[p.visibleDaemonLogs,p.visibleDaemonRawLines,p.visibleTraceEntries,p.visibleWebEvents]),w=i.useCallback(async()=>{var h;const g=aw({events:p.diagnosticEvents,summary:p.diagnosticsSummary,sources:p.sourceStates});try{await((h=navigator.clipboard)==null?void 0:h.writeText(g)),ot.showToast("Copied diagnostic bundle to clipboard.","success")}catch(b){ot.showToast(b instanceof Error?b.message:"Could not copy diagnostic bundle","warning")}},[p.diagnosticEvents,p.diagnosticsSummary,p.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(uw,{quickFilter:n,quickFilterCounts:p.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:l,onCopyDiagnostics:()=>{w()},onCopyVisible:()=>{x()},onToggleAutoRefresh:()=>r.setAutoRefresh(g=>!g),onRefresh:r.refresh,onClear:r.clear}),s.jsx(mw,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(pw,{diagnosticsSummary:p.diagnosticsSummary,diagnosticEventsCount:p.diagnosticEvents.length,sourceStates:p.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(hw,{patterns:p.diagnosticsSummary.repeatedPatterns}),s.jsx(fw,{streams:r,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:p.diagnosticEvents,visibleDaemonLogs:p.visibleDaemonLogs,visibleDaemonRawLines:p.visibleDaemonRawLines,visibleTraceEntries:p.visibleTraceEntries,visibleWebEvents:p.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:m})]})}function bw(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 Su(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 gw(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const l=String((o==null?void 0:o.lifecycle)||"").trim(),c=Su((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 yw(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Oa(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 Fa(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Wa(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Vl(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 vw(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function ww(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 jw(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 kw({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=i.useState(""),[o,l]=i.useState(null),[c,d]=i.useState(!1),m=bb(e,{enabled:!!e,includeSessions:!0,limit:qi,intervalMs:pf}),u=m.diagnostics,p=m.loading,x=m.applyDiagnostics,w=i.useMemo(()=>bw({diagnostics:u,loading:p,refreshing:c,error:n}),[u,p,c,n]),g=i.useMemo(()=>new Map(t.map(L=>[L.sessionId||L.id,L])),[t]),h=i.useCallback(async()=>{if(e){d(!0);try{const L=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:qi}),N=Fa(L);if(!(N!=null&&N.success))throw new Error((N==null?void 0:N.error)||"Could not load hosted runtime diagnostics");x(N.diagnostics||N.result||null),a("")}catch(L){const N=L instanceof Error?L.message:"Could not load hosted runtime diagnostics";a(N)}finally{d(!1)}}},[x,e,r]);i.useEffect(()=>{!e||u||p||c||h()},[u,p,e,h,c]);const b=i.useCallback(async(L,N)=>{const D=`${L}:${N.sessionId}`;if(!(L==="session_host_stop_session"&&!window.confirm(`Stop ${N.displayName}?
89
+ `)}function iw(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function lw(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function cw({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:l,searchQuery:c,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:p}){const x=Ov(n,o),w=Hv(e,c),g=zv(t,c),h=Gv(x,c),b=Vv(a,c),y=iw(w,l),f=l==="all"?g:[],M=lw(h,l),S=l==="issues"?[]:b,v=qv({daemonLogs:w,daemonRawLines:g,trace:h,webEvents:b}),T=sw({daemonLogs:y,daemonRawLines:f,trace:M,webEvents:S}),A=nw(T),k=Jv({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:p,daemonLogKind:r,daemonLogsCount:w.length,daemonRawLineCount:g.length,traceCount:h.length,webEventCount:b.length});return{filteredDaemonLogs:w,filteredDaemonRawLines:g,filteredTraceEntries:h,filteredWebEvents:b,visibleDaemonLogs:y,visibleDaemonRawLines:f,visibleTraceEntries:M,visibleWebEvents:S,quickFilterCounts:v,diagnosticEvents:T,diagnosticsSummary:A,sourceStates:k}}function dw(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function ku(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function bo(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 Ba(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 uw({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${bo(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:ku(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 mw({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(p=>s.jsx("button",{type:"button",onClick:()=>a(p.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===p.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:p.label},p.id))}),s.jsx("input",{value:r,onChange:p=>o(p.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 pw({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:$v.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 hw({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:l,traceFetchError:c}){var u,p;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((p=e.latestIssue)==null?void 0:p.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 ${Ba(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 ${Ba(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:ku(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 ${Ba(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: ",dw(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 fw({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 xw({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(uw,{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,p)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${p}`)),e.daemonLogKind!=="text"&&a.map((u,p)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${bo(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-${p}`))]})]}),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 ${bo(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:qs(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:qs(u.payload,360)||"No payload"})]},u.id))]})]})]})}function bw({machineId:e,sendDaemonCommand:t}){const r=Xv({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),p=i.useMemo(()=>cw({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&&p.diagnosticEvents.length>0){const g=u.current?"smooth":"instant";setTimeout(()=>{var h;(h=m.current)==null||h.scrollIntoView({behavior:g}),u.current=!0},50)}},[p.diagnosticEvents.length,r.autoRefresh]);const x=i.useCallback(async()=>{var h;const g=Yv({daemonLogs:p.visibleDaemonLogs,daemonRawLines:p.visibleDaemonRawLines,trace:p.visibleTraceEntries,webEvents:p.visibleWebEvents});if(!g.trim()){ot.showToast("No visible logs to copy.","info");return}try{await((h=navigator.clipboard)==null?void 0:h.writeText(g)),ot.showToast("Copied visible logs to clipboard.","success")}catch(b){ot.showToast(b instanceof Error?b.message:"Could not copy visible logs","warning")}},[p.visibleDaemonLogs,p.visibleDaemonRawLines,p.visibleTraceEntries,p.visibleWebEvents]),w=i.useCallback(async()=>{var h;const g=ow({events:p.diagnosticEvents,summary:p.diagnosticsSummary,sources:p.sourceStates});try{await((h=navigator.clipboard)==null?void 0:h.writeText(g)),ot.showToast("Copied diagnostic bundle to clipboard.","success")}catch(b){ot.showToast(b instanceof Error?b.message:"Could not copy diagnostic bundle","warning")}},[p.diagnosticEvents,p.diagnosticsSummary,p.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(mw,{quickFilter:n,quickFilterCounts:p.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:l,onCopyDiagnostics:()=>{w()},onCopyVisible:()=>{x()},onToggleAutoRefresh:()=>r.setAutoRefresh(g=>!g),onRefresh:r.refresh,onClear:r.clear}),s.jsx(pw,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(hw,{diagnosticsSummary:p.diagnosticsSummary,diagnosticEventsCount:p.diagnosticEvents.length,sourceStates:p.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(fw,{patterns:p.diagnosticsSummary.repeatedPatterns}),s.jsx(xw,{streams:r,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:p.diagnosticEvents,visibleDaemonLogs:p.visibleDaemonLogs,visibleDaemonRawLines:p.visibleDaemonRawLines,visibleTraceEntries:p.visibleTraceEntries,visibleWebEvents:p.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:m})]})}function gw(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 Su(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 yw(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const l=String((o==null?void 0:o.lifecycle)||"").trim(),c=Su((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 vw(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Oa(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 Fa(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Wa(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Vl(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 ww(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function jw(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 kw(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 Sw({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=i.useState(""),[o,l]=i.useState(null),[c,d]=i.useState(!1),m=bb(e,{enabled:!!e,includeSessions:!0,limit:qi,intervalMs:pf}),u=m.diagnostics,p=m.loading,x=m.applyDiagnostics,w=i.useMemo(()=>gw({diagnostics:u,loading:p,refreshing:c,error:n}),[u,p,c,n]),g=i.useMemo(()=>new Map(t.map(L=>[L.sessionId||L.id,L])),[t]),h=i.useCallback(async()=>{if(e){d(!0);try{const L=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:qi}),N=Fa(L);if(!(N!=null&&N.success))throw new Error((N==null?void 0:N.error)||"Could not load hosted runtime diagnostics");x(N.diagnostics||N.result||null),a("")}catch(L){const N=L instanceof Error?L.message:"Could not load hosted runtime diagnostics";a(N)}finally{d(!1)}}},[x,e,r]);i.useEffect(()=>{!e||u||p||c||h()},[u,p,e,h,c]);const b=i.useCallback(async(L,N)=>{const D=`${L}:${N.sessionId}`;if(!(L==="session_host_stop_session"&&!window.confirm(`Stop ${N.displayName}?
90
90
  This will terminate the hosted runtime.`))){l(D);try{const $=await r(e,L,{sessionId:N.sessionId}),E=Fa($);if(!(E!=null&&E.success))throw new Error((E==null?void 0:E.error)||"Session host action failed");const C=L==="session_host_resume_session"?"resumed":L==="session_host_restart_session"?"restarted":"stopped";ot.showToast(`Session host ${C}: ${N.displayName}`,"success"),await h()}catch($){const E=$ instanceof Error?$.message:"Session host action failed";ot.showToast(E,"warning"),a(E)}finally{l($=>$===D?null:$)}}},[e,h,r]),y=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 N=await r(e,"session_host_prune_duplicate_sessions",{}),D=Fa(N);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Duplicate prune failed");const $=D.result||{},E=Array.isArray($.prunedSessionIds)?$.prunedSessionIds.length:0,C=typeof $.duplicateGroupCount=="number"?$.duplicateGroupCount:0;ot.showToast(`Pruned ${E} duplicate runtime(s) across ${C} group(s)`,"success"),await h()}catch(N){const D=N instanceof Error?N.message:"Duplicate prune failed";ot.showToast(D,"warning"),a(D)}finally{l(N=>N==="session_host_prune_duplicate_sessions"?null:N)}}},[e,h,r]),f=i.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((L,N)=>(N.lastActivityAt||0)-(L.lastActivityAt||0)),[u==null?void 0:u.sessions]),M=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)||[]}:gw(f),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,f]),S=M.liveRuntimes,v=M.recoverySnapshots,T=M.inactiveRecords,A=i.useMemo(()=>jw(S),[S]),k=i.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),j=i.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(L=>L.level==="warn"||L.level==="error")||null,[u==null?void 0:u.recentLogs]),B=(L,N)=>{var U;const D=o===`session_host_resume_session:${L.sessionId}`,$=o===`session_host_restart_session:${L.sessionId}`,E=o===`session_host_stop_session:${L.sessionId}`,C=Su(L.meta),I=g.get(L.sessionId),O=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,P=N==="recovery"?"Recover":"Resume",R=yw(N);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:L.displayName||(I==null?void 0:I.cliName)||L.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${ww(L.lifecycle)}`,children:L.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:L.workspaceLabel||(I==null?void 0:I.runtimeWorkspaceLabel)||L.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:L.runtimeKey}),L.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",L.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((U=L.writeOwner)==null?void 0:U.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:vw(L.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(ic,{size:11})," ",O]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Vl(L.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",R]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[N==="recovery"&&(L.lifecycle==="interrupted"||L.lifecycle==="failed"||L.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{b("session_host_resume_session",L)},children:D?`${P}ing…`:P}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{b("session_host_restart_session",L)},children:$?"Restarting…":"Restart"}),N==="live"&&(L.lifecycle==="running"||L.lifecycle==="starting"||L.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:()=>{b("session_host_stop_session",L)},children:E?"Stopping…":"Stop"})]})]})},L.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(os,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:gx()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[A>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{y()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${A})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${w.toneClass}`,children:w.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:p||c,children:[s.jsx(Ar,{size:13}),p||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(Ir,{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:v.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:Vl(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Wa(u.hostStartedAt)})]})]}),j&&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(Ir,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:j.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Wa(j.timestamp),j.sessionId?` · ${j.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(Co,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Oa("live")}),S.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:S.map(L=>B(L,"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(os,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Oa("recovery")}),v.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:v.map(L=>B(L,"recovery"))})]}),T.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:Oa("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:T.map(L=>B(L,"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"}),k.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:k.map(L=>{var D;const N=f.find($=>$.sessionId===L.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:(N==null?void 0:N.displayName)||((D=g.get(L.sessionId))==null?void 0:D.cliName)||L.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[L.action,L.lifecycle?` · ${L.lifecycle}`:"",L.detail?` · ${L.detail}`:"",L.error?` · ${L.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${L.success===!1?"text-red-300":"text-text-secondary"}`,children:Wa(L.timestamp)})]},`${L.sessionId}:${L.timestamp}:${L.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 Sw({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 Ha({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 Ka({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 Nw({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=Rd(e),p=Ps(e,m),x=jr(e,p),w=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(Ha,{icon:s.jsx(Qt,{size:13}),children:"Current Chats"}),s.jsx(Ka,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(g=>{const h=po(g);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(g),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(g)}),h>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Kn(h)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Cs(g)})]},g.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ha,{icon:s.jsx(uc,{size:13}),children:"Recent Launches"}),s.jsx(Ka,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(g=>{const{metaText:h,updatedLabel:b}=zd(g);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(g),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:g.label}),b&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:b})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:h})]},g.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ha,{icon:s.jsx(Ir,{size:13}),children:"Daemon Update"}),s.jsx(Ka,{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.",p&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",p,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(Ar,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:w})]})]})})]})]})}function Cw(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function Iw({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?"⭐ ":"",zn(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 Mw={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 ln(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ua({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:l,sendDaemonCommand:c,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const p=Ys(),{handleLaunchIde:x,handleStopCli:w,handleRestartIde:g,handleStopIde:h,handleDetectIdes:b,launchingIde:y,launchingAgentType:f,addLog:M}=l,[S,v]=i.useState(null),T=i.useCallback(_=>{_&&p(ls(_))},[p]),A=Mw[e],k=e==="ide",j=e==="acp",B=i.useMemo(()=>n.filter(_=>Is(_,e)),[e,n]),L=i.useMemo(()=>new Map(B.map(_=>[_.type,_.displayName||_.type])),[B]),[N,D]=i.useState(""),[$,E]=i.useState(""),[C,I]=i.useState([]),[O,P]=i.useState(""),[R,U]=i.useState(""),[W,me]=i.useState([]),[ie,ee]=i.useState(!1),[ce,je]=i.useState(!1),[Ne,q]=i.useState(""),[ge,fe]=i.useState(!1),[we,xe]=i.useState(()=>Nt()),[Se,J]=i.useState(null),[he,ae]=i.useState(m?"__custom__":d||t.defaultWorkspaceId||""),[ue,oe]=i.useState(m||""),[de,Q]=i.useState([]),[ve,le]=i.useState(!1),[pe,ne]=i.useState(""),[Ie,Ce]=i.useState([]),[_e,K]=i.useState(!1),[Me,Te]=i.useState(""),He=i.useRef(null),[Ge,Xe]=i.useState(null),Ye=i.useRef("__home__"),[tt,ct]=i.useState("__home__"),[mt,pt]=i.useState(!1),F=i.useRef(0),be=de.filter(_=>!a.some(Y=>Y.type===_&&vt(Y.status)!=="stopped")),Ae=i.useRef({});i.useEffect(()=>{t.defaultWorkspaceId&&!he&&ae(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),i.useEffect(()=>{if(m){ae("__custom__"),oe(m);return}d&&(ae(d),oe(""))},[d,m]),i.useEffect(()=>{k||N&&(B.some(_=>_.type===N)||(D(""),U("")))},[B,k,N]);const Be=(()=>{if(he==="__custom__")return ue.trim();if(!he)return"";const _=(t.workspaces||[]).find(Y=>Y.id===he);return(_==null?void 0:_.path)||""})(),qe=i.useCallback(_=>{const Y=Ae.current[_];Y&&(clearTimeout(Y),delete Ae.current[_]),Q(ye=>ye.includes(_)?ye.filter(We=>We!==_):ye)},[]),G=i.useRef(new Set),z=i.useCallback(async _=>{if(c){K(!0),Te("");try{const Y=await Qn(c,r,_);ne(Y.path),oe(Y.path),Ce(Y.directories)}catch(Y){Te(Y instanceof Error?Y.message:"Could not load folder")}finally{K(!1)}}},[r,c]),X=i.useCallback(()=>{if(!c)return;ae("__custom__"),le(!0);const _=a.map(ye=>ye.workspace),Y=Jn(t.platform,Xn(ue.trim(),Be,m,_,t.defaultWorkspacePath,(t.workspaces||[]).map(ye=>ye.path)));z(Y)},[ue,m,z,t.defaultWorkspacePath,t.platform,t.workspaces,a,Be,c]),se=i.useCallback(_=>{const Y=String(_.workspace||"").trim();if(!Y)return;const ye=(t.workspaces||[]).find(We=>ln(We.path)===ln(Y));if(ye){ae(ye.id),oe("");return}ae("__custom__"),oe(Y)},[t.workspaces]),H=i.useCallback(_=>{const Y=String(_.workspace||"").trim();if(!Y)return{workspaceId:null,workspacePath:"",useHome:!0};const ye=(t.workspaces||[]).find(We=>ln(We.path)===ln(Y));return ye?{workspaceId:ye.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Y,useHome:!1}},[t.workspaces]),V=i.useCallback(async _=>{if(!c||!_||e!=="cli"){me([]),ee(!1),je(!1),q("");return}const Y=F.current+1;F.current=Y,ee(!0),q("");try{const ye=await c(r,"list_saved_sessions",{providerType:_,kind:"cli",limit:30});if(F.current!==Y)return;const We=(ye==null?void 0:ye.result)??ye;me(Array.isArray(We==null?void 0:We.sessions)?We.sessions:[])}catch(ye){if(F.current!==Y)return;me([]),q(ye instanceof Error?ye.message:"Could not load saved sessions")}finally{F.current===Y&&(ee(!1),je(!0))}},[e,r,c]),te=i.useMemo(()=>{if(e!=="cli"||!N)return null;const _=L.get(N)||N;return{routeId:r,daemonId:r,providerSessionId:R||void 0,transport:"pty",mode:"chat",agentName:_,agentType:N,status:"idle",title:_,messages:[],ideType:N,workspaceName:Be,workspacePath:Be,displayPrimary:_,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${N}`}},[e,r,L,Be,R,N]),re=i.useCallback(_=>{if(e==="ide"||!_){I([]);return}I(xo(r,_))},[e,r]),ke=i.useCallback((_,Y)=>{e==="ide"||!_||(_y(r,_,Y),I(xo(r,_)))},[e,r]);i.useEffect(()=>{F.current+=1,U(""),re(N),je(!1),me([]),q(""),ee(!1)},[e,re,V,N]);const Ee=i.useMemo(()=>W.find(_=>_.providerSessionId===R)||null,[W,R]);i.useEffect(()=>{if(!R)return;const _=W.find(Y=>Y.providerSessionId===R);_!=null&&_.canResume||U("")},[W,R]);const Oe=i.useCallback((_,Y)=>{He.current=Y,Ye.current=_.selectedWorkspaceKey||"__home__",ct(_.selectedWorkspaceKey||"__home__"),Xe(_)},[]),Re=i.useCallback(()=>{He.current&&(pt(!0),He.current().finally(()=>{He.current=null,pt(!1),Xe(null)}))},[]),Fe=i.useCallback(_=>{if(!_)return;Q(ye=>ye.includes(_)?ye:[...ye,_]);const Y=Ae.current[_];Y&&clearTimeout(Y),Ae.current[_]=setTimeout(()=>{Q(ye=>ye.includes(_)?ye.filter(We=>We!==_):ye),delete Ae.current[_]},2e4)},[]);i.useEffect(()=>{for(const Y of a)vt(Y.status)!=="stopped"&&(de.includes(Y.type)&&!G.current.has(Y.type)&&(G.current.add(Y.type),M("info",`${L.get(Y.type)||Y.type} launched`,!0)),qe(Y.type));const _=new Set(a.filter(Y=>vt(Y.status)!=="stopped").map(Y=>Y.type));G.current.forEach(Y=>{!de.includes(Y)&&!_.has(Y)&&G.current.delete(Y)})},[M,qe,a,de,L]),i.useEffect(()=>()=>{Object.values(Ae.current).forEach(clearTimeout),Ae.current={}},[]);const[Ue,Le]=i.useState({}),[Ze,et]=i.useState(null);i.useEffect(()=>{if(!k||!r||!c)return;(async()=>{try{const Y=await c(r,"get_ide_extensions",{}),ye=(Y==null?void 0:Y.result)||Y;ye!=null&&ye.success&&(ye!=null&&ye.ideExtensions)&&Le(ye.ideExtensions)}catch{}})()},[k,r,c]);const gt=_=>k?lt(_.type):e==="cli"?_.cliName:_.acpName,yt=k?t.detectedIdes||[]:[],dt=i.useCallback(async _=>{const Y=(_==null?void 0:_.type)||N,ye=(_==null?void 0:_.workspacePath)??Be;if(k){await x(Y,ye?{workspace:ye}:void 0)&&Fe(Y);return}const We=await l.runLaunchCliCore({cliType:Y,dir:_!=null&&_.workspaceId?void 0:ye||void 0,workspaceId:(_==null?void 0:_.workspaceId)||void 0,useHome:(_==null?void 0:_.useHome)||!(_!=null&&_.workspaceId)&&!ye,argsStr:(_==null?void 0:_.argsStr)??($||void 0),model:(_==null?void 0:_.model)??(j&&O||void 0),resumeSessionId:(_==null?void 0:_.resumeSessionId)||!j&&e==="cli"&&Y===N&&R||void 0});if(We.success||We.pending){const De=(_==null?void 0:_.argsStr)??$;!k&&(De!=null&&De.trim())&&(au(r,Y,De),re(Y)),Fe(Y),We.success&&We.sessionId&&T(We.sessionId)}},[l,x,j,k,$,O,re,Fe,r,T,Be,R,N]),xt=rd(k?"ide":j?"acp":"cli",!k&&!j&&!!R),Ve=nd(k?"ide":j?"acp":"cli",!k&&!j&&!!R),Ht=()=>{var De;const _=k?lt(N):L.get(N)||N,Y=!k&&!j&&!!R,{options:ye,selectedKey:We}=js({machine:t,currentWorkspaceId:he&&he!=="__custom__"?he:null,currentWorkspacePath:Be});Oe({title:Y?zo(_):bs("start-fresh",_),description:Y?Go():gs("start-fresh"),confirmLabel:xt,busyLabel:Ve,workspaceOptions:ye,selectedWorkspaceKey:We,details:[{label:"Mode",value:A.label},{label:"Provider",value:_},...!k&&e==="cli"&&R?[{label:"Resume",value:((De=W.find(Ke=>Ke.providerSessionId===R))==null?void 0:De.title)||R}]:[],...!k&&$.trim()?[{label:"Arguments",value:$.trim()}]:[],...j&&O.trim()?[{label:"Model",value:O.trim()}]:[]]},async()=>{const Ke=ye.find(rt=>rt.key===Ye.current);Ke!=null&&Ke.workspaceId?(ae(Ke.workspaceId),oe("")):Ke!=null&&Ke.workspacePath?(ae("__custom__"),oe(Ke.workspacePath)):(ae(""),oe("")),await dt({workspaceId:(Ke==null?void 0:Ke.workspaceId)??null,workspacePath:(Ke==null?void 0:Ke.workspacePath)??"",useHome:!(Ke!=null&&Ke.workspaceId)&&!(Ke!=null&&Ke.workspacePath)})})},Z=_=>{k?h(_):w(_.type,_.workspace,_.id)},$e=i.useCallback(async(_,Y,ye=!1)=>{if(_.mode===Y){ye&&_.sessionId&&T(_.sessionId);return}if(!c||!_.sessionId){ye&&_.sessionId&&T(_.sessionId);return}try{await c(r,"set_cli_view_mode",{targetSessionId:_.sessionId,cliType:_.type,mode:Y}),ye&&T(_.sessionId)}catch(We){const De=Sd(We);kd(We)?console.warn(De?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",We instanceof Error?We.message:String(We)):console.error("Failed to switch CLI view mode:",We)}},[r,T,c]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${A.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 ",A.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?yt.length>0?yt.map(_=>{const Y=a.find(rt=>(rt.type||"").toLowerCase()===(_.type||"").toLowerCase()&&vt(rt.status)!=="stopped"),ye=_.running||!!Y,We=!!Y&&Y.cdpConnected,De=de.includes(_.type||_.id||""),Ke=N===(_.type||"");return s.jsxs("button",{onClick:()=>{if(We&&Y){const rt=Y.sessionId;rt?p(ls(rt),{state:{openRemoteForTabKey:rt}}):p("/dashboard",{state:{openRemoteForTabKey:Y.id}});return}De||D(rt=>rt===(_.type||"")?"":_.type||"")},disabled:!!y||De,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${We?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ke?"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:y&&y!==_.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(_.type)}),ye&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${We?"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:_.name||lt(_.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${We?"text-green-400":De?"text-orange-400":Ke?"text-accent-primary":"text-text-muted"}`,children:We?"Open Session":De?"Starting...":Ke?"Configure":"Select"})]})]},_.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:b,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(Wm,{size:14})," Scan System"]})]}):B.length>0?B.map(_=>{const Y=N===_.type,ye=de.includes(_.type),De=!!a.find(Ke=>Ke.type===_.type&&vt(Ke.status)!=="stopped");return s.jsxs("button",{onClick:()=>D(Ke=>Ke===_.type?"":_.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Y?"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:_.icon}),De&&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:_.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ye?"text-orange-400":Y?"text-accent-primary":"text-text-muted"}`,children:ye?"Starting...":Y?"Configure":"Select"})]})]},_.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."})]})}),N&&(k?yt.find(_=>_.type===N):B.find(_=>_.type===N))&&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:k?lt(N):L.get(N)||N})]}),s.jsx(Iw,{machine:t,selectedWorkspace:he,resolvedWorkspacePath:Be,customPath:ue,canBrowse:!!c,onWorkspaceChange:ae,onCustomPathChange:oe,onOpenBrowseDialog:X}),!k&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!j&&e==="cli"&&s.jsx(iu,{busy:!!f||!!y||de.includes(N),savedSessionsLoading:ie,savedSessionsError:Ne,savedSessionsLoaded:ce,savedSessionsCount:W.length,selectedSession:Ee,onRefresh:()=>void V(N),onOpenHistory:()=>{N&&(fe(!0),ou({hasLoadedInitialResults:ce,isLoading:ie})&&V(N))},onClearSelection:()=>U("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[j&&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:O,onChange:_=>P(_.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:$,onChange:_=>E(_.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(_=>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:_,children:[s.jsx("button",{type:"button",className:"min-w-0 max-w-[220px] truncate px-2.5 py-1.5 text-left",onClick:()=>E(_),children:_}),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(N,_),"aria-label":`Remove startup arguments: ${_}`,title:"Remove startup arguments",children:s.jsx(jt,{size:12})})]},_))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:Ht,disabled:!!f||!!y||de.includes(N),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===N||y===N?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+de.filter(_=>!a.some(Y=>Y.type===_&&vt(Y.status)!=="stopped")).length,")"]}),a.length===0&&be.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 ",A.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[be.map(_=>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(_)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?lt(_):L.get(_)||_}),s.jsx("div",{className:"text-[11px] text-text-muted",children:f===_?"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:${_}`)),a.map(_=>{const Y=k?_:null,ye=!k&&!j?_:null,We=vt(_.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(_.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[gt(_),(Y==null?void 0:Y.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Y.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:_.workspace||"—"}),u&&_.git&&_.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:De=>{De.stopPropagation(),u(_.daemonId??r,_.workspace)},children:s.jsx(zs,{git:_.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(zs,{git:_.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(ye==null?void 0:ye.mode)&&s.jsx("span",{className:ye.mode==="chat"?"text-violet-400":"text-text-secondary",children:ye.mode==="chat"?"Chat view":"Terminal view"})]}),ye&&(ye.runtimeKey||ye.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ye.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 ",ye.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 De;(De=navigator.clipboard)==null||De.writeText(`adhdev attach ${ye.runtimeKey}`),v(ye.runtimeKey||null),window.setTimeout(()=>{v(Ke=>Ke===ye.runtimeKey?null:Ke)},1200)},children:S===ye.runtimeKey?"Copied":"Copy"})]}),ye.runtimeWriteOwner&&s.jsx("span",{style:{color:ye.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ye.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Cw(ye.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 ${We==="stopped"?"bg-red-500/[0.08] text-red-500":We==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:We}),k&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const De=_.sessionId;if(De){p(ls(De),{state:{openRemoteForTabKey:De}});return}p("/dashboard",{state:{openRemoteForTabKey:_.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(Rt,{size:13})}),s.jsx("button",{onClick:()=>{const De=_.workspace||"",{options:Ke,selectedKey:rt}=js({machine:t,currentWorkspacePath:De});Oe({title:bs("restart-ide",lt(_.type)),description:gs("restart-ide"),confirmLabel:Gs("restart-ide"),busyLabel:Vs("restart-ide"),workspaceOptions:Ke,selectedWorkspaceKey:rt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:lt(_.type)}]},async()=>{const Tt=Ke.find(es=>es.key===Ye.current),bt=(Tt==null?void 0:Tt.workspacePath)??"";if(bt&&bt!==De){await dt({type:_.type,workspacePath:bt});return}await g(_)})},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(Ar,{size:14})})]}),j&&s.jsx("button",{onClick:()=>{const De=_.sessionId;De&&T(De)},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:!_.sessionId,children:s.jsx(Qt,{size:14})}),ye&&We!=="stopped"&&s.jsxs(s.Fragment,{children:[ye.mode&&s.jsx(Ho,{mode:ye.mode,onChange:De=>void $e(ye,De,!1),compact:!0}),s.jsx("button",{onClick:()=>{const De=_.sessionId;De&&T(De)},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:!_.sessionId,children:ye.mode==="chat"?s.jsx(Qt,{size:14}):s.jsx(Rt,{size:13})})]}),We==="stopped"?s.jsx("button",{onClick:()=>{const De=_.workspace||"",Ke=k?lt(_.type):gt(_),{options:rt,selectedKey:Tt}=js({machine:t,currentWorkspacePath:De});Oe({title:bs("restart-stopped",Ke),description:gs("restart-stopped"),confirmLabel:Gs("restart-stopped"),busyLabel:Vs("restart-stopped"),workspaceOptions:rt,selectedWorkspaceKey:Tt,details:[{label:"Mode",value:A.label},{label:"Provider",value:Ke}]},async()=>{const bt=rt.find(es=>es.key===Ye.current);await dt({type:_.type,workspaceId:(bt==null?void 0:bt.workspaceId)??null,workspacePath:(bt==null?void 0:bt.workspacePath)??"",useHome:!(bt!=null&&bt.workspaceId)&&!(bt!=null&&bt.workspacePath)})})},disabled:de.includes(_.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:de.includes(_.type)?"⏳":s.jsx(Io,{size:14})}):s.jsx("button",{onClick:()=>Z(_),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(jt,{size:14})})]})]}),Y&&Y.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Y.aiAgents.map(De=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Mn(De.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[De.name," · ",vt(De.status)]},De.id))}),Y&&(Ue[Y.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:(Ue[Y.type]||[]).map(De=>s.jsxs("button",{disabled:Ze===`${Y.type}.${De.type}`,onClick:async()=>{const Ke=`${Y.type}.${De.type}`;et(Ke);try{await c(r,"set_ide_extension",{ideType:Y.type,extensionType:De.type,enabled:!De.enabled}),Le(rt=>({...rt,[Y.type]:(rt[Y.type]||[]).map(Tt=>Tt.type===De.type?{...Tt,enabled:!Tt.enabled}:Tt)}))}catch(rt){console.error("Extension toggle failed:",rt)}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 ${De.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 ${De.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),De.name,s.jsx("span",{className:"text-[9px] font-normal",children:De.enabled?"ON":"OFF"})]},De.type))})]})]},_.id)})]}),ve&&c&&s.jsx(Zn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:pe,directories:Ie,busy:_e,error:Me,confirmLabel:"Use this folder",onClose:()=>le(!1),onNavigate:_=>{z(_)},onConfirm:_=>{oe(_),ae("__custom__"),le(!1)}}),Ge&&s.jsx(ti,{title:Ge.title,description:Ge.description,details:Ge.details,workspaceOptions:Ge.workspaceOptions,selectedWorkspaceKey:tt,onWorkspaceChange:_=>{Ye.current=_,ct(_)},confirmLabel:Ge.confirmLabel,busyLabel:Ge.busyLabel,busy:mt,onConfirm:Re,onCancel:()=>{He.current=null,Xe(null)}}),ge&&te&&s.jsx(Vo,{activeConv:te,ides:[],isCreatingChat:!1,isRefreshingHistory:ie,savedSessions:W,isSavedSessionsLoading:ie,isResumingSavedSessionId:Se,savedHistoryFilters:we,missingWorkspaceResumePath:Be||null,onSavedHistoryFiltersChange:xe,onClose:()=>fe(!1),onNewChat:()=>{U(""),fe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{V(N)},onResumeSavedSession:_=>{if(!_.canResume||Se)return;const Y=H(_);U(_.providerSessionId),se(_),J(_.providerSessionId),fe(!1),dt({type:_.providerType,workspaceId:Y.workspaceId,workspacePath:Y.workspacePath,useHome:Y.useHome,resumeSessionId:_.providerSessionId}).finally(()=>{J(ye=>ye===_.providerSessionId?null:ye)})}})]})}const ql=[{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 Tw({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:l,getIcon:c,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:p,onOpenGitDialog:x}){var b;const[w,g]=i.useState(d);i.useEffect(()=>{g(d)},[d]);const h=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:ql.map(y=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${w===y.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>g(y.id),children:[s.jsx("span",{children:y.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${w===y.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:h[y.id]})]},y.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(b=ql.find(y=>y.id===w))==null?void 0:b.helper})]}),w==="ide"&&s.jsx(Ua,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:c,actions:l,sendDaemonCommand:p,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),w==="cli"&&s.jsx(Ua,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:c,actions:l,sendDaemonCommand:p,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),w==="acp"&&s.jsx(Ua,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:o,getIcon:c,actions:l,sendDaemonCommand:p,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x})]})}function Aw({onNicknameSynced:e}={}){var oe,de,Q,ve,le,pe,ne,Ie,Ce,_e;const{id:t}=um(),r=Ys(),n=wo(),{sendCommand:a}=kt(),o=Rr(),l=gd(),c=Yc(),d=c.ides||[],m=c.initialLoaded??!0,u=d.find(K=>K.id===t&&K.type==="adhdev-daemon"),p=d.some(K=>K.type==="adhdev-daemon"),x=t?(oe=c.connectionRetryStatuses)==null?void 0:oe[t]:void 0,w=!!(x!=null&&x.blocked),[g,h]=i.useState("workspace"),[b,y]=i.useState(null),f=i.useCallback((K,Me)=>{y({daemonId:K,workspace:Me})},[]),[M,S]=i.useState("ide"),v=i.useRef(null),[T,A]=i.useState(null),k=i.useRef("__home__"),[j,B]=i.useState("__home__"),[L,N]=i.useState(!1),D=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||g!=="overview")return;const K=u.machine;(typeof(K==null?void 0:K.cpus)!="number"||typeof(K==null?void 0:K.totalMem)!="number"||typeof(K==null?void 0:K.arch)!="string"||typeof(K==null?void 0:K.release)!="string")&&l(t,{minFreshMs:3e4}).catch(()=>{})},[g,l,u,t]),xb(t&&g==="overview"?[t]:[],{enabled:g==="overview",intervalMs:cf});const $=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},E=Nv({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:D});i.useEffect(()=>ot.onToast(Me=>{c.setToasts(He=>{if(He.some(Ye=>Ye.message===Me.message&&Me.timestamp-Ye.timestamp<3e3))return He;const Xe={id:Me.id,message:Me.message,type:Me.type,timestamp:Me.timestamp,targetKey:Me.targetKey,actions:Me.actions};return[...He.slice(-4),Xe]});const Te=Me.duration||5e3;setTimeout(()=>c.setToasts(He=>He.filter(Ge=>Ge.id!==Me.id)),Te)}),[c]);const C=(u==null?void 0:u.availableProviders)||[],I={};for(const K of C)I[K.type]=K.icon;const O=K=>I[K]||"",P=u?{id:u.id,hostname:kc(u,{fallbackId:u.id}),platform:((de=u.machine)==null?void 0:de.platform)||"unknown",arch:((Q=u.machine)==null?void 0:Q.arch)||"",cpus:((ve=u.machine)==null?void 0:ve.cpus)||0,totalMem:((le=u.machine)==null?void 0:le.totalMem)||0,freeMem:(pe=u.machine)==null?void 0:pe.freeMem,availableMem:(ne=u.machine)==null?void 0:ne.availableMem,loadavg:(Ie=u.machine)==null?void 0:Ie.loadavg,uptime:(Ce=u.machine)==null?void 0:Ce.uptime,release:((_e=u.machine)==null?void 0:_e.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,R=d.filter(K=>K.daemonId===t&&K.type!=="adhdev-daemon").filter(K=>!Mr(K)&&!$s(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,version:K.version||"",instanceId:K.instanceId||"",status:K.status,workspace:K.workspace||null,terminals:K.terminals||0,aiAgents:eh(K.aiAgents||(K.agents||[]).map(Me=>({id:Me.name,name:Me.name,status:Me.status,version:Me.version}))),activeChat:K.activeChat||null,chats:K.chats||[],childSessions:K.childSessions||[],cdpConnected:K.cdpConnected||!1,daemonId:t,lastMessageAt:K.lastMessageAt})),U=d.filter(K=>K.daemonId===t&&Mr(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,cliName:K.cliName||K.type,status:K.status,workspace:K.workspace||"",activeChat:K.activeChat||null,providerSessionId:K.providerSessionId,mode:K.mode,runtimeKey:K.runtimeKey,runtimeDisplayName:K.runtimeDisplayName,runtimeWorkspaceLabel:K.runtimeWorkspaceLabel,runtimeWriteOwner:K.runtimeWriteOwner||null,runtimeAttachedClients:K.runtimeAttachedClients||[],daemonId:t,lastMessageAt:K.lastMessageAt})),W=d.filter(K=>K.daemonId===t&&$s(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,acpName:K.cliName||K.type,status:K.status,workspace:K.workspace||"",activeChat:K.activeChat||null,providerSessionId:K.providerSessionId,daemonId:t,lastMessageAt:K.lastMessageAt})),me=u?Lt(u,{fallbackId:t}):"",ie="workspace",ee=n.state,ce=ee==null?void 0:ee.initialMachineTab,je=ee==null?void 0:ee.initialWorkspaceCategory,Ne=ee==null?void 0:ee.initialWorkspaceId,q=ee==null?void 0:ee.initialWorkspacePath,ge=ce==="ides"||ce==="clis"||ce==="acps"?"workspace":ce||ie,fe=ce==="ides"?"ide":ce==="clis"?"cli":ce==="acps"?"acp":je,we=[...R.map(K=>{var Me;return{id:`ide:${K.type}:${K.workspace||""}`,label:((Me=K.activeChat)==null?void 0:Me.title)||K.type,kind:"ide",providerType:K.type,subtitle:K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:K.lastMessageAt||0}}),...U.map(K=>{var Me;return{id:`cli:${K.type}:${K.workspace||""}`,label:((Me=K.activeChat)==null?void 0:Me.title)||K.cliName,kind:"cli",providerType:K.type,providerSessionId:K.providerSessionId,subtitle:K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:K.lastMessageAt||0}}),...W.map(K=>{var Me;return{id:`acp:${K.type}:${K.workspace||""}`,label:((Me=K.activeChat)==null?void 0:Me.title)||K.acpName,kind:"acp",providerType:K.type,providerSessionId:K.providerSessionId,subtitle:Ns(K.summaryMetadata)||K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:K.lastMessageAt||0}})].sort((K,Me)=>(Me.lastLaunchedAt||0)-(K.lastLaunchedAt||0)),xe=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(K=>({id:K.id,label:K.title||K.providerName||K.providerType,kind:K.kind,providerType:K.providerType,providerSessionId:K.providerSessionId,subtitle:Ns(K.summaryMetadata)||K.workspace||void 0,workspace:K.workspace,summaryMetadata:K.summaryMetadata,lastLaunchedAt:K.lastLaunchedAt})):we,Se=i.useMemo(()=>{var Me;const K=((Me=c.connectionStates)==null?void 0:Me[t||""])||void 0;return d.filter(Te=>Te.daemonId===t&&Te.type!=="adhdev-daemon").flatMap(Te=>qo(Te,{connectionStates:t&&K?{[t]:K}:void 0,defaultConnectionState:K})).filter(Te=>!(Te.transport==="pty"&&Te.mode==="terminal")).sort((Te,He)=>po(He)-po(Te))},[d,c.connectionStates,t]),J=i.useCallback(K=>{const Me=Bd(K);Me&&r(ls(Me))},[r]),he=i.useCallback(()=>{v.current&&(N(!0),v.current().finally(()=>{v.current=null,N(!1),A(null)}))},[]),ae=i.useCallback(K=>{if(!P)return;const{options:Me,selectedKey:Te}=js({machine:P,currentWorkspacePath:K.workspace}),He=async()=>{S(K.kind),h("workspace")};v.current=async()=>{const Ge=Me.find(tt=>tt.key===k.current),Xe=(Ge==null?void 0:Ge.workspacePath)??null,Ye=(Ge==null?void 0:Ge.workspaceId)??null;if(K.kind==="ide"&&K.providerType){await E.handleLaunchIde(K.providerType,Xe?{workspace:Xe}:void 0);return}if((K.kind==="cli"||K.kind==="acp")&&K.providerType){await E.runLaunchCliCore({cliType:K.providerType,dir:Ye?void 0:Xe||"",workspaceId:Ye||void 0,model:K.kind==="acp"&&Nc(K.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:K.providerSessionId});return}await He()},k.current=Te,B(Te),A({title:K.kind==="ide"?bs("restart-ide",K.label):K.providerSessionId?zo(K.label):bs("start-fresh",K.label),description:K.kind==="ide"?gs("restart-ide"):K.providerSessionId?Go():gs("start-fresh"),confirmLabel:K.kind==="ide"?Gs("restart-ide"):K.providerSessionId?Rn(!0):Gs("start-fresh"),busyLabel:K.kind==="ide"?Vs("restart-ide"):K.providerSessionId?Ko(!0):Vs("start-fresh"),workspaceOptions:Me,details:[{label:"Mode",value:K.kind.toUpperCase()},...K.providerType?[{label:"Provider",value:K.providerType}]:[]]})},[E,P]);if(i.useEffect(()=>{h(ge)},[ie,ge,t]),i.useEffect(()=>{fe&&S(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:$,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 ue=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Rt,{size:14})," Workspace"]}),count:R.length+U.length+W.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(os,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Wn,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Km,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Om,{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:$,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:[E.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:E.nicknameInput,onChange:K=>E.setNicknameInput(K.target.value),onKeyDown:K=>{K.key==="Enter"&&E.handleSaveNickname(),K.key==="Escape"&&E.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:E.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:()=>E.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:()=>{E.setEditingNickname(!0),E.setNicknameInput(P.machineNickname||"")},title:"Click to set nickname",children:me}),w?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:ue.map(K=>s.jsxs("button",{onClick:()=>h(K.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${g===K.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[K.label,K.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${g===K.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:K.count})]},K.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:[g==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(Nw,{machineEntry:u,providers:C,recentLaunches:xe,currentConversations:Se,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",Pd(u))}catch{}},onOpenRecent:ae,onOpenConversation:J}),s.jsx(Tw,{machine:P,machineId:t,providers:C,ideSessions:R,cliSessions:U,acpSessions:W,actions:E,getIcon:O,initialCategory:M,initialWorkspaceId:Ne,initialWorkspacePath:q,sendDaemonCommand:a,onOpenGitDialog:f})]}),g==="providers"&&s.jsx(Dv,{machineId:t,providers:C,sendDaemonCommand:a}),g==="overview"&&s.jsx(Cv,{machineId:t,machine:P,ideSessions:R,cliSessions:U,acpSessions:W,actions:E,sendDaemonCommand:a}),g==="session-host"&&s.jsx(kw,{machineId:t,cliSessions:U,sendDaemonCommand:a}),g==="logs"&&s.jsx(xw,{machineId:t,sendDaemonCommand:a})]})})}),E.launchPick&&P&&s.jsx(Sw,{machine:P,launchPick:E.launchPick,actions:E}),T&&s.jsx(ti,{title:T.title,description:T.description,details:T.details,workspaceOptions:T.workspaceOptions,selectedWorkspaceKey:j,onWorkspaceChange:K=>{k.current=K,B(K)},confirmLabel:T.confirmLabel,busyLabel:T.busyLabel,busy:L,onConfirm:he,onCancel:()=>{v.current=null,A(null)}}),b&&s.jsx(ju,{daemonId:b.daemonId,workspace:b.workspace,onClose:()=>y(null)}),s.jsx(ad,{toasts:c.toasts||[],onDismiss:K=>c.setToasts(Me=>Me.filter(Te=>Te.id!==K)),onClickToast:K=>{K.targetKey&&r(ls(K.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 N=await r(e,"session_host_prune_duplicate_sessions",{}),D=Fa(N);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Duplicate prune failed");const $=D.result||{},E=Array.isArray($.prunedSessionIds)?$.prunedSessionIds.length:0,C=typeof $.duplicateGroupCount=="number"?$.duplicateGroupCount:0;ot.showToast(`Pruned ${E} duplicate runtime(s) across ${C} group(s)`,"success"),await h()}catch(N){const D=N instanceof Error?N.message:"Duplicate prune failed";ot.showToast(D,"warning"),a(D)}finally{l(N=>N==="session_host_prune_duplicate_sessions"?null:N)}}},[e,h,r]),f=i.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((L,N)=>(N.lastActivityAt||0)-(L.lastActivityAt||0)),[u==null?void 0:u.sessions]),M=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)||[]}:yw(f),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,f]),S=M.liveRuntimes,v=M.recoverySnapshots,T=M.inactiveRecords,A=i.useMemo(()=>kw(S),[S]),k=i.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),j=i.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(L=>L.level==="warn"||L.level==="error")||null,[u==null?void 0:u.recentLogs]),B=(L,N)=>{var U;const D=o===`session_host_resume_session:${L.sessionId}`,$=o===`session_host_restart_session:${L.sessionId}`,E=o===`session_host_stop_session:${L.sessionId}`,C=Su(L.meta),I=g.get(L.sessionId),O=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,P=N==="recovery"?"Recover":"Resume",R=vw(N);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:L.displayName||(I==null?void 0:I.cliName)||L.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${jw(L.lifecycle)}`,children:L.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:L.workspaceLabel||(I==null?void 0:I.runtimeWorkspaceLabel)||L.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:L.runtimeKey}),L.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",L.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((U=L.writeOwner)==null?void 0:U.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:ww(L.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(ic,{size:11})," ",O]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Vl(L.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",R]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[N==="recovery"&&(L.lifecycle==="interrupted"||L.lifecycle==="failed"||L.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{b("session_host_resume_session",L)},children:D?`${P}ing…`:P}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{b("session_host_restart_session",L)},children:$?"Restarting…":"Restart"}),N==="live"&&(L.lifecycle==="running"||L.lifecycle==="starting"||L.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:()=>{b("session_host_stop_session",L)},children:E?"Stopping…":"Stop"})]})]})},L.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(os,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:gx()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[A>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{y()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${A})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${w.toneClass}`,children:w.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:p||c,children:[s.jsx(Ar,{size:13}),p||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(Ir,{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:v.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:Vl(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Wa(u.hostStartedAt)})]})]}),j&&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(Ir,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:j.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Wa(j.timestamp),j.sessionId?` · ${j.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(Co,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Oa("live")}),S.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:S.map(L=>B(L,"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(os,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Oa("recovery")}),v.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:v.map(L=>B(L,"recovery"))})]}),T.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:Oa("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:T.map(L=>B(L,"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"}),k.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:k.map(L=>{var D;const N=f.find($=>$.sessionId===L.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:(N==null?void 0:N.displayName)||((D=g.get(L.sessionId))==null?void 0:D.cliName)||L.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[L.action,L.lifecycle?` · ${L.lifecycle}`:"",L.detail?` · ${L.detail}`:"",L.error?` · ${L.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${L.success===!1?"text-red-300":"text-text-secondary"}`,children:Wa(L.timestamp)})]},`${L.sessionId}:${L.timestamp}:${L.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 Nw({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 Ha({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 Ka({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 Cw({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=Rd(e),p=Ps(e,m),x=jr(e,p),w=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(Ha,{icon:s.jsx(Qt,{size:13}),children:"Current Chats"}),s.jsx(Ka,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(g=>{const h=po(g);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(g),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(g)}),h>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Kn(h)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Cs(g)})]},g.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ha,{icon:s.jsx(uc,{size:13}),children:"Recent Launches"}),s.jsx(Ka,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(g=>{const{metaText:h,updatedLabel:b}=zd(g);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(g),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:g.label}),b&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:b})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:h})]},g.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ha,{icon:s.jsx(Ir,{size:13}),children:"Daemon Update"}),s.jsx(Ka,{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.",p&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",p,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(Ar,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:w})]})]})})]})]})}function Iw(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function Mw({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?"⭐ ":"",zn(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 Tw={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 ln(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ua({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:l,sendDaemonCommand:c,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const p=Ys(),{handleLaunchIde:x,handleStopCli:w,handleRestartIde:g,handleStopIde:h,handleDetectIdes:b,launchingIde:y,launchingAgentType:f,addLog:M}=l,[S,v]=i.useState(null),T=i.useCallback(_=>{_&&p(ls(_))},[p]),A=Tw[e],k=e==="ide",j=e==="acp",B=i.useMemo(()=>n.filter(_=>Is(_,e)),[e,n]),L=i.useMemo(()=>new Map(B.map(_=>[_.type,_.displayName||_.type])),[B]),[N,D]=i.useState(""),[$,E]=i.useState(""),[C,I]=i.useState([]),[O,P]=i.useState(""),[R,U]=i.useState(""),[W,me]=i.useState([]),[ie,ee]=i.useState(!1),[ce,je]=i.useState(!1),[Ne,q]=i.useState(""),[ge,fe]=i.useState(!1),[we,xe]=i.useState(()=>Nt()),[Se,J]=i.useState(null),[he,ae]=i.useState(m?"__custom__":d||t.defaultWorkspaceId||""),[ue,oe]=i.useState(m||""),[de,Q]=i.useState([]),[ve,le]=i.useState(!1),[pe,ne]=i.useState(""),[Ie,Ce]=i.useState([]),[_e,K]=i.useState(!1),[Me,Te]=i.useState(""),He=i.useRef(null),[Ge,Xe]=i.useState(null),Ye=i.useRef("__home__"),[tt,ct]=i.useState("__home__"),[mt,pt]=i.useState(!1),F=i.useRef(0),be=de.filter(_=>!a.some(Y=>Y.type===_&&vt(Y.status)!=="stopped")),Ae=i.useRef({});i.useEffect(()=>{t.defaultWorkspaceId&&!he&&ae(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),i.useEffect(()=>{if(m){ae("__custom__"),oe(m);return}d&&(ae(d),oe(""))},[d,m]),i.useEffect(()=>{k||N&&(B.some(_=>_.type===N)||(D(""),U("")))},[B,k,N]);const Be=(()=>{if(he==="__custom__")return ue.trim();if(!he)return"";const _=(t.workspaces||[]).find(Y=>Y.id===he);return(_==null?void 0:_.path)||""})(),qe=i.useCallback(_=>{const Y=Ae.current[_];Y&&(clearTimeout(Y),delete Ae.current[_]),Q(ye=>ye.includes(_)?ye.filter(We=>We!==_):ye)},[]),G=i.useRef(new Set),z=i.useCallback(async _=>{if(c){K(!0),Te("");try{const Y=await Qn(c,r,_);ne(Y.path),oe(Y.path),Ce(Y.directories)}catch(Y){Te(Y instanceof Error?Y.message:"Could not load folder")}finally{K(!1)}}},[r,c]),X=i.useCallback(()=>{if(!c)return;ae("__custom__"),le(!0);const _=a.map(ye=>ye.workspace),Y=Jn(t.platform,Xn(ue.trim(),Be,m,_,t.defaultWorkspacePath,(t.workspaces||[]).map(ye=>ye.path)));z(Y)},[ue,m,z,t.defaultWorkspacePath,t.platform,t.workspaces,a,Be,c]),se=i.useCallback(_=>{const Y=String(_.workspace||"").trim();if(!Y)return;const ye=(t.workspaces||[]).find(We=>ln(We.path)===ln(Y));if(ye){ae(ye.id),oe("");return}ae("__custom__"),oe(Y)},[t.workspaces]),H=i.useCallback(_=>{const Y=String(_.workspace||"").trim();if(!Y)return{workspaceId:null,workspacePath:"",useHome:!0};const ye=(t.workspaces||[]).find(We=>ln(We.path)===ln(Y));return ye?{workspaceId:ye.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Y,useHome:!1}},[t.workspaces]),V=i.useCallback(async _=>{if(!c||!_||e!=="cli"){me([]),ee(!1),je(!1),q("");return}const Y=F.current+1;F.current=Y,ee(!0),q("");try{const ye=await c(r,"list_saved_sessions",{providerType:_,kind:"cli",limit:30});if(F.current!==Y)return;const We=(ye==null?void 0:ye.result)??ye;me(Array.isArray(We==null?void 0:We.sessions)?We.sessions:[])}catch(ye){if(F.current!==Y)return;me([]),q(ye instanceof Error?ye.message:"Could not load saved sessions")}finally{F.current===Y&&(ee(!1),je(!0))}},[e,r,c]),te=i.useMemo(()=>{if(e!=="cli"||!N)return null;const _=L.get(N)||N;return{routeId:r,daemonId:r,providerSessionId:R||void 0,transport:"pty",mode:"chat",agentName:_,agentType:N,status:"idle",title:_,messages:[],ideType:N,workspaceName:Be,workspacePath:Be,displayPrimary:_,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${N}`}},[e,r,L,Be,R,N]),re=i.useCallback(_=>{if(e==="ide"||!_){I([]);return}I(xo(r,_))},[e,r]),ke=i.useCallback((_,Y)=>{e==="ide"||!_||(_y(r,_,Y),I(xo(r,_)))},[e,r]);i.useEffect(()=>{F.current+=1,U(""),re(N),je(!1),me([]),q(""),ee(!1)},[e,re,V,N]);const Ee=i.useMemo(()=>W.find(_=>_.providerSessionId===R)||null,[W,R]);i.useEffect(()=>{if(!R)return;const _=W.find(Y=>Y.providerSessionId===R);_!=null&&_.canResume||U("")},[W,R]);const Oe=i.useCallback((_,Y)=>{He.current=Y,Ye.current=_.selectedWorkspaceKey||"__home__",ct(_.selectedWorkspaceKey||"__home__"),Xe(_)},[]),Re=i.useCallback(()=>{He.current&&(pt(!0),He.current().finally(()=>{He.current=null,pt(!1),Xe(null)}))},[]),Fe=i.useCallback(_=>{if(!_)return;Q(ye=>ye.includes(_)?ye:[...ye,_]);const Y=Ae.current[_];Y&&clearTimeout(Y),Ae.current[_]=setTimeout(()=>{Q(ye=>ye.includes(_)?ye.filter(We=>We!==_):ye),delete Ae.current[_]},2e4)},[]);i.useEffect(()=>{for(const Y of a)vt(Y.status)!=="stopped"&&(de.includes(Y.type)&&!G.current.has(Y.type)&&(G.current.add(Y.type),M("info",`${L.get(Y.type)||Y.type} launched`,!0)),qe(Y.type));const _=new Set(a.filter(Y=>vt(Y.status)!=="stopped").map(Y=>Y.type));G.current.forEach(Y=>{!de.includes(Y)&&!_.has(Y)&&G.current.delete(Y)})},[M,qe,a,de,L]),i.useEffect(()=>()=>{Object.values(Ae.current).forEach(clearTimeout),Ae.current={}},[]);const[Ue,Le]=i.useState({}),[Ze,et]=i.useState(null);i.useEffect(()=>{if(!k||!r||!c)return;(async()=>{try{const Y=await c(r,"get_ide_extensions",{}),ye=(Y==null?void 0:Y.result)||Y;ye!=null&&ye.success&&(ye!=null&&ye.ideExtensions)&&Le(ye.ideExtensions)}catch{}})()},[k,r,c]);const gt=_=>k?lt(_.type):e==="cli"?_.cliName:_.acpName,yt=k?t.detectedIdes||[]:[],dt=i.useCallback(async _=>{const Y=(_==null?void 0:_.type)||N,ye=(_==null?void 0:_.workspacePath)??Be;if(k){await x(Y,ye?{workspace:ye}:void 0)&&Fe(Y);return}const We=await l.runLaunchCliCore({cliType:Y,dir:_!=null&&_.workspaceId?void 0:ye||void 0,workspaceId:(_==null?void 0:_.workspaceId)||void 0,useHome:(_==null?void 0:_.useHome)||!(_!=null&&_.workspaceId)&&!ye,argsStr:(_==null?void 0:_.argsStr)??($||void 0),model:(_==null?void 0:_.model)??(j&&O||void 0),resumeSessionId:(_==null?void 0:_.resumeSessionId)||!j&&e==="cli"&&Y===N&&R||void 0});if(We.success||We.pending){const De=(_==null?void 0:_.argsStr)??$;!k&&(De!=null&&De.trim())&&(au(r,Y,De),re(Y)),Fe(Y),We.success&&We.sessionId&&T(We.sessionId)}},[l,x,j,k,$,O,re,Fe,r,T,Be,R,N]),xt=rd(k?"ide":j?"acp":"cli",!k&&!j&&!!R),Ve=nd(k?"ide":j?"acp":"cli",!k&&!j&&!!R),Ht=()=>{var De;const _=k?lt(N):L.get(N)||N,Y=!k&&!j&&!!R,{options:ye,selectedKey:We}=js({machine:t,currentWorkspaceId:he&&he!=="__custom__"?he:null,currentWorkspacePath:Be});Oe({title:Y?zo(_):bs("start-fresh",_),description:Y?Go():gs("start-fresh"),confirmLabel:xt,busyLabel:Ve,workspaceOptions:ye,selectedWorkspaceKey:We,details:[{label:"Mode",value:A.label},{label:"Provider",value:_},...!k&&e==="cli"&&R?[{label:"Resume",value:((De=W.find(Ke=>Ke.providerSessionId===R))==null?void 0:De.title)||R}]:[],...!k&&$.trim()?[{label:"Arguments",value:$.trim()}]:[],...j&&O.trim()?[{label:"Model",value:O.trim()}]:[]]},async()=>{const Ke=ye.find(rt=>rt.key===Ye.current);Ke!=null&&Ke.workspaceId?(ae(Ke.workspaceId),oe("")):Ke!=null&&Ke.workspacePath?(ae("__custom__"),oe(Ke.workspacePath)):(ae(""),oe("")),await dt({workspaceId:(Ke==null?void 0:Ke.workspaceId)??null,workspacePath:(Ke==null?void 0:Ke.workspacePath)??"",useHome:!(Ke!=null&&Ke.workspaceId)&&!(Ke!=null&&Ke.workspacePath)})})},Z=_=>{k?h(_):w(_.type,_.workspace,_.id)},$e=i.useCallback(async(_,Y,ye=!1)=>{if(_.mode===Y){ye&&_.sessionId&&T(_.sessionId);return}if(!c||!_.sessionId){ye&&_.sessionId&&T(_.sessionId);return}try{await c(r,"set_cli_view_mode",{targetSessionId:_.sessionId,cliType:_.type,mode:Y}),ye&&T(_.sessionId)}catch(We){const De=Sd(We);kd(We)?console.warn(De?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",We instanceof Error?We.message:String(We)):console.error("Failed to switch CLI view mode:",We)}},[r,T,c]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${A.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 ",A.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?yt.length>0?yt.map(_=>{const Y=a.find(rt=>(rt.type||"").toLowerCase()===(_.type||"").toLowerCase()&&vt(rt.status)!=="stopped"),ye=_.running||!!Y,We=!!Y&&Y.cdpConnected,De=de.includes(_.type||_.id||""),Ke=N===(_.type||"");return s.jsxs("button",{onClick:()=>{if(We&&Y){const rt=Y.sessionId;rt?p(ls(rt),{state:{openRemoteForTabKey:rt}}):p("/dashboard",{state:{openRemoteForTabKey:Y.id}});return}De||D(rt=>rt===(_.type||"")?"":_.type||"")},disabled:!!y||De,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${We?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ke?"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:y&&y!==_.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(_.type)}),ye&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${We?"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:_.name||lt(_.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${We?"text-green-400":De?"text-orange-400":Ke?"text-accent-primary":"text-text-muted"}`,children:We?"Open Session":De?"Starting...":Ke?"Configure":"Select"})]})]},_.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:b,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(Wm,{size:14})," Scan System"]})]}):B.length>0?B.map(_=>{const Y=N===_.type,ye=de.includes(_.type),De=!!a.find(Ke=>Ke.type===_.type&&vt(Ke.status)!=="stopped");return s.jsxs("button",{onClick:()=>D(Ke=>Ke===_.type?"":_.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Y?"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:_.icon}),De&&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:_.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ye?"text-orange-400":Y?"text-accent-primary":"text-text-muted"}`,children:ye?"Starting...":Y?"Configure":"Select"})]})]},_.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."})]})}),N&&(k?yt.find(_=>_.type===N):B.find(_=>_.type===N))&&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:k?lt(N):L.get(N)||N})]}),s.jsx(Mw,{machine:t,selectedWorkspace:he,resolvedWorkspacePath:Be,customPath:ue,canBrowse:!!c,onWorkspaceChange:ae,onCustomPathChange:oe,onOpenBrowseDialog:X}),!k&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!j&&e==="cli"&&s.jsx(iu,{busy:!!f||!!y||de.includes(N),savedSessionsLoading:ie,savedSessionsError:Ne,savedSessionsLoaded:ce,savedSessionsCount:W.length,selectedSession:Ee,onRefresh:()=>void V(N),onOpenHistory:()=>{N&&(fe(!0),ou({hasLoadedInitialResults:ce,isLoading:ie})&&V(N))},onClearSelection:()=>U("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[j&&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:O,onChange:_=>P(_.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:$,onChange:_=>E(_.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(_=>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:_,children:[s.jsx("button",{type:"button",className:"min-w-0 max-w-[220px] truncate px-2.5 py-1.5 text-left",onClick:()=>E(_),children:_}),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(N,_),"aria-label":`Remove startup arguments: ${_}`,title:"Remove startup arguments",children:s.jsx(jt,{size:12})})]},_))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:Ht,disabled:!!f||!!y||de.includes(N),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===N||y===N?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+de.filter(_=>!a.some(Y=>Y.type===_&&vt(Y.status)!=="stopped")).length,")"]}),a.length===0&&be.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 ",A.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[be.map(_=>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(_)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?lt(_):L.get(_)||_}),s.jsx("div",{className:"text-[11px] text-text-muted",children:f===_?"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:${_}`)),a.map(_=>{const Y=k?_:null,ye=!k&&!j?_:null,We=vt(_.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(_.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[gt(_),(Y==null?void 0:Y.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Y.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:_.workspace||"—"}),u&&_.git&&_.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:De=>{De.stopPropagation(),u(_.daemonId??r,_.workspace)},children:s.jsx(zs,{git:_.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(zs,{git:_.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(ye==null?void 0:ye.mode)&&s.jsx("span",{className:ye.mode==="chat"?"text-violet-400":"text-text-secondary",children:ye.mode==="chat"?"Chat view":"Terminal view"})]}),ye&&(ye.runtimeKey||ye.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ye.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 ",ye.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 De;(De=navigator.clipboard)==null||De.writeText(`adhdev attach ${ye.runtimeKey}`),v(ye.runtimeKey||null),window.setTimeout(()=>{v(Ke=>Ke===ye.runtimeKey?null:Ke)},1200)},children:S===ye.runtimeKey?"Copied":"Copy"})]}),ye.runtimeWriteOwner&&s.jsx("span",{style:{color:ye.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ye.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Iw(ye.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 ${We==="stopped"?"bg-red-500/[0.08] text-red-500":We==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:We}),k&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const De=_.sessionId;if(De){p(ls(De),{state:{openRemoteForTabKey:De}});return}p("/dashboard",{state:{openRemoteForTabKey:_.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(Rt,{size:13})}),s.jsx("button",{onClick:()=>{const De=_.workspace||"",{options:Ke,selectedKey:rt}=js({machine:t,currentWorkspacePath:De});Oe({title:bs("restart-ide",lt(_.type)),description:gs("restart-ide"),confirmLabel:Gs("restart-ide"),busyLabel:Vs("restart-ide"),workspaceOptions:Ke,selectedWorkspaceKey:rt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:lt(_.type)}]},async()=>{const Tt=Ke.find(es=>es.key===Ye.current),bt=(Tt==null?void 0:Tt.workspacePath)??"";if(bt&&bt!==De){await dt({type:_.type,workspacePath:bt});return}await g(_)})},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(Ar,{size:14})})]}),j&&s.jsx("button",{onClick:()=>{const De=_.sessionId;De&&T(De)},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:!_.sessionId,children:s.jsx(Qt,{size:14})}),ye&&We!=="stopped"&&s.jsxs(s.Fragment,{children:[ye.mode&&s.jsx(Ho,{mode:ye.mode,onChange:De=>void $e(ye,De,!1),compact:!0}),s.jsx("button",{onClick:()=>{const De=_.sessionId;De&&T(De)},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:!_.sessionId,children:ye.mode==="chat"?s.jsx(Qt,{size:14}):s.jsx(Rt,{size:13})})]}),We==="stopped"?s.jsx("button",{onClick:()=>{const De=_.workspace||"",Ke=k?lt(_.type):gt(_),{options:rt,selectedKey:Tt}=js({machine:t,currentWorkspacePath:De});Oe({title:bs("restart-stopped",Ke),description:gs("restart-stopped"),confirmLabel:Gs("restart-stopped"),busyLabel:Vs("restart-stopped"),workspaceOptions:rt,selectedWorkspaceKey:Tt,details:[{label:"Mode",value:A.label},{label:"Provider",value:Ke}]},async()=>{const bt=rt.find(es=>es.key===Ye.current);await dt({type:_.type,workspaceId:(bt==null?void 0:bt.workspaceId)??null,workspacePath:(bt==null?void 0:bt.workspacePath)??"",useHome:!(bt!=null&&bt.workspaceId)&&!(bt!=null&&bt.workspacePath)})})},disabled:de.includes(_.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:de.includes(_.type)?"⏳":s.jsx(Io,{size:14})}):s.jsx("button",{onClick:()=>Z(_),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(jt,{size:14})})]})]}),Y&&Y.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Y.aiAgents.map(De=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Mn(De.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[De.name," · ",vt(De.status)]},De.id))}),Y&&(Ue[Y.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:(Ue[Y.type]||[]).map(De=>s.jsxs("button",{disabled:Ze===`${Y.type}.${De.type}`,onClick:async()=>{const Ke=`${Y.type}.${De.type}`;et(Ke);try{await c(r,"set_ide_extension",{ideType:Y.type,extensionType:De.type,enabled:!De.enabled}),Le(rt=>({...rt,[Y.type]:(rt[Y.type]||[]).map(Tt=>Tt.type===De.type?{...Tt,enabled:!Tt.enabled}:Tt)}))}catch(rt){console.error("Extension toggle failed:",rt)}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 ${De.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 ${De.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),De.name,s.jsx("span",{className:"text-[9px] font-normal",children:De.enabled?"ON":"OFF"})]},De.type))})]})]},_.id)})]}),ve&&c&&s.jsx(Zn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:pe,directories:Ie,busy:_e,error:Me,confirmLabel:"Use this folder",onClose:()=>le(!1),onNavigate:_=>{z(_)},onConfirm:_=>{oe(_),ae("__custom__"),le(!1)}}),Ge&&s.jsx(ti,{title:Ge.title,description:Ge.description,details:Ge.details,workspaceOptions:Ge.workspaceOptions,selectedWorkspaceKey:tt,onWorkspaceChange:_=>{Ye.current=_,ct(_)},confirmLabel:Ge.confirmLabel,busyLabel:Ge.busyLabel,busy:mt,onConfirm:Re,onCancel:()=>{He.current=null,Xe(null)}}),ge&&te&&s.jsx(Vo,{activeConv:te,ides:[],isCreatingChat:!1,isRefreshingHistory:ie,savedSessions:W,isSavedSessionsLoading:ie,isResumingSavedSessionId:Se,savedHistoryFilters:we,missingWorkspaceResumePath:Be||null,onSavedHistoryFiltersChange:xe,onClose:()=>fe(!1),onNewChat:()=>{U(""),fe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{V(N)},onResumeSavedSession:_=>{if(!_.canResume||Se)return;const Y=H(_);U(_.providerSessionId),se(_),J(_.providerSessionId),fe(!1),dt({type:_.providerType,workspaceId:Y.workspaceId,workspacePath:Y.workspacePath,useHome:Y.useHome,resumeSessionId:_.providerSessionId}).finally(()=>{J(ye=>ye===_.providerSessionId?null:ye)})}})]})}const ql=[{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 Aw({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:l,getIcon:c,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:p,onOpenGitDialog:x}){var b;const[w,g]=i.useState(d);i.useEffect(()=>{g(d)},[d]);const h=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:ql.map(y=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${w===y.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>g(y.id),children:[s.jsx("span",{children:y.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${w===y.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:h[y.id]})]},y.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(b=ql.find(y=>y.id===w))==null?void 0:b.helper})]}),w==="ide"&&s.jsx(Ua,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:c,actions:l,sendDaemonCommand:p,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),w==="cli"&&s.jsx(Ua,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:c,actions:l,sendDaemonCommand:p,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),w==="acp"&&s.jsx(Ua,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:o,getIcon:c,actions:l,sendDaemonCommand:p,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x})]})}function _w({onNicknameSynced:e}={}){var oe,de,Q,ve,le,pe,ne,Ie,Ce,_e;const{id:t}=um(),r=Ys(),n=wo(),{sendCommand:a}=kt(),o=Rr(),l=gd(),c=Yc(),d=c.ides||[],m=c.initialLoaded??!0,u=d.find(K=>K.id===t&&K.type==="adhdev-daemon"),p=d.some(K=>K.type==="adhdev-daemon"),x=t?(oe=c.connectionRetryStatuses)==null?void 0:oe[t]:void 0,w=!!(x!=null&&x.blocked),[g,h]=i.useState("workspace"),[b,y]=i.useState(null),f=i.useCallback((K,Me)=>{y({daemonId:K,workspace:Me})},[]),[M,S]=i.useState("ide"),v=i.useRef(null),[T,A]=i.useState(null),k=i.useRef("__home__"),[j,B]=i.useState("__home__"),[L,N]=i.useState(!1),D=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||g!=="overview")return;const K=u.machine;(typeof(K==null?void 0:K.cpus)!="number"||typeof(K==null?void 0:K.totalMem)!="number"||typeof(K==null?void 0:K.arch)!="string"||typeof(K==null?void 0:K.release)!="string")&&l(t,{minFreshMs:3e4}).catch(()=>{})},[g,l,u,t]),xb(t&&g==="overview"?[t]:[],{enabled:g==="overview",intervalMs:cf});const $=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},E=Cv({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:D});i.useEffect(()=>ot.onToast(Me=>{c.setToasts(He=>{if(He.some(Ye=>Ye.message===Me.message&&Me.timestamp-Ye.timestamp<3e3))return He;const Xe={id:Me.id,message:Me.message,type:Me.type,timestamp:Me.timestamp,targetKey:Me.targetKey,actions:Me.actions};return[...He.slice(-4),Xe]});const Te=Me.duration||5e3;setTimeout(()=>c.setToasts(He=>He.filter(Ge=>Ge.id!==Me.id)),Te)}),[c]);const C=(u==null?void 0:u.availableProviders)||[],I={};for(const K of C)I[K.type]=K.icon;const O=K=>I[K]||"",P=u?{id:u.id,hostname:kc(u,{fallbackId:u.id}),platform:((de=u.machine)==null?void 0:de.platform)||"unknown",arch:((Q=u.machine)==null?void 0:Q.arch)||"",cpus:((ve=u.machine)==null?void 0:ve.cpus)||0,totalMem:((le=u.machine)==null?void 0:le.totalMem)||0,freeMem:(pe=u.machine)==null?void 0:pe.freeMem,availableMem:(ne=u.machine)==null?void 0:ne.availableMem,loadavg:(Ie=u.machine)==null?void 0:Ie.loadavg,uptime:(Ce=u.machine)==null?void 0:Ce.uptime,release:((_e=u.machine)==null?void 0:_e.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,R=d.filter(K=>K.daemonId===t&&K.type!=="adhdev-daemon").filter(K=>!Mr(K)&&!$s(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,version:K.version||"",instanceId:K.instanceId||"",status:K.status,workspace:K.workspace||null,terminals:K.terminals||0,aiAgents:eh(K.aiAgents||(K.agents||[]).map(Me=>({id:Me.name,name:Me.name,status:Me.status,version:Me.version}))),activeChat:K.activeChat||null,chats:K.chats||[],childSessions:K.childSessions||[],cdpConnected:K.cdpConnected||!1,daemonId:t,lastMessageAt:K.lastMessageAt})),U=d.filter(K=>K.daemonId===t&&Mr(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,cliName:K.cliName||K.type,status:K.status,workspace:K.workspace||"",activeChat:K.activeChat||null,providerSessionId:K.providerSessionId,mode:K.mode,runtimeKey:K.runtimeKey,runtimeDisplayName:K.runtimeDisplayName,runtimeWorkspaceLabel:K.runtimeWorkspaceLabel,runtimeWriteOwner:K.runtimeWriteOwner||null,runtimeAttachedClients:K.runtimeAttachedClients||[],daemonId:t,lastMessageAt:K.lastMessageAt})),W=d.filter(K=>K.daemonId===t&&$s(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,acpName:K.cliName||K.type,status:K.status,workspace:K.workspace||"",activeChat:K.activeChat||null,providerSessionId:K.providerSessionId,daemonId:t,lastMessageAt:K.lastMessageAt})),me=u?Lt(u,{fallbackId:t}):"",ie="workspace",ee=n.state,ce=ee==null?void 0:ee.initialMachineTab,je=ee==null?void 0:ee.initialWorkspaceCategory,Ne=ee==null?void 0:ee.initialWorkspaceId,q=ee==null?void 0:ee.initialWorkspacePath,ge=ce==="ides"||ce==="clis"||ce==="acps"?"workspace":ce||ie,fe=ce==="ides"?"ide":ce==="clis"?"cli":ce==="acps"?"acp":je,we=[...R.map(K=>{var Me;return{id:`ide:${K.type}:${K.workspace||""}`,label:((Me=K.activeChat)==null?void 0:Me.title)||K.type,kind:"ide",providerType:K.type,subtitle:K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:K.lastMessageAt||0}}),...U.map(K=>{var Me;return{id:`cli:${K.type}:${K.workspace||""}`,label:((Me=K.activeChat)==null?void 0:Me.title)||K.cliName,kind:"cli",providerType:K.type,providerSessionId:K.providerSessionId,subtitle:K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:K.lastMessageAt||0}}),...W.map(K=>{var Me;return{id:`acp:${K.type}:${K.workspace||""}`,label:((Me=K.activeChat)==null?void 0:Me.title)||K.acpName,kind:"acp",providerType:K.type,providerSessionId:K.providerSessionId,subtitle:Ns(K.summaryMetadata)||K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:K.lastMessageAt||0}})].sort((K,Me)=>(Me.lastLaunchedAt||0)-(K.lastLaunchedAt||0)),xe=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(K=>({id:K.id,label:K.title||K.providerName||K.providerType,kind:K.kind,providerType:K.providerType,providerSessionId:K.providerSessionId,subtitle:Ns(K.summaryMetadata)||K.workspace||void 0,workspace:K.workspace,summaryMetadata:K.summaryMetadata,lastLaunchedAt:K.lastLaunchedAt})):we,Se=i.useMemo(()=>{var Me;const K=((Me=c.connectionStates)==null?void 0:Me[t||""])||void 0;return d.filter(Te=>Te.daemonId===t&&Te.type!=="adhdev-daemon").flatMap(Te=>qo(Te,{connectionStates:t&&K?{[t]:K}:void 0,defaultConnectionState:K})).filter(Te=>!(Te.transport==="pty"&&Te.mode==="terminal")).sort((Te,He)=>po(He)-po(Te))},[d,c.connectionStates,t]),J=i.useCallback(K=>{const Me=Bd(K);Me&&r(ls(Me))},[r]),he=i.useCallback(()=>{v.current&&(N(!0),v.current().finally(()=>{v.current=null,N(!1),A(null)}))},[]),ae=i.useCallback(K=>{if(!P)return;const{options:Me,selectedKey:Te}=js({machine:P,currentWorkspacePath:K.workspace}),He=async()=>{S(K.kind),h("workspace")};v.current=async()=>{const Ge=Me.find(tt=>tt.key===k.current),Xe=(Ge==null?void 0:Ge.workspacePath)??null,Ye=(Ge==null?void 0:Ge.workspaceId)??null;if(K.kind==="ide"&&K.providerType){await E.handleLaunchIde(K.providerType,Xe?{workspace:Xe}:void 0);return}if((K.kind==="cli"||K.kind==="acp")&&K.providerType){await E.runLaunchCliCore({cliType:K.providerType,dir:Ye?void 0:Xe||"",workspaceId:Ye||void 0,model:K.kind==="acp"&&Nc(K.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:K.providerSessionId});return}await He()},k.current=Te,B(Te),A({title:K.kind==="ide"?bs("restart-ide",K.label):K.providerSessionId?zo(K.label):bs("start-fresh",K.label),description:K.kind==="ide"?gs("restart-ide"):K.providerSessionId?Go():gs("start-fresh"),confirmLabel:K.kind==="ide"?Gs("restart-ide"):K.providerSessionId?Rn(!0):Gs("start-fresh"),busyLabel:K.kind==="ide"?Vs("restart-ide"):K.providerSessionId?Ko(!0):Vs("start-fresh"),workspaceOptions:Me,details:[{label:"Mode",value:K.kind.toUpperCase()},...K.providerType?[{label:"Provider",value:K.providerType}]:[]]})},[E,P]);if(i.useEffect(()=>{h(ge)},[ie,ge,t]),i.useEffect(()=>{fe&&S(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:$,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 ue=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Rt,{size:14})," Workspace"]}),count:R.length+U.length+W.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(os,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Wn,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Km,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Om,{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:$,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:[E.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:E.nicknameInput,onChange:K=>E.setNicknameInput(K.target.value),onKeyDown:K=>{K.key==="Enter"&&E.handleSaveNickname(),K.key==="Escape"&&E.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:E.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:()=>E.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:()=>{E.setEditingNickname(!0),E.setNicknameInput(P.machineNickname||"")},title:"Click to set nickname",children:me}),w?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:ue.map(K=>s.jsxs("button",{onClick:()=>h(K.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${g===K.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[K.label,K.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${g===K.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:K.count})]},K.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:[g==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(Cw,{machineEntry:u,providers:C,recentLaunches:xe,currentConversations:Se,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",Pd(u))}catch{}},onOpenRecent:ae,onOpenConversation:J}),s.jsx(Aw,{machine:P,machineId:t,providers:C,ideSessions:R,cliSessions:U,acpSessions:W,actions:E,getIcon:O,initialCategory:M,initialWorkspaceId:Ne,initialWorkspacePath:q,sendDaemonCommand:a,onOpenGitDialog:f})]}),g==="providers"&&s.jsx(Ev,{machineId:t,providers:C,sendDaemonCommand:a}),g==="overview"&&s.jsx(Iv,{machineId:t,machine:P,ideSessions:R,cliSessions:U,acpSessions:W,actions:E,sendDaemonCommand:a}),g==="session-host"&&s.jsx(Sw,{machineId:t,cliSessions:U,sendDaemonCommand:a}),g==="logs"&&s.jsx(bw,{machineId:t,sendDaemonCommand:a})]})})}),E.launchPick&&P&&s.jsx(Nw,{machine:P,launchPick:E.launchPick,actions:E}),T&&s.jsx(ti,{title:T.title,description:T.description,details:T.details,workspaceOptions:T.workspaceOptions,selectedWorkspaceKey:j,onWorkspaceChange:K=>{k.current=K,B(K)},confirmLabel:T.confirmLabel,busyLabel:T.busyLabel,busy:L,onConfirm:he,onCancel:()=>{v.current=null,A(null)}}),b&&s.jsx(ju,{daemonId:b.daemonId,workspace:b.workspace,onClose:()=>y(null)}),s.jsx(ad,{toasts:c.toasts||[],onDismiss:K=>c.setToasts(Me=>Me.filter(Te=>Te.id!==K)),onClickToast:K=>{K.targetKey&&r(ls(K.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 cn=[{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."}],_w={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function wn(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 Lw(e){const t=wn(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 Rw(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function Pw(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 Dw(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 za(e){return{..._w,...(e==null?void 0:e.policy)||{}}}function Ew({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=$d(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(wt,{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(lu,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function $w(){var Ye,tt,ct,mt,pt;const{sendCommand:e}=kt(),{ides:t}=cs(),r=t.find(F=>F.daemonMode||F.type==="adhdev-daemon"),n=(r==null?void 0:r.id)||"",a=[];let o=[];if(r){const F=r.availableProviders||[];o=Ax(F);for(const be of F)be.category==="cli"&&a.push({id:be.type||be.id,name:be.displayName||be.name||be.type,meshCoordinator:be.meshCoordinator})}const[l,c]=i.useState([]),[d,m]=i.useState(null),[u,p]=i.useState(!0),[x,w]=i.useState(null),[g,h]=i.useState(!1),[b,y]=i.useState(null),[f,M]=i.useState({}),[S,v]=i.useState([]),[T,A]=i.useState(null),[k,j]=i.useState(null),[B,L]=i.useState(!1),[N,D]=i.useState(null),[$,E]=i.useState(null),[C,I]=i.useState(!1),[O,P]=i.useState(!1),[R,U]=i.useState(!1),[W,me]=i.useState(""),[ie,ee]=i.useState(""),[ce,je]=i.useState(!1),[Ne,q]=i.useState(""),[ge,fe]=i.useState(""),[we,xe]=i.useState(!1),[Se,J]=i.useState(""),[he,ae]=i.useState([]),ue=l.find(F=>F.id===d)||null;i.useEffect(()=>{M(Object.fromEntries(((ue==null?void 0:ue.nodes)||[]).map(F=>[F.id,wn(F)])))},[ue]),i.useEffect(()=>{const F=_x(o);we&&he.length===0&&F.length>0&&ae(F)},[we,o,he.length]),i.useEffect(()=>{const F=new Set(((ue==null?void 0:ue.nodes)||[]).map(be=>be.id));T&&!F.has(T)&&A(null)},[ue,T]);const oe=i.useCallback(async()=>{if(n){p(!0);try{const F=await e(n,"list_meshes");F!=null&&F.success?(c(F.meshes||[]),w(null)):w((F==null?void 0:F.error)||"Failed to load meshes")}catch(F){w((F==null?void 0:F.message)||"Failed to load meshes")}finally{p(!1)}}},[n,e]),de=i.useCallback(async F=>{if(!n||!F){v([]);return}try{const be=await e(n,"get_mesh_queue",{meshId:F});be!=null&&be.success?v(Array.isArray(be.queue)?be.queue:[]):v([])}catch{v([])}},[n,e]),Q=i.useCallback(async F=>{var be;if(!n||!F){E(null),me(""),ee("");return}I(!0);try{const Ae=await e(n,"get_mesh_host_pairing",{meshId:F});Ae!=null&&Ae.success?(E(Ae),me(Ae.hostAddress||((be=Ae.meshHost)==null?void 0:be.hostAddress)||"")):E({success:!1,error:(Ae==null?void 0:Ae.error)||"Failed to load Mesh Host pairing"}),ee("")}catch(Ae){E({success:!1,error:(Ae==null?void 0:Ae.message)||"Failed to load Mesh Host pairing"}),ee("")}finally{I(!1)}},[n,e]);i.useEffect(()=>{oe()},[oe]),i.useEffect(()=>{de(d)},[de,d]),i.useEffect(()=>{Q(d)},[Q,d]);async function ve(){if(!(!n||!d))try{L(!0),D(null);const F=await e(n,"mesh_status",{meshId:d});if((F==null?void 0:F.success)===!1){j(null),D((F==null?void 0:F.error)||"mesh_status failed");return}const be=xu(F);be?j(be):(j(null),D("mesh_status returned an unexpected payload."))}catch(F){j(null),D((F==null?void 0:F.message)||"Failed to load mesh graph")}finally{L(!1)}}i.useEffect(()=>{d&&(j(null),D(null),ve())},[d]);async function le(){var F;if(!(!n||!Ne.trim()))try{const be=await e(n,"create_mesh",{name:Ne.trim(),repoIdentity:ge.trim()||void 0});be!=null&&be.success?(je(!1),q(""),fe(""),await oe(),m(((F=be.mesh)==null?void 0:F.id)||null)):w((be==null?void 0:be.error)||"Create failed")}catch(be){w((be==null?void 0:be.message)||"Create failed")}}async function pe(F){if(!(!n||!confirm("Delete this mesh?")))try{await e(n,"delete_mesh",{meshId:F}),m(null),await oe()}catch(be){w((be==null?void 0:be.message)||"Delete failed")}}async function ne(){if(!(!n||!d||!Se.trim()))try{const F=await e(n,"add_mesh_node",{meshId:d,workspace:Se.trim(),providerPriority:io(he,o)});F!=null&&F.success?(xe(!1),J(""),ae([]),await oe(),await de(d)):w((F==null?void 0:F.error)||"Add node failed")}catch(F){w((F==null?void 0:F.message)||"Add node failed")}}async function Ie(F){var Be;if(!n||!d)return;const be=za(ue),Ae=((Be=cn.find(qe=>qe.value===be.sessionCleanupOnNodeRemove))==null?void 0:Be.label)||"Preserve history and runtimes";if(confirm(`Remove this node?
96
+ `})]})}const cn=[{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."}],Lw={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function wn(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 Rw(e){const t=wn(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 Pw(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function Dw(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 Ew(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 za(e){return{...Lw,...(e==null?void 0:e.policy)||{}}}function $w({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=$d(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(wt,{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(lu,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function Bw(){var Ye,tt,ct,mt,pt;const{sendCommand:e}=kt(),{ides:t}=cs(),r=t.find(F=>F.daemonMode||F.type==="adhdev-daemon"),n=(r==null?void 0:r.id)||"",a=[];let o=[];if(r){const F=r.availableProviders||[];o=Ax(F);for(const be of F)be.category==="cli"&&a.push({id:be.type||be.id,name:be.displayName||be.name||be.type,meshCoordinator:be.meshCoordinator})}const[l,c]=i.useState([]),[d,m]=i.useState(null),[u,p]=i.useState(!0),[x,w]=i.useState(null),[g,h]=i.useState(!1),[b,y]=i.useState(null),[f,M]=i.useState({}),[S,v]=i.useState([]),[T,A]=i.useState(null),[k,j]=i.useState(null),[B,L]=i.useState(!1),[N,D]=i.useState(null),[$,E]=i.useState(null),[C,I]=i.useState(!1),[O,P]=i.useState(!1),[R,U]=i.useState(!1),[W,me]=i.useState(""),[ie,ee]=i.useState(""),[ce,je]=i.useState(!1),[Ne,q]=i.useState(""),[ge,fe]=i.useState(""),[we,xe]=i.useState(!1),[Se,J]=i.useState(""),[he,ae]=i.useState([]),ue=l.find(F=>F.id===d)||null;i.useEffect(()=>{M(Object.fromEntries(((ue==null?void 0:ue.nodes)||[]).map(F=>[F.id,wn(F)])))},[ue]),i.useEffect(()=>{const F=_x(o);we&&he.length===0&&F.length>0&&ae(F)},[we,o,he.length]),i.useEffect(()=>{const F=new Set(((ue==null?void 0:ue.nodes)||[]).map(be=>be.id));T&&!F.has(T)&&A(null)},[ue,T]);const oe=i.useCallback(async()=>{if(n){p(!0);try{const F=await e(n,"list_meshes");F!=null&&F.success?(c(F.meshes||[]),w(null)):w((F==null?void 0:F.error)||"Failed to load meshes")}catch(F){w((F==null?void 0:F.message)||"Failed to load meshes")}finally{p(!1)}}},[n,e]),de=i.useCallback(async F=>{if(!n||!F){v([]);return}try{const be=await e(n,"get_mesh_queue",{meshId:F});be!=null&&be.success?v(Array.isArray(be.queue)?be.queue:[]):v([])}catch{v([])}},[n,e]),Q=i.useCallback(async F=>{var be;if(!n||!F){E(null),me(""),ee("");return}I(!0);try{const Ae=await e(n,"get_mesh_host_pairing",{meshId:F});Ae!=null&&Ae.success?(E(Ae),me(Ae.hostAddress||((be=Ae.meshHost)==null?void 0:be.hostAddress)||"")):E({success:!1,error:(Ae==null?void 0:Ae.error)||"Failed to load Mesh Host pairing"}),ee("")}catch(Ae){E({success:!1,error:(Ae==null?void 0:Ae.message)||"Failed to load Mesh Host pairing"}),ee("")}finally{I(!1)}},[n,e]);i.useEffect(()=>{oe()},[oe]),i.useEffect(()=>{de(d)},[de,d]),i.useEffect(()=>{Q(d)},[Q,d]);async function ve(){if(!(!n||!d))try{L(!0),D(null);const F=await e(n,"mesh_status",{meshId:d});if((F==null?void 0:F.success)===!1){j(null),D((F==null?void 0:F.error)||"mesh_status failed");return}const be=xu(F);be?j(be):(j(null),D("mesh_status returned an unexpected payload."))}catch(F){j(null),D((F==null?void 0:F.message)||"Failed to load mesh graph")}finally{L(!1)}}i.useEffect(()=>{d&&(j(null),D(null),ve())},[d]);async function le(){var F;if(!(!n||!Ne.trim()))try{const be=await e(n,"create_mesh",{name:Ne.trim(),repoIdentity:ge.trim()||void 0});be!=null&&be.success?(je(!1),q(""),fe(""),await oe(),m(((F=be.mesh)==null?void 0:F.id)||null)):w((be==null?void 0:be.error)||"Create failed")}catch(be){w((be==null?void 0:be.message)||"Create failed")}}async function pe(F){if(!(!n||!confirm("Delete this mesh?")))try{await e(n,"delete_mesh",{meshId:F}),m(null),await oe()}catch(be){w((be==null?void 0:be.message)||"Delete failed")}}async function ne(){if(!(!n||!d||!Se.trim()))try{const F=await e(n,"add_mesh_node",{meshId:d,workspace:Se.trim(),providerPriority:io(he,o)});F!=null&&F.success?(xe(!1),J(""),ae([]),await oe(),await de(d)):w((F==null?void 0:F.error)||"Add node failed")}catch(F){w((F==null?void 0:F.message)||"Add node failed")}}async function Ie(F){var Be;if(!n||!d)return;const be=za(ue),Ae=((Be=cn.find(qe=>qe.value===be.sessionCleanupOnNodeRemove))==null?void 0:Be.label)||"Preserve history and runtimes";if(confirm(`Remove this node?
97
97
 
98
- Node removal cleanup policy: ${Ae}`))try{await e(n,"remove_mesh_node",{meshId:d,nodeId:F}),T===F&&A(null),await oe(),await de(d)}catch(qe){w((qe==null?void 0:qe.message)||"Remove node failed")}}async function Ce(F){if(!n||!d)return;const be={...za(ue),...F};try{h(!0),w(null);const Ae=await e(n,"update_mesh",{meshId:d,policy:be});if((Ae==null?void 0:Ae.success)===!1){w(Ae.error||"Policy update failed");return}await oe()}catch(Ae){w((Ae==null?void 0:Ae.message)||"Policy update failed")}finally{h(!1)}}async function _e(){var F;if(!(!n||!d||!W.trim()||!ie.trim())){P(!0);try{const be=await e(n,"configure_mesh_host_pairing",{meshId:d,hostAddress:W.trim(),token:ie.trim()});be!=null&&be.success?(E(be),me(be.hostAddress||((F=be.meshHost)==null?void 0:F.hostAddress)||W.trim()),await oe()):E({success:!1,error:(be==null?void 0:be.error)||"Failed to save Mesh Host pairing"})}catch(be){E({success:!1,error:(be==null?void 0:be.message)||"Failed to save Mesh Host pairing"})}finally{P(!1)}}}async function K(){if(!(!n||!d||!ie.trim())){U(!0);try{const F=await e(n,"join_mesh_host_pairing",{meshId:d,token:ie.trim()});F!=null&&F.success?(E(F),ee(""),await oe(),await Q(d),await ve()):E({success:!1,meshHost:F==null?void 0:F.meshHost,manualPairing:F==null?void 0:F.manualPairing,error:(F==null?void 0:F.error)||"Failed to apply Mesh Host join"})}catch(F){E({success:!1,error:(F==null?void 0:F.message)||"Failed to apply Mesh Host join"})}finally{U(!1)}}}async function Me(F){if(!n||!d)return;const be=io(f[F.id]||wn(F),o),Ae={...F.policy||{}};delete Ae.provider_priority,be.length?Ae.providerPriority=be:delete Ae.providerPriority;try{y(F.id),w(null);const Be=await e(n,"update_mesh_node",{meshId:d,nodeId:F.id,policy:Ae});if((Be==null?void 0:Be.success)===!1){w(Be.error||"Node policy update failed");return}await oe()}catch(Be){w((Be==null?void 0:Be.message)||"Node policy update failed")}finally{y(null)}}if(!n)return s.jsx(wr,{icon:s.jsx(ns,{}),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(!ue)return s.jsxs(wr,{icon:s.jsx(ns,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>je(!0),children:"+ Create Mesh"}),children:[x&&s.jsx(Es,{variant:"error",className:"mb-4",children:x}),ce&&s.jsx(wt,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(At,{label:"Name",children:s.jsx(cr,{value:Ne,onChange:F=>q(F.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(At,{label:"Repo Identity (optional)",children:s.jsx(cr,{value:ge,onChange:F=>fe(F.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:le,disabled:!Ne.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>je(!1),children:"Cancel"})]})]})}),u?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):l.length===0?s.jsx(Pn,{icon:s.jsx(ns,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:l.map(F=>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(F.id),children:[s.jsx("div",{className:"font-semibold text-sm",children:F.name}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:F.repoIdentity||"No repo identity"}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[F.nodes.length," node(s)"]})]},F.id))})]});const Te=za(ue),He=($==null?void 0:$.meshHost)||ue.meshHost||{},Ge=((Ye=$==null?void 0:$.manualPairing)==null?void 0:Ye.status)||((tt=He.pairing)==null?void 0:tt.status)||"not_configured",Xe=((ct=$==null?void 0:$.manualPairing)==null?void 0:ct.description)||"Manual address/token config is saved locally; Apply join sends the token once to the Mesh Host command endpoint. P2P runtime signaling remains outside this slice.";return s.jsxs(wr,{icon:s.jsx(ns,{}),title:ue.name,subtitle:ue.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:()=>pe(ue.id),children:"Delete"})]}),children:[x&&s.jsx(Es,{variant:"error",className:"mb-4",children:x}),s.jsx(wt,{title:"Mesh Host pairing",description:"Standalone manual pairing. Save a Mesh Host address/token, apply the join to the host command endpoint, then check persisted status.",children:s.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(280px,420px)]",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-4 text-sm",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"text-text-muted",children:"Local role"}),s.jsx("span",{className:"rounded-full border border-accent-primary/25 bg-accent-primary/10 px-2 py-0.5 text-xs font-semibold text-accent-primary",children:He.role||"host"}),s.jsx("span",{className:"text-text-muted",children:"Pairing"}),s.jsx("span",{className:"rounded-full border border-border-subtle px-2 py-0.5 text-xs font-mono text-text-primary",children:C?"loading":Ge})]}),s.jsxs("div",{className:"mt-3 grid gap-2 text-xs text-text-muted",children:[s.jsxs("div",{children:["Host address: ",s.jsx("code",{className:"text-text-primary",children:He.hostAddress||"not configured"})]}),s.jsxs("div",{children:["Token id: ",s.jsx("code",{className:"text-text-primary",children:((mt=He.pairing)==null?void 0:mt.tokenId)||"not configured"})]}),s.jsxs("div",{children:["Can own coordinator: ",s.jsx("code",{className:"text-text-primary",children:String(He.canOwnCoordinator??He.role!=="member")})]}),s.jsxs("div",{children:["Can own queue: ",s.jsx("code",{className:"text-text-primary",children:String(He.canOwnQueue??He.role!=="member")})]})]}),s.jsx("p",{className:"mt-3 text-xs leading-relaxed text-text-secondary",children:Xe}),($==null?void 0:$.error)&&s.jsx("div",{className:"mt-3 rounded-lg border border-red-500/25 bg-red-500/10 px-3 py-2 text-xs text-red-300",children:$.error})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-panel p-4",children:[s.jsx(At,{label:"Mesh Host address",hint:"Example: http://127.0.0.1:3847 or a reachable HTTPS/WSS host endpoint.",children:s.jsx(cr,{value:W,onChange:F=>me(F.target.value),placeholder:"http://127.0.0.1:3847",disabled:O||R})}),s.jsx(At,{label:"Pairing token",hint:"The raw token is used once to derive a local token id; it is not displayed after save.",children:s.jsx(cr,{value:ie,onChange:F=>ee(F.target.value),placeholder:"paste Mesh Host pairing token",type:"password",disabled:O||R})}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:_e,disabled:O||R||!W.trim()||!ie.trim(),children:O?"Saving...":"Save manual pairing"}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:K,disabled:R||O||!ie.trim(),children:R?"Applying...":"Apply join"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>Q(d),disabled:C||O||R,children:C?"Checking...":"Check saved config"})]})]})]})}),s.jsxs(wt,{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(At,{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:Te.requirePreTaskCheckpoint?"yes":"no",onChange:F=>Ce({requirePreTaskCheckpoint:F.target.value==="yes"}),disabled:g,children:[s.jsx("option",{value:"no",children:"No"}),s.jsx("option",{value:"yes",children:"Yes"})]})}),s.jsx(At,{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:Te.requirePostTaskCheckpoint?"yes":"no",onChange:F=>Ce({requirePostTaskCheckpoint:F.target.value==="yes"}),disabled:g,children:[s.jsx("option",{value:"yes",children:"Yes"}),s.jsx("option",{value:"no",children:"No"})]})}),s.jsx(At,{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:Te.requireApprovalForPush?"required":"not_required",onChange:F=>Ce({requireApprovalForPush:F.target.value==="required"}),disabled:g,children:[s.jsx("option",{value:"required",children:"Require approval before push"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(At,{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:Te.requireApprovalForDestructiveGit?"required":"not_required",onChange:F=>Ce({requireApprovalForDestructiveGit:F.target.value==="required"}),disabled:g,children:[s.jsx("option",{value:"required",children:"Require approval"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(At,{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:Te.dirtyWorkspaceBehavior||"warn",onChange:F=>Ce({dirtyWorkspaceBehavior:F.target.value}),disabled:g,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(At,{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(Te.maxParallelTasks??2),onChange:F=>Ce({maxParallelTasks:Number(F.target.value)}),disabled:g,children:[1,2,3,4,5,6,7,8].map(F=>s.jsx("option",{value:F,children:F},F))})})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(At,{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:Te.sessionCleanupOnNodeRemove||"preserve",onChange:F=>Ce({sessionCleanupOnNodeRemove:F.target.value}),disabled:g,children:cn.map(F=>s.jsx("option",{value:F.value,children:F.label},F.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((pt=cn.find(F=>F.value===Te.sessionCleanupOnNodeRemove))==null?void 0:pt.description)||cn[0].description})]}),g&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),s.jsxs(wt,{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:ve,disabled:B,children:B?"Loading...":"Refresh Graph"})]}),N&&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:N}),k?s.jsx(vu,{status:k,emptyMessage:"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon.",daemonId:n,sendDaemonCommand:e}):s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:B?"Loading graph...":"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon."})]}),s.jsxs(wt,{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:()=>xe(!0),children:"+ Add Node"})}),we&&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:()=>xe(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(jt,{size:16})})]}),s.jsx(At,{label:"Workspace Path",children:s.jsx(cr,{value:Se,onChange:F=>J(F.target.value),placeholder:"/Users/dev/projects/myapp",autoFocus:!0})}),s.jsx(At,{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:he,availableProviders:o,onChange:ae})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:ne,disabled:!Se.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>xe(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),ue.nodes.length===0?s.jsx(Pn,{icon:s.jsx(Ss,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:ue.nodes.map(F=>{const be=wn(F),Ae=Lw(F),Be=Rw(F,S),qe=Dw(F,r),G=T===F.id;return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary cursor-pointer transition-colors ${G?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`,role:"button",tabIndex:0,onClick:()=>A(G?null:F.id),onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),A(G?null:F.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:F.workspace.split("/").pop()}),Be.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:[Be.length," active task",Be.length===1?"":"s"]})]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:F.workspace}),s.jsx("div",{className:"mt-3 max-w-2xl",onClick:z=>z.stopPropagation(),children:s.jsxs(At,{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[F.id]??be,availableProviders:o,onChange:z=>M(X=>({...X,[F.id]:z})),disabled:b===F.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:z=>{z.stopPropagation(),Me(F)},disabled:b===F.id,children:b===F.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:Ae.configured?"text-text-primary font-mono":"text-amber-400",children:Ae.label}),Ae.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",Ae.launchBlockedMessage,")"]})]})]})})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:z=>{z.stopPropagation(),Ie(F.id)},children:s.jsx(jt,{size:14})})]}),G&&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:F.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:Ae.configured?"text-green-400":"text-amber-400",children:Ae.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:F.repoRoot||F.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",qe.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:"})," ",Be.length>0||qe.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"}),Be.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:Be.map(z=>s.jsx("li",{className:"font-mono",children:Pw(z)},z.id))})]}),qe.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:qe.map(z=>s.jsxs("li",{className:"font-mono",children:[z.provider," / ",z.status," / ",z.id]},z.id))})]})]})]},F.id)})})]}),s.jsx(Ew,{meshId:ue.id,availableCliAgents:a})]})}function fi(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Bw(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(Bw(e),{credentials:"same-origin",...t})}function Nu(){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 Ow{constructor(){Qe(this,"adapters",new Map);Qe(this,"states",new Map);Qe(this,"runtimeListeners",new Map);Qe(this,"screenshotCallbacks",new Map);Qe(this,"statusCallbacks",new Set);Qe(this,"stateChangeCallbacks",new Set);Qe(this,"ptyInputSender",null)}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);const n=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(a=>a(n,r))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}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"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,r){return!1}sendPtyInput(t,r,n){return this.ptyInputSender?this.ptyInputSender(t,r,n):!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 Kt=new Ow;function Fw(){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 dn=Fw(),Yl=3e3,Ww=3e4;let Ot=null,Hw=0;const Fn=new Map;let ms=null,Sr=null;function Xl(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function pr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function Kw(e){return e==="connected"?"connected":e}async function jn(e,t,r){const n=cd(e,r||{}),a=Ot;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++Hw}_${Date.now()}`;return new Promise((l,c)=>{const d=setTimeout(()=>{Fn.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);Fn.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 go(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 Cu(e,t,r){const n=Ot;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=cd(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}}Kt.registerPtyInputSender(Cu);class Uw{constructor(t){Qe(this,"daemonId");Qe(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 jn(this.daemonId,t,r)}async sendInput(t,r){return jn(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 jn(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());Kt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ms=setInterval(r,2e3)}stopScreenshots(t){ms&&(clearInterval(ms),ms=null)}}let Dt=null;function zw(e){return(!Dt||Dt.daemonId!==e)&&(Dt=new Uw(e)),Dt}function Gw({children:e}){const t=i.useRef(Cr()),r=Cr();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((h,b)=>{c(h),Sr==null||Sr(h,b)},[]),m=i.useRef(null),u=i.useRef(),p=i.useRef(Yl),x=i.useRef(!0),w=i.useRef(!1),g=i.useRef("initial_connect");return i.useEffect(()=>{x.current=!0,w.current=!1;function h(){var f,M;if(!x.current||((f=m.current)==null?void 0:f.readyState)===WebSocket.OPEN||((M=m.current)==null?void 0:M.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${dn}...`),pr("connect_attempt",{url:dn,reason:g.current,delayMs:p.current});let y;try{y=new WebSocket(dn)}catch(S){console.error("[Standalone WS] Failed to create WebSocket:",S),b();return}m.current=y,y.onopen=()=>{if(!x.current){y.close();return}d("connected"),p.current=Yl,pr("open",{url:dn,reason:g.current}),Jt.resubscribeAll({sendData:go}),console.log("[Standalone WS] Connected")},Ot=y,y.onmessage=S=>{var v,T;try{const A=JSON.parse(S.data);if((A.type==="command_result"||A.type==="error")&&A.requestId){const k=Fn.get(A.requestId);k&&(Fn.delete(A.requestId),A.type==="error"?k.reject(new Error(((v=A.data)==null?void 0:v.message)||"Command failed")):k.resolve(A.data));return}if(A.type==="session_output"){const k=A.sessionId||A.cliId||A.cliType;k&&Kt.emitSessionOutput(k,typeof A.data=="string"?A.data:"",typeof A.seq=="number"?A.seq:void 0);return}if(A.type==="runtime_snapshot"){Kt.emitRuntimeSnapshot(A.sessionId,typeof A.text=="string"?A.text:"",typeof A.seq=="number"?A.seq:0,!!A.truncated,typeof A.cols=="number"?A.cols:void 0,typeof A.rows=="number"?A.rows:void 0);return}if(A.type==="topic_update"){const k=A.update;k&&Jt.publish(k);return}if(A.type==="status"||A.type==="initial_state"){const k=A.data;if(!k)return;const{injectEntries:j,markLoaded:B,getIdes:L}=t.current,N=k.instanceId||"standalone",D=L().find(C=>C.id===N),$=zw(N);Kt.register(N,$),Kt.setState(N,"connected"),d("connected",N),Kt.emitStatus(N,k);const E=Ln(k,{daemonId:N,existingDaemon:D,existingEntries:L()});Xl("ws_status",{type:A.type,daemonId:N,sessions:(k.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:(k.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Xl("entries",{daemonId:N,entries:E.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}))}),E.length>0&&j(E,{authoritativeDaemonIds:[N]}),B(),l.current!==N&&((T=o.current)==null||T.call(o),l.current=N,o.current=Jt.subscribe({sendData:go},N,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${N}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const I=t.current.getIdes(),O=I.find(R=>R.id===N),P=Ln(C.status,{daemonId:N,existingDaemon:O,existingEntries:I,timestamp:C.timestamp});P.length>0&&t.current.injectEntries(P,{authoritativeDaemonIds:[N]}),C.userName&&a.current&&a.current(C.userName)}))}}catch(A){console.error("[Standalone WS] Parse error:",A)}},y.onclose=S=>{x.current&&(Dt==null||Dt.stopScreenshots(),Dt&&Kt.setState(Dt.daemonId,"disconnected"),d("disconnected"),m.current=null,g.current=`close:${S.code}${S.wasClean?":clean":":unclean"}`,pr("close",{code:S.code,reason:S.reason||"",wasClean:S.wasClean}),b())},y.onerror=S=>{w.current||!x.current||(g.current="error",pr("error",{message:S instanceof Event?"event":String(S),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",S))}}function b(){if(!x.current)return;clearTimeout(u.current);const y=p.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),pr("schedule_reconnect",{reason:g.current,delayMs:y}),u.current=setTimeout(()=>{p.current=Math.min(p.current*1.5,Ww),h()},y)}return h(),()=>{var y;x.current=!1,w.current=!0,(y=o.current)==null||y.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),Dt&&(Dt.stopScreenshots(),Kt.unregister(Dt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function Vw({children:e}){const[t,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(Sr=(l,c)=>{r(l),c&&a(c)},()=>{Sr=null}),[]);const o=i.useMemo(()=>{const l=t==="connected",c=Kw(t),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:t,isConnected:l,connectionStates:d}},[t,n]);return s.jsx(Mm,{connectionOverrides:o,children:s.jsx(Gw,{children:e})})}const Iu="adhdev_standalone_font_preferences",ks={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},sa=[{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"}],Tr=[{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"}],qw=new Set(sa.map(e=>e.id)),Yw=new Set(Tr.map(e=>e.id));function Gt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:kn("chat",t.chat),code:kn("code",t.code),terminal:kn("terminal",t.terminal)}}function kn(e,t){const r=ks[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"?qw:Yw).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Sn(e,t){var a;const r=kn(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?sa:Tr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function Xw(e){const t=Gt(e),r=Sn("chat",t.chat),n=Sn("code",t.code),a=Sn("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function hs(e,t=document.documentElement){const r=Gt(e),n=Xw(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function yo(e){const t=Gt(e);try{localStorage.setItem(Iu,JSON.stringify(t))}catch{}return t}function Jw(){try{const e=localStorage.getItem(Iu);if(e)return Gt(JSON.parse(e))}catch{}return ks}function Qw(){return hs(Jw())}function hr(e,t){var n;const r=e==="chat"?sa:Tr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const Zw=[{id:"dashboard",path:"/dashboard",icon:s.jsx(oc,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(os,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(Hs,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(Wn,{}),label:"Settings"}];function ej({children:e}){const t=Ys(),r=wo(),n=i.useMemo(()=>Zw.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(lc,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(cc,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Hx,{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 tj=[{icon:s.jsx(os,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Qt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(dc,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Rt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Hs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(lc,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],sj=[{icon:s.jsx(zm,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(oc,{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(Bm,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(ic,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Fm,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],rj=[{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 nj(){return s.jsxs(wr,{icon:s.jsx(cc,{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(wt,{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(wt,{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:tj.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(wt,{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:dd.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:md.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:ud.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(wt,{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:sj.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(wt,{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:rj.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(Pn,{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(tp,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Ga(e,t,r){return{...e,[t]:r}}function Va({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:Sn(e,n)})]})]})]})}function aj({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(Va,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:sa,onChange:u=>o(Ga(e,"chat",u))}),s.jsx(Va,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Tr,onChange:u=>o(Ga(e,"code",u))}),s.jsx(Va,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Tr,onChange:u=>o(Ga(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: ",hr("chat",e.chat.preset)," · Code: ",hr("code",e.code.preset)," · Terminal: ",hr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",hr("chat",ks.chat.preset)," / ",hr("code",ks.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 oj(){const{ides:e}=cs(),t=e.find(q=>q.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=kt(),{userName:a}=cs(),[o,l]=i.useState(a||""),[c,d]=i.useState(null),[m,u]=i.useState(null),[p,x]=i.useState(ks),[w,g]=i.useState(!1),[h,b]=i.useState(""),[y,f]=i.useState(""),[M,S]=i.useState("127.0.0.1"),[v,T]=i.useState(""),[A,k]=i.useState(""),[j,B]=i.useState(""),[L,N]=i.useState(""),[D,$]=i.useState(""),[E,C]=i.useState(!1),I=async()=>{const ge=await(await Ut("/auth/session")).json();d(ge)},O=async()=>{const ge=await(await Ut("/api/v1/standalone/preferences")).json();u(ge),S(ge.standaloneBindHost);const fe=Gt(ge.standaloneFontPreferences);x(fe),hs(fe),yo(fe)};i.useEffect(()=>{a!==void 0&&l(a)},[a]),i.useEffect(()=>{Promise.all([I(),O()]).catch(q=>{N(q instanceof Error?q.message:String(q))})},[]),i.useEffect(()=>{hs(p)},[p]);const P=q=>{const ge=q.target.value.trim();t!=null&&t.id&&ge!==a&&n(t.id,"set_user_name",{userName:ge}).catch(console.error)},[R,U]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),W=q=>{U(q);try{localStorage.setItem("adhdev_sound",q?"1":"0")}catch{}},me=async()=>{b(""),f(""),g(!0);try{const q=Gt(p),ge=await Ut("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:q})}),fe=await ge.json();if(!ge.ok)throw new Error((fe==null?void 0:fe.error)||"Failed to save standalone font preferences");const we=Gt(fe.standaloneFontPreferences);u(fe),x(we),hs(we),yo(we),f("Standalone chat fonts saved for this self-hosted dashboard.")}catch(q){b(q instanceof Error?q.message:String(q))}finally{g(!1)}},ie=()=>{const q=Gt(m==null?void 0:m.standaloneFontPreferences);b(""),f(""),x(q),hs(q)},ee=()=>{b(""),f(""),x(ks),hs(ks)},ce=async()=>{N(""),$(""),C(!0);try{const q=await Ut("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:M})}),ge=await q.json();if(!q.ok)throw new Error((ge==null?void 0:ge.error)||"Failed to save standalone network preference");u(ge),S(ge.standaloneBindHost),$(ge.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(q){N(q instanceof Error?q.message:String(q))}finally{C(!1)}},je=async()=>{if(N(""),$(""),A.trim().length<4){N("Password must be at least 4 characters.");return}if(A!==j){N("New password and confirmation do not match.");return}C(!0);try{const q=await Ut("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:A})}),ge=await q.json();if(!q.ok)throw new Error((ge==null?void 0:ge.error)||"Failed to save password");d(ge),await O(),T(""),k(""),B(""),$(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Nu()}catch(q){N(q instanceof Error?q.message:String(q))}finally{C(!1)}},Ne=async()=>{N(""),$(""),C(!0);try{const q=await Ut("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),ge=await q.json();if(!q.ok)throw new Error((ge==null?void 0:ge.error)||"Failed to clear password");d(ge),await O(),T(""),k(""),B(""),$("Standalone password disabled.")}catch(q){N(q instanceof Error?q.message:String(q))}finally{C(!1)}};return s.jsxs(wr,{icon:s.jsx(Wn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Es,{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(Es,{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(wt,{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(wt,{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:M==="127.0.0.1",onChange:()=>S("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:M==="0.0.0.0",onChange:()=>S("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:()=>{ce()},disabled:E,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:E?"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(wt,{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."}),L&&s.jsx(Es,{variant:"error",children:L}),D&&s.jsx(Es,{variant:"success",children:D}),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:v,onChange:q=>T(q.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:A,onChange:q=>k(q.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:j,onChange:q=>B(q.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{je()},disabled:E,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:E?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{Ne()},disabled:E,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(wt,{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(q=>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 ${q.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:q.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:q.type})]},q.type))})}),s.jsx(wt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Jx,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(wt,{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(tb,{})]}),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(cb,{})]}),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(aj,{value:p,savedValue:Gt(m==null?void 0:m.standaloneFontPreferences),saving:w,error:h,notice:y,onChange:x,onSave:()=>{me()},onResetToSaved:ie,onResetToDefaults:ee})]}),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(mb,{})]})]})}),s.jsx(wt,{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(qx,{}),s.jsx(ps,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ep,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:R,onChange:W})]})}),s.jsx(wt,{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($m,{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:q=>l(q.target.value),onBlur:P,onKeyDown:q=>{q.key==="Enter"&&q.currentTarget.blur()}})]})})})]})}Fx();ib();Qw();const ij=nc({baseUrl:"",getToken:fi});function lj({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),p=async()=>{a(!0),d("");try{const g=await(await Ut("/auth/session")).json();r(g)}catch(w){d(w instanceof Error?w.message:String(w))}finally{a(!1)}};i.useEffect(()=>{p()},[]),i.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let w=!1;return(async()=>{try{const g=await Ut("/api/v1/standalone/preferences");if(!g.ok)return;const h=await g.json();if(w)return;const b=Gt(h.standaloneFontPreferences);hs(b),yo(b)}catch{}})(),()=>{w=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const x=async w=>{w.preventDefault(),u(!0),d("");try{const g=await Ut("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),h=await g.json();if(!g.ok)throw new Error((h==null?void 0:h.error)||"Login failed");r(h),l(""),Nu()}catch(g){d(g instanceof Error?g.message:String(g))}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:w=>l(w.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 Jl(){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(Xa,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Xa,{to:"/dashboard",replace:!0})}function cj(){const e=i.useMemo(()=>({sendCommand:jn,sendData:go,sendPtyInput:Cu}),[]);return s.jsx(mm,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(_m,{client:ij,children:s.jsx(lj,{children:s.jsx(Vw,{children:s.jsx(Rm,{value:e,children:s.jsx(ej,{children:s.jsxs(pm,{children:[s.jsx(ts,{path:"/dashboard",element:s.jsx(Sv,{})}),s.jsx(ts,{path:"/machine",element:s.jsx(Jl,{})}),s.jsx(ts,{path:"/machines/:id",element:s.jsx(Aw,{})}),s.jsx(ts,{path:"/machines",element:s.jsx(Jl,{})}),s.jsx(ts,{path:"/about",element:s.jsx(nj,{})}),s.jsx(ts,{path:"/settings",element:s.jsx(oj,{})}),s.jsx(ts,{path:"/mesh",element:s.jsx($w,{})}),s.jsx(ts,{path:"*",element:s.jsx(Xa,{to:"/dashboard",replace:!0})})]})})})})})})})}Xf({connectionManager:Kt});hm(document.getElementById("root")).render(s.jsx(cj,{}));
98
+ Node removal cleanup policy: ${Ae}`))try{await e(n,"remove_mesh_node",{meshId:d,nodeId:F}),T===F&&A(null),await oe(),await de(d)}catch(qe){w((qe==null?void 0:qe.message)||"Remove node failed")}}async function Ce(F){if(!n||!d)return;const be={...za(ue),...F};try{h(!0),w(null);const Ae=await e(n,"update_mesh",{meshId:d,policy:be});if((Ae==null?void 0:Ae.success)===!1){w(Ae.error||"Policy update failed");return}await oe()}catch(Ae){w((Ae==null?void 0:Ae.message)||"Policy update failed")}finally{h(!1)}}async function _e(){var F;if(!(!n||!d||!W.trim()||!ie.trim())){P(!0);try{const be=await e(n,"configure_mesh_host_pairing",{meshId:d,hostAddress:W.trim(),token:ie.trim()});be!=null&&be.success?(E(be),me(be.hostAddress||((F=be.meshHost)==null?void 0:F.hostAddress)||W.trim()),await oe()):E({success:!1,error:(be==null?void 0:be.error)||"Failed to save Mesh Host pairing"})}catch(be){E({success:!1,error:(be==null?void 0:be.message)||"Failed to save Mesh Host pairing"})}finally{P(!1)}}}async function K(){if(!(!n||!d||!ie.trim())){U(!0);try{const F=await e(n,"join_mesh_host_pairing",{meshId:d,token:ie.trim()});F!=null&&F.success?(E(F),ee(""),await oe(),await Q(d),await ve()):E({success:!1,meshHost:F==null?void 0:F.meshHost,manualPairing:F==null?void 0:F.manualPairing,error:(F==null?void 0:F.error)||"Failed to apply Mesh Host join"})}catch(F){E({success:!1,error:(F==null?void 0:F.message)||"Failed to apply Mesh Host join"})}finally{U(!1)}}}async function Me(F){if(!n||!d)return;const be=io(f[F.id]||wn(F),o),Ae={...F.policy||{}};delete Ae.provider_priority,be.length?Ae.providerPriority=be:delete Ae.providerPriority;try{y(F.id),w(null);const Be=await e(n,"update_mesh_node",{meshId:d,nodeId:F.id,policy:Ae});if((Be==null?void 0:Be.success)===!1){w(Be.error||"Node policy update failed");return}await oe()}catch(Be){w((Be==null?void 0:Be.message)||"Node policy update failed")}finally{y(null)}}if(!n)return s.jsx(wr,{icon:s.jsx(ns,{}),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(!ue)return s.jsxs(wr,{icon:s.jsx(ns,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>je(!0),children:"+ Create Mesh"}),children:[x&&s.jsx(Es,{variant:"error",className:"mb-4",children:x}),ce&&s.jsx(wt,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(At,{label:"Name",children:s.jsx(cr,{value:Ne,onChange:F=>q(F.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(At,{label:"Repo Identity (optional)",children:s.jsx(cr,{value:ge,onChange:F=>fe(F.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:le,disabled:!Ne.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>je(!1),children:"Cancel"})]})]})}),u?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):l.length===0?s.jsx(Pn,{icon:s.jsx(ns,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:l.map(F=>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(F.id),children:[s.jsx("div",{className:"font-semibold text-sm",children:F.name}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:F.repoIdentity||"No repo identity"}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[F.nodes.length," node(s)"]})]},F.id))})]});const Te=za(ue),He=($==null?void 0:$.meshHost)||ue.meshHost||{},Ge=((Ye=$==null?void 0:$.manualPairing)==null?void 0:Ye.status)||((tt=He.pairing)==null?void 0:tt.status)||"not_configured",Xe=((ct=$==null?void 0:$.manualPairing)==null?void 0:ct.description)||"Manual address/token config is saved locally; Apply join sends the token once to the Mesh Host command endpoint. P2P runtime signaling remains outside this slice.";return s.jsxs(wr,{icon:s.jsx(ns,{}),title:ue.name,subtitle:ue.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:()=>pe(ue.id),children:"Delete"})]}),children:[x&&s.jsx(Es,{variant:"error",className:"mb-4",children:x}),s.jsx(wt,{title:"Mesh Host pairing",description:"Standalone manual pairing. Save a Mesh Host address/token, apply the join to the host command endpoint, then check persisted status.",children:s.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(280px,420px)]",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-4 text-sm",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"text-text-muted",children:"Local role"}),s.jsx("span",{className:"rounded-full border border-accent-primary/25 bg-accent-primary/10 px-2 py-0.5 text-xs font-semibold text-accent-primary",children:He.role||"host"}),s.jsx("span",{className:"text-text-muted",children:"Pairing"}),s.jsx("span",{className:"rounded-full border border-border-subtle px-2 py-0.5 text-xs font-mono text-text-primary",children:C?"loading":Ge})]}),s.jsxs("div",{className:"mt-3 grid gap-2 text-xs text-text-muted",children:[s.jsxs("div",{children:["Host address: ",s.jsx("code",{className:"text-text-primary",children:He.hostAddress||"not configured"})]}),s.jsxs("div",{children:["Token id: ",s.jsx("code",{className:"text-text-primary",children:((mt=He.pairing)==null?void 0:mt.tokenId)||"not configured"})]}),s.jsxs("div",{children:["Can own coordinator: ",s.jsx("code",{className:"text-text-primary",children:String(He.canOwnCoordinator??He.role!=="member")})]}),s.jsxs("div",{children:["Can own queue: ",s.jsx("code",{className:"text-text-primary",children:String(He.canOwnQueue??He.role!=="member")})]})]}),s.jsx("p",{className:"mt-3 text-xs leading-relaxed text-text-secondary",children:Xe}),($==null?void 0:$.error)&&s.jsx("div",{className:"mt-3 rounded-lg border border-red-500/25 bg-red-500/10 px-3 py-2 text-xs text-red-300",children:$.error})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-panel p-4",children:[s.jsx(At,{label:"Mesh Host address",hint:"Example: http://127.0.0.1:3847 or a reachable HTTPS/WSS host endpoint.",children:s.jsx(cr,{value:W,onChange:F=>me(F.target.value),placeholder:"http://127.0.0.1:3847",disabled:O||R})}),s.jsx(At,{label:"Pairing token",hint:"The raw token is used once to derive a local token id; it is not displayed after save.",children:s.jsx(cr,{value:ie,onChange:F=>ee(F.target.value),placeholder:"paste Mesh Host pairing token",type:"password",disabled:O||R})}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:_e,disabled:O||R||!W.trim()||!ie.trim(),children:O?"Saving...":"Save manual pairing"}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:K,disabled:R||O||!ie.trim(),children:R?"Applying...":"Apply join"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>Q(d),disabled:C||O||R,children:C?"Checking...":"Check saved config"})]})]})]})}),s.jsxs(wt,{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(At,{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:Te.requirePreTaskCheckpoint?"yes":"no",onChange:F=>Ce({requirePreTaskCheckpoint:F.target.value==="yes"}),disabled:g,children:[s.jsx("option",{value:"no",children:"No"}),s.jsx("option",{value:"yes",children:"Yes"})]})}),s.jsx(At,{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:Te.requirePostTaskCheckpoint?"yes":"no",onChange:F=>Ce({requirePostTaskCheckpoint:F.target.value==="yes"}),disabled:g,children:[s.jsx("option",{value:"yes",children:"Yes"}),s.jsx("option",{value:"no",children:"No"})]})}),s.jsx(At,{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:Te.requireApprovalForPush?"required":"not_required",onChange:F=>Ce({requireApprovalForPush:F.target.value==="required"}),disabled:g,children:[s.jsx("option",{value:"required",children:"Require approval before push"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(At,{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:Te.requireApprovalForDestructiveGit?"required":"not_required",onChange:F=>Ce({requireApprovalForDestructiveGit:F.target.value==="required"}),disabled:g,children:[s.jsx("option",{value:"required",children:"Require approval"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(At,{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:Te.dirtyWorkspaceBehavior||"warn",onChange:F=>Ce({dirtyWorkspaceBehavior:F.target.value}),disabled:g,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(At,{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(Te.maxParallelTasks??2),onChange:F=>Ce({maxParallelTasks:Number(F.target.value)}),disabled:g,children:[1,2,3,4,5,6,7,8].map(F=>s.jsx("option",{value:F,children:F},F))})})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(At,{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:Te.sessionCleanupOnNodeRemove||"preserve",onChange:F=>Ce({sessionCleanupOnNodeRemove:F.target.value}),disabled:g,children:cn.map(F=>s.jsx("option",{value:F.value,children:F.label},F.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((pt=cn.find(F=>F.value===Te.sessionCleanupOnNodeRemove))==null?void 0:pt.description)||cn[0].description})]}),g&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),s.jsxs(wt,{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:ve,disabled:B,children:B?"Loading...":"Refresh Graph"})]}),N&&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:N}),k?s.jsx(vu,{status:k,emptyMessage:"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon.",daemonId:n,sendDaemonCommand:e}):s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:B?"Loading graph...":"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon."})]}),s.jsxs(wt,{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:()=>xe(!0),children:"+ Add Node"})}),we&&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:()=>xe(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(jt,{size:16})})]}),s.jsx(At,{label:"Workspace Path",children:s.jsx(cr,{value:Se,onChange:F=>J(F.target.value),placeholder:"/Users/dev/projects/myapp",autoFocus:!0})}),s.jsx(At,{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:he,availableProviders:o,onChange:ae})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:ne,disabled:!Se.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>xe(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),ue.nodes.length===0?s.jsx(Pn,{icon:s.jsx(Ss,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:ue.nodes.map(F=>{const be=wn(F),Ae=Rw(F),Be=Pw(F,S),qe=Ew(F,r),G=T===F.id;return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary cursor-pointer transition-colors ${G?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`,role:"button",tabIndex:0,onClick:()=>A(G?null:F.id),onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),A(G?null:F.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:F.workspace.split("/").pop()}),Be.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:[Be.length," active task",Be.length===1?"":"s"]})]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:F.workspace}),s.jsx("div",{className:"mt-3 max-w-2xl",onClick:z=>z.stopPropagation(),children:s.jsxs(At,{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[F.id]??be,availableProviders:o,onChange:z=>M(X=>({...X,[F.id]:z})),disabled:b===F.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:z=>{z.stopPropagation(),Me(F)},disabled:b===F.id,children:b===F.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:Ae.configured?"text-text-primary font-mono":"text-amber-400",children:Ae.label}),Ae.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",Ae.launchBlockedMessage,")"]})]})]})})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:z=>{z.stopPropagation(),Ie(F.id)},children:s.jsx(jt,{size:14})})]}),G&&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:F.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:Ae.configured?"text-green-400":"text-amber-400",children:Ae.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:F.repoRoot||F.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",qe.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:"})," ",Be.length>0||qe.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"}),Be.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:Be.map(z=>s.jsx("li",{className:"font-mono",children:Dw(z)},z.id))})]}),qe.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:qe.map(z=>s.jsxs("li",{className:"font-mono",children:[z.provider," / ",z.status," / ",z.id]},z.id))})]})]})]},F.id)})})]}),s.jsx($w,{meshId:ue.id,availableCliAgents:a})]})}function fi(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Ow(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(Ow(e),{credentials:"same-origin",...t})}function Nu(){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 Fw{constructor(){Qe(this,"adapters",new Map);Qe(this,"states",new Map);Qe(this,"runtimeListeners",new Map);Qe(this,"screenshotCallbacks",new Map);Qe(this,"statusCallbacks",new Set);Qe(this,"stateChangeCallbacks",new Set);Qe(this,"ptyInputSender",null)}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);const n=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(a=>a(n,r))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}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"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,r){return!1}sendPtyInput(t,r,n){return this.ptyInputSender?this.ptyInputSender(t,r,n):!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 Kt=new Fw;function Ww(){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 dn=Ww(),Yl=3e3,Hw=3e4;let Ot=null,Kw=0;const Fn=new Map;let ms=null,Sr=null;function Xl(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function pr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function Uw(e){return e==="connected"?"connected":e}async function jn(e,t,r){const n=cd(e,r||{}),a=Ot;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++Kw}_${Date.now()}`;return new Promise((l,c)=>{const d=setTimeout(()=>{Fn.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);Fn.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 go(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 Cu(e,t,r){const n=Ot;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=cd(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}}Kt.registerPtyInputSender(Cu);class zw{constructor(t){Qe(this,"daemonId");Qe(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 jn(this.daemonId,t,r)}async sendInput(t,r){return jn(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 jn(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());Kt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ms=setInterval(r,2e3)}stopScreenshots(t){ms&&(clearInterval(ms),ms=null)}}let Dt=null;function Gw(e){return(!Dt||Dt.daemonId!==e)&&(Dt=new zw(e)),Dt}function Vw({children:e}){const t=i.useRef(Cr()),r=Cr();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((h,b)=>{c(h),Sr==null||Sr(h,b)},[]),m=i.useRef(null),u=i.useRef(),p=i.useRef(Yl),x=i.useRef(!0),w=i.useRef(!1),g=i.useRef("initial_connect");return i.useEffect(()=>{x.current=!0,w.current=!1;function h(){var f,M;if(!x.current||((f=m.current)==null?void 0:f.readyState)===WebSocket.OPEN||((M=m.current)==null?void 0:M.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${dn}...`),pr("connect_attempt",{url:dn,reason:g.current,delayMs:p.current});let y;try{y=new WebSocket(dn)}catch(S){console.error("[Standalone WS] Failed to create WebSocket:",S),b();return}m.current=y,y.onopen=()=>{if(!x.current){y.close();return}d("connected"),p.current=Yl,pr("open",{url:dn,reason:g.current}),Jt.resubscribeAll({sendData:go}),console.log("[Standalone WS] Connected")},Ot=y,y.onmessage=S=>{var v,T;try{const A=JSON.parse(S.data);if((A.type==="command_result"||A.type==="error")&&A.requestId){const k=Fn.get(A.requestId);k&&(Fn.delete(A.requestId),A.type==="error"?k.reject(new Error(((v=A.data)==null?void 0:v.message)||"Command failed")):k.resolve(A.data));return}if(A.type==="session_output"){const k=A.sessionId||A.cliId||A.cliType;k&&Kt.emitSessionOutput(k,typeof A.data=="string"?A.data:"",typeof A.seq=="number"?A.seq:void 0);return}if(A.type==="runtime_snapshot"){Kt.emitRuntimeSnapshot(A.sessionId,typeof A.text=="string"?A.text:"",typeof A.seq=="number"?A.seq:0,!!A.truncated,typeof A.cols=="number"?A.cols:void 0,typeof A.rows=="number"?A.rows:void 0);return}if(A.type==="topic_update"){const k=A.update;k&&Jt.publish(k);return}if(A.type==="status"||A.type==="initial_state"){const k=A.data;if(!k)return;const{injectEntries:j,markLoaded:B,getIdes:L}=t.current,N=k.instanceId||"standalone",D=L().find(C=>C.id===N),$=Gw(N);Kt.register(N,$),Kt.setState(N,"connected"),d("connected",N),Kt.emitStatus(N,k);const E=Ln(k,{daemonId:N,existingDaemon:D,existingEntries:L()});Xl("ws_status",{type:A.type,daemonId:N,sessions:(k.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:(k.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Xl("entries",{daemonId:N,entries:E.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}))}),E.length>0&&j(E,{authoritativeDaemonIds:[N]}),B(),l.current!==N&&((T=o.current)==null||T.call(o),l.current=N,o.current=Jt.subscribe({sendData:go},N,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${N}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const I=t.current.getIdes(),O=I.find(R=>R.id===N),P=Ln(C.status,{daemonId:N,existingDaemon:O,existingEntries:I,timestamp:C.timestamp});P.length>0&&t.current.injectEntries(P,{authoritativeDaemonIds:[N]}),C.userName&&a.current&&a.current(C.userName)}))}}catch(A){console.error("[Standalone WS] Parse error:",A)}},y.onclose=S=>{x.current&&(Dt==null||Dt.stopScreenshots(),Dt&&Kt.setState(Dt.daemonId,"disconnected"),d("disconnected"),m.current=null,g.current=`close:${S.code}${S.wasClean?":clean":":unclean"}`,pr("close",{code:S.code,reason:S.reason||"",wasClean:S.wasClean}),b())},y.onerror=S=>{w.current||!x.current||(g.current="error",pr("error",{message:S instanceof Event?"event":String(S),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",S))}}function b(){if(!x.current)return;clearTimeout(u.current);const y=p.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),pr("schedule_reconnect",{reason:g.current,delayMs:y}),u.current=setTimeout(()=>{p.current=Math.min(p.current*1.5,Hw),h()},y)}return h(),()=>{var y;x.current=!1,w.current=!0,(y=o.current)==null||y.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),Dt&&(Dt.stopScreenshots(),Kt.unregister(Dt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function qw({children:e}){const[t,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(Sr=(l,c)=>{r(l),c&&a(c)},()=>{Sr=null}),[]);const o=i.useMemo(()=>{const l=t==="connected",c=Uw(t),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:t,isConnected:l,connectionStates:d}},[t,n]);return s.jsx(Mm,{connectionOverrides:o,children:s.jsx(Vw,{children:e})})}const Iu="adhdev_standalone_font_preferences",ks={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},sa=[{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"}],Tr=[{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"}],Yw=new Set(sa.map(e=>e.id)),Xw=new Set(Tr.map(e=>e.id));function Gt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:kn("chat",t.chat),code:kn("code",t.code),terminal:kn("terminal",t.terminal)}}function kn(e,t){const r=ks[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"?Yw:Xw).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Sn(e,t){var a;const r=kn(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?sa:Tr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function Jw(e){const t=Gt(e),r=Sn("chat",t.chat),n=Sn("code",t.code),a=Sn("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function hs(e,t=document.documentElement){const r=Gt(e),n=Jw(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function yo(e){const t=Gt(e);try{localStorage.setItem(Iu,JSON.stringify(t))}catch{}return t}function Qw(){try{const e=localStorage.getItem(Iu);if(e)return Gt(JSON.parse(e))}catch{}return ks}function Zw(){return hs(Qw())}function hr(e,t){var n;const r=e==="chat"?sa:Tr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const ej=[{id:"dashboard",path:"/dashboard",icon:s.jsx(oc,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(os,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(Hs,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(Wn,{}),label:"Settings"}];function tj({children:e}){const t=Ys(),r=wo(),n=i.useMemo(()=>ej.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(lc,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(cc,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Hx,{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 sj=[{icon:s.jsx(os,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Qt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(dc,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Rt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Hs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(lc,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],rj=[{icon:s.jsx(zm,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(oc,{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(Bm,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(ic,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Fm,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],nj=[{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 aj(){return s.jsxs(wr,{icon:s.jsx(cc,{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(wt,{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(wt,{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:sj.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(wt,{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:dd.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:md.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:ud.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(wt,{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:rj.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(wt,{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:nj.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(Pn,{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(tp,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Ga(e,t,r){return{...e,[t]:r}}function Va({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:Sn(e,n)})]})]})]})}function oj({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(Va,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:sa,onChange:u=>o(Ga(e,"chat",u))}),s.jsx(Va,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Tr,onChange:u=>o(Ga(e,"code",u))}),s.jsx(Va,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Tr,onChange:u=>o(Ga(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: ",hr("chat",e.chat.preset)," · Code: ",hr("code",e.code.preset)," · Terminal: ",hr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",hr("chat",ks.chat.preset)," / ",hr("code",ks.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 ij(){const{ides:e}=cs(),t=e.find(q=>q.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=kt(),{userName:a}=cs(),[o,l]=i.useState(a||""),[c,d]=i.useState(null),[m,u]=i.useState(null),[p,x]=i.useState(ks),[w,g]=i.useState(!1),[h,b]=i.useState(""),[y,f]=i.useState(""),[M,S]=i.useState("127.0.0.1"),[v,T]=i.useState(""),[A,k]=i.useState(""),[j,B]=i.useState(""),[L,N]=i.useState(""),[D,$]=i.useState(""),[E,C]=i.useState(!1),I=async()=>{const ge=await(await Ut("/auth/session")).json();d(ge)},O=async()=>{const ge=await(await Ut("/api/v1/standalone/preferences")).json();u(ge),S(ge.standaloneBindHost);const fe=Gt(ge.standaloneFontPreferences);x(fe),hs(fe),yo(fe)};i.useEffect(()=>{a!==void 0&&l(a)},[a]),i.useEffect(()=>{Promise.all([I(),O()]).catch(q=>{N(q instanceof Error?q.message:String(q))})},[]),i.useEffect(()=>{hs(p)},[p]);const P=q=>{const ge=q.target.value.trim();t!=null&&t.id&&ge!==a&&n(t.id,"set_user_name",{userName:ge}).catch(console.error)},[R,U]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),W=q=>{U(q);try{localStorage.setItem("adhdev_sound",q?"1":"0")}catch{}},me=async()=>{b(""),f(""),g(!0);try{const q=Gt(p),ge=await Ut("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:q})}),fe=await ge.json();if(!ge.ok)throw new Error((fe==null?void 0:fe.error)||"Failed to save standalone font preferences");const we=Gt(fe.standaloneFontPreferences);u(fe),x(we),hs(we),yo(we),f("Standalone chat fonts saved for this self-hosted dashboard.")}catch(q){b(q instanceof Error?q.message:String(q))}finally{g(!1)}},ie=()=>{const q=Gt(m==null?void 0:m.standaloneFontPreferences);b(""),f(""),x(q),hs(q)},ee=()=>{b(""),f(""),x(ks),hs(ks)},ce=async()=>{N(""),$(""),C(!0);try{const q=await Ut("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:M})}),ge=await q.json();if(!q.ok)throw new Error((ge==null?void 0:ge.error)||"Failed to save standalone network preference");u(ge),S(ge.standaloneBindHost),$(ge.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(q){N(q instanceof Error?q.message:String(q))}finally{C(!1)}},je=async()=>{if(N(""),$(""),A.trim().length<4){N("Password must be at least 4 characters.");return}if(A!==j){N("New password and confirmation do not match.");return}C(!0);try{const q=await Ut("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:A})}),ge=await q.json();if(!q.ok)throw new Error((ge==null?void 0:ge.error)||"Failed to save password");d(ge),await O(),T(""),k(""),B(""),$(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Nu()}catch(q){N(q instanceof Error?q.message:String(q))}finally{C(!1)}},Ne=async()=>{N(""),$(""),C(!0);try{const q=await Ut("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),ge=await q.json();if(!q.ok)throw new Error((ge==null?void 0:ge.error)||"Failed to clear password");d(ge),await O(),T(""),k(""),B(""),$("Standalone password disabled.")}catch(q){N(q instanceof Error?q.message:String(q))}finally{C(!1)}};return s.jsxs(wr,{icon:s.jsx(Wn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Es,{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(Es,{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(wt,{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(wt,{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:M==="127.0.0.1",onChange:()=>S("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:M==="0.0.0.0",onChange:()=>S("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:()=>{ce()},disabled:E,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:E?"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(wt,{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."}),L&&s.jsx(Es,{variant:"error",children:L}),D&&s.jsx(Es,{variant:"success",children:D}),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:v,onChange:q=>T(q.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:A,onChange:q=>k(q.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:j,onChange:q=>B(q.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{je()},disabled:E,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:E?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{Ne()},disabled:E,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(wt,{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(q=>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 ${q.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:q.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:q.type})]},q.type))})}),s.jsx(wt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Jx,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(wt,{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(tb,{})]}),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(cb,{})]}),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(oj,{value:p,savedValue:Gt(m==null?void 0:m.standaloneFontPreferences),saving:w,error:h,notice:y,onChange:x,onSave:()=>{me()},onResetToSaved:ie,onResetToDefaults:ee})]}),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(mb,{})]})]})}),s.jsx(wt,{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(qx,{}),s.jsx(ps,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ep,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:R,onChange:W})]})}),s.jsx(wt,{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($m,{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:q=>l(q.target.value),onBlur:P,onKeyDown:q=>{q.key==="Enter"&&q.currentTarget.blur()}})]})})})]})}Fx();ib();Zw();const lj=nc({baseUrl:"",getToken:fi});function cj({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),p=async()=>{a(!0),d("");try{const g=await(await Ut("/auth/session")).json();r(g)}catch(w){d(w instanceof Error?w.message:String(w))}finally{a(!1)}};i.useEffect(()=>{p()},[]),i.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let w=!1;return(async()=>{try{const g=await Ut("/api/v1/standalone/preferences");if(!g.ok)return;const h=await g.json();if(w)return;const b=Gt(h.standaloneFontPreferences);hs(b),yo(b)}catch{}})(),()=>{w=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const x=async w=>{w.preventDefault(),u(!0),d("");try{const g=await Ut("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),h=await g.json();if(!g.ok)throw new Error((h==null?void 0:h.error)||"Login failed");r(h),l(""),Nu()}catch(g){d(g instanceof Error?g.message:String(g))}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:w=>l(w.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 Jl(){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(Xa,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Xa,{to:"/dashboard",replace:!0})}function dj(){const e=i.useMemo(()=>({sendCommand:jn,sendData:go,sendPtyInput:Cu}),[]);return s.jsx(mm,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(_m,{client:lj,children:s.jsx(cj,{children:s.jsx(qw,{children:s.jsx(Rm,{value:e,children:s.jsx(tj,{children:s.jsxs(pm,{children:[s.jsx(ts,{path:"/dashboard",element:s.jsx(Nv,{})}),s.jsx(ts,{path:"/machine",element:s.jsx(Jl,{})}),s.jsx(ts,{path:"/machines/:id",element:s.jsx(_w,{})}),s.jsx(ts,{path:"/machines",element:s.jsx(Jl,{})}),s.jsx(ts,{path:"/about",element:s.jsx(aj,{})}),s.jsx(ts,{path:"/settings",element:s.jsx(ij,{})}),s.jsx(ts,{path:"/mesh",element:s.jsx(Bw,{})}),s.jsx(ts,{path:"*",element:s.jsx(Xa,{to:"/dashboard",replace:!0})})]})})})})})})})}Xf({connectionManager:Kt});hm(document.getElementById("root")).render(s.jsx(dj,{}));