@adhdev/daemon-standalone 0.9.82-rc.164 → 0.9.82-rc.166

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.
@@ -0,0 +1,99 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-C45SzZMr.js","assets/vendor-DNk1FT1R.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
+ var hm=Object.defineProperty;var pm=(e,t,r)=>t in e?hm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var We=(e,t,r)=>pm(e,typeof t!="symbol"?t+"":t,r);import{r as l,j as s,M as Ao,a as fm,b as xm,c as bm,R as ft,d as vr,t as gm,e as ym,u as Ir,D as vm,f as so,g as ro,E as wm,i as jm,C as km,h as Sm,B as Nm,k as Cm,l as Mm,m as Im,n as Tm,H as Vr,P as qr,o as Am,p as _m,q as Lm,s as Pm,v as Rm,w as _o,x as Dm,y as Em,z as $m,A as Bm,F as Xt,N as no,G as Om}from"./vendor-DNk1FT1R.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&n(i)}).observe(document,{childList:!0,subtree:!0});function r(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(a){if(a.ep)return;a.ep=!0;const o=r(a);fetch(a.href,o)}})();function Fm(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),r=[];return{record(n){const a={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...n,payload:n.payload?{...n.payload}:{}};return r.push(a),r.length>t&&r.splice(0,r.length-t),a},list(n={}){const a=Math.max(1,Math.floor(n.limit||100));return r.filter(o=>!n.interactionId||o.interactionId===n.interactionId).filter(o=>!n.topic||o.topic===n.topic).filter(o=>!n.kind||o.kind===n.kind).slice(-a).map(o=>({...o,payload:o.payload?{...o.payload}:{}}))},clear(){r.splice(0,r.length)}}}const Ds=Fm();function Ii(e){const t={};for(const r of e)r.transport&&(t[r.transport]=(t[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:t}}function Hm(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Ti(e){return Array.isArray(e)?[...e]:[]}function cc(e,t){if(!e)return t??null;const r=Object.prototype.hasOwnProperty.call(e,"messages"),n=Object.prototype.hasOwnProperty.call(e,"activeModal"),a=typeof e.id=="string"?e.id.trim():"",o=typeof(t==null?void 0:t.id)=="string"?t.id.trim():"",i=!!a&&!!o&&a!==o;return t?{...t,...e,messages:r?Ti(e.messages):i?[]:t.messages,activeModal:n?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...r?{messages:Ti(e.messages)}:{},...n?{activeModal:e.activeModal??null}:{}}}function lr(e,t){const r=Hm(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(t==null?void 0:t.parentSessionId)??null,providerSessionId:e.providerSessionId??(t==null?void 0:t.providerSessionId),providerName:r??(t==null?void 0:t.providerName)??(t==null?void 0:t.cliName)??(t==null?void 0:t.type)??e.providerName??e.providerType,title:e.title??(t==null?void 0:t.title)??r??(t==null?void 0:t.providerName)??e.providerName??e.providerType,workspace:e.workspace??(t==null?void 0:t.workspace)??null,mode:e.mode??(t==null?void 0:t.mode),capabilities:e.capabilities??(t==null?void 0:t.sessionCapabilities)??(t==null?void 0:t.capabilities)??[],cdpConnected:e.cdpConnected??(t==null?void 0:t.cdpConnected),activeChat:cc(e.activeChat,t==null?void 0:t.activeChat),controlValues:e.controlValues??(t==null?void 0:t.controlValues),providerControls:e.providerControls??(t==null?void 0:t.providerControls),summaryMetadata:e.summaryMetadata??(t==null?void 0:t.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(t==null?void 0:t.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(t==null?void 0:t.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(t==null?void 0:t.lastMessagePreview),lastMessageRole:e.lastMessageRole??(t==null?void 0:t.lastMessageRole),lastMessageAt:e.lastMessageAt??(t==null?void 0:t.lastMessageAt),lastMessageHash:e.lastMessageHash??(t==null?void 0:t.lastMessageHash),unread:e.unread??(t==null?void 0:t.unread),lastSeenAt:e.lastSeenAt??(t==null?void 0:t.lastSeenAt),inboxBucket:e.inboxBucket??(t==null?void 0:t.inboxBucket),completionMarker:e.completionMarker??(t==null?void 0:t.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(t==null?void 0:t.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(t==null?void 0:t.surfaceHidden),resume:e.resume??(t==null?void 0:t.resume),runtimeKey:e.runtimeKey??(t==null?void 0:t.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(t==null?void 0:t.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(t==null?void 0:t.runtimeWorkspaceLabel),settings:e.settings??(t==null?void 0:t.settings)}}function dc(e,t,r){if(!(t!=null&&t.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const n=t.map(a=>{const o=e.find(i=>i.id===a.id);return o?lr(a,o):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(t.map(o=>o.id));for(const o of e)a.has(o.id)||n.push(o)}return n}function Ai(e){return!!e&&typeof e=="object"&&"text"in e}function Lo(e,t){const r=(t==null?void 0:t.joiner)??" ",n=(t==null?void 0:t.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(o=>typeof o=="string"?o:Ai(o)?String(o.text||""):"").join(r):Ai(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Es(e){return Lo(e,{normalizeWhitespace:!0})}const uc=l.createContext({ides:[],updateRouteChats:()=>{},initialLoaded:!1,toasts:[],setToasts:()=>{},wsStatus:"connected",isConnected:!0,connectionStates:{},connectionTransports:{},showReconnected:!1,userName:void 0,setUserName:()=>{},isP2PActive:!1,p2pStates:{},userRole:void 0,connectionRetryStatuses:void 0}),mc=l.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function _i(e){var r,n;let t=0;return e.activeChat!==void 0&&(t+=4),(r=e.childSessions)!=null&&r.length&&(t+=2),e.workspace&&(t+=1),e.machine&&(t+=1),(n=e.agents)!=null&&n.length&&(t+=1),t}function hc(e,t,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=t.version??r.version??e.version,o=t.serverVersion??e.serverVersion??r.serverVersion,i=t.versionMismatch===!0||e.versionMismatch===!0,c=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,d=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),o&&(n.serverVersion=o),d&&(n.versionUpdateReason=d),a&&o&&a===o?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||i&&a&&o&&a!==o)&&(n.versionMismatch=!0),c&&(n.versionUpdateRequired=!0),n)}function Wm(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function ca(e){if(!e||typeof e!="object")return"";const t=e,r=Wm(Es(t.content).slice(0,512));return[String(t.id||""),String(t._localId||""),String(t._turnKey||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),r].join(":")}function Km(e,t){if(!Array.isArray(e))return e;if(t!=null&&t.has(e))return{count:e.length,sharedRef:!0};let r=2166136261;for(const n of e){const a=ca(n);for(let o=0;o<a.length;o+=1)r^=a.charCodeAt(o),r=Math.imul(r,16777619)>>>0}return{count:e.length,hash:r.toString(16).padStart(8,"0"),first:ca(e[0]),last:ca(e[e.length-1])}}function ao(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function oo(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(ao(e)&&ao(t)){const i=e.messages;Array.isArray(i)&&i===t.messages&&r.add(i)}if(Array.isArray(e)&&Array.isArray(t)){const i=Math.min(e.length,t.length);for(let c=0;c<i;c+=1)oo(e[c],t[c],r);return}const n=e,a=t,o=new Set([...Object.keys(n),...Object.keys(a)]);for(const i of o)i!=="messages"&&oo(n[i],a[i],r)}function mr(e,t){return Array.isArray(e)?e.map(r=>mr(r,t)):!e||typeof e!="object"?e:ao(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Km(a,t):mr(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,mr(n,t)]))}function Um(e,t){try{const r=new WeakSet;return oo(e,t,r),JSON.stringify(mr(e,r))===JSON.stringify(mr(t,r))}catch{return!1}}function io(e,t,r){return Um(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function pc(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function zm(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Li(e,t,r,n){var c;const a=(c=t.chats)!=null&&c.length?t.chats:e.chats,o=dc(e.childSessions,t.childSessions,{preserveMissing:n}),i=cc(t.activeChat,e.activeChat);return hc(e,t,{...e,...t,chats:a,childSessions:o,activeChat:i,_lastUpdate:r})}function Gm(e,t,r){var a,o;const n={};t.status&&t.status!==e.status&&(n.status=t.status),t.cdpConnected!==void 0&&(n.cdpConnected=t.cdpConnected),t.childSessions!==void 0&&(n.childSessions=dc(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(n.chats=t.chats);for(const i of["title","workspace","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])zm(n,t,i);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function Vm(e,t,r,n){const a=Gm(e,t,n),o=Object.keys(a).length>0?hc(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return io(e,o,r)}function qm(e){const t=new Set(e.map(o=>o.id)),r=new Set,n=new Set,a=new Set;for(const o of e){const i=pc(o);i&&r.add(i),i&&o.type!=="adhdev-daemon"&&n.add(i),i&&o.type==="adhdev-daemon"&&o._sessionListAuthoritative&&a.add(i)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function Ym(e,t,r,n,a,o){return!a.has(t)||!o.has(t)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function Xm(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function Jm(e,t,r){var u,p;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(x=>({...x,_lastUpdate:n}));const o=new Map;for(const x of t)o.set(x.id,x);const{incomingIds:i,incomingDaemonIds:c,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:m}=qm(e);for(const x of e){const w=o.get(x.id);if(!w){o.set(x.id,{...x,_lastUpdate:n});continue}const b=_i(x),f=_i(w),k=pc(x),y=!a.has(k);if(b>f){const v=Li(w,x,n,y);o.set(x.id,io(w,v,n));continue}if(b<f){o.set(x.id,Vm(w,x,n,y));continue}const h=x.timestamp||n,j=w._lastUpdate||w.timestamp||0;if(h>=j){const v=Li(w,x,n,y);o.set(x.id,io(w,v,n));continue}(u=x.chats)!=null&&u.length&&!((p=w.chats)!=null&&p.length)&&o.set(x.id,{...w,chats:x.chats})}for(const[x,w]of o){const b=w.daemonId||x.split(":")[0];if(!c.has(b))continue;if(a.has(b)&&m.has(b)&&!i.has(x)){o.delete(x);continue}const f=n-(w._lastUpdate||w.timestamp||0);Ym(w,b,f,i,a,d)&&o.delete(x)}for(const[x,w]of o){const b=w.daemonId||x.split(":")[0];if(Xm(w,b,c,d,o))continue;n-(w._lastUpdate||w.timestamp||0)>3e5&&w.status!=="online"&&o.delete(x)}return Array.from(o.values())}function Qm(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Zm({children:e,connectionOverrides:t}){const[r,n]=l.useState([]),[a,o]=l.useState(!1),[i,c]=l.useState([]),[d,m]=l.useState(void 0),u=l.useRef(r);l.useEffect(()=>{u.current=r},[r]);const p=l.useCallback((y,h)=>{n(j=>{let v=!1;const g=j.map(S=>S.id!==y||S.chats===h?S:(v=!0,{...S,chats:h}));return v?g:j})},[]),x=l.useCallback((y,h)=>{n(j=>{const v=j.length===0?y:Jm(y,j,h),g=!Qm(j,v);return g&&Ds.record({kind:"dashboard.entries_applied",payload:{incoming:Ii(y),next:Ii(v)}}),g?v:j})},[]),w=l.useCallback(()=>o(!0),[]),b=l.useMemo(()=>({injectEntries:x,markLoaded:w,getIdes:()=>u.current}),[x,w]),f=t,k=l.useMemo(()=>({ides:r,updateRouteChats:p,initialLoaded:a,toasts:i,setToasts:c,wsStatus:(f==null?void 0:f.wsStatus)??"connected",isConnected:(f==null?void 0:f.isConnected)??!0,connectionStates:(f==null?void 0:f.connectionStates)??{},connectionTransports:(f==null?void 0:f.connectionTransports)??{},showReconnected:(f==null?void 0:f.showReconnected)??!1,retryConnection:f==null?void 0:f.retryConnection,retryServerConnection:f==null?void 0:f.retryServerConnection,connectionLoginUrl:f==null?void 0:f.connectionLoginUrl,isP2PActive:(f==null?void 0:f.isP2PActive)??!1,p2pStates:(f==null?void 0:f.p2pStates)??{},userRole:f==null?void 0:f.userRole,connectionRetryStatuses:f==null?void 0:f.connectionRetryStatuses,userName:d,setUserName:m}),[r,p,a,i,f==null?void 0:f.wsStatus,f==null?void 0:f.isConnected,f==null?void 0:f.connectionStates,f==null?void 0:f.connectionTransports,f==null?void 0:f.showReconnected,f==null?void 0:f.retryConnection,f==null?void 0:f.retryServerConnection,f==null?void 0:f.connectionLoginUrl,f==null?void 0:f.isP2PActive,f==null?void 0:f.p2pStates,f==null?void 0:f.userRole,f==null?void 0:f.connectionRetryStatuses,d]);return s.jsx(mc.Provider,{value:b,children:s.jsx(uc.Provider,{value:k,children:e})})}function ss(){return l.useContext(uc)}function wr(){return l.useContext(mc)}function fc(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(c){return c.startsWith("http")?c:`${t}${c.startsWith("/")?"":"/"}${c}`}function o(c){const d=r==null?void 0:r(),m=a(c),u=c.startsWith("http")?new URL(m):new URL(m,typeof window<"u"?window.location.origin:"http://localhost");return d&&u.searchParams.set("token",d),!c.startsWith("http")&&!t?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function i(c,d={}){const m={"Content-Type":"application/json",...d.headers||{}},u=r==null?void 0:r();u&&(m.Authorization=`Bearer ${u}`);const p=a(c),x=new AbortController,w=setTimeout(()=>x.abort(),15e3);try{const b=await fetch(p,{...d,headers:m,signal:x.signal});if(b.status===401)throw n==null||n(),new Error("Unauthorized");if(!b.ok){const f=await b.json().catch(()=>({error:b.statusText}));throw new Error(f.error||`API Error: ${b.status}`)}return b.json()}finally{clearTimeout(w)}}return{getDaemons:()=>i("/api/v1/daemons"),getDaemonStatus:c=>i(`/api/v1/daemons/${c}/status`),sendCommand:(c,d,m={})=>i(`/api/v1/daemons/${c}/command`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),execTerminal:(c,d,m)=>i(`/api/v1/daemons/${c}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:m})}),sendAgentMessage:(c,d,m)=>i(`/api/v1/shortcuts/${c}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:m})}),getAgentStatus:c=>i(`/api/v1/shortcuts/${c}/status`),approveAgent:(c,d,m)=>i(`/api/v1/shortcuts/${c}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:m?"approve":"reject"})}),getMuxState:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/state`),getMuxSocketInfo:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/socket-info`),controlMux:(c,d,m={})=>i(`/api/v1/mux/${encodeURIComponent(c)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),getMuxEventsUrl:c=>o(`/api/v1/mux/${encodeURIComponent(c)}/events`),getRuntimeEventsUrl:c=>o(`/api/v1/runtime/${encodeURIComponent(c)}/events`),request:i}}const eh=fc({baseUrl:"http://localhost:3847"}),th=l.createContext(eh);function sh({client:e,children:t}){return s.jsx(th.Provider,{value:e,children:t})}const rh={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},xc=l.createContext(rh);function nh({value:e,children:t}){return s.jsx(xc.Provider,{value:e,children:t})}function lt(){return l.useContext(xc)}function ah(e){let t=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)t^=n.charCodeAt(a),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function oh(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function ih(e){return e?ah([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),oh(e.content)]):""}const Be={size:18};function bc({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function Po({size:e=Be.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function es({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),s.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),s.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),s.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function gc({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"9",cy:"7",r:"4"}),s.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),s.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function lh({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function ch({size:e=Be.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function yc({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),s.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),s.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),s.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function dh({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),s.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),s.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),s.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),s.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function Qn({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function vc({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),s.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function uh({size:e=Be.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function ws({size:e=Be.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Bt({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Ro({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("polyline",{points:"14 2 14 8 20 8"}),s.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),s.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function $s({size:e=Be.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function Zn({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function jr({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),s.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Bs({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M12 22v-5"}),s.jsx("path",{d:"M9 8V2"}),s.jsx("path",{d:"M15 8V2"}),s.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function Qt({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"5",r:"2"}),s.jsx("circle",{cx:"5",cy:"19",r:"2"}),s.jsx("circle",{cx:"19",cy:"19",r:"2"}),s.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),s.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),s.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function mh({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"12 2 2 7 12 12 22 7 12 2"}),s.jsx("polyline",{points:"2 12 12 17 22 12"}),s.jsx("polyline",{points:"2 17 12 22 22 17"})]})}function wc({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Do({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),s.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),s.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function jc({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function hh({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),s.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),s.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function Eo({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"4 17 10 11 4 5"}),s.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function ph({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function kc({size:e=Be.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Sc({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function gt({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function fh({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),s.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),s.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),s.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function xh({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),s.jsx("path",{d:"M12 2v6"}),s.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function bh({size:e=Be.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function gh({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),s.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function Tr({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function yh({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"5"}),s.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),s.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),s.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),s.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),s.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),s.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),s.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),s.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function vh({size:e=Be.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function wh({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function jh({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),s.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function kh({size:e=Be.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function Sh({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),s.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function Nh({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function Ch({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),s.jsx("path",{d:"M13 2h9v9"}),s.jsx("path",{d:"M22 2L13 11"})]})}function Mh({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function Ih({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),s.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),s.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),s.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),s.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),s.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),s.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),s.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),s.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),s.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function Th({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function Ah({size:e=Be.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const Nc="adhdev_chat_activity_visible",Pi=new Set(["hidden","debug","internal"]),Ri=new Set(["visible","user","chat"]),_h=new Set(["debug","trace","internal"]),Lh=new Set(["tool_call","terminal_command","runtime_activity"]),Ph=new Set(["runtime_status","provider_chrome","control"]),Rh=new Set(["thought","tool","terminal"]);function Cc(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Cs(e){return typeof e=="string"?e.trim().toLowerCase():""}function da(e,t,r){return e[r]??(t==null?void 0:t[r])}function Di(e,t,r){const n=e;return r.some(a=>n[a]===!0||(t==null?void 0:t[a])===!0)}function Dh(e,t){const r=Cs(e.kind);return r||(t==="tool"?"tool":"standard")}function ua(e,t,r){const n=Cc(e),a=typeof(n==null?void 0:n.label)=="string"?n.label.trim():"";return a||(t==="terminal"||r==="terminal_command"?"Terminal":t==="tool"||r==="tool_call"?"Tool":t==="thought"?"Thought":r==="runtime_activity"?"Runtime":"Activity")}function Eh(e){const t=e.content;return Array.isArray(t)&&t.some(r=>!!r&&typeof r=="object"&&r.type!=="text")}function $o(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=Cc(e),r=Cs(e.role),n=Dh(e,r),a=Cs(da(e,t,"visibility")),o=Cs(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),i=Cs(da(e,t,"audience")),c=Cs(da(e,t,"source")),d=Pi.has(a)||Pi.has(o)||_h.has(i)||Di(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),m=Ri.has(a)||Ri.has(o)||i==="chat"||Di(e,t,["userFacing"]),u=Rh.has(n)||Lh.has(c);if(d)return{surface:u?"activity":"internal",isUserFacing:!1,isActivityFacing:u,isInternal:!u,role:r,kind:n,label:ua(e,n,c)};if(m)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:ua(e,n,c)};if((r==="system"||n==="system")&&Eh(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:"Chat"};if(Ph.has(c)||r==="system"||n==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:r,kind:n,label:"Internal"};if(u)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:r,kind:n,label:ua(e,n,c)};const p=(r==="user"||r==="human"||r==="assistant")&&(n==="standard"||n==="");return{surface:p?"chat":"internal",isUserFacing:p,isActivityFacing:!1,isInternal:!p,role:r,kind:n,label:p?"Chat":"Internal"}}function $h(e){return(Array.isArray(e)?e:[]).filter(t=>$o(t).isUserFacing)}function Mc(e){return(Array.isArray(e)?e:[]).filter(t=>$o(t).isActivityFacing)}function Bh(e,t,r){return!r||t.length===0?e:[...e,...t].sort((n,a)=>{const o=Number(n.receivedAt??n.timestamp??0)||0,i=Number(a.receivedAt??a.timestamp??0)||0;if(o!==i)return o-i;const c=Number(n.index??0)||0,d=Number(a.index??0)||0;return c-d})}function Ei(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(Nc))==="1"}catch{return!1}}const Ic=[fm,{singleTilde:!1}],Tc=[Ic,xm,bm],Oh=[Ic],Bo=200,Fh=80,$i=650,Vs=new Map;function _n(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function Hh(e,t){if(!Array.isArray(e)||e.length===0)return"0:empty";const r=String(t||"").trim();if(r)return`${e.length}:${r}`;const n=e[e.length-1];return`${e.length}:${ih(n)}`}function Wh(e,t,r,n){return e||!t?!1:_n(r,n)}function Kh({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=Fh,bottomThresholdPx:a=Bo}){const o=Math.max(0,Number(e)||0),i=Math.max(0,Number(t)||0),c=Math.max(0,Number(r)||0);return Math.max(0,i-c)<=0?{showTop:!1,showBottom:!1}:{showTop:o>n,showBottom:Math.max(0,i-o-c)>a}}function Uh(e){return Kh({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function cr(e,t=Bo){return!!e&&e.fromBottom>=t}function zh(e,t){return _n(e,t)?!cr(e):!0}function Gh({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function Vh({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function ma(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function Ac(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function qh(e,t,r){return Number(e.receivedAt||r[Ln(e,t)]||0)||0}function _c(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Yh(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function qs(e,t){if(!e)return t;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||t}catch{return e.split(/[\\/]/).filter(Boolean).pop()||t}}function ha(e){if(typeof e.uri=="string"&&e.uri)return e.uri;if(typeof e.data=="string"&&e.data&&typeof e.mimeType=="string"&&e.mimeType)return`data:${e.mimeType};base64,${e.data}`}function Yr(e,t,r){return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2 text-sm",role:"note",children:[s.jsx("span",{className:"font-medium",children:e}),t?s.jsx("span",{className:"ml-1 break-all",children:t}):null,r?s.jsx("div",{className:"mt-1 opacity-80",style:{whiteSpace:"pre-wrap"},children:r}):null]})}function Bi(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):_c(e)?s.jsx(Ao,{remarkPlugins:Tc,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function Ys({parts:e,renderAsPreformatted:t}){return s.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return s.jsx("div",{children:Bi(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=ha(r),o=r.alt||r.description||qs(r.uri,"image");return a?s.jsx("img",{src:a,alt:o,className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):s.jsx("div",{children:Yr("Image",o,r.mimeType)},`image-fallback-${n}`)}if(r.type==="audio"){const a=ha(r);return a?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("audio",{controls:!0,src:a,className:"max-w-full"}),r.transcript?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:r.transcript}):null]},`audio-${n}`):s.jsx("div",{children:Yr("Audio",qs(r.uri,"audio"),r.transcript||r.mimeType)},`audio-fallback-${n}`)}if(r.type==="video"){const a=ha(r),o=r.title||r.name||r.alt||qs(r.uri,"video"),i=[r.transcript,r.description,r.mimeType].filter(Boolean).join(`
3
+ `);return s.jsxs("div",{className:"flex flex-col gap-1",children:[a?s.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):Yr("Video",o,i),a&&i?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:i}):null]},`video-${n}`)}if(r.type==="resource_link"){const a=r.title||r.name||qs(r.uri,"resource"),o=[r.description,r.mimeType].filter(Boolean).join(`
4
+ `);return s.jsxs("div",{className:"flex flex-col gap-1",children:[r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",download:!0,className:"underline break-all",children:a}):Yr("Resource",a,o),r.uri&&o?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:o}):null]},`resource-link-${n}`)}if(r.type==="resource"&&r.resource){const a=qs(r.resource.uri,"resource");if(r.resource.text)return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[s.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),Bi(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return s.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${n}`)}return null})})}function Ln(e,t){const r=e,n=Lo(e.content,{joiner:`
5
+ `});return[e.id?`id:${e.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",e.role?`role:${e.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${t}`].filter(Boolean).join("|")}const Xh=l.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(Ao,{remarkPlugins:Oh,children:t.text}),s.jsx("span",{className:"action-time",children:Ac(t.timestamp)})]})},(e,t)=>e.log===t.log),Jh=l.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:i,onToggleTextExpanded:c}){var C,N,O;const d=(t.role||"").toLowerCase(),m=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),p=$o(t),x=Yh(t.content)?t.content:null,w=!!(x!=null&&x.some(_=>_.type!=="text")),b=Lo(t.content,{joiner:`
6
+ `});if(p.isActivityFacing&&u!=="thought"&&u!=="tool"&&u!=="terminal"){const _=p.label||"Activity";return s.jsxs("div",{className:"self-start chat-msg-activity","data-chat-activity-row":"true",children:[s.jsxs("div",{className:"chat-msg-activity-meta","aria-label":"Activity message",children:[s.jsx("span",{className:"activity-dot"}),s.jsx("span",{children:_})]}),w&&x?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(Ys,{parts:x,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:b})]})}if(u==="thought"){const _=typeof((C=t.meta)==null?void 0:C.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":p.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(bh,{size:13}),s.jsx("span",{children:_})]}),s.jsx("div",{className:"chat-msg-body",children:b})]})}if(u==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":p.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-tool-meta","aria-label":"Tool message",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),s.jsx("span",{className:"tool-label",children:"Tool"})]}),w&&x?s.jsx("div",{className:"tool-text w-full",children:s.jsx(Ys,{parts:x,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:b})]});if(u==="terminal"){const _=(N=t.meta)!=null&&N.isRunning?"⏳":"✅",T=typeof((O=t.meta)==null?void 0:O.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":p.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:_}),s.jsx("span",{children:T})]}),w&&x?s.jsx("div",{className:"chat-msg-body",children:s.jsx(Ys,{parts:x,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:b})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:w&&x?s.jsx(Ys,{parts:x,renderAsPreformatted:!1}):b.slice(0,100)});const f=t.meta,y=(typeof(f==null?void 0:f.renderMode)=="string"?f.renderMode.trim():"")==="preformatted",h=b,j=!1,v=h,g=y,S=!g&&_c(v),M=["chat-message-row",m?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:M,children:(h||w||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${h||w?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:m?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:Ac(r)})]}),(h||w)&&s.jsx("div",{className:"chat-markdown",children:w&&x?s.jsx(Ys,{parts:x,renderAsPreformatted:g}):g?s.jsx("pre",{className:"chat-preformatted",children:v}):S?s.jsx(Ao,{remarkPlugins:Tc,children:v}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:v})}),j]})})},(e,t)=>e.message===t.message&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),Qh=l.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:o=!1,isWorking:i=!1,contextKey:c="",receivedAtMap:d={},lastMessageHash:m,showActivityMessages:u=!1,emptyState:p,onLoadMore:x,isLoadingMore:w,hasMoreHistory:b,hiddenLiveCount:f=0,loadError:k,scrollToBottomRequestNonce:y,isVisible:h=!0},j){const v=l.useRef(null),g=l.useRef(null),S=l.useRef(null),M=l.useRef(0),C=l.useRef(""),N=l.useRef(""),O=l.useRef(!1),_=l.useRef(null),T=l.useRef(!1),H=l.useRef(null),R=l.useRef(!1),[F,A]=l.useState(new Set),[I,$]=l.useState({showTop:!1,showBottom:!1}),E=l.useRef(!1),L=l.useRef(!1),U=l.useRef(h),B=l.useRef(h),K=l.useRef(null);B.current=h;const J=()=>{const oe=v.current;return oe?oe.scrollHeight-oe.scrollTop-oe.clientHeight<Bo:!0},X=l.useCallback(()=>{const oe=v.current,P=oe?Uh(oe):{showTop:!1,showBottom:!1};$(ue=>ue.showTop===P.showTop&&ue.showBottom===P.showBottom?ue:P)},[]),ae=l.useCallback((oe="auto")=>{var ue;const P=v.current;P&&(P.scrollTo({top:P.scrollHeight,behavior:oe}),(ue=P.ownerDocument.defaultView)==null||ue.requestAnimationFrame(()=>X()))},[X]),de=l.useCallback((oe="auto")=>{var ue;const P=v.current;P&&(P.scrollTo({top:0,behavior:oe}),(ue=P.ownerDocument.defaultView)==null||ue.requestAnimationFrame(()=>X()))},[X]),ke=l.useCallback(()=>{var Ie;const oe=v.current,P=(Ie=window.getSelection)==null?void 0:Ie.call(window);if(!oe||!P||P.rangeCount===0||P.isCollapsed){R.current=!1;return}const ue=P.anchorNode,Se=P.focusNode;R.current=!!(ue&&Se&&oe.contains(ue)&&oe.contains(Se))},[]),q=l.useMemo(()=>{const oe=$h(t),P=Mc(t);return Bh(oe,P,u)},[t,u]),ve=q.length===t.length?m:void 0,be=Hh(q,ve),we=l.useCallback(()=>{const oe=v.current;if(!oe||!c||!B.current)return;const P={top:oe.scrollTop,fromBottom:Math.max(0,oe.scrollHeight-oe.scrollTop-oe.clientHeight),messageFingerprint:be};K.current={contextKey:c,snapshot:P},Vs.set(c,P)},[c,be]),xe=l.useCallback((oe="auto")=>{_.current!=null&&cancelAnimationFrame(_.current),_.current=requestAnimationFrame(()=>{_.current=null,ae(oe)})},[ae]),Ce=l.useCallback(()=>{E.current=!1,T.current=!0,L.current=!0,H.current!=null&&window.clearTimeout(H.current),H.current=window.setTimeout(()=>{T.current=!1,H.current=null},$i)},[]);l.useEffect(()=>{const oe=!O.current,P=N.current!==c;if(N.current=c,oe||P){O.current=!0;const Se=c?Vs.get(c):null,Ie=!!Se&&_n(Se,be);E.current=Ie?cr(Se):!1,T.current=zh(Se,be),R.current||(Ie?requestAnimationFrame(()=>{const te=v.current;te&&(ma(te,Se),E.current=cr(Se),X(),L.current=!0)}):xe("auto")),M.current=q.length,C.current=be;return}q.length>M.current;const ue=be!==C.current;Gh({hasSelection:R.current,userScrolledUp:E.current,hasChatContentChanged:ue})&&xe("auto"),M.current=q.length,C.current=be},[be,c,q.length,xe,X]),l.useEffect(()=>{y&&(Ce(),R.current||xe("auto"))},[Ce,xe,y]),l.useEffect(()=>{const oe=U.current;oe&&!h&&we(),B.current=h,U.current=h;const P=c?Vs.get(c):null;if(Wh(oe,h,P,be)){if(!P)return;E.current=cr(P),T.current=!1,R.current||requestAnimationFrame(()=>{const ue=v.current;ue&&(ma(ue,P),X())});return}},[h,c,be,Ce,we,xe,X]),l.useEffect(()=>()=>{const oe=K.current;oe&&Vs.set(oe.contextKey,oe.snapshot),_.current!=null&&cancelAnimationFrame(_.current),H.current!=null&&window.clearTimeout(H.current)},[]),l.useEffect(()=>{const oe=g.current,P=v.current;if(!oe||!P)return;const ue=()=>{H.current!=null&&window.clearTimeout(H.current),H.current=window.setTimeout(()=>{T.current=!1,H.current=null},$i)},Se=new ResizeObserver(()=>{X();const Ie=T.current;Vh({hasSelection:R.current,userScrolledUp:E.current,contextAutoScrollActive:Ie})&&(xe("auto"),Ie&&ue())});return Se.observe(oe),P!==oe&&Se.observe(P),()=>{Se.disconnect(),H.current!=null&&(window.clearTimeout(H.current),H.current=null)}},[xe,c,X]),l.useImperativeHandle(j,()=>({scrollToBottom:(oe="smooth")=>{ae(oe)}}),[ae]),l.useEffect(()=>{const oe=v.current;if(!oe)return;let P;const ue=()=>{we(),clearTimeout(P),P=setTimeout(()=>{E.current=!J(),X()},50)};return oe.addEventListener("scroll",ue,{passive:!0}),()=>{oe.removeEventListener("scroll",ue),clearTimeout(P)}},[we,X]),l.useEffect(()=>(document.addEventListener("selectionchange",ke),()=>document.removeEventListener("selectionchange",ke)),[ke]);const Q=l.useRef(0),ge=l.useRef(!1);l.useEffect(()=>{const oe=v.current;if(!oe||!ge.current||Q.current===0)return;const P=oe.scrollHeight-Q.current;P>0&&(oe.scrollTop=P),X(),we(),Q.current=0,ge.current=!1},[q.length,we,X]),l.useEffect(()=>{if(L.current||!c)return;const oe=Vs.get(c),P=v.current;if(!(!oe||!P)){if(!_n(oe,be)){ae("auto"),L.current=!0;return}ma(P,oe),E.current=cr(oe),X(),L.current=!0}},[c,be,q.length,ae,X]);const ce=()=>{const oe=v.current;oe&&(Q.current=oe.scrollHeight),ge.current=!0,x==null||x()},ye=()=>{E.current=!0,de("smooth"),we()},me=()=>{Ce(),ae("smooth"),we()},fe=l.useMemo(()=>{const oe=q.map((Ie,te)=>({type:"message",data:Ie,index:te,ts:qh(Ie,te,d)}));if(!r||r.length===0)return oe;const P=[...r].sort((Ie,te)=>Ie.timestamp-te.timestamp).map((Ie,te)=>({type:"action",data:Ie,index:te,ts:Ie.timestamp})),ue=[];let Se=0;for(const Ie of oe){for(;Se<P.length&&Ie.ts>0&&P[Se].ts<Ie.ts;)ue.push(P[Se++]);ue.push(Ie)}for(;Se<P.length;)ue.push(P[Se++]);return ue},[q,r,d]),le=f>0||!!b,pe=f>0?`↑ Show ${Math.min(f,80)} earlier messages${f>80?` (${f} hidden)`:""}`:k?`↻ ${k}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:v,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:g,className:"chat-container-content",children:[w&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),le&&!w&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:ce,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${k&&f===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:pe})}),fe.length===0&&!le&&(p||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),fe.map(oe=>{if(oe.type==="action"){const De=oe.data;return s.jsx(Xh,{log:De},`action-${oe.index}`)}const P=oe.data,ue=oe.index,Se=Ln(P,ue),Ie=P.receivedAt||d[Se],te=`${c}-${Se}`,Ne=F.has(te);return s.jsx(Jh,{message:P,receivedAt:Ie,agentName:n,userName:a,isCliMode:o,isTextExpanded:Ne,onToggleTextExpanded:()=>A(De=>{const Ee=new Set(De);return Ne?Ee.delete(te):Ee.add(te),Ee})},`msg-${Se}`)}),i&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),s.jsx("div",{className:"min-h-10",ref:S})]})}),(I.showTop||I.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[I.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:ye,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),I.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:me,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Zh=l.memo(Qh,(e,t)=>e.messages===t.messages&&e.actionLogs===t.actionLogs&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isWorking===t.isWorking&&e.contextKey===t.contextKey&&e.receivedAtMap===t.receivedAtMap&&e.lastMessageHash===t.lastMessageHash&&e.showActivityMessages===t.showActivityMessages&&e.emptyState===t.emptyState&&e.onLoadMore===t.onLoadMore&&e.isLoadingMore===t.isLoadingMore&&e.hasMoreHistory===t.hasMoreHistory&&e.hiddenLiveCount===t.hiddenLiveCount&&e.loadError===t.loadError&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isVisible===t.isVisible),ep="modulepreload",tp=function(e){return"/"+e},Oi={},sp=function(t,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),c=(i==null?void 0:i.nonce)||(i==null?void 0:i.getAttribute("nonce"));a=Promise.allSettled(r.map(d=>{if(d=tp(d),d in Oi)return;Oi[d]=!0;const m=d.endsWith(".css"),u=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const p=document.createElement("link");if(p.rel=m?"stylesheet":ep,m||(p.as="script"),p.crossOrigin="",p.href=d,c&&p.setAttribute("nonce",c),document.head.appendChild(p),m)return new Promise((x,w)=>{p.addEventListener("load",x),p.addEventListener("error",()=>w(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return a.then(i=>{for(const c of i||[])c.status==="rejected"&&o(c.reason);return t().catch(o)})};let Fi=!1;const Lc=l.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:o="measured"},i)=>{const c=l.useRef(null),[d,m]=l.useState(null),u=l.useRef([]),p=l.useRef(!1),x=l.useRef(!1),w=l.useRef(!1),b=l.useRef(!1),f=()=>{const k=c.current;if(k){p.current&&(k.clear(),p.current=!1);for(const y of u.current)k.write(y.data,y.onProcessed);u.current=[],x.current&&(k.fit(),x.current=!1),w.current&&(k.bumpResize(),w.current=!1),b.current&&(k.scrollToTop(),b.current=!1)}};return l.useImperativeHandle(i,()=>({write:(k,y)=>{c.current?c.current.write(k,y):u.current.push({data:k,onProcessed:y})},clear:()=>{c.current?c.current.clear():(u.current=[],p.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(u.current=[],p.current=!0)},resize:(k,y)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(k,y)},fit:()=>{c.current?c.current.fit():x.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():w.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():b.current=!0},getSelection:()=>{var k,y;return((y=(k=c.current)==null?void 0:k.getSelection)==null?void 0:y.call(k))||""},getVisibleText:()=>{var k,y;return((y=(k=c.current)==null?void 0:k.getVisibleText)==null?void 0:y.call(k))||""}}),[]),l.useEffect(()=>{d&&f()},[d]),l.useEffect(()=>{let k=!1;return sp(()=>import("./terminal-C45SzZMr.js"),__vite__mapDeps([0,1,2])).then(y=>{Fi||(Fi=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),k||m(()=>y.GhosttyTerminalView)}).catch(y=>{console.error("[CliTerminal] failed to load terminal renderer",y)}),()=>{k=!0}},[]),d?s.jsx(d,{ref:c,onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:o,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});Lc.displayName="CliTerminal";function Xr({label:e,value:t,sub:r,icon:n}){return s.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsx("span",{className:"text-base flex items-center",children:n}),s.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),s.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:t}),r&&s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function Hi({value:e,max:t,label:r,color:n="#8b5cf6",detail:a,compact:o=!1}){const i=t>0?Math.min(Math.round(e/t*100),100):0,c=i>85?"#ef4444":i>60?"var(--status-warning)":n;return o?s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-0.5",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),s.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[i,"%"]})]}),s.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${i}%`,background:c}})})]}):s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-1.5",children:[s.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),s.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[i,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${i}%`,background:`linear-gradient(90deg, ${c}, ${c}cc)`}})}),a&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function rp({cursorPos:e,viewportRef:t,imgRef:r}){var h;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(h=t.current)==null?void 0:h.getBoundingClientRect();if(!o)return null;const i=n.naturalWidth||a.width,c=n.naturalHeight||a.height,d=i/c,m=a.width/a.height;let u,p,x,w;d>m?(u=a.width,p=a.width/d,x=0,w=(a.height-p)/2):(p=a.height,u=a.height*d,x=(a.width-u)/2,w=0);const b=a.left-o.left+x+u*e.nx,f=a.top-o.top+w+p*e.ny,k=Math.max(8,Math.min(o.width-8,b)),y=Math.max(8,Math.min(o.height-8,f));return s.jsxs("div",{style:{position:"absolute",left:k-8,top:y-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[s.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function np({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:i,setImeText:c,handleImeSubmit:d,isConnActive:m,zoom:u,isMobile:p,mobileFillZoom:x,onZoomOut:w,onZoomReset:b,onZoomIn:f,transportType:k,screenshotUsage:y,lastActionStatus:h}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:j=>j.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[s.jsxs("div",{onClick:t,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{n(j=>!j),o(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&s.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:s.jsx("input",{type:"text",placeholder:"Type & Enter...",value:i,autoFocus:!0,onTouchStart:j=>j.stopPropagation(),onChange:j=>c(j.target.value),onKeyDown:j=>{d(j)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{o(j=>!j),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:m?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:m?"#22c55e":"#eab308",boxShadow:m?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:m?"#22c55e":"#eab308"},children:m?"Connected":"WS"})]}),u>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),k==="direct"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),k==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),y&&y.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:y.budgetExhausted?"#ef4444":"#c4b5fd",background:y.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:y.budgetExhausted?"TURN blocked":`TURN ${y.dailyUsedMinutes}/${y.dailyBudgetMinutes}m`}),h&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:h})]})]}),a&&s.jsxs("div",{onTouchStart:j=>j.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",u<=(p?x:1)+.01?p?"FILL":"FIT":`${Math.round(u*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:j=>{j.stopPropagation(),w()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:j=>{j.stopPropagation(),b()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:p?"FILL":"FIT"}),s.jsx("button",{onClick:j=>{j.stopPropagation(),f()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function ap({waitingLabel:e,waitingHint:t,transportType:r}){return s.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[s.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-white/10 bg-white/[0.04] shadow-[0_10px_30px_rgba(0,0,0,0.35)]",style:{animation:"remote-float 2.8s ease-in-out infinite"},children:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),s.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),s.jsx("div",{className:"text-[11px] text-white/40",children:t}),r==="relay"&&s.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function op(){if(typeof window>"u")return!1;try{return window.__ADHDEV_DEBUG_RENDERS__===!0||window.localStorage.getItem("adhdev_debug_renders")==="1"}catch{return window.__ADHDEV_DEBUG_RENDERS__===!0}}function Wi(e){return e==null||typeof e=="number"||typeof e=="boolean"?e:typeof e=="string"?e.length>64?`${e.slice(0,61)}...`:e:Array.isArray(e)?`Array(${e.length})`:typeof e=="object"?"Object":typeof e}function Ar(e,t){const r=l.useRef(null),n=l.useRef(0);l.useEffect(()=>{if(!op())return;n.current+=1;const a=r.current;if(!a){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([i,c])=>[i,Wi(c)]))}),r.current=t;return}const o=Object.keys({...a,...t}).filter(i=>!Object.is(a[i],t[i]));o.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:o,snapshot:Object.fromEntries(o.map(i=>[i,Wi(t[i])]))}),r.current=t})}function ip({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:i,panXRef:c,panYRef:d,setPanX:m,setPanY:u,setZoom:p,lastWheelTimeRef:x,onAction:w,setLastActionStatus:b,spawnRippleFromNormalized:f,clampPan:k,isMobile:y,mobileFillZoom:h}){const[j,v]=l.useState(null),g=l.useRef(null),S=l.useRef(null),M=l.useRef(null),C=l.useRef(!1),N=l.useRef(null),O=l.useRef(0),_=l.useRef(null),T=l.useRef(1),H=l.useRef({x:0,y:0}),R=l.useRef(!1),F=l.useRef(n),A=l.useRef(w),I=30,$=550,E=18,L=60,U=400,B=12,K=()=>{if(g.current)return;const ae={nx:.5,ny:.5};g.current=ae,v(ae)};return l.useEffect(()=>{F.current=n,n==="mouse"&&K()},[n]),l.useEffect(()=>{A.current=w},[w]),l.useEffect(()=>{const ae=e.current;if(!ae)return;const de=xe=>{if(!r.current)return null;const Ce=r.current.getBoundingClientRect();return!Ce.width||!Ce.height?null:{nx:Math.max(0,Math.min(1,(xe.clientX-Ce.left)/Ce.width)),ny:Math.max(0,Math.min(1,(xe.clientY-Ce.top)/Ce.height))}},ke=(xe,Ce)=>{if(!r.current)return{dnx:0,dny:0};const Q=r.current,ge=Q.getBoundingClientRect(),ce=Q.naturalWidth||ge.width,ye=Q.naturalHeight||ge.height,me=ce/ye,fe=ge.width/ge.height;let le,pe;return me>fe?(le=ge.width,pe=ge.width/me):(pe=ge.height,le=ge.height*me),{dnx:xe/le,dny:Ce/pe}},q=(xe,Ce,Q)=>{if(Q<=1.05)return;const ge=-(xe-.5)*100,ce=-(Ce-.5)*100,ye=k(ge,ce,Q);(Math.abs(ye.x-c.current)>.1||Math.abs(ye.y-d.current)>.1)&&(m(ye.x),u(ye.y),c.current=ye.x,d.current=ye.y)},ve=xe=>{const Ce=t.current;if(Ce&&xe.target instanceof Node&&Ce.contains(xe.target))xe.preventDefault();else return;if(xe.touches.length===1){const Q=xe.touches[0];S.current={x:Q.clientX,y:Q.clientY,time:Date.now()},M.current={x:Q.clientX,y:Q.clientY},R.current||(C.current=!1),N.current=setTimeout(()=>{if(!C.current&&!R.current)if(C.current=!0,F.current==="mouse"){const ge=g.current||{nx:.5,ny:.5};b("Right Click"),f(ge.nx,ge.ny,"right"),A.current("input_click",{...ge,button:"right"}).catch(()=>{})}else{const ge=de(Q);ge&&(b("Right Click"),f(ge.nx,ge.ny,"right"),A.current("input_click",{...ge,button:"right"}).catch(()=>{}))}},500);return}if(xe.touches.length===2){N.current&&clearTimeout(N.current),C.current=!0,R.current=!0;const Q=xe.touches[1].clientX-xe.touches[0].clientX,ge=xe.touches[1].clientY-xe.touches[0].clientY;_.current=Math.sqrt(Q*Q+ge*ge),T.current=i.current,H.current={x:(xe.touches[0].clientX+xe.touches[1].clientX)/2,y:(xe.touches[0].clientY+xe.touches[1].clientY)/2}}},be=xe=>{const Ce=t.current;if(Ce&&xe.target instanceof Node&&Ce.contains(xe.target)&&xe.preventDefault(),xe.touches.length===1&&M.current){const Q=xe.touches[0],ge=Q.clientX-M.current.x,ce=Q.clientY-M.current.y;if(!C.current&&S.current){const ye=Q.clientX-S.current.x,me=Q.clientY-S.current.y;Math.sqrt(ye*ye+me*me)>8&&(C.current=!0,N.current&&clearTimeout(N.current))}if(C.current)if(F.current==="mouse"){const ye=ke(ge,ce),me=g.current||{nx:.5,ny:.5},fe=Math.max(0,Math.min(1,me.nx+ye.dnx)),le=Math.max(0,Math.min(1,me.ny+ye.dny));g.current={nx:fe,ny:le},v({nx:fe,ny:le}),b(`Cursor: ${Math.round(fe*100)}%, ${Math.round(le*100)}%`),q(fe,le,i.current);const pe=Date.now();pe-x.current>=30&&(x.current=pe,A.current("input_mouseMoved",{nx:fe,ny:le}).catch(()=>{}))}else if(i.current>1){const ye=t.current;if(ye){const me=ye.clientWidth,fe=ye.clientHeight,le=c.current+ge/me*100,pe=d.current+ce/fe*100,oe=k(le,pe,i.current);m(oe.x),u(oe.y),c.current=oe.x,d.current=oe.y}}else{const ye=de(Q);if(ye){const me=Date.now();me-x.current>=40&&(x.current=me,b("Scroll"),A.current("input_wheel",{nx:ye.nx,ny:ye.ny,deltaX:Math.round(-ge*2.5),deltaY:Math.round(-ce*2.5)}).catch(()=>{}))}}M.current={x:Q.clientX,y:Q.clientY};return}if(xe.touches.length===2&&_.current!==null){const Q=xe.touches[1].clientX-xe.touches[0].clientX,ge=xe.touches[1].clientY-xe.touches[0].clientY,ye=Math.sqrt(Q*Q+ge*ge)/_.current,me=(xe.touches[0].clientX+xe.touches[1].clientX)/2,fe=(xe.touches[0].clientY+xe.touches[1].clientY)/2,le=me-H.current.x,pe=fe-H.current.y,oe=Math.abs(ye-1)>.03;if(F.current==="mouse"){if(oe){const P=Math.max(o,Math.min(5,T.current*ye));p(P),i.current=P}else if(Math.abs(le)>2||Math.abs(pe)>2){const P=g.current||{nx:.5,ny:.5},ue=Date.now();ue-x.current>=30&&(x.current=ue,b("Scroll"),A.current("input_wheel",{nx:P.nx,ny:P.ny,deltaX:Math.round(-le*3),deltaY:Math.round(-pe*3)}).catch(()=>{}))}}else{const P=Math.max(o,Math.min(5,T.current*ye));p(P),i.current=P;const ue=t.current;if(ue&&P>1){const Se=ue.clientWidth,Ie=ue.clientHeight,te=c.current+le/Se*100,Ne=d.current+pe/Ie*100,De=k(te,Ne,P);m(De.x),u(De.y),c.current=De.x,d.current=De.y}}H.current={x:me,y:fe}}},we=xe=>{var Ce;if(N.current&&clearTimeout(N.current),_.current=null,xe.touches.length===1&&R.current){const Q=xe.touches[0];S.current={x:Q.clientX,y:Q.clientY,time:Date.now()},M.current={x:Q.clientX,y:Q.clientY},C.current=!0;return}if(xe.touches.length===0){if(R.current){R.current=!1,C.current=!1;return}if(xe.changedTouches.length===1){const Q=xe.changedTouches[0],ge=Date.now(),ce=ge-(((Ce=S.current)==null?void 0:Ce.time)||0),ye=S.current?Q.clientX-S.current.x:0,me=S.current?Q.clientY-S.current.y:0,fe=Math.sqrt(ye*ye+me*me);if(F.current==="mouse"){if(ce<I||ce>$||fe>E){C.current=!1;return}const le=g.current||de(Q);le&&(b(`Click: ${Math.round(le.nx*100)}%, ${Math.round(le.ny*100)}%`),f(le.nx,le.ny,"left"),A.current("input_click",{...le}).catch(()=>{}))}else{if(C.current){C.current=!1;return}if(ce<L||ce>U||fe>B){C.current=!1;return}const le=de(Q);if(!le)return;ge-O.current<300?(b("Double tap"),f(le.nx,le.ny,"double"),A.current("input_click",{...le,clickCount:2}).catch(()=>{}),O.current=0):(b(`Tap: ${Math.round(le.nx*100)}%, ${Math.round(le.ny*100)}%`),f(le.nx,le.ny,"left"),A.current("input_click",{...le}).catch(()=>{}),O.current=ge)}}C.current=!1}};return ae.addEventListener("touchstart",ve,{passive:!1}),ae.addEventListener("touchmove",be,{passive:!1}),ae.addEventListener("touchend",we,{passive:!1}),()=>{ae.removeEventListener("touchstart",ve),ae.removeEventListener("touchmove",be),ae.removeEventListener("touchend",we),N.current&&clearTimeout(N.current)}},[e,t,r,o,i,c,d,m,u,p,x,b,f,k]),{cursorPos:j,cursorPosRef:g,handleToggleInputMode:()=>{a(ae=>{const de=ae==="touch"?"mouse":"touch";return de==="mouse"&&K(),de})},handleZoomReset:()=>{const ae=y?h:1;p(ae),i.current=ae,m(0),u(0),c.current=0,d.current=0}}}function Pc({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:o}){const i=l.useRef(null),c=l.useRef(null),d=l.useRef(null),[m,u]=l.useState(null),[p,x]=l.useState(""),[,w]=l.useState(!1),[b,f]=l.useState([]),k=l.useRef(0),[y,h]=l.useState(!1),[j,v]=l.useState(!1),g=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[S,M]=l.useState(g?"mouse":"touch"),[C,N]=l.useState(1),O=l.useRef(!1),[_,T]=l.useState(1),[H,R]=l.useState(0),[F,A]=l.useState(0);Ar("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:S,zoom:_,panX:H,panY:F,isMenuOpen:y,isImeOpen:j});const I=l.useRef(0),$=l.useRef(_),E=l.useRef(H),L=l.useRef(F);l.useEffect(()=>{$.current=_},[_]),l.useEffect(()=>{E.current=H},[H]),l.useEffect(()=>{L.current=F},[F]),l.useEffect(()=>{var ce;(ce=i.current)==null||ce.focus()},[]);const U=r==="connected",B=n,K=U?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",J=U?"The remote stream is warming up":"Waiting for the remote stream to catch up";l.useEffect(()=>{if(!g||O.current||!B)return;const ce=d.current,ye=c.current;if(!ce||!ye)return;const me=()=>{const fe=ye.clientWidth,le=ye.clientHeight,pe=ce.naturalWidth,oe=ce.naturalHeight;if(!pe||!oe||!fe||!le)return;const P=Math.min(fe/pe,le/oe),Se=Math.max(fe/pe,le/oe)/P;Se>1.01&&(N(Se),T(Se),$.current=Se),O.current=!0};ce.complete&&ce.naturalWidth?me():ce.addEventListener("load",me,{once:!0})},[B,g]);const X=.5;l.useEffect(()=>{_<=X&&(R(0),A(0))},[_,X]);const ae=(ce,ye,me)=>{if(me<=X)return{x:0,y:0};const fe=(me-1)/(2*me)*100,le=(me-1)/(2*me)*100;return{x:Math.max(-fe,Math.min(fe,ce)),y:Math.max(-le,Math.min(le,ye))}},de=(ce,ye)=>{if(!d.current)return null;const me=d.current.getBoundingClientRect();return!me.width||!me.height?null:{nx:Math.max(0,Math.min(1,(ce-me.left)/me.width)),ny:Math.max(0,Math.min(1,(ye-me.top)/me.height))}},ke=(ce,ye,me)=>{const fe=c.current;if(!fe)return;const le=fe.getBoundingClientRect(),pe=++k.current;f(oe=>[...oe,{id:pe,x:ce-le.left,y:ye-le.top,type:me}]),setTimeout(()=>f(oe=>oe.filter(P=>P.id!==pe)),600)},q=(ce,ye,me)=>{const fe=d.current,le=c.current;if(!fe||!le)return;const pe=fe.getBoundingClientRect(),oe=le.getBoundingClientRect(),P=fe.naturalWidth||pe.width,ue=fe.naturalHeight||pe.height,Se=P/ue,Ie=pe.width/pe.height;let te,Ne,De,Ee;Se>Ie?(te=pe.width,Ne=pe.width/Se,De=0,Ee=(pe.height-Ne)/2):(Ne=pe.height,te=pe.height*Se,De=(pe.width-te)/2,Ee=0);const ze=pe.left-oe.left+De+te*ce,Qe=pe.top-oe.top+Ee+Ne*ye,Ze=++k.current;f(rt=>[...rt,{id:Ze,x:ze,y:Qe,type:me}]),setTimeout(()=>f(rt=>rt.filter(et=>et.id!==Ze)),600)},ve=async ce=>{var me;const ye=de(ce.clientX,ce.clientY);if(ye){u(`Click: ${Math.round(ye.nx*100)}%, ${Math.round(ye.ny*100)}%`),ke(ce.clientX,ce.clientY,"left"),(me=i.current)==null||me.focus();try{const fe=await e("input_click",{nx:ye.nx,ny:ye.ny});fe!=null&&fe.success||t(`❌ Click failed: ${fe==null?void 0:fe.error}`)}catch(fe){t(`❌ Click error: ${fe.message||fe}`)}}},be=async(ce,ye,me,fe=0)=>{try{await e("input_key",{type:me?"char":"keyDown",key:ce,code:ye,text:me?ce:void 0,unmodifiedText:me?ce:void 0,modifiers:fe})}catch(le){t(`❌ Key error: ${le.message||le}`)}},we=async ce=>{if(ce.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ce.key)&&ce.preventDefault();let me=0;ce.altKey&&(me|=1),ce.ctrlKey&&(me|=2),ce.metaKey&&(me|=4),ce.shiftKey&&(me|=8),u(`Key: ${ce.key}`),await be(ce.key,ce.code,ce.key.length===1,me)},xe=async ce=>{if(ce.key==="Enter"){if(ce.nativeEvent.isComposing)return;if(p){const ye=p;x(""),u(`IME Sent: ${ye}`);try{const me=await e("input_type",{text:ye});me!=null&&me.success||t(`❌ IME error: ${me==null?void 0:me.error}`)}catch(me){t(`❌ IME error: ${me.message}`)}}else u("Key: Enter"),await be("Enter","Enter",!1)}};l.useEffect(()=>{const ce=i.current;if(!ce)return;const ye=me=>{var fe;if((fe=d.current)!=null&&fe.contains(me.target)){me.preventDefault();const le=Date.now();if(le-I.current<40)return;I.current=le;const pe=de(me.clientX,me.clientY);if(!pe)return;u(`Scroll: ${Math.round(me.deltaY)}`),e("input_wheel",{nx:pe.nx,ny:pe.ny,deltaX:Math.round(me.deltaX),deltaY:Math.round(me.deltaY)}).catch(()=>{})}};return ce.addEventListener("wheel",ye,{passive:!1}),()=>ce.removeEventListener("wheel",ye)},[e]);const{cursorPos:Ce,handleToggleInputMode:Q,handleZoomReset:ge}=ip({containerRef:i,viewportRef:c,imgRef:d,inputMode:S,setInputMode:M,minZoom:X,zoomRef:$,panXRef:E,panYRef:L,setPanX:R,setPanY:A,setZoom:T,lastWheelTimeRef:I,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:q,clampPan:ae,isMobile:g,mobileFillZoom:C});return s.jsxs("div",{ref:i,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:we,onContextMenu:ce=>ce.preventDefault(),onFocus:()=>w(!0),onBlur:()=>w(!1),tabIndex:0,children:[s.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[B?s.jsx("img",{ref:d,src:B,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${_}) translate(${H}%, ${F}%)`,transformOrigin:"center center",cursor:S==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ve,onContextMenu:ce=>ce.preventDefault(),onDragStart:ce=>ce.preventDefault()}):s.jsx(ap,{waitingLabel:K,waitingHint:J,transportType:o}),S==="mouse"&&B&&s.jsx(rp,{cursorPos:Ce,viewportRef:c,imgRef:d}),b.map(ce=>{const me={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ce.type];return s.jsxs("div",{style:{position:"absolute",left:ce.x,top:ce.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${me}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),s.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${me}, 0.9)`,boxShadow:`0 0 12px rgba(${me}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ce.id)})]}),s.jsx(np,{inputMode:S,onToggleInputMode:Q,isImeOpen:j,setIsImeOpen:v,isMenuOpen:y,setIsMenuOpen:h,imeText:p,setImeText:x,handleImeSubmit:xe,isConnActive:U,zoom:_,isMobile:g,mobileFillZoom:C,onZoomOut:()=>T(ce=>Math.max(.5,ce-.25)),onZoomReset:ge,onZoomIn:()=>T(ce=>Math.min(5,ce+.25)),transportType:o,screenshotUsage:a,lastActionStatus:m}),s.jsx("style",{children:`
7
+ @keyframes slideUp {
8
+ from { opacity: 0; transform: translateY(6px); }
9
+ to { opacity: 1; transform: translateY(0); }
10
+ }
11
+ @keyframes slideUpSidebar {
12
+ from { opacity: 0; transform: translateY(6px); }
13
+ to { opacity: 1; transform: translateY(0); }
14
+ }
15
+ @keyframes click-ripple-ring {
16
+ 0% { transform: scale(0.3); opacity: 1; }
17
+ 100% { transform: scale(2.2); opacity: 0; }
18
+ }
19
+ @keyframes click-ripple-dot {
20
+ 0% { transform: scale(1); opacity: 0.9; }
21
+ 50% { transform: scale(1.8); opacity: 0.6; }
22
+ 100% { transform: scale(0.5); opacity: 0; }
23
+ }
24
+ @keyframes remote-float {
25
+ 0% { transform: translateY(0px); }
26
+ 50% { transform: translateY(-7px); }
27
+ 100% { transform: translateY(0px); }
28
+ }
29
+ `})]})}function ea(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,o=Date.now()-e,i=Math.floor(o/1e3);if(i<a)return n;const c=Math.floor(i/60);if(c<60)return`${c}m${r}`;const d=Math.floor(c/60);if(d<24)return`${d}h${r}`;const m=Math.floor(d/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const Rc=e=>ea(e);function lp(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden,completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function Ws(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating"||e.status==="long_generating"||e.status==="streaming",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function cp(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...lp(a)})};for(const n of e)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const a of n.childSessions||[])r(a.id,a)}return t}function Pn(e,t){if(e.sessionId){const r=t.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,completionMarker:"",seenCompletionMarker:""}}function ta(e,t,r){const n=Pn(e,t),a=Ws(e),o=a.isReconnecting,i=a.isConnecting,c=a.isGenerating,d=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d,u=n.inboxBucket==="working"||c,x=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:x,requiresAction:m,isWorking:u,isReconnecting:o,isConnecting:i,isGenerating:c,isWaiting:d,inboxBucket:m?"needs_attention":u?"working":x?"task_complete":"idle"}}function dp(e,t,r){return ta(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Dc({activeConv:e,onModalButton:t}){const[r,n]=l.useState(null);if(l.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Ws(e).isWaiting||!e.modalButtons)return null;const o=c=>{r||(n(c),t(c))},i=c=>c.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return s.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&s.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[s.jsx(jr,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((c,d)=>{const m=i(c).toLowerCase(),u=/^(run|approve|accept|yes|allow|always)/.test(m),p=/^(reject|deny|delete|remove|abort)/.test(m),x=r===c,w=r!==null;return s.jsx("button",{onClick:()=>o(c),disabled:w,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${u?"font-extrabold":p?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${w&&!x?"opacity-40":"opacity-100"} ${w?"cursor-not-allowed":"cursor-pointer"}`,style:u?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:p?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:x?"⏳ ...":i(c)},d)})})]})]})}const Oo="adhdev_controls_bar_visible",lo="adhdev:controlsbarvisibilitychange";function pa(e){if(!e)return!1;try{return e.getItem(Oo)==="1"}catch{return!1}}function up(e,t){if(t)try{t.setItem(Oo,e?"1":"0")}catch{}}function mp(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(lo,{detail:{visible:e}}))}function Fo(){const[e,t]=l.useState(()=>typeof window>"u"?!1:pa(window.localStorage)),r=l.useRef(e),n=l.useCallback((i,c=!0)=>{r.current=i,t(i),typeof window<"u"&&up(i,window.localStorage),c&&mp(i)},[]);l.useEffect(()=>{const i=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:pa(window.localStorage);r.current=u,t(u)},c=d=>{if(d.key!==Oo)return;const m=pa(window.localStorage);r.current=m,t(m)};return window.addEventListener(lo,i),window.addEventListener("storage",c),()=>{window.removeEventListener(lo,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{n(i)},[n]),o=l.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:o}}var hp=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function pp(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function Tt(e,t){if(pp(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":hp.has(r)?"generating":r==="error"?"error":r==="stopped"?"stopped":r==="starting"?"starting":r==="panel_hidden"?"panel_hidden":r==="not_monitored"?"not_monitored":r==="disconnected"?"disconnected":"idle"}function co(e){return Tt(e)==="generating"}function Ki(e,t){return Tt(e,t)==="waiting_approval"}function xt(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function fp(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const r=Math.floor(t/60),n=t%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const a=Math.floor(r/24),o=r%24;return`${a}d ${o}h`}function fa(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Ec(e,t){const r=typeof t=="string"?t.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const a=n.replace(/[\\/]+$/,""),o=a.split(/[\\/]/).filter(Boolean);return o[o.length-1]||a}function xp(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const t=e.split("_"),r=t[t.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function bp(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function gp(e){return xp(e.trim().replace(/\.local$/i,""))}function yp(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function $c(e,t={}){var a,o;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(o=e.system)==null?void 0:o.hostname].find(i=>typeof i=="string"&&i.trim().length>0&&!bp(i));if(r&&r!=="Unknown")return gp(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Ct(e,t={}){return yp(e)||$c(e,t)}function Bc(e){return!e||!Array.isArray(e.items)?[]:e.items.map(t=>String((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim()).filter(Boolean)}function Oc(e,t,r={}){const n=String(t).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(o=>String((o==null?void 0:o.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function gs(e,t){return Bc(e).join(" · ")}function kr(e){return e.transport==="pty"}function Ls(e){return e.transport==="acp"}function vp(e,t){var r,n;return(r=t==null?void 0:t.providerLabels)!=null&&r[e]?t.providerLabels[e]:(n=t==null?void 0:t.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:xt(e)}function Ui(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),i=xt(r||"").trim().toLowerCase();return n===a||n===o||n===i}function wp(e,t=[],r=[]){var d,m,u,p;const n=Tt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(n==="waiting_approval")return"waiting_approval";if(n==="generating")return"generating";const a=t.find(x=>Ki(x.status,{activeModal:x.activeModal})||co(x.status));if(a)return Tt(a.status,{activeModal:a.activeModal});const o=r.find(x=>Ki(x.status,{activeModal:x.activeModal})||co(x.status));if(o)return Tt(o.status,{activeModal:o.activeModal});if(n&&n!=="idle")return n;const i=Tt((d=t[0])==null?void 0:d.status,{activeModal:(m=t[0])==null?void 0:m.activeModal});if(i!=="idle")return i;const c=Tt((u=r[0])==null?void 0:u.status,{activeModal:(p=r[0])==null?void 0:p.activeModal});return c!=="idle"?c:"idle"}function jp(e){return Tt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function kp(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),o=t.get(a),i=Tt(n.status);if(!o){t.set(a,{...n,status:i});continue}const c=r.indexOf(o.status||"idle"),d=r.indexOf(i||"idle");d>=0&&(c<0||d<c)&&t.set(a,{...n,status:i})}return Array.from(t.values())}function Sp(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function Np(e){var r,n;const t=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return t&&Sp(t.receivedAt)||0}function Cp(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function uo(e){return Math.max(Cp(e),Np(e.activeChat))}function Mp(e,t,r,n,a,o){const i=t-e;if(i!==0)return i;const c=r.localeCompare(n);return c!==0?c:a.localeCompare(o)}function Ho(e,t){return Mp(uo(e),uo(t),Ct(e,{fallbackId:e.id}),Ct(t,{fallbackId:t.id}),e.id,t.id)}const Fc="adhdev_notification_prefs",zi={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Ip(){try{const e=localStorage.getItem(Fc);if(e){const t=JSON.parse(e);return{...zi,...t}}}catch{}return{...zi}}function Tp(e){try{localStorage.setItem(Fc,JSON.stringify(e))}catch{}}let Ut=Ip(),xn=[];function Ap(){xn.forEach(e=>e())}function _p(e){Ut={...Ut,...e},Tp(Ut),Ap()}function Lp(){const[,e]=l.useState(0);l.useEffect(()=>{const r=()=>e(n=>n+1);return xn.push(r),()=>{xn=xn.filter(n=>n!==r)}},[]);const t=l.useCallback(r=>{_p(r)},[]);return[{...Ut},t]}function hr(e){if(!Ut.globalEnabled)return!1;switch(e){case"disconnect":return Ut.disconnectAlert;case"completion":return Ut.completionAlert;case"approval":return Ut.approvalAlert;case"browser":return Ut.browserNotifications;default:return!0}}const Pp={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Hc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Wc(){return"Notification"in window&&Notification.permission==="granted"}let as=null;function Rp(e){return e!==!1}async function Dp(){if(as!==null)return as;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return as=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(as=!!await e.pushManager.getSubscription(),as):(as=!1,!1)}catch{return as=!1,!1}}function mo(e,t,r){if(Wc())try{const n=new Notification(e,{body:t,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function Ep(e,t={}){const r={...Pp,...t},n=l.useRef(new Map),a=l.useRef(0),[o,i]=l.useState(null);l.useEffect(()=>{let d=!1;return Dp().then(m=>{d||i(m)}),()=>{d=!0}},[]);const c=l.useCallback((d,m,u)=>{const p=Date.now();p-a.current<r.throttleMs||(a.current=p,mo(d,m,u))},[r.throttleMs]);l.useEffect(()=>{var d;if(!(!r.enabled||!Wc())&&hr("browser")&&!Rp(o)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,Tt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const u=n.current.get(m.id),p=Tt(m.status,{activeModal:m.activeModal}),x=m.name||m.id;if(r.onApproval&&hr("approval")&&p==="waiting_approval"&&u!=="waiting_approval"){const w=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${x} — Approval needed`,w.slice(0,120),`approval-${m.id}`)}r.onComplete&&hr("completion")&&co(u)&&p==="idle"&&c(`✅ ${x} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&p==="error"&&u!=="error"&&c(`⚠️ ${x} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,p)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,c])}const $p=/^(run|approve|accept|yes|allow|always)/,Bp=/^(run|approve|accept|yes|allow|always|proceed|save)/,Op=/^(reject|deny|delete|remove|abort|cancel|no)/;function Wo(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Fp(e){const t=Wo(e).toLowerCase();return $p.test(t)?"primary":Op.test(t)?"danger":"default"}function Hp(e){return Bp.test(Wo(e).toLowerCase())?"approve":"reject"}function Wp(e){return e.map((t,r)=>({label:Wo(t),variant:Fp(t),action:Hp(t),button:t,buttonIndex:r}))}function Kp(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Up(e,t,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,t,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,t,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class zp{constructor(){We(this,"dedupMap",new Map);We(this,"DEDUP_WINDOW_MS",5e3);We(this,"DEDUP_MAX_SIZE",50);We(this,"DEDUP_CLEANUP_AGE_MS",1e4);We(this,"toastCallbacks",[]);We(this,"statusEventCallbacks",[]);We(this,"resolveActionFn",null);We(this,"viewRequestRespondFn",null);We(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,o]of this.dedupMap)r-o>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(o=>o.id===t.daemonId&&o.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const o=this.ides.find(i=>i.id===a&&i.type==="adhdev-daemon");if(o)return o}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}handleRawEvent(t,r){var b;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),o=n||t.daemonId||"",i=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),c=`${o}:${t.event}:${i}`;if(this.isDuplicate(c))return;for(const f of this.statusEventCallbacks)f(t);const d=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(d==null?void 0:d.type)||"";let u=xt(m);const p=this.resolveOwningDaemon(t);if(p){const f=Ct(p,{fallbackId:p.id});f&&(u=!m||m==="adhdev-daemon"?f:`${f}/${u}`)}let x="",w="info";if(t.event==="agent:generating_completed"){const f=t.duration?` (${t.duration}s)`:"";x=`✅ ${u} agent task completed${f}`,w="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started")if(t.event==="agent:waiting_approval"){if(x=`⚡ ${u} approval needed`,w="warning",(b=t.modalButtons)!=null&&b.length&&this.resolveActionFn){const f=this.resolveActionRouteTarget(t);if(!f)return;const k=this.resolveActionFn,y=Wp(t.modalButtons).map(v=>({label:v.label,variant:v.variant,onClick:()=>{k(f,"resolve_action",{action:v.action,button:v.button,buttonIndex:v.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),h=Kp(u,t.modalMessage,x),j=Date.now();this.emitToast({id:j,message:h,type:w,timestamp:j,targetKey:n||f,actions:y,duration:15e3}),x=""}}else if(t.event==="monitor:long_generating"){const f=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";x=`⚠️ ${u} agent is taking a long time${f}`,w="warning",hr("browser")&&!document.hasFocus()&&mo(`⚠️ ${u} — Long Running`,`Agent has been generating for over ${f.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const f=t.requesterName||"A team member",k=t.requestId,y=t.orgId;if(x=`👁️ ${f} wants to view your session`,w="warning",k&&y&&this.viewRequestRespondFn){const h=Date.now(),j=Up(y,k,this.viewRequestRespondFn,(v,g)=>console.error(`[EventManager] ${v} view request failed:`,g));this.emitToast({id:h,message:x,type:w,timestamp:h,actions:j,duration:3e4}),x=""}hr("browser")&&!document.hasFocus()&&mo("👁️ View Request",`${f} wants to view your session`,`view-request-${k}`)}else t.event==="team:view_request_approved"?(x="✅ View request approved",w="success"):t.event==="team:view_request_rejected"&&(x=`❌ ${t.targetName||"Team member"} declined your view request`,w="warning");if(x){const f=Date.now();this.emitToast({id:f,message:x,type:w,timestamp:f,targetKey:n||t.daemonId,duration:5e3})}}}const Je=new zp,Gi=new Map;function Rn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ps(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function sa(e){return Rn(e)?Rn(e.result)?e.result:e:null}function Gp(e){const t=sa(e);return!t||!Rn(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function Jr(e){const t=sa(e);return!t||!Rn(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Xs(e){const t=sa(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Qr(e){const t=sa(e);return!!t&&t.success===!1}function Vp(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";Je.showToast(n.toast.message,a);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const a=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";Je.showToast(n.notification.body,a)}}}function qp(e,t){return e&&Ps(e.currentValue)?e.currentValue:t}function Yp(e,t){return Ps(t)?Ps(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Xp(e,t){var o,i;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if(Ps(c))return c}const n=(o=t.controlValues)==null?void 0:o[e];if(Ps(n))return n;const a=(i=t.defaultValues)==null?void 0:i[e];return Ps(a)?a:void 0}function bn(e,t){return e.options||t[e.id]||[]}const Jp={antigravity:new Set(["new_session"]),"claude-cli":new Set(["compact","new_session"]),"claude-code-vscode":new Set(["new_session"]),codex:new Set(["new_session"])};function Qp(e,t,r){var n;return((n=Jp[t])==null?void 0:n.has(r.id))===!0}function Ko(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Qp(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function xa(e,t){return{value:t}}function Zp(e,t,r){var a;return r?((a=bn(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const ef={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function tf({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:i}){const{sendCommand:c}=lt(),d=`${e}:${t||n}`,m=ef[n]||"#94a3b8",[u,p]=l.useState({}),x=l.useRef({}),w=l.useRef(i);x.current=u,w.current=i;const b=l.useRef(0),f={};for(const I of o||[])I.defaultValue!==void 0&&(f[I.id]=I.defaultValue);const k={...f,...i||{},...Date.now()<b.current?u:{}};l.useEffect(()=>{i&&Date.now()>b.current&&p({})},[i]);const[y,h]=l.useState(Gi.get(d)||{}),[j,v]=l.useState(null),[g,S]=l.useState(null),M=l.useCallback(async(I,$={})=>{const E={...$,...t&&{targetSessionId:t}};return await c(e,I,E)},[e,t,c]),C=l.useCallback(async(I,$={})=>{const E=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await M("invoke_provider_script",{...E,scriptName:I,...$})},[M,n,r,t]),N=l.useCallback((I,$,E)=>{const L=qp(E,$);p(U=>({...U,[I.id]:L})),Vp(E==null?void 0:E.effects)},[]),O=l.useCallback((I,$)=>{p(E=>{const L={...E};return $===void 0?delete L[I.id]:L[I.id]=$,L}),b.current=0},[]);if(!o||o.length===0)return null;const _=Ko(o,{hostIdeType:r,providerType:n});if(_.length===0)return null;const T=async I=>{if(j===I.id){v(null);return}if(bn(I,y).length>0){v(I.id);return}if(I.dynamic&&I.listScript){S(I.id);try{const E=await C(I.listScript,{}),L=Gp(E);if(!L){const K=Xs(E);K&&Je.showToast(K,"warning");return}const U=L.options;h(K=>{const J={...K,[I.id]:U};return Gi.set(d,J),J});const B=Xp(I.id,{localOverrideUntil:b.current,localValues:x.current,controlValues:w.current,defaultValues:f});if(Yp(B,L.currentValue)){const K=L.currentValue;p(J=>({...J,[I.id]:K}))}v(I.id)}catch(E){const L=E instanceof Error?E.message:`Could not load ${I.label}`;Je.showToast(L,"warning")}finally{S(null)}}},H=async(I,$)=>{v(null);const E=(i==null?void 0:i[I.id])??f[I.id];p(L=>({...L,[I.id]:$})),b.current=Date.now()+5e3;try{if(!I.setScript)return;const L=await C(I.setScript,xa(I,$)),U=Jr(L);if(U&&!U.ok||Qr(L))throw new Error((U==null?void 0:U.error)||Xs(L)||`Could not update ${I.label}`);N(I,$,U)}catch(L){O(I,E);const U=L instanceof Error?L.message:`Could not update ${I.label}`;Je.showToast(U,"warning")}},R=async I=>{const $=bn(I,y).map(J=>J.value);if($.length===0)return;const E=String(k[I.id]||""),U=($.indexOf(E)+1)%$.length,B=$[U];if(typeof B!="string")return;const K=(i==null?void 0:i[I.id])??f[I.id];p(J=>({...J,[I.id]:B})),b.current=Date.now()+5e3;try{if(!I.setScript)return;const J=await C(I.setScript,xa(I,B)),X=Jr(J);if(X&&!X.ok||Qr(J))throw new Error((X==null?void 0:X.error)||Xs(J)||`Could not update ${I.label}`);N(I,B,X)}catch(J){O(I,K);const X=J instanceof Error?J.message:`Could not update ${I.label}`;Je.showToast(X,"warning")}},F=async I=>{const E=!k[I.id],L=(i==null?void 0:i[I.id])??f[I.id];p(U=>({...U,[I.id]:E})),b.current=Date.now()+5e3;try{if(!I.setScript)return;const U=await C(I.setScript,xa(I,E)),B=Jr(U);if(B&&!B.ok||Qr(U))throw new Error((B==null?void 0:B.error)||Xs(U)||`Could not update ${I.label}`);N(I,E,B)}catch(U){O(I,L);const B=U instanceof Error?U.message:`Could not update ${I.label}`;Je.showToast(B,"warning")}},A=async I=>{if(!I.invokeScript)return;if(I.confirmMessage){const E=[I.confirmTitle,I.confirmMessage,I.confirmLabel].filter(U=>typeof U=="string"&&U.trim().length>0);if(!window.confirm(E.join(`
30
+
31
+ `)))return}const $=(i==null?void 0:i[I.id])??f[I.id];try{const E=await C(I.invokeScript),L=Jr(E);if(L&&!L.ok||Qr(E))throw new Error((L==null?void 0:L.error)||Xs(E)||`Could not run ${I.label}`);L&&N(I,$??!0,L)}catch(E){O(I,$);const L=E instanceof Error?E.message:`Could not run ${I.label}`;Je.showToast(L,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${m}33`,background:`${m}12`,color:m},children:a}),_.map(I=>{const $=String(k[I.id]||""),E=Zp(I,y,$),L=j===I.id,U=g===I.id,B=bn(I,y),K="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium transition-colors whitespace-nowrap";switch(I.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${K} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:L?`${m}55`:"var(--border-default)",background:L?`${m}10`:"var(--surface-tertiary)",color:$?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void T(I),title:I.label,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:U?"Loading…":E||I.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),L&&B.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>v(null)}),s.jsxs("div",{className:"absolute bottom-full left-0 z-[60] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[s.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:I.label}),B.map(J=>s.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-[12px] transition-colors",style:{background:J.value===$?`${m}14`:"transparent",color:J.value===$?"var(--text-primary)":"var(--text-secondary)",borderLeft:J.value===$?`2px solid ${m}`:"2px solid transparent"},title:J.description||J.label,onMouseEnter:X=>{X.currentTarget.style.background=`${m}10`},onMouseLeave:X=>{X.currentTarget.style.background=J.value===$?`${m}14`:"transparent"},onClick:()=>void H(I,J.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:J.label}),J.value===$&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},J.value))]})]})]},I.id);case"cycle":return s.jsxs("button",{type:"button",className:`${K} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:$?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void R(I),title:`Click to cycle: ${B.map(J=>J.label).join(" → ")}`,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:E||I.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},I.id);case"toggle":return s.jsxs("button",{type:"button",className:`${K} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:$?`${m}44`:"var(--border-default)",background:$?`${m}14`:"var(--surface-tertiary)",color:$?m:"var(--text-muted)"},onClick:()=>void F(I),"aria-pressed":!!$,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),I.label]},I.id);case"action":return s.jsxs("button",{type:"button",className:`${K} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void A(I),children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:I.resultDisplay==="inline"&&$?`${I.label}: ${$}`:I.label})]},I.id);case"display":return s.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:$?"var(--text-primary)":"var(--text-muted)"},children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:$?`${I.label}: ${$}`:I.label})]},I.id);default:return null}})]})})}function sf({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:c,controlValues:d}){const{isVisible:m}=Fo(),u=Ko(c,{hostIdeType:a,providerType:o});return!e||t||u.length===0||!m?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(tf,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:u,controlValues:d})})}const Js=5,Kc=10*1024*1024;function rf({hasDraft:e,isBusy:t=!1}){return!e||t}function nf(e){return new Promise((t,r)=>{const n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(e)})}async function af(e){if(e.size>Kc)return null;const t=await nf(e),r=t.indexOf(",");if(r<0)return null;const n=t.slice(r+1);return{mimeType:e.type||"image/png",data:n,name:e.name,previewUrl:t}}function of(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const Uc=l.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,onSend:i,onForceSend:c,canForceSend:d=!1,isActive:m=!0,showControlsToggle:u=!1,animateVisibility:p=!0,onControlsToggle:x,messageInput:w}){const b=l.useRef(null),f=l.useRef(null),[k,y]=l.useState(""),[h,j]=l.useState([]),[v,g]=l.useState(null),[S,M]=l.useState(!1),C=l.useRef(!1),{isVisible:N,toggleVisibility:O}=Fo(),_=of(w),T=!!k.trim()||h.length>0;l.useEffect(()=>{y(""),j([]),g(null)},[t]),l.useEffect(()=>{var L;m&&((L=b.current)==null||L.focus({preventScroll:!0}))},[t,m]);const H=l.useCallback(async L=>{g(null);const U=Array.from(L).filter(de=>de.type.startsWith("image/"));if(U.length===0)return;const B=Js-h.length;if(B<=0){g(`Max ${Js} images`);return}const K=U.slice(0,B);if(K.filter(de=>de.size>Kc).length>0){g("Image too large (max 10 MB)");return}const ae=(await Promise.all(K.map(af))).filter(de=>de!==null);j(de=>[...de,...ae])},[h.length]),R=l.useCallback(L=>{j(U=>U.filter((B,K)=>K!==L))},[]),F=l.useCallback(async()=>{const L=k.trim();if(!L&&h.length===0||a||C.current)return;C.current=!0;const U=h.length>0?[...h]:void 0;try{await i(L,U)!==!1&&(y(""),j([]),g(null))}finally{C.current=!1}},[k,h,a,i]),A=l.useCallback(async()=>{if(!d||!c)return;const L=k.trim();if(!L&&h.length===0||C.current)return;C.current=!0;const U=h.length>0?[...h]:void 0;try{await c(L,U)!==!1&&(y(""),j([]),g(null))}finally{C.current=!1}},[h,d,k,c]),I=l.useCallback(L=>{_&&(L.preventDefault(),M(!0))},[_]),$=l.useCallback(()=>M(!1),[]),E=l.useCallback(L=>{_&&(L.preventDefault(),M(!1),L.dataTransfer.files.length>0&&H(L.dataTransfer.files))},[_,H]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",p?"transition-all duration-200 ease-out":"",S?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:m?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:m?200:0,opacity:m?1:0,transform:m?"translateY(0)":"translateY(10px)",padding:m?"10px 12px":"0 12px",pointerEvents:m?"auto":"none"},"aria-hidden":!m,onDragOver:I,onDragLeave:$,onDrop:E,children:[h.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:h.map((L,U)=>s.jsxs("div",{className:"relative group w-14 h-14 rounded-lg overflow-hidden border border-border-subtle shrink-0",style:{background:"var(--surface-secondary)"},children:[s.jsx("img",{src:L.previewUrl,alt:L.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>R(U),className:"absolute top-0.5 right-0.5 w-4 h-4 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-[10px] leading-none","aria-label":`Remove ${L.name}`,children:"✕"})]},U))}),s.jsxs("div",{className:"flex gap-2 items-center",title:m?`Send message to ${r}`:void 0,children:[u&&s.jsx("button",{type:"button",onClick:()=>{O(),x==null||x()},"aria-label":N?"Hide controls":"Show controls","aria-pressed":N,title:N?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:s.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),_&&s.jsxs(s.Fragment,{children:[s.jsx("input",{ref:f,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:L=>{L.target.files&&H(L.target.files),L.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var L;return(L=f.current)==null?void 0:L.click()},disabled:h.length>=Js,title:h.length>=Js?`Max ${Js} images`:"Attach image",className:"h-10 w-8 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center disabled:opacity-40","aria-label":"Attach image",children:s.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"})})})]}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("input",{ref:b,type:"text",placeholder:o||(_&&h.length>0?"Add a message (optional)...":`Send message to ${r}...`),value:k,onChange:L=>y(L.target.value),onPaste:L=>{if(_&&L.clipboardData.files.length>0&&Array.from(L.clipboardData.files).some(K=>K.type.startsWith("image/"))){L.preventDefault(),H(L.clipboardData.files);return}const U=L.clipboardData.getData("text");U&&y(B=>B+U),L.preventDefault()},onKeyDown:L=>{if(L.key==="Enter"){if(L.nativeEvent.isComposing){L.preventDefault();return}L.preventDefault(),F()}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),s.jsx("button",{onClick:()=>{F()},disabled:rf({hasDraft:T,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${T&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:T&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":"Send message",children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:T?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})}),d&&s.jsx("button",{type:"button",onClick:()=>{A()},disabled:!T,className:`h-10 px-3 rounded-full text-[11px] font-medium border border-border-subtle shrink-0 transition-colors ${T?"bg-bg-secondary text-text-primary hover:bg-[var(--surface-tertiary)]":"bg-bg-secondary text-text-muted cursor-default opacity-60"}`,"aria-label":"Force send message now",title:"Force send message now",children:"Force"})]}),(v||_&&S)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${v?"text-red-400":"text-[var(--accent-primary)]"}`,children:v||"Drop image here"}),o&&!v&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:o})]})});function Vi(e){if(!e||!Number.isFinite(e))return"—";try{return`${new Date(e).toLocaleString()} (${e})`}catch{return String(e)}}function qi(e){if(!e)return"";const t=Date.now()-e;if(t<0)return"";const r=Math.floor(t/1e3);if(r<60)return`${r}s ago`;const n=Math.floor(r/60);if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function lf({sessionId:e,daemonId:t,onClose:r}){const{sendCommand:n}=lt(),[a,o]=l.useState(!0),[i,c]=l.useState(null),[d,m]=l.useState(null),u=l.useCallback(async()=>{o(!0),m(null);try{const p=await n(t,"get_session_info",{targetSessionId:e}),x=p&&typeof p=="object"?p:{},w=x.result&&typeof x.result=="object"?x.result:x;w!=null&&w.success?c(w):(m((w==null?void 0:w.error)||"Failed to load session info"),c(null))}catch(p){m((p==null?void 0:p.message)||String(p)),c(null)}finally{o(!1)}},[n,t,e]);return l.useEffect(()=>{u()},[u]),l.useEffect(()=>{const p=x=>{x.key==="Escape"&&r()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[r]),s.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Session info",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onClick:r,style:{pointerEvents:"auto"},children:s.jsxs("div",{className:"bg-[var(--surface-primary)] text-text-primary border border-border-default rounded-lg shadow-xl max-w-2xl w-full max-h-[85vh] flex flex-col",onClick:p=>p.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-border-subtle px-4 py-3",children:[s.jsx("h2",{className:"text-base font-semibold",children:"Session info"}),s.jsx("button",{type:"button",onClick:r,className:"text-text-secondary hover:text-text-primary px-2 py-1 rounded","aria-label":"Close",children:"×"})]}),s.jsxs("div",{className:"overflow-y-auto px-4 py-3 text-sm space-y-4",children:[a&&s.jsx("div",{className:"text-text-secondary",children:"Loading…"}),d&&s.jsx("div",{className:"text-red-500",children:d}),(i==null?void 0:i.session)&&s.jsxs(Yi,{title:"Session",children:[s.jsx(Lt,{k:"Session ID",v:s.jsx(Qs,{children:i.session.sessionId})}),s.jsx(Lt,{k:"Provider",v:`${i.session.providerName||i.session.providerType} (${i.session.providerType})`}),i.session.transport&&s.jsx(Lt,{k:"Transport",v:i.session.transport}),i.session.workspace&&s.jsx(Lt,{k:"Workspace",v:s.jsx(Qs,{children:i.session.workspace})}),s.jsx(Lt,{k:"Spawned at",v:s.jsxs(s.Fragment,{children:[Vi(i.session.spawnedAtMs),i.session.spawnedAtMs?s.jsx("span",{className:"text-text-secondary ml-2",children:qi(i.session.spawnedAtMs)}):null]})}),i.session.providerSessionId&&s.jsx(Lt,{k:"Provider session ID",v:s.jsx(Qs,{children:i.session.providerSessionId})})]}),(i==null?void 0:i.coordinator)&&s.jsxs(Yi,{title:"Mesh coordinator",children:[s.jsx(Lt,{k:"Mesh ID",v:s.jsx(Qs,{children:i.coordinator.meshId})}),i.coordinator.cliType&&s.jsx(Lt,{k:"Coordinator CLI",v:i.coordinator.cliType}),s.jsx(Lt,{k:"Started at",v:s.jsxs(s.Fragment,{children:[Vi(i.coordinator.startedAt),i.coordinator.startedAt?s.jsx("span",{className:"text-text-secondary ml-2",children:qi(i.coordinator.startedAt)}):null]})}),i.coordinator.injection&&s.jsx(Lt,{k:"Prompt injection",v:`${i.coordinator.injection.mode}${i.coordinator.injection.target?` → ${i.coordinator.injection.target}`:""}`}),i.coordinator.mcpConfigPath&&s.jsx(Lt,{k:"MCP config",v:s.jsx(Qs,{children:i.coordinator.mcpConfigPath})}),i.coordinator.extraSystemPrompt&&s.jsx(Xi,{title:"Per-launch extra prompt",body:i.coordinator.extraSystemPrompt,defaultOpen:!0}),i.coordinator.systemPrompt&&s.jsx(Xi,{title:"Final system prompt (click to expand)",body:i.coordinator.systemPrompt})]}),i&&!i.coordinator&&s.jsx("div",{className:"text-text-secondary italic",children:"This isn't a mesh coordinator session, so no coordinator-specific prompt was injected. The agent runs with whatever defaults its CLI ships with."})]}),s.jsxs("div",{className:"border-t border-border-subtle px-4 py-2 flex justify-end gap-2",children:[s.jsx("button",{type:"button",onClick:()=>void u(),className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:"px-3 py-1 text-sm rounded bg-accent text-white hover:opacity-90",children:"Close"})]})]})})}function Yi({title:e,children:t}){return s.jsxs("div",{children:[s.jsx("h3",{className:"text-xs uppercase tracking-wide text-text-secondary mb-1",children:e}),s.jsx("div",{className:"space-y-1",children:t})]})}function Lt({k:e,v:t}){return s.jsxs("div",{className:"flex gap-3",children:[s.jsx("div",{className:"w-44 shrink-0 text-text-secondary",children:e}),s.jsx("div",{className:"min-w-0 break-all",children:t})]})}function Qs({children:e}){return s.jsx("code",{className:"font-mono text-xs",children:e})}function Xi({title:e,body:t,defaultOpen:r=!1}){const[n,a]=l.useState(r);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:()=>a(o=>!o),className:"text-xs uppercase tracking-wide text-text-secondary hover:text-text-primary",style:{pointerEvents:"auto"},children:[n?"▾":"▸"," ",e]}),n&&s.jsx("pre",{className:"mt-1 p-2 bg-[var(--surface-secondary)] border border-border-subtle rounded text-xs whitespace-pre-wrap overflow-x-auto max-h-96 overflow-y-auto",children:t})]})}function cf({sessionId:e,daemonId:t}){const[r,n]=l.useState(!1);return!e||!t?null:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:()=>n(!0),title:"Session info — system prompt, MCP config, spawned at, …","aria-label":"Session info",className:"inline-flex items-center justify-center w-6 h-6 rounded-full text-text-secondary hover:text-text-primary hover:bg-surface-secondary text-sm leading-none",style:{pointerEvents:"auto"},children:"ⓘ"}),r&&s.jsx(lf,{sessionId:e,daemonId:t,onClose:()=>n(!1)})]})}const Ye=e=>e.transport==="pty",Ks=(e,t)=>Ye(e)?e.mode||"terminal":"chat",zc=(e,t)=>Ye(e)&&Ks(e)==="terminal",Ve=e=>e.transport==="acp",df=180;function ts(e){return e.streamSource!=="agent-stream"}function js(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Gc(e){return e.machineName||""}function _r(e){return js(e)}function Kt(e){return e.agentType||""}function Dn(e){return e.hostIdeType||""}function Uo(e){return e.displayPrimary||e.agentName||"Agent"}function Vc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function uf(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function qc(e){const t=uf(e),r=Es(t==null?void 0:t.content),n=Es(e.lastMessagePreview);return r||n||""}function mf(e,t=df){const r=Es(e);if(!r||t<=0)return"";const n=Array.from(r);return n.length<=t?r:`${n.slice(0,Math.max(0,t-1)).join("").trimEnd()}…`}function hf(e){return mf(qc(e)||e.displaySecondary||"")}function Yc(e){return[e.displaySecondary,Gc(e)].filter(Boolean)}function Os(e){return e.agentName||xt(Kt(e))}function pf(e){var t,r;if(!ts(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return xt(Dn(e)||Kt(e))}function Xc(e){return ts(e)?e.sessionId:e.nativeSessionId}function Ji(e){return ts(e)?"native":e.tabKey}function ff(e){return e.sessionId}function xf(e,t){if(t)return ts(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function bf(e,t){const r=Kt(e),n=ts(e),a=Ye(e)||Ve(e),o=n?a?Os(e)||(t==null?void 0:t.cliName)||xt(Dn(e)||r):t!=null&&t.type?xt(t.type):xt(Dn(e)||r):Os(e);return{isNativeConversation:n,isCli:Ye(e),isAcp:Ve(e),isCliTerminal:zc(e),providerType:r,displayLabel:o,targetEntry:xf(e,t)}}function ds(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:Ye(e)||Ve(e)?{agentType:Kt(e)}:e.streamSource==="agent-stream"?{agentType:Kt(e)}:t}function us(e){return e?_r(e):""}function Zs(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function zo(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Qi(e){const t=e instanceof Error?e.message:String(e||""),r=t.toLowerCase();return r.includes("still processing the previous prompt")?"Message queued and will send after the current reply finishes.":r.includes("awaiting confirmation")?"Resolve the pending approval prompt before sending another message.":r.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":r.includes("not running")?"Runtime is not available right now.":t||"Unable to send message right now."}function Jc(){return"select_session"}function gf(){return"open_panel"}function yf({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function Zi(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Zr(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function pr(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Go(e){return e instanceof Error?e.message:String(e||"")}function el(e){const t=Go(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function tl(e,t){const r=Go(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function sl(e,t,r,n={}){const a=ds(r);if(!t||t.length===0)return{message:e,...n.force?{force:!0}:{},...a};const o=t.map(i=>({type:"image",mimeType:i.mimeType,data:i.data,alt:i.name}));return e&&o.push({type:"text",text:e}),{message:e,input:{parts:o,textFallback:e},...n.force?{force:!0}:{},...a}}function ra({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,o]=l.useState(!1),[i,c]=l.useState(!1),[d,m]=l.useState(null),u=l.useRef(!1),p=l.useRef(null);l.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const x=l.useCallback(async(y,h)=>{if(!t||u.current)return!1;const j=y.trim(),v=zo(t);if(yf({hasMessage:!!j,blockedMessage:v,sendInFlight:u.current}))return v&&m(v),!1;const g=Date.now(),S={tabKey:t.tabKey,message:j,timestamp:g};if(Zi(p.current,S))return m(null),!0;u.current=!0,c(!0),m(null),p.current=S;try{const M=us(t);if(!M)return p.current=Zr(p.current,S),m("Unable to send message right now."),!1;const C=await e(M,"send_chat",sl(j,h,t)),N=pr(C);if(N!=null&&N.deduplicated)return m(null),!0;if((N==null?void 0:N.sent)===!1)throw new Error((N==null?void 0:N.error)||"Send failed");if((N==null?void 0:N.success)===!1)throw new Error((N==null?void 0:N.error)||"Send failed");return m(null),!0}catch(M){const C=Go(M);return C.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",C):console.warn("Send blocked/failed",M),p.current=Zr(p.current,S),m(Qi(M)),!1}finally{u.current=!1,c(!1)}},[t,e]),w=l.useCallback(async(y,h)=>{if(!t||u.current)return!1;const j=y.trim();if(!j&&(!h||h.length===0))return!1;const v=Date.now(),g={tabKey:t.tabKey,message:`force:${j}`,timestamp:v};if(Zi(p.current,g))return m(null),!0;u.current=!0,c(!0),m(null),p.current=g;try{const S=us(t);if(!S)return p.current=Zr(p.current,g),m("Unable to send message right now."),!1;const M=await e(S,"send_chat",sl(j,h,t,{force:!0})),C=pr(M);if((C==null?void 0:C.success)===!1||(C==null?void 0:C.sent)===!1)throw new Error((C==null?void 0:C.error)||"Send failed");return m(null),!0}catch(S){return console.warn("Force send blocked/failed",S),p.current=Zr(p.current,g),m(Qi(S)),!1}finally{u.current=!1,c(!1)}},[t,e]),b=l.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(y){console.error("Relaunch failed",y)}},[t,e]),f=l.useCallback(async y=>{if(t)try{const j=(t.modalButtons||[]).indexOf(y),v=y.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),g=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(v),S=us(t);if(!S)return;const M=await e(S,"resolve_action",{button:y,action:g?"approve":"reject",...j>=0&&{buttonIndex:j},...ds(t)}),C=pr(M);C.success||r(N=>[...N,{routeId:t.tabKey,text:tl(y,C==null?void 0:C.error),timestamp:Date.now()}])}catch(h){el(h)||console.error("[ModalButton] Error:",h),r(j=>[...j,{routeId:t.tabKey,text:el(h)?tl(y,h):`❌ **${y}** error`,timestamp:Date.now()}])}},[t,e,r]),k=l.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,gf(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(y){console.error("Focus agent failed",y)}finally{o(!1)}}},[t,a,e]);return{isSendingChat:i,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:x,handleForceSendChat:w,handleRelaunch:b,handleModalButton:f,handleFocusAgent:k}}const vf=10,wf=8e3,jf=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function kf(e){return e.replace(/(Authorization\s*:\s*Bearer\s+)[^\s'"`]+/gi,"$1[REDACTED:bearer]").replace(/(Bearer\s+)[A-Za-z0-9._~+\/-]{12,}=*/gi,"$1[REDACTED:bearer]").replace(/\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]{20,}\b/g,"[REDACTED:github-token]").replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:api-key]").replace(/\b(?:adk|adm)_[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:adhdev-token]").replace(/((?:api[_-]?key|token|secret|password|passwd|client[_-]?secret)\s*[:=]\s*)[^\s,'"`}&]+/gi,"$1[REDACTED:secret]").replace(/([?&](?:api[_-]?key|token|secret|password|client_secret)=)[^&#\s]+/gi,"$1[REDACTED:secret]")}function ho(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(jf.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=kf(e);return n.length>8e3?`${n.slice(0,8e3)}…[truncated ${n.length-8e3} chars]`:n}if(typeof e!="object")return String(e);if(r>=6)return"[MaxDepth]";if(Array.isArray(e)){const n=e.slice(-20).map(a=>ho(a,t,r+1));return e.length>20?[{truncatedBefore:e.length-20},...n]:n}return Object.fromEntries(Object.entries(e).slice(0,80).map(([n,a])=>[n,ho(a,n,r+1)]))}function er(e,t){return Array.isArray(e)?e.slice(-t):[]}function Sf(e,t=Date.now()){const r=e&&t-e.firstAt<=wf,n=r?e.count+1:1;return n>=vf?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function Qc(e){var n,a;const{activeConv:t}=e,r={version:1,createdAt:new Date(e.now??Date.now()).toISOString(),url:e.locationHref??(typeof window<"u"?window.location.href:void 0),activeConversation:{routeId:t.routeId,tabKey:t.tabKey,sessionId:t.sessionId,providerSessionId:t.providerSessionId,transport:t.transport,agentName:t.agentName,agentType:t.agentType,hostIdeType:t.hostIdeType,status:t.status,connectionState:t.connectionState,title:t.title,workspaceName:t.workspaceName,displayPrimary:t.displayPrimary,displaySecondary:t.displaySecondary,streamSource:t.streamSource,lastMessageHash:t.lastMessageHash},messageCounts:{live:((n=e.chatTailState.liveMessages)==null?void 0:n.length)??t.messages.length,activeConversation:t.messages.length,visible:e.visibleMessages.length,history:((a=e.chatTailState.historyMessages)==null?void 0:a.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:er(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:er(t.messages,10),visibleMessagesTail:er(e.visibleMessages,5),historyMessagesTail:er(e.chatTailState.historyMessages,5),actionLogsTail:er(e.actionLogs.filter(o=>o.routeId===t.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chatTail:{hasLiveSnapshot:!!e.chatTailState.hasLiveSnapshot,hasMoreHistory:!!e.chatTailState.hasMoreHistory,historyError:e.chatTailState.historyError||null},ui:e.ui,browser:typeof navigator<"u"?{userAgent:navigator.userAgent,language:navigator.language,online:navigator.onLine}:null};return ho(r)}function Zc(e,t={}){const r=e&&typeof e=="object"?e:{},n=t.locatorCopyStatus??(t.locatorCopied===!1?"failed":"copied"),a=n==="copied"?"locator copied":n==="manual"?"locator shown for manual copy":"locator copy failed";return r.delivery==="daemon_file"?`Chat debug signal sent${typeof r.bundleId=="string"&&r.bundleId.trim()?` (${r.bundleId})`:""}; saved on daemon, ${a}.`:`Chat debug signal sent; ${a}.`}async function ed(e){var t;if(typeof navigator<"u"&&((t=navigator.clipboard)!=null&&t.writeText)&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(e),"copied"}catch(r){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",r)}if(typeof document<"u"&&document.body){let r=null;try{if(r=document.createElement("textarea"),r.value=e,r.setAttribute("readonly","true"),r.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(r),r.focus(),r.select(),document.execCommand("copy"))return"copied"}catch{}finally{r==null||r.remove()}}if(typeof window<"u"&&typeof window.prompt=="function")try{return window.prompt("Copy ADHDev chat debug locator:",e),"manual"}catch{}return"failed"}function td(e){const t=e&&typeof e=="object"?e:{};if(t.delivery==="daemon_file"){const r=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(t.bundleId||"")}`,`savedPath: ${String(t.savedPath||"")}`,`sizeBytes: ${String(t.sizeBytes||"")}`,`createdAt: ${String(t.createdAt||"")}`];return t.summary&&typeof t.summary=="object"&&r.push("","summary:",JSON.stringify(t.summary,null,2)),Array.isArray(t.warnings)&&t.warnings.length>0&&r.push("","warnings:",...t.warnings.map(n=>`- ${String(n)}`)),r.join(`
32
+ `)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
33
+
34
+ \`\`\`json
35
+ ${JSON.stringify(t.bundle,null,2)}
36
+ \`\`\``:`# ADHDev Chat Debug Bundle
37
+
38
+ \`\`\`json
39
+ ${JSON.stringify(t,null,2)}
40
+ \`\`\``}function ba(e,t){return`${e}:${t}`}function Nf(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function tr(e,t){Nf()&&console.debug(`[subscription-manager] ${e}`,t)}class Cf{constructor(){We(this,"active",new Map);We(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var u;const i=ba(n.topic,n.key),c=this.active.get(i);let d=!0;if(c)c.handlers.add(a),c.lastUpdate&&a(c.lastUpdate);else{const p={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,p),tr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((u=t.sendData)==null?void 0:u.call(t,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(i,t,o.retryIntervalMs)}const m=()=>{var w;this.clearRetry(i);const p=this.active.get(i);if(!p||(p.handlers.delete(a),p.handlers.size>0))return;this.active.delete(i);const x={type:"unsubscribe",topic:n.topic,key:n.key};tr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(w=t.sendData)==null||w.call(t,r,x)};return m.initialSendAccepted=d,m}publish(t){const r=ba(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Ds.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),n.handlers.forEach(a=>{a(t),Ds.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,r,n){const a=ba(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;tr("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=t.sendData)==null||r.call(t,n.daemonId,n.request)}resubscribeForDaemon(t,r){var a;const n=Array.from(this.active.values()).filter(o=>o.daemonId===t);tr("resubscribe_daemon",{daemonId:t,count:n.length,subscriptions:n.map(o=>({topic:o.request.topic,key:o.request.key}))});for(const o of n)(a=r.sendData)==null||a.call(r,o.daemonId,o.request)}scheduleRetry(t,r,n){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var c;this.retryTimers.delete(t);const o=this.active.get(t);if(!o)return;const i=((c=r.sendData)==null?void 0:c.call(r,o.daemonId,o.request))??!1;tr("subscribe_retry",{id:t,accepted:i,topic:o.request.topic,key:o.request.key}),i||this.scheduleRetry(t,r,n)},n);this.retryTimers.set(t,a)}clearRetry(t){const r=this.retryTimers.get(t);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(t))}}const Gt=new Cf;function Mf(e,t){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===t&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,mode:n.mode,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash,completionMarker:n.completionMarker,seenCompletionMarker:n.seenCompletionMarker,settings:n.settings});for(const o of n.childSessions||[]){if(!(o!=null&&o.id))continue;const i=r.get(o.id)||{};r.set(o.id,{...i,...o})}}return r}function If(e){const t=[],r=new Map;for(const n of e)if(n.parentId){const a=r.get(n.parentId)||[];a.push(n),r.set(n.parentId,a)}else t.push(n);return{topLevel:t,childrenByParent:r}}function ga(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function Tf(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function Af(e){Tf()&&console.debug("[dashboard-conversations] statusPayloadToEntries",e.map(t=>({id:t.id,daemonId:t.daemonId,sessionId:t.sessionId,instanceId:t.instanceId,providerSessionId:t.providerSessionId,transport:t.transport,type:t.type})))}function En(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:i}=t,c=i||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:m,childrenByParent:u}=If(d),p=Mf(o,n),x=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,w=m.filter(k=>k.kind==="workspace"&&k.transport==="cdp-page"),b=m.filter(k=>k.kind==="agent"&&k.transport==="pty"),f=m.filter(k=>k.kind==="agent"&&k.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:c,...e.version&&{version:e.version},...x&&{machine:x,platform:x.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:w.some(k=>!!k.cdpConnected)});for(const k of w){const y=p.get(k.id),h=lr(k,y),j=(u.get(k.id)||[]).map(v=>lr(v,p.get(v.id)));r.push({id:`${n}:ide:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,status:h.cdpConnected?"online":"detected",daemonId:n,instanceId:ga(n,k.id),workspace:h.workspace,terminals:0,childSessions:j,agents:j.map(v=>({id:v.id,name:v.providerName||v.providerType,type:v.providerType,status:v.status})),activeChat:h.activeChat,chats:[],cdpConnected:h.cdpConnected,...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},...h.settings!==void 0&&{settings:h.settings},...h.messageInput!==void 0&&{messageInput:h.messageInput},timestamp:c})}for(const k of b){const y=p.get(k.id),h=lr(k,y);r.push({id:`${n}:cli:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:ga(n,k.id),cliName:h.providerName||h.providerType,mode:h.mode||(y==null?void 0:y.mode)||"terminal",workspace:h.workspace||"",activeChat:h.activeChat,...h.resume!==void 0&&{resume:h.resume},...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},...h.settings!==void 0&&{settings:h.settings},...h.messageInput!==void 0&&{messageInput:h.messageInput},timestamp:c,_isCli:!0})}for(const k of f){const y=p.get(k.id),h=lr(k,y);r.push({id:`${n}:acp:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:ga(n,k.id),cliName:h.providerName||h.providerType,mode:"chat",workspace:h.workspace||"",activeChat:h.activeChat,...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},...h.settings!==void 0&&{settings:h.settings},...h.messageInput!==void 0&&{messageInput:h.messageInput},timestamp:c,_isAcp:!0})}return Af(r),r}const _f=15e3,Lf=15e3,Pf=6e4,Rf=1200,rl=12,Df=8e3,Ef=4e3,ya=new Map,va=new Map,en=new Set,fr=new Map;function $f(e){if(!e||typeof e!="object")return null;const t=e,r=t.status;if(r&&typeof r=="object")return r;const n=t.result;if(n&&typeof n=="object"&&"status"in n){const a=n.status;if(a&&typeof a=="object")return a}return t}function nl(e,t){const r=fr.get(e);!r||r.size===0||(fr.delete(e),r.forEach(n=>n(t)))}function Bf(e,t){return new Promise(r=>{const n=fr.get(e)||new Set;fr.set(e,n);const a=i=>{clearTimeout(o),n.delete(a),n.size===0&&fr.delete(e),r(i)},o=setTimeout(()=>a(!1),t);n.add(a)})}function Lr(){const{sendCommand:e,sendData:t}=lt(),{injectEntries:r,getIdes:n}=wr();return l.useCallback(async(a,o)=>{if(!a)return;const i=(o==null?void 0:o.minFreshMs)??Pf,c=va.get(a)||0;if(!(o!=null&&o.force)&&en.has(a)&&c>0||!(o!=null&&o.force)&&c>0&&Date.now()-c<i)return;const d=ya.get(a);if(d)return d;const m=(async()=>{if(t&&!en.has(a)){const f=Gt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},k=>{const y=n(),h=y.find(v=>v.id===a),j=En(k.status,{daemonId:a,existingDaemon:h,existingEntries:y,timestamp:k.timestamp});j.length>0&&r(j),va.set(a,Date.now()),nl(a,!0)});if(f.initialSendAccepted?en.add(a):en.delete(a),!(o!=null&&o.force)&&f.initialSendAccepted&&await Bf(a,Rf))return}const u=await e(a,"get_status_metadata"),p=$f(u);if(!p)return;const x=n(),w=x.find(f=>f.id===a),b=En(p,{daemonId:a,existingDaemon:w,existingEntries:x,timestamp:p.timestamp||Date.now()});b.length>0&&r(b,{authoritativeDaemonIds:[a]}),va.set(a,Date.now()),nl(a,!0)})().finally(()=>{ya.delete(a)});return ya.set(a,m),m},[n,r,e,t])}function Of(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const Ff=60,Hf=50;function sd(e={}){return e.isCliLike?Hf:Ff}function Wf(e={}){return sd(e)}function bt(e){return(typeof e=="string"?e.trim():"")||void 0}function zt(e,t){const r=bt(t);return r?`${e}:${r}`:void 0}function Zt(e,t,r){const n=zt(t,r),a=bt(r);n&&e.push(n),a&&e.push(a)}function As(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function rd(e){return bt(e.providerSessionId)||bt(e.sessionId)||bt(e.tabKey)||bt(e.routeId)}function na(e){return As([bt(e.historySessionId),bt(e.providerSessionId),bt(e.sessionId)])}function Vt(e){const t=[];return Zt(t,"provider",e.providerSessionId),Zt(t,"session",e.sessionId),Zt(t,"tab",e.tabKey),Zt(t,"route",e.routeId),As(t)}function Kf(e){const t=[];return bt(e.providerSessionId)?(Zt(t,"provider",e.providerSessionId),As(t)):bt(e.sessionId)?(Zt(t,"session",e.sessionId),As(t)):bt(e.tabKey)?(Zt(t,"tab",e.tabKey),As(t)):bt(e.routeId)?(Zt(t,"route",e.routeId),As(t)):[]}function Sr(e){return zt("provider",e.providerSessionId)||zt("session",e.sessionId)||zt("tab",e.tabKey)||zt("route",e.routeId)||"unknown:"}function Pr(e){return na(e)[0]}function Uf(e){const t=bt(e.providerSessionId),r=bt(e.sessionId),n=bt(e.tabKey),a=bt(e.routeId),o=[zt("provider",t),zt("session",r),zt("tab",n),zt("route",a)].filter(d=>typeof d=="string"),i=Vt({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),c=Sr({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:c,targetKey:c,targetValue:rd({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:Pr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:i}}function po(e,t){const r=Uf(e);return Kf(t).some(n=>r.lookupKeys.includes(n))}const Rr=60,zf=1e3,Vo=12e4,Gf=new Set(["generating","waiting_approval","starting","streaming","working"]),fo=new Map;function qo(e,t,r){return`${e}::${t}::${r||t}`}function $n(e=Rr){return{liveMessages:[],hasLiveSnapshot:!1,cursor:Vf([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Vf(e,t=Rr){return{tailLimit:t}}function al(e,t){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function xo(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(xo).join(`
41
+ `);if(typeof e=="object"){const t=e;return xo(t.text??t.content??t.value??"")}return String(e)}function qf(e){return xo(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function Yf(e){return e.length===0||e.every(qf)}function Xf(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="generating"||t==="long_generating"||t==="streaming"||t==="working"||t==="starting"}function Jf(e,t){return Math.max(Math.max(0,t),Array.isArray(e.liveMessages)?e.liveMessages.length:0)}function Qf(e,t,r,n,a){if(!Xf(n))return!1;const o=Jf(e,t);if(o<=0)return!1;if(Yf(r))return!0;if(a&&typeof a=="object"){const i=a.selected,c=a.fallbackReason;if(i==="native-history"||typeof c=="string"&&c!==""&&!c.startsWith("native_history_"))return!1}return r.length<o}function Zf(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}class ex{constructor(t){We(this,"manager");We(this,"sendData");We(this,"daemonId");We(this,"sessionId");We(this,"historySessionId");We(this,"subscriptionKey");We(this,"fallbackRecentCount");We(this,"snapshot");We(this,"transportSubscription",null);We(this,"listeners",new Set);We(this,"retainCount",0);We(this,"loadHistoryPromise",null);We(this,"pendingDisconnectTimer",null);this.manager=t.manager||Gt,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount??0),this.snapshot=$n(Math.max(0,t.tailLimit??Rr))}updateOptions(t){if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount)),t.tailLimit!==void 0){const r=Math.max(0,t.tailLimit);r!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect()))}}getSnapshot(){return this.snapshot}clearLiveSnapshot(){this.snapshot={...$n(this.snapshot.cursor.tailLimit),hasLiveSnapshot:!0},this.emit()}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=this.snapshot.hasLiveSnapshot,a=n?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),o=await t({offset:this.snapshot.historyOffset,excludeRecentCount:a}),i=Array.isArray(o.messages)?o.messages:[],c=!n&&i.length===0&&o.hasMore!==!0&&this.fallbackRecentCount>0;this.snapshot={...this.snapshot,historyMessages:[...i,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+i.length,hasMoreHistory:c?!0:o.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),t=>{this.handleUpdate(t)},{retryIntervalMs:zf}))}disconnect(){var t;(t=this.transportSubscription)==null||t.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(t=>t(this.snapshot))}handleUpdate(t){if(t.error)return;const r=Zf(t),n=t.messageSource;if(Qf(this.snapshot,this.fallbackRecentCount,r,t.status,n))return;const a={tailLimit:this.snapshot.cursor.tailLimit};al(this.snapshot.liveMessages)===al(r)&&this.snapshot.cursor.tailLimit===a.tailLimit||(this.snapshot={...this.snapshot,liveMessages:r,hasLiveSnapshot:!0,cursor:a,messageSource:n},this.emit())}}function nd(e){const t=qo(e.daemonId,e.sessionId,e.historySessionId),r=fo.get(t);if(r)return r.updateOptions(e),r;const n=new ex(e);return fo.set(t,n),n}function tx(e,t,r){if(!e||!t)return;const n=`${e}::${t}::`,a=qo(e,t,r);for(const[o,i]of fo.entries())(o===a||o.startsWith(n))&&i.clearLiveSnapshot()}function sx(e,t){return{...e,loadHistoryPage:t}}function rx(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function nx(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Gf.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=t.now??Date.now(),a=Math.max(0,Number(t.recentActivityMs??Vo)),o=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return o>0?n-o<=a:Array.isArray(e.messages)&&e.messages.length>0}function ax(e=Vo){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function ox(e,t={}){const r=new Set,n=[];for(const a of e){if(!nx(a,t))continue;const o=_r(a),i=a.sessionId||"";if(!o||!i)continue;const c=Pr(a),d=qo(o,i,c||i);r.has(d)||(r.add(d),n.push({daemonId:o,sessionId:i,historySessionId:c||i,subscriptionKey:`daemon:${o}:session:${i}`}))}return n.sort(rx),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function ix(e,t){const{sendData:r,sendCommand:n}=lt(),a=(t==null?void 0:t.enabled)!==!1,o=_r(e),i=e.sessionId||"",c=Pr(e)||i,d=`daemon:${o}:session:${i}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??Rr),u=l.useMemo(()=>!a||!o||!i?null:nd({daemonId:o,sessionId:i,historySessionId:c,subscriptionKey:d,sendData:r,tailLimit:m,fallbackRecentCount:e.messages.length}),[e.messages.length,o,a,c,r,i,d,m]),[p,x]=l.useState(()=>(u==null?void 0:u.getSnapshot())||$n(m));l.useEffect(()=>{if(!u){x($n(m));return}u.retain(),x(u.getSnapshot());const b=u.subscribe(f=>{x(f)});return()=>{b(),u.release()}},[u,m]);const w=l.useCallback(async()=>{!u||!o||!i||await u.loadHistoryPage(async({offset:b,excludeRecentCount:f})=>{const k=e.agentType,y=await n(o,"chat_history",{agentType:k,offset:b,limit:30,targetSessionId:i,historySessionId:c,excludeRecentCount:f}),h=y&&typeof y=="object"&&"result"in y?y.result||{}:y||{};return{messages:Array.isArray(h.messages)?h.messages:[],hasMore:h.hasMore===!0}})},[e.agentType,u,o,c,n,i]);return l.useMemo(()=>sx(p,w),[w,p])}function lx(e,t){const{sendData:r}=lt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??Rr),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Vo)),i=ax(o),[c,d]=l.useState(0);l.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(p=>p+1)},i);return()=>{clearInterval(u)}},[e.length,n,i]);const m=l.useMemo(()=>ox(e,{recentActivityMs:o}),[e,o,c]);l.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const u=m.descriptors.map(p=>nd({...p,sendData:r,tailLimit:a}));return u.forEach(p=>{p.retain()}),()=>{u.forEach(p=>p.release())}},[m.signature,n,r,a])}function cx(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function ol(e){const t=String(e.role||"").toLowerCase();if(t!=="user"&&t!=="assistant")return!1;const r=String(e.kind||"standard").toLowerCase();return r===""||r==="standard"}function dx(e,t){if(e.length===0)return[];if(t.some(ol))return[];const r=[],n=new Set;for(let a=e.length-1;a>=0&&r.length<2;a-=1){const o=e[a];if(!o||!ol(o))continue;const i=String(o.role||"").toLowerCase();n.has(i)||(n.add(i),r.unshift(o))}return r}function ux(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,a=Math.max(0,r.length-n),o=a>0?r.slice(0,a):[],i=a>0?r.slice(-n):r,c=dx(o,i),d=c.length>0?[...c,...i]:i;return t.length===0?d:[...t,...d]}function mx(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function hx(e){return mx(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const gn=new Map,bo=new Set;function il(e,t){!e||gn.get(e)===t||(t?gn.set(e,!0):gn.delete(e),bo.forEach(n=>n(e,t)))}function px(e){return e?gn.get(e)===!0:!1}function fx(e){return bo.add(e),()=>{bo.delete(e)}}function xx(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function bx(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function gx(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function ad(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function od(e){const t=typeof e.completionMarker=="string"?e.completionMarker.trim():"";return t||(e.lastMessageHash?e.lastMessageHash:e.lastMessageAt?String(e.lastMessageAt):e.lastUpdated?String(e.lastUpdated):"")}function yx(e){return ad(e)?!1:e.inboxBucket==="task_complete"&&od(e).length>0}function ll(e){return e.branch||"detached HEAD"}function vx(e){if(e.error)return`${ll(e)} · Git error: ${e.error}`;const t=[ll(e)];return e.changedFiles>0?t.push(xx(e.changedFiles,"file")+" changed"):e.dirty||t.push("clean"),e.ahead>0&&t.push(`ahead ${e.ahead}`),e.behind>0&&t.push(`behind ${e.behind}`),e.hasConflicts&&t.push("conflicts"),t.join(" · ")}function wx(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${vx(t)}`}function jx(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function kx(e,t={}){if(t.enabled===!1)return[];if(!gx(e))return[];const r=ad(e)?"working":yx(e)?"complete":null;if(!r)return[];const n=r==="complete"?od(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${bx(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:wx(r,e.git),timestamp:jx(e,e.git),meta:{source:"git-system-bubble",phase:r,workspace:e.workspacePath,repoRoot:e.git.repoRoot,branch:e.git.branch,changedFiles:e.git.changedFiles,hasConflicts:e.git.hasConflicts}}]}const Sx=60;function Nx(e){return e.status==="long_generating"?"Agent has been generating for a long time. Send queues your message; Force sends it immediately.":e.status==="generating"||e.status==="streaming"?"Agent is generating. Send queues your message; Force sends it immediately.":e.status==="waiting_approval"&&(!e.modalButtons||e.modalButtons.length===0)?"Agent is waiting for approval. Approval controls will appear when available.":null}function go({activeConv:e,ideEntry:t,handleSendChat:r,handleForceSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:d,userName:m,scrollToBottomRequestNonce:u,isInputActive:p=!0,isVisible:x=!0}){var Q,ge,ce,ye,me,fe,le;const w=l.useRef(new Map),b=l.useRef(void 0),f=Lr(),{sendCommand:k}=lt(),{isVisible:y}=Fo();Ar("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:d.length,isSendingChat:a});const h=ft.useMemo(()=>Ws(e),[e.status,e.connectionState]);ft.useEffect(()=>{const pe=e.sessionId;if(pe)return il(pe,h.isGenerating),()=>{il(pe,!1)}},[e.sessionId,h.isGenerating]);const j=l.useMemo(()=>bf(e,t),[e,t]),v=l.useMemo(()=>{var pe;return Ko((pe=j.targetEntry)==null?void 0:pe.providerControls,{hostIdeType:e.hostIdeType,providerType:j.providerType})},[e.hostIdeType,j.providerType,(Q=j.targetEntry)==null?void 0:Q.providerControls]),g=sd({isCliLike:j.isCli||j.isAcp}),S=Wf({isCliLike:j.isCli||j.isAcp}),M=ix(e,{enabled:x&&!!e.sessionId,tailLimit:S}),[C,N]=l.useState(g),[O,_]=l.useState(()=>Ei()),T=e.tabKey,H=M.historyMessages,R=M.hasMoreHistory,F=M.historyError,A=cx(e,M),I=Mc(A).length;l.useEffect(()=>{N(g)},[g,T]);const $=Math.max(0,A.length-C),E=Uo(e),L=_r(e),U=hx(e),B=zo(e),K=Nx(e),J=o||B||K,X=!!B,[ae,de]=l.useState(!1);l.useEffect(()=>{const pe=j.targetEntry;L&&(!pe||pe.providerControls===void 0||pe.controlValues===void 0)&&f(L,{minFreshMs:3e4}).catch(()=>{})},[L,j.isAcp,(ge=j.targetEntry)==null?void 0:ge.providerControls,(ce=j.targetEntry)==null?void 0:ce.controlValues,f]);const ke=l.useCallback(async()=>{if(!ae){if(A.length>C){N(pe=>Math.min(A.length,pe+Sx));return}de(!0);try{await M.loadHistoryPage()}finally{de(!1)}}},[M,ae,A.length,C]),{allMessages:q,receivedAtMap:ve}=l.useMemo(()=>{const pe=ux({historyMessages:H,liveMessages:A,visibleLiveCount:C}),oe=kx(e),P=oe.length>0?[...pe,...oe]:pe,ue={};return P.forEach((Se,Ie)=>{const te=`${e.tabKey}:${Ln(Se,Ie)}`;let Ne=Of(Se)||w.current.get(te)||0;Ne||(Ne=Date.now(),w.current.set(te,Ne)),ue[Ln(Se,Ie)]=Ne}),{allMessages:P,receivedAtMap:ue}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,$,H,A,C]),be=l.useMemo(()=>d.filter(pe=>pe.routeId===e.tabKey).sort((pe,oe)=>pe.timestamp-oe.timestamp),[d,e.tabKey]),we=l.useCallback(async()=>{var Ie,te;if(!L)return;const pe=Qc({activeConv:e,visibleMessages:q,actionLogs:d,controls:(Ie=j.targetEntry)==null?void 0:Ie.providerControls,controlValues:(te=j.targetEntry)==null?void 0:te.controlValues,visibleBarControlCount:v.length,chatTailState:{liveMessages:M.liveMessages,hasLiveSnapshot:M.hasLiveSnapshot,hasMoreHistory:R,historyError:F,historyMessages:H},ui:{controlsVisible:y,visibleLiveCount:C,activityVisible:O,activityCount:I,hiddenLiveCount:$,isInputActive:p,isVisible:x}}),oe=await k(L,"get_chat_debug_bundle",{agentType:j.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:pe}),P=pr(oe),ue=td(P),Se=await ed(ue);Se==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),Je.showToast(Zc(P,{locatorCopyStatus:Se}),Se==="failed"?"warning":"success")},[e,d,I,q,y,M.hasLiveSnapshot,M.liveMessages,j.providerType,(ye=j.targetEntry)==null?void 0:ye.controlValues,(me=j.targetEntry)==null?void 0:me.providerControls,L,R,$,H,p,x,F,k,O,v.length,C]);l.useEffect(()=>{const pe=oe=>{oe.key===Nc&&_(Ei())};return window.addEventListener("storage",pe),()=>window.removeEventListener("storage",pe)},[]);const xe=l.useCallback(()=>{const pe=Sf(b.current);b.current=pe.state,pe.shouldCollect&&we().catch(oe=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",oe),Je.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[we]),Ce=l.useMemo(()=>{if(A.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((h.isGenerating||e.status==="streaming")&&de(!1),e.status==="not_monitored"&&U)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Bs,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx($s,{size:14})," Open ",E," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&U)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(wc,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx($s,{size:14})," Open ",E," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!ae)return!R&&H.length===0?s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"No messages yet"})]}):s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,U,i,R,H.length,c,ae,A.length,E,h.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[s.jsx("div",{className:"chat-activity-toggle-bar",children:s.jsx("div",{className:"ml-auto flex items-center gap-1",children:s.jsx(cf,{sessionId:e.sessionId,daemonId:e.daemonId})})}),s.jsx(Zh,{messages:q,actionLogs:be,agentName:Os(e)||E||"Agent",userName:m,isCliMode:j.isCli||j.isAcp,isWorking:h.isGenerating,contextKey:e.tabKey,receivedAtMap:ve,lastMessageHash:e.lastMessageHash,showActivityMessages:O,onLoadMore:ke,isLoadingMore:ae,hasMoreHistory:R,hiddenLiveCount:$,loadError:F??void 0,emptyState:Ce,scrollToBottomRequestNonce:u,isVisible:x}),s.jsx(sf,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:j.providerType,displayLabel:j.displayLabel,controls:(fe=j.targetEntry)==null?void 0:fe.providerControls,controlValues:(le=j.targetEntry)==null?void 0:le.controlValues,isActive:p,isCliTerminal:j.isCliTerminal}),!j.isCliTerminal&&s.jsx(Uc,{contextKey:e.tabKey,panelLabel:E,isSending:a,isBusy:X,statusMessage:J,onSend:r,onForceSend:n,canForceSend:!!n&&h.isGenerating&&!X,isActive:p,showControlsToggle:v.length>0,onControlsToggle:xe,messageInput:e.messageInput})]})}let id=ss;function ld(){return id()}class Cx{constructor(){We(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{var n;(n=this.listeners.get(t))==null||n.delete(r)}}emit(t,...r){var n;(n=this.listeners.get(t))==null||n.forEach(a=>a(...r))}}let cd=new Cx;class Mx{sendPtyInput(t,r,n){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,r){return!1}get(t){}onScreenshot(t,r){return()=>{}}onRuntimeEvent(t,r,n){return()=>{}}requestRuntimeSnapshot(t,r,n){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let at=new Mx;function Ix(e){e.dashboardWS&&(cd=e.dashboardWS),e.connectionManager&&(at=e.connectionManager),e.useDaemonsHook&&(id=e.useDaemonsHook)}const Tx=.5,Ax=1.25;function nt(e){return Uo(e)}function ys(e){return Yc(e).join(" · ")}function dd(e){const t=qc(e);return t||(e.title?e.title:ys(e)||"No messages yet")}function ud(e,t){const{isReconnecting:r,isConnecting:n}=Ws(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function _x(e,t){const r=["Chat",...Yc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function ms(e){return ud(e)||ys(e)}function Lx(e){return`${nt(e)} · ${dd(e)}`}function Px(e){const t=Dn(e),r=t?xt(t):Os(e);return`${nt(e)} — ${r||"Agent"}`}function Rx(e){return Os(e)||"CLI"}function md(e){return Vc(e)}function hd(e){return e?`Remote · ${nt(e)||e.workspaceName||"Session"}`:"Remote"}function Dx({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var se;ss();const{sendPtyInput:d}=lt(),[m,u]=l.useState(!1),p=l.useRef(!1);p.current=m;const[x,w]=l.useState("Runtime terminal unavailable"),[b,f]=l.useState(!1),[k,y]=l.useState(null),[h,j]=l.useState(!1),[v,g]=l.useState(!1),[S,M]=l.useState(1),[C,N]=l.useState(!1),[O,_]=l.useState({width:0,height:0}),[T,H]=l.useState({width:0,height:0}),[R,F]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[A,I]=l.useState(null),$=l.useRef(null),E=l.useRef(null),L=l.useRef(!1),U=l.useRef(!1),B=l.useRef(i),K=l.useRef(0),J=l.useRef(!1),X=l.useRef(""),ae=l.useRef(null),de=l.useRef(!1),ke=l.useRef(!1),q=l.useRef(null),ve=l.useRef(null),be=l.useRef(null),we=32*1024,xe=()=>{var W,V,ee,ne;return((V=(W=$.current)==null?void 0:W.ownerDocument)==null?void 0:V.defaultView)||((ne=(ee=E.current)==null?void 0:ee.ownerDocument)==null?void 0:ne.defaultView)||window},Ce=W=>{const V=xe();return{ownerWindow:V,frameId:V.requestAnimationFrame(W)}},Q=()=>{const W=q.current;if(W){try{W.ownerWindow.cancelAnimationFrame(W.frameId)}catch{}q.current=null}},ge=()=>{const W=ve.current;if(W){try{W.ownerWindow.clearTimeout(W.timeoutId)}catch{}ve.current=null}},ce=()=>{const W=be.current;if(W){try{W.ownerWindow.clearTimeout(W.timeoutId)}catch{}be.current=null}},ye=()=>{i&&q.current===null&&(q.current=Ce(()=>{et()}))},me=e.tabKey,fe=e.sessionId||"",le=e.daemonId||((se=e.routeId)==null?void 0:se.split(":")[0])||e.routeId||"",pe=zo(e),oe=m?o||pe:x,P=Tx,ue=Ax,Se=.05,Ie=()=>{const W=T.width,V=T.height;if(!Number.isFinite(O.width)||O.width<=0||!Number.isFinite(O.height)||O.height<=0||!Number.isFinite(W)||W<=0||!Number.isFinite(V)||V<=0)return 1;const ee=O.width/W,ne=O.height/V;return Number(Math.min(ue,Math.max(P,Math.min(ee,ne))).toFixed(2))},te=Ie(),Ne=L.current&&S>te,De=Number.isFinite(T.width)&&T.width>0?Math.max(O.width,Math.round(T.width*S)):O.width,Ee=Number.isFinite(T.height)&&T.height>0?Math.max(O.height,Math.round(T.height*S)):O.height,ze=()=>{Ce(()=>{const W=E.current;W&&(W.scrollLeft=0,W.scrollTop=W.scrollHeight-W.clientHeight)})},Qe=()=>{var W,V;K.current=0,J.current=!1,X.current="",ae.current=null,de.current=!1,ke.current=!1,L.current||(U.current=!1,M(1)),q.current!==null&&Q(),u(!1),w("Runtime terminal unavailable"),ce(),ge(),y(null),I(null),N(!1),f(!1),j(!1),g(!1),(V=(W=r.current)==null?void 0:W.reset)==null||V.call(W)},Ze=()=>{var W,V;K.current=0,J.current=!1,X.current="",ae.current=null,de.current=!1,ke.current=!1,q.current!==null&&Q(),u(!0),w(""),ce(),ge(),y(null),I(null),N(!1),f(!1),j(!1),g(!1),(V=(W=r.current)==null?void 0:W.reset)==null||V.call(W)},rt=()=>{ke.current&&(ke.current=!1,Ce(()=>{var W,V;(V=(W=r.current)==null?void 0:W.scrollToTop)==null||V.call(W)}))},et=()=>{if(q.current=null,!i)return;const W=X.current;if(!W)return;const V=W.slice(0,we);X.current=W.slice(V.length);const ee=r.current;if(!ee){X.current=V+X.current,ye();return}ee.write(V,()=>{if(X.current.length>0){ye();return}rt()})},ct=W=>{W&&(X.current+=W,ye())},Xe=(W,V=0,ee,ne,D={})=>{var he,je,Me,$e;const ie=!!D.force;!ie&&V>0&&K.current>=V||!ie&&V===0&&J.current||(K.current=V,V>0&&j(!0),u(!0),w(""),typeof ee=="number"&&typeof ne=="number"&&ee>0&&ne>0&&((je=(he=r.current)==null?void 0:he.resize)==null||je.call(he,ee,ne)),X.current="",($e=(Me=r.current)==null?void 0:Me.reset)==null||$e.call(Me),W?ct(W):rt())};l.useEffect(()=>{Qe()},[fe]),l.useEffect(()=>{var V;if(!fe)return;const W=((V=at.onRuntimeEvent)==null?void 0:V.call(at,fe,ee=>{if(!(!ee||ee.sessionId!==fe)){if(ee.type==="runtime_snapshot"){if(!i){ae.current={text:ee.text||"",seq:ee.seq||0,cols:ee.cols,rows:ee.rows,force:!!ee.force};return}Xe(ee.text||"",ee.seq||0,ee.cols,ee.rows,{force:!!ee.force});return}if(ee.type==="session_output"){J.current=!0,typeof ee.seq=="number"&&(K.current=Math.max(K.current,ee.seq),ee.seq>0&&j(!0)),p.current||u(!0),p.current||w(""),typeof ee.data=="string"&&ct(ee.data);return}if(ee.type==="session_cleared"){if(!i){de.current=!0,X.current="",ae.current=null;return}Ze();return}if(ee.type==="session_io_error"){const ne=typeof ee.error=="string"&&ee.error?ee.error:typeof ee.reason=="string"&&ee.reason?ee.reason:"unknown error";u(!1),w(`Runtime input failed: ${ne}`);return}}},le))||(()=>{});return()=>{W()}},[le,fe,r,i]);const pt=async(W={})=>{var V;if(!le||!fe)return{success:!1,error:"daemonId and sessionId are required"};W.preserveStatus||w(W.loadingMessage||"Loading runtime terminal...");try{const ee=await((V=at.requestRuntimeSnapshot)==null?void 0:V.call(at,le,fe,{sinceSeq:W.sinceSeq,force:W.force}));return ee&&ee.success===!1?(W.preserveStatus||(u(!1),w(`Runtime terminal unavailable: ${ee.error}`)),ee):ee||{success:!0}}catch(ee){const ne=(ee==null?void 0:ee.message)||String(ee);return W.preserveStatus||(u(!1),w(`Runtime terminal unavailable: ${ne}`)),{success:!1,error:ne}}},Ae=async W=>{var ie,he;const V=((ie=$.current)==null?void 0:ie.ownerDocument)||document,ee=V.defaultView||window,ne=(he=ee.navigator)==null?void 0:he.clipboard;if(ne!=null&&ne.writeText&&ee.isSecureContext)try{return await ne.writeText(W),!0}catch{}let D=null;try{return D=V.createElement("textarea"),D.value=W,D.setAttribute("readonly","true"),D.style.position="fixed",D.style.left="-9999px",D.style.top="0",V.body.appendChild(D),D.focus(),D.select(),V.execCommand("copy")}catch{return!1}finally{D==null||D.remove()}},Fe=W=>{ge(),I(W);const V=xe();ve.current={ownerWindow:V,timeoutId:V.setTimeout(()=>{ve.current=null,I(ee=>ee===W?null:ee)},2200)}},st=W=>{ce(),y(W);const V=xe();be.current={ownerWindow:V,timeoutId:V.setTimeout(()=>{be.current=null,y(ee=>ee===W?null:ee)},2200)}},qe=async()=>{var D,ie,he,je;const W=((ie=(D=r.current)==null?void 0:D.getSelection)==null?void 0:ie.call(D))||"",V=((je=(he=r.current)==null?void 0:he.getVisibleText)==null?void 0:je.call(he))||"",ee=W.trimEnd()||V.trimEnd();if(!ee){Fe("Nothing to copy");return}if(!await Ae(ee)){Fe("Copy failed");return}Fe(W.trimEnd()?"Copied selection":"Copied visible terminal")},Ke=W=>{if(!m||!i)return;((d==null?void 0:d(le,fe,W))??!1)||Fe("Terminal input failed")},z=async()=>{if(b)return;f(!0),y("Loading older terminal output..."),ke.current=!0;const W=await pt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(f(!1),(W==null?void 0:W.success)===!1){ke.current=!1,y(`Older terminal output unavailable: ${W.error}`);return}g(!0),st("Older terminal output loaded"),Ce(()=>{var V;(V=r.current)==null||V.bumpResize()})};l.useEffect(()=>{var V,ee;if(!fe)return;le&&((V=at.getState)==null?void 0:V.call(at,le))==="connected"&&pt();const W=(ee=at.onStateChange)==null?void 0:ee.call(at,(ne,D)=>{ne!==le||D!=="connected"||pt()});return()=>{W==null||W()}},[le,fe,r]),l.useEffect(()=>{t&&Qe()},[t,me,r]),l.useEffect(()=>{var ne,D;const W=$.current,V=(D=(ne=W==null?void 0:W.ownerDocument)==null?void 0:ne.defaultView)==null?void 0:D.ResizeObserver;if(!W||!V)return;const ee=new V(ie=>{const he=ie[0];if(!he)return;const{width:je,height:Me}=he.contentRect;_($e=>{const Te=Math.round(je),Le=Math.round(Me);return $e.width===Te&&$e.height===Le?$e:{width:Te,height:Le}})});return ee.observe(W),()=>ee.disconnect()},[]),l.useEffect(()=>{if(L.current)return;const W=Ie();!Number.isFinite(W)||W<=0||M(V=>U.current?W<V-Se?W:V:(U.current=!0,W))},[T.height,T.width,O.height,O.width]),l.useEffect(()=>{Ne&&ze()},[Ne,Ee,De]),l.useEffect(()=>{var ee;const W=B.current;if(B.current=i,!i)return;W||g(!1),de.current&&(de.current=!1,Ze());const V=ae.current;V&&(ae.current=null,Xe(V.text,V.seq,V.cols,V.rows,{force:!!V.force})),le&&fe&&((ee=at.getState)==null?void 0:ee.call(at,le))==="connected"&&pt(),X.current&&q.current===null&&ye(),Ce(()=>{var ne;(ne=r.current)==null||ne.bumpResize()})},[le,i,fe]),l.useEffect(()=>()=>{q.current!==null&&Q(),ge(),ce()},[]),l.useEffect(()=>{const W=ne=>{var ie;const D=ne.detail;D!=null&&D.sessionId&&D.sessionId!==fe||m&&((ie=r.current)==null||ie.bumpResize())},V=xe(),ee=V===window?[window]:[window,V];for(const ne of ee)ne.addEventListener("adhdev:fit-cli-terminal",W);return()=>{for(const ne of ee)ne.removeEventListener("adhdev:fit-cli-terminal",W)}},[m,fe,r]);const Y=m&&h&&!v&&(R.atTop||!R.canScroll)||b||!!k;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:$,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[Y&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{z()},disabled:!fe||b,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:b?"Loading older...":"Load older terminal output"}),k&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:k})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[A&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:A}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{qe()},disabled:!m,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>N(W=>!W),disabled:!m,"aria-label":"Open terminal control keys","aria-expanded":C,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),C&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":"Terminal control keys",className:"absolute right-0 top-10 w-56 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>N(!1),"aria-label":"Close terminal control keys",children:"×"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke("\x1B"),children:"Esc"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke(" "),children:"Tab"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke("\r"),children:"Enter"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke("\x1B[A"),"aria-label":"Arrow up",children:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke("\x1B[D"),"aria-label":"Arrow left",children:"←"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke("\x1B[B"),"aria-label":"Arrow down",children:"↓"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke("\x1B[C"),"aria-label":"Arrow right",children:"→"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke(""),children:"Ctrl-C"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke(""),children:"Ctrl-D"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke(""),children:"Bksp"})]})]})]}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{L.current=!0,M(W=>{const V=Math.max(te,Number((W-.1).toFixed(2)));return V>te&&ze(),V})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{L.current=!0,M(W=>{const V=Math.min(ue,Number((W+.1).toFixed(2)));return V>te&&ze(),V})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:E,className:Ne?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:De>0?`${De}px`:"100%",height:Ee>0?`${Ee}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:T.width>0?`${T.width}px`:"100%",height:T.height>0?`${T.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:S},children:s.jsx(Lc,{ref:r,readOnly:!m||!i,sizingMode:"measured",onViewportMetrics:H,onScrollMetrics:F,onInput:W=>{!m||(d==null||d(le,fe,W))}})})})}),!m&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:x})]}),s.jsx(Uc,{contextKey:e.tabKey,panelLabel:nt(e),isSending:a,isBusy:!!pe,statusMessage:oe,onSend:async W=>pe?!1:n(W),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1})]})}const Ex=5e3,$x=12e3;function Bx(e){return e==="disconnected"||e==="reconnecting"}function Ox({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=Ex,reconnectActionDelayMs:o=$x}){const i=Bx(e),[c,d]=l.useState(()=>!i||a<=0),[m,u]=l.useState(()=>!i||o<=0),p=l.useRef(!1);l.useEffect(()=>{if(!i){d(!1);return}if(p.current=!1,a<=0){p.current=!0,d(!0);return}d(!1);const g=setTimeout(()=>{p.current=!0,d(!0)},a);return()=>clearTimeout(g)},[a,i]),l.useEffect(()=>{if(!i){u(!1);return}if(o<=0){u(!0);return}u(!1);const g=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(g)},[o,i]);const x=i?c:e==="offline"||e==="auth_failed",w=!!(n&&e!=="auth_failed"&&(!i||m)),b=l.useMemo(()=>!t||e!=="connected"?!1:a<=0||p.current,[a,t,e]),f=e==="auth_failed"?"red":e==="offline"?"orange":"accent",k={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},y={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},h={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},j="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",v={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[x&&s.jsx("div",{className:j,style:v,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:k[f],border:y[f],color:h[f]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&"Network offline",e==="disconnected"&&"Reconnecting",e==="reconnecting"&&"Reconnecting",e==="auth_failed"&&(r?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),w&&s.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>n==null?void 0:n(),disabled:e==="offline",children:"Reconnect now"})]})}),b&&s.jsx("div",{className:j,style:v,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function Fx({terminalBackend:e,isStandalone:t=!1,machineLabel:r,machineKey:n}){const a=l.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[o,i]=l.useState(!1);if(l.useEffect(()=>{if(!a){i(!1);return}try{i(localStorage.getItem(a)==="1")}catch{i(!1)}},[a]),!t||!e||e.backend!=="xterm"||o)return null;const c=(r==null?void 0:r.trim())||"This machine",d=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}i(!0)};return s.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[s.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[s.jsxs("span",{children:[c," is using `xterm` fallback."]}),s.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),s.jsx("button",{type:"button",onClick:d,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function pd({mode:e,onChange:t,compact:r=!1}){const n=r?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?s.jsx(Eo,{size:n}):s.jsx(ws,{size:n})})}const Ht="New session",fd="A connected machine is ready. Start a new session with any installed provider — CLI, ACP, or IDE.";function Hx(e){if(!e||e.isGitRepo===!1||e.reason==="not_git_repo")return null;if(e.hasConflicts)return`${e.branch||"Git"} · conflicts${e.changedFiles>0?` ${e.changedFiles}`:""}`;const t=[e.branch||"Git"];return e.changedFiles>0&&t.push(`±${e.changedFiles}`),e.ahead>0&&t.push(`↑${e.ahead}`),e.behind>0&&t.push(`↓${e.behind}`),t.length===1&&e.dirty&&t.push("dirty"),t.join(" ")}function Wx(e){return!e||e.isGitRepo===!1||e.reason==="not_git_repo"?null:e.hasConflicts?"conflict":e.error?"error":e.dirty||e.changedFiles>0||e.ahead>0||e.behind>0?"dirty":"quiet"}function Kx(e){switch(e){case"conflict":return"border-red-500/25 bg-red-500/[0.08] text-red-400";case"error":return"border-yellow-500/25 bg-yellow-500/[0.08] text-yellow-500";case"dirty":return"border-orange-500/25 bg-orange-500/[0.08] text-orange-400";case"quiet":default:return"border-emerald-500/15 bg-emerald-500/[0.06] text-emerald-500"}}function Bn({git:e,className:t="",compact:r=!1}){const n=Hx(e),a=Wx(e);if(!n||!a)return null;const o=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return s.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${Kx(a)} ${t}`.trim(),title:o.join(" · ")||n,"data-git-tone":a,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:n})]})}function Ux({wsStatus:e,isConnected:t,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),o=a.filter(c=>c==="connected").length,i=a.filter(c=>c==="connecting"||c==="new"||c==="checking").length;return r>0&&i>0&&o===0?{tone:"limited",title:"Connected to dashboard",subtitle:"Connecting to machine..."}:t?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function cl({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function dl({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const i=ea(e.updatedAt),c=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${c?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",i].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[c?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),o()},children:"Delete"})]})]})}function zx({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:p,onShowAllHidden:x,onResetPanelsToMain:w,inboxOpen:b,onInboxOpenChange:f,hiddenOpen:k,onHiddenOpenChange:y,onOpenNewSession:h,onOpenDashboardGuide:j,guideNudgeVisible:v=!1,actionShortcuts:g,notifications:S,notificationUnreadCount:M,onOpenNotification:C,onMarkNotificationRead:N,onMarkNotificationUnread:O,onDeleteNotification:_,onOpenGitDialog:T,onOpenMeshGraph:H}){var Ce;const{ides:R,p2pStates:F={}}=ss(),A=!!e&&Ye(e)&&!Ve(e),I=!!e&&Ve(e),$=!!(e!=null&&e.daemonId)&&!!((Ce=e==null?void 0:e.coordinator)!=null&&Ce.meshId),E=c||(e?zc(e)?"terminal":"chat":null),[L,U]=l.useState(!1),B=l.useRef(null),K=l.useRef(null),J=R.filter(Q=>Q.type==="adhdev-daemon"),X=Ux({wsStatus:t,isConnected:r,daemonCount:J.length,p2pStates:F}),ae=X.subtitle,de=X.tone==="connected"?"#22c55e":X.tone==="limited"?"#eab308":"#ef4444",ke=X.tone==="connected"?"0 0 4px #22c55e80":X.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",q=l.useMemo(()=>S.filter(Q=>!Q.readAt),[S]),ve=l.useMemo(()=>S.filter(Q=>!!Q.readAt),[S]),be=l.useMemo(()=>q.slice(0,9),[q]),we=M;l.useEffect(()=>{if(!b)return;const Q=ge=>{var ce;(ce=B.current)!=null&&ce.contains(ge.target)||f(!1)};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[b,f]),l.useEffect(()=>{if(!k)return;const Q=ge=>{var ce;(ce=K.current)!=null&&ce.contains(ge.target)||y(!1)};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[k,y]),l.useEffect(()=>{if(!k&&!b)return;const Q=ge=>{if(!ge.altKey)return;const ce=ge.code.match(/^Digit([1-9])$/);if(!ce)return;const ye=Number(ce[1])-1,me=k?u[ye]:void 0,fe=b?be[ye]:void 0;if(!(!me&&!fe)){if(ge.preventDefault(),ge.stopPropagation(),me){p==null||p(me),y(!1);return}fe&&(C(fe),f(!1))}};return window.addEventListener("keydown",Q,!0),()=>window.removeEventListener("keydown",Q,!0)},[u,k,b,be,y,f,C,p]);const xe=Q=>{if(!Q)return;const ge=n.find(ce=>ce.tabKey===Q);ge&&(m==null||m(ge))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(ws,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?nt(e):"Dashboard"}),s.jsx("span",{title:X.title,"aria-label":X.title,className:"header-title-status-dot",style:{background:de,boxShadow:ke}}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:de,boxShadow:ke}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[ae&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ae]}),h&&s.jsx("button",{type:"button",onClick:h,className:"btn btn-secondary btn-sm ml-2",title:`${Ht}${g!=null&&g.openNewSession?` (${g.openNewSession})`:""}`,"aria-label":Ht,children:s.jsx(Sc,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[j&&s.jsxs("button",{type:"button",onClick:j,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:"Dashboard guide","aria-label":"Open dashboard guide",children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),v&&s.jsx("span",{children:"Guide"})]}),e&&(A||I||!Ve(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:ys(e)||nt(e),children:nt(e)}),T&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:()=>T(e.daemonId,e.workspacePath),children:s.jsx(Bn,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Bn,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),$&&H&&s.jsxs("button",{type:"button",onClick:()=>H(e),className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",title:"Open live repo mesh graph",children:[s.jsx(Qt,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:"Mesh graph"})]}),(A||I)&&i&&s.jsxs(s.Fragment,{children:[A&&d&&E&&s.jsx(pd,{mode:E,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:I?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(gt,{size:14})})]}),!Ve(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(Ro,{size:14})}),!A&&!Ve(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Bt,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:B,children:[s.jsxs("div",{className:`dashboard-header-hidden${L?" is-drop-target":""}`,ref:K,onDragEnter:Q=>{Q.dataTransfer.types.includes("text/tab-key")&&(Q.preventDefault(),U(!0))},onDragOver:Q=>{Q.dataTransfer.types.includes("text/tab-key")&&(Q.preventDefault(),Q.dataTransfer.dropEffect="move",U(!0))},onDragLeave:Q=>{Q.currentTarget.contains(Q.relatedTarget)||U(!1)},onDrop:Q=>{const ge=Q.dataTransfer.getData("text/tab-key");Q.preventDefault(),U(!1),xe(ge)},children:[s.jsxs("button",{type:"button",onClick:()=>y(!k),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${g!=null&&g.toggleHiddenTabs?` (${g.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(Do,{size:16}),u.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),k&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),s.jsx(cl,{value:g==null?void 0:g.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[w&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:w,children:"Reset panels"}),u.length>0&&x&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{x(),y(!1)},children:"Restore all"})]})]}),e&&m&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),s.jsx(cl,{value:g==null?void 0:g.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:nt(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(Q=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{p==null||p(Q),y(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:nt(Q)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(Q)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(Q)+1]}):null,ys(Q)]})]},Q.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>f(!b),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Tr,{size:16}),we>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:we})]}),b&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[q.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),q.map(Q=>s.jsx(dl,{notification:Q,shortcutIndex:be.indexOf(Q)>=0?be.indexOf(Q)+1:void 0,onOpen:()=>C(Q),onMarkRead:()=>N(Q.id),onMarkUnread:()=>O(Q.id),onDelete:()=>_(Q.id)},Q.id))]}),ve.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),ve.map(Q=>s.jsx(dl,{notification:Q,onOpen:()=>C(Q),onMarkRead:()=>N(Q.id),onMarkUnread:()=>O(Q.id),onDelete:()=>_(Q.id)},Q.id))]}),S.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function jt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Gx(e,t){return String(e||"")!==String(t||"")}function Vx(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.resumableOnly;return!r&&!n&&!a&&!o?e:e.filter(i=>!(o&&!i.canResume||r&&![i.title,i.preview].map(d=>String(d||"").toLowerCase()).join(`
42
+ `).includes(r)||n&&!String(i.workspace||"").toLowerCase().includes(n)||a&&!Bc(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
43
+ `).includes(a)))}function qx(e,t="recent"){const r=e.slice();return r.sort((n,a)=>{if(t==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const o=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(o!==0)return o}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function xd(e,t={}){return qx(Vx(e,t),t.sortMode||"recent")}function On(e){return e?"Resume saved history":"Start fresh"}function Yo(e){return e?"Resuming saved history…":"Starting fresh…"}function Yx(){return"Start fresh"}function Xx(e,t=!1){return e==="cli"?On(t):e==="ide"?"Start IDE":"Start ACP session"}function Jx(e,t=!1){return e==="cli"?Yo(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Qx(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Zx(){return"Open saved history"}function eb(){return"Saved History"}function Xo(){return"Use saved history when you want continuity in the same provider conversation."}function tb(){return"No saved history found yet."}function sb(){return"Refresh saved history"}function rb(){return"Refreshing saved history…"}function Fn(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function Hn(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Wn(e){return e==="start-fresh"?"Start fresh":"Restart"}function Kn(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function bd(e){return`Resume saved history with ${e}?`}function gd(){return"Review or change the target workspace before resuming saved history."}function nb(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function yd({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:m,onClose:u,onNewChat:p,onSwitchSession:x,onRefreshHistory:w,onResumeSavedSession:b}){var _;const f=t.find(T=>T.id===e.routeId),k=(f==null?void 0:f.chats)||[],y=(_=f==null?void 0:f.activeChat)==null?void 0:_.id,h=Ye(e)&&!Ve(e),[j,v]=l.useState(()=>jt()),g=c||j,S=String(d||"").trim(),M=T=>{if(m){m(T);return}v(T)},C=l.useMemo(()=>a.map(T=>{const H=String(T.workspace||"").trim();return T.canResume||H||!S?T:{...T,workspace:S,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[S,a]),N=l.useMemo(()=>xd(C,{textQuery:g.textQuery,workspaceQuery:g.workspaceQuery,modelQuery:g.modelQuery,resumableOnly:g.resumableOnly,sortMode:g.sortMode}),[C,g.modelQuery,g.resumableOnly,g.sortMode,g.textQuery,g.workspaceQuery]),O=s.jsxs("div",{className:"fixed inset-0 z-[1300] 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:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:h?eb():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Px(e)}),h&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Xo()})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(gt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!h&&s.jsx("button",{onClick:p,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),h?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:g.textQuery,onChange:T=>M({...g,textQuery:T.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:g.workspaceQuery,onChange:T=>M({...g,workspaceQuery:T.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:g.modelQuery,onChange:T=>M({...g,modelQuery:T.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:g.sortMode,onChange:T=>M({...g,sortMode:T.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:g.resumableOnly,onChange:T=>M({...g,resumableOnly:T.target.checked})}),"Resume-ready only"]})]}),N.map(T=>{const H=e.providerSessionId===T.providerSessionId,R=H||!T.canResume||!!i,F=T.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{R||!b||b(T)},disabled:R,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${H?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${R?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${H?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:T.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:nb(T.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:T.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[T.workspace||"Workspace unknown",F?" · selected workspace":"",gs(T.summaryMetadata)?` · ${gs(T.summaryMetadata)}`:"",T.messageCount>0?` · ${T.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:H?"ACTIVE":T.canResume?F?"RESUME IN SELECTED WORKSPACE":i===T.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},T.id)})]}):k.map(T=>s.jsxs("div",{onClick:()=>{x(e.routeId,T.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${y===T.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${y===T.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[T.id.substring(0,12),"..."]}),y===T.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},T.id)),(h&&!o&&N.length===0||!h&&k.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(gh,{size:32})}),s.jsx("div",{className:"text-[13px]",children:h?a.length>0?"No saved history matches these filters.":tb():"No recent chat sessions found."})]}),h&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:rb()})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:w,disabled:n||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||o?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zn,{size:13})," ",h?sb():"Refresh History"]})})})]})]});return typeof document>"u"?O:vr.createPortal(O,document.body)}const ul={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Done"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Attention"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Update"}};function vd({toasts:e,onDismiss:t,onClickToast:r}){return s.jsx("div",{className:"fixed right-4 z-[9999] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const a=ul[n.type]||ul.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var o;(o=n.actions)!=null&&o.length||r&&r(n)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:o=>{o.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(gt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((o,i)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${o.variant==="primary"||o.variant==="danger",""}`,style:o.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:o.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:c=>{c.stopPropagation(),o.onClick(),t(n.id)},children:o.label},i))})]})]},n.id)})})}const ab=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function ob(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function ib(e){return e.sessionId||e.instanceId||e.agentType}function wa(e,t){return t||e||"unknown"}function wd(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Ct(r,{fallbackId:r.id}));return t}function jd(e,t={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=t.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:t.connectionStates?t.connectionStates[r]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Jo(e,t={}){return lb(e,jd(e,t))}function lb(e,t={}){var p,x,w,b,f,k,y;const r=[],n=t.machineName,a=t.connectionState,o=ob(e),i=e.workspace||"",c=vp(e.type,{agentName:e.cliName}),d=Ye(e)||Ve(e)?c:xt(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(h=>{var j,v,g;return{sessionId:h.id,instanceId:h.id,providerSessionId:h.providerSessionId,activeChatId:(j=h.activeChat)==null?void 0:j.id,transport:h.transport,sessionCapabilities:h.capabilities,agentType:h.providerType,agentName:h.providerName||xt(h.providerType),status:h.status,title:h.title,lastMessagePreview:h.lastMessagePreview,lastMessageRole:h.lastMessageRole,lastMessageAt:h.lastMessageAt,lastMessageHash:h.lastMessageHash,messages:((v=h.activeChat)==null?void 0:v.messages)||[],activeModal:((g=h.activeChat)==null?void 0:g.activeModal)||void 0,unread:h.unread,lastSeenAt:h.lastSeenAt,lastUpdated:h.lastUpdated,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,surfaceHidden:h.surfaceHidden,git:h.git,settings:h.settings,coordinator:h.coordinator,messageInput:h.messageInput}}):[],u=ab(e);if(u){const h=e.sessionId||e.instanceId,j=(p=e.settings)==null?void 0:p.meshCoordinatorFor,v=(x=e.settings)==null?void 0:x.meshNodeFor,g=j?" (Coordinator)":v?" (Mesh Node)":"",S=c+g,M=(w=e.activeChat)==null?void 0:w.activeModal,C=M&&Array.isArray(M.buttons)&&M.buttons.length>0,N=wp(e.activeChat,[{status:e.status,activeModal:(b=e.activeChat)==null?void 0:b.activeModal}],e.agents||[]),O=e.activeChat||{title:"",messages:[]};let _=O.title&&String(O.title).trim()?String(O.title).trim():"";const T=(f=e.activeChat)==null?void 0:f.id,H=e.chats;if(T&&Array.isArray(H)&&H.length>0){const E=H.find(L=>L.id===T||L.id&&String(L.id)===String(T));E!=null&&E.title&&String(E.title).trim()&&(_=String(E.title).trim())}const R=(Ye(e)||Ve(e),e.type),F=(Ye(e)||Ve(e))&&Ui(_,S,R)?"":_,A=O.messages||[],I=typeof T=="string"&&T.trim()?T:e.providerSessionId,$=e.coordinator||(typeof((k=e.settings)==null?void 0:k.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:h,providerSessionId:e.providerSessionId,historySessionId:I,nativeSessionId:h,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:Ye(e)?e.mode||"terminal":"chat",agentName:S,agentType:R,status:N,title:F,messages:A,resume:e.resume,hostIdeType:!Ye(e)&&!Ve(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:F||o||(Ye(e)?e.mode==="chat"?S:`Terminal${g}`:S),displaySecondary:Ye(e)&&o?S:d,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:C?M.buttons:void 0,modalMessage:C?M.message:void 0,streamSource:"native",tabKey:wa(h,e.id),machineName:n,connectionState:a,settings:e.settings,coordinator:$,messageInput:e.messageInput})}if(u&&(Ye(e)||Ve(e)))return r;for(const h of m){const j=h.activeModal&&Array.isArray(h.activeModal.buttons)&&h.activeModal.buttons.length>0,v=jp(h),g=ib(h),S=`${e.id}:${g}`,M=h.title&&String(h.title).trim()||"",C=Ui(M,h.agentName,h.agentType)?"":M,N=h.messages||[];if(!(h.transport==="cdp-webview"||!!h.sessionId||!!h.providerSessionId||N.length>0||j||!!C||!["idle","panel_hidden","disconnected","not_monitored"].includes(v)))continue;const _=h.coordinator||(typeof((y=h.settings)==null?void 0:y.meshCoordinatorFor)=="string"&&h.settings.meshCoordinatorFor?{meshId:h.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:h.sessionId||h.instanceId,providerSessionId:h.providerSessionId,historySessionId:h.activeChatId||h.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:h.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:h.sessionCapabilities,mode:"chat",agentName:h.agentName,agentType:h.agentType,status:v,title:C,messages:N,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:h.git||e.git,displayPrimary:C||o||h.agentName||d,displaySecondary:`${d} · ${h.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:h.lastMessagePreview,lastMessageRole:h.lastMessageRole,lastMessageAt:h.lastMessageAt,lastMessageHash:h.lastMessageHash,lastUpdated:h.lastUpdated||e.lastUpdated,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,modalButtons:j?h.activeModal.buttons:void 0,modalMessage:j?h.activeModal.message:void 0,streamSource:"agent-stream",tabKey:wa(h.sessionId||h.instanceId,S),machineName:n,connectionState:a,settings:h.settings,coordinator:_,messageInput:h.messageInput})}return r.length===0&&r.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:wa(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function kd(e){return String(e.type||e.id||"").trim()}function cb(e){var t;return e.category!=="cli"||!kd(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function db(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!cb(a))continue;const o=kd(a);if(!o||t.has(o))continue;t.add(o);const i=String(a.displayName||a.name||o),c=a.detectedPath||((n=a.lastDetection)==null?void 0:n.path)||null;r.push({type:o,label:i,icon:a.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c})}return r}function Dr(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],r=new Set,n=[];for(const a of t){const o=typeof a=="string"?a.trim():"";!o||r.has(o)||(r.add(o),n.push(o))}return n}function yo(e,t){const r=new Set(t.map(n=>n.type));return Dr(e).filter(n=>r.has(n))}function ub(e){return e.map(t=>t.type)}function mb(e,t){const r=Dr(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function hb(e,t){return Dr(e).filter(r=>r!==t)}function ml(e,t,r){const n=Dr(e),a=n.indexOf(t);if(a<0)return n;const o=n.filter(c=>c!==t);if(r==="top")return[t,...o];if(r==="bottom")return[...o,t];const i=r==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(i,0,t),o}function hl({direction:e}){return s.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="up"?s.jsx("polyline",{points:"18 15 12 9 6 15"}):s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function pl({value:e,availableProviders:t,onChange:r,disabled:n=!1,saveButton:a}){const[o,i]=l.useState(""),c=l.useMemo(()=>new Map(t.map(x=>[x.type,x])),[t]),d=l.useMemo(()=>yo(e,t),[e,t]),m=e.length-d.length,u=t.filter(x=>!d.includes(x.type)),p=()=>{o&&(r(mb(d,o)),i(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:d.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):d.map((x,w)=>{const b=c.get(x);return s.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border-subtle bg-bg-primary px-3 py-2 sm:flex-row sm:items-center sm:justify-between",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",w+1]}),(b==null?void 0:b.icon)&&s.jsx("span",{"aria-hidden":"true",children:b.icon}),s.jsx("span",{className:"font-mono text-[12px] text-text-primary",children:x}),s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:"available"})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:b?`${b.label} · ${b.statusLabel}`:x})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:n||w===0,title:"Move up",onClick:()=>r(ml(d,x,"up")),children:s.jsx(hl,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:n||w===d.length-1,title:"Move down",onClick:()=>r(ml(d,x,"down")),children:s.jsx(hl,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(hb(d,x)),children:"Remove"})]})]},x)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:"Add available CLI provider"}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:o,onChange:x=>i(x.target.value),disabled:n||u.length===0,children:[s.jsx("option",{value:"",children:u.length?"Select provider…":"No additional detected CLI providers"}),u.map(x=>s.jsxs("option",{value:x.type,children:[x.label," (",x.type,")"]},x.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!o,onClick:p,children:"Add provider"}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Inventory is filtered to CLI providers detected on this machine. New launches use this order; existing running sessions may need restart.",m>0?` ${m} provider${m===1?"":"s"} from the saved policy are not detected now and will be omitted when saved.`:""]})]})}function pb(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function Sd(e,t){const r=pb(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Nd=[{id:"antigravity",name:"Antigravity",icon:"🌀"},{id:"cursor",name:"Cursor",icon:"⚡"},{id:"kiro",name:"Kiro",icon:"🎯"},{id:"pearai",name:"PearAI",icon:"🍐"},{id:"trae",name:"Trae",icon:"🔮"},{id:"vscode",name:"VS Code",icon:"💙"},{id:"vscodium",name:"VSCodium",icon:"💚"},{id:"windsurf",name:"Windsurf",icon:"🏄"}],Cd=[{id:"aider-cli",name:"Aider",icon:"🛠️"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"gemini-cli",name:"Gemini CLI",icon:"✨"},{id:"github-copilot-cli",name:"GitHub Copilot CLI",icon:"🤖"},{id:"goose-cli",name:"Goose",icon:"🪿"},{id:"opencode-cli",name:"OpenCode CLI",icon:"🧩"}],Md=[{id:"cline",name:"Cline",icon:"🧠"},{id:"codex",name:"Codex",icon:"📦"},{id:"roo-code",name:"Roo Code",icon:"🦘"},{id:"claude-code-vscode",name:"Claude Code (VS Code)",icon:"🟠"}],fb=Nd,xb=Cd,bb=Md;function qt(...e){return gm(ym(e))}function gb({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:qt("dashboard-header",o),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function xr({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:o="max-w-6xl",contentClassName:i,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(gb,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:qt("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const vo="adhdev:themechange";function yb(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Ms(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Is(e){return e==="system"?yb():e}function Id(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function yn(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(vo,{detail:{preference:e,theme:t}}))}function vb(){const e=Ms(),t=Is(e);Id(t),yn(e,t)}function Us(){const[e,t]=l.useState(Ms),[r,n]=l.useState(()=>Is(Ms()));l.useEffect(()=>{Id(r)},[r]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const m=d.matches?"light":"dark";n(m),yn("system",m)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=d=>{const m=d.detail||{},u=m.preference,p=m.theme;t(u==="dark"||u==="light"||u==="system"?u:Ms()),n(p==="dark"||p==="light"?p:Is(Ms()))},c=d=>{if(d.key!=="theme")return;const m=Ms(),u=Is(m);t(m),n(u)};return window.addEventListener(vo,i),window.addEventListener("storage",c),()=>{window.removeEventListener(vo,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=Is(i);t(i),n(c);try{localStorage.setItem("theme",i)}catch{}yn(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=Is(c);n(d);try{localStorage.setItem("theme",c)}catch{}return yn(c,d),c})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const fl={dark:"Dark",light:"Light",system:"System"};function wb({collapsed:e}){const{preference:t,cycleTheme:r}=Us(),n=t==="dark"?s.jsx(vh,{size:16}):t==="light"?s.jsx(yh,{size:16}):s.jsx(wh,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${fl[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:fl[t]})]})}function ja(e,t){return e?typeof e=="function"?e(t):e:null}function jb({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const[m,u]=l.useState(!1),[p,x]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),w=()=>u(!0),b=()=>u(!1),f=()=>{x(j=>{const v=!j;try{localStorage.setItem(d,v?"1":"0")}catch{}return v})},k=l.useMemo(()=>({collapsed:p,mobileMenuOpen:m,openMobileMenu:w,closeMobileMenu:b,toggleCollapsed:f}),[p,m]),y=j=>`nav-item${j.active?" active":""} cursor-pointer ${p?"justify-center py-2.5 px-0":""}${j.className?` ${j.className}`:""}`,h=j=>s.jsxs("div",{className:y(j),id:`nav-${j.id}`,onClick:()=>{j.onSelect(),b()},title:p?j.title??(typeof j.label=="string"?j.label:void 0):j.title,children:[s.jsx("span",{className:"nav-icon",children:j.icon}),!p&&j.label]},j.id);return s.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${p?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:w,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),m&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:b,onKeyDown:j=>j.key==="Escape"&&b()}),s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${p?"justify-center gap-0":""}`,children:ja(t,k)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:b,children:s.jsx(gt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(h)}),n.map(j=>s.jsxs("div",{className:j.className??"border-t border-border-subtle pt-2 mt-2",children:[!p&&j.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:j.title}):null,j.items.map(h)]},j.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(h),ja(o,k),s.jsx(wb,{collapsed:p}),ja(i,k)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function it({title:e,icon:t,description:r,accentColor:n,className:a,children:o}){return s.jsxs("div",{className:qt("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&s.jsxs("div",{className:"mb-4",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[t&&s.jsx("span",{className:"mr-1.5",children:t}),e]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),o]})}function Un({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:qt("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const kb={error:"bg-red-500/10 border-red-500/30 text-red-400",warning:"bg-yellow-500/10 border-yellow-500/30 text-yellow-400",success:"bg-green-500/10 border-green-500/30 text-green-400",info:"bg-indigo-500/10 border-indigo-500/30 text-indigo-400"},Sb={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function _s({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:qt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",kb[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Sb[e]}),s.jsx("span",{children:t})]}),r&&s.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function ht({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:qt("mb-5",n),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),r,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function Ss(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:qt("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const Nb={online:"bg-green-500/10 text-green-400 border-green-500/30",idle:"bg-yellow-500/10 text-yellow-400 border-yellow-500/30",busy:"bg-orange-500/10 text-orange-400 border-orange-500/30",error:"bg-red-500/10 text-red-400 border-red-500/30",offline:"bg-gray-500/10 text-text-secondary border-gray-500/30"},Cb={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Mb({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:qt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Nb[e],r),children:[s.jsx("span",{className:qt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Cb[e])}),n]})}function ls({label:e,description:t,checked:r,disabled:n,onChange:a,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o,s.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function Ib({onPrefChange:e}){const[t,r]=Lp(),[n,a]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const i=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return i(),window.addEventListener("focus",i),document.addEventListener("visibilitychange",i),()=>{window.removeEventListener("focus",i),document.removeEventListener("visibilitychange",i)}},[]);const o=(i,c)=>{r({[i]:c}),e==null||e(i,c)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(ls,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Tr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:i=>o("globalEnabled",i)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(ls,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Bt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:i=>o("browserNotifications",i)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{Hc().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(ls,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(jh,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:i=>o("completionAlert",i)}),s.jsx(ls,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(kh,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:i=>o("approvalAlert",i)}),s.jsx(ls,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Bs,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:i=>o("disconnectAlert",i)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function zn(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Tb(e,t){const r=zn(e),n=zn(t);if(!r||!n)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function Qo(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function br(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Tb(r,t)>=0)return!1;const n=zn(r),a=zn(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Ab(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function ka(e,t){return e instanceof Error?e.message:t}function _b({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const o=e.filter(i=>i.type==="adhdev-daemon");return o.length===0?s.jsx(Un,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:t||"Install ADHDev on a machine and sign in to connect it here."}):s.jsx("div",{className:"flex flex-col gap-2",children:o.map(i=>s.jsx(Pb,{ide:i,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},i.id))})}function xl({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:o}){const i=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return vr.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:c=>c.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${i}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function Lb(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...fb,...xb,...bb].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function Pb({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var R,F;const[o,i]=l.useState("idle"),[c,d]=l.useState(""),[m,u]=l.useState(null),[p,x]=l.useState("idle"),[w,b]=l.useState(""),f=e.version||null,k=((R=e.machine)==null?void 0:R.platform)||((F=e.system)==null?void 0:F.platform)||"",y=Ct(e,{fallbackId:e.id}),h=k==="win32"?"🪟":k==="darwin"?"🍎":"🐧",j=t.filter(A=>A.daemonId===e.id&&A.transport==="cdp-page"),v=t.filter(A=>A.daemonId===e.id&&A.transport==="pty"),g=t.filter(A=>A.daemonId===e.id&&A.transport==="acp"),S=e.p2p,M=async()=>{if(r){i("upgrading"),d("Starting upgrade...");try{const A=Ab(await r(e.id,"daemon_upgrade",{}));A.alreadyLatest?(i("done"),d(`Already on v${A.version||"latest"}.`)):A.upgraded||A.success?(i("done"),d(`Upgrade to v${A.version||"latest"} started. Daemon is restarting...`)):(i("error"),d(A.error||"Upgrade failed"))}catch(A){i("error"),d(ka(A,"Connection lost during upgrade"))}}},C=async()=>{if(u(null),!!n){x("loading");try{await n(e.id),x("done"),b("Machine disconnected.")}catch(A){x("error"),b(ka(A,"Failed to disconnect"))}}},N=async()=>{if(u(null),!!a){x("loading");try{await a(e.id),x("done"),b("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(A){x("error"),b(ka(A,"Failed to revoke token"))}}},O="0.9.81",_=Qo(e,O),T=br(e,O),H=j.length+v.length+g.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:h}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:y}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),f&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${_?"":"bg-bg-secondary"}`,style:_?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",f,!_&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&_&&s.jsx("button",{onClick:M,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${O}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${T?"↑ Update now":`↑ Update${` to v${O}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:p==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:p==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Mb,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[S&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${S.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${S.state==="connecting"||S.state==="new"?"animate-pulse":""}`,style:S.state==="connecting"||S.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",S.state==="connected"?"connected":S.state==="connecting"||S.state==="new"?"connecting...":S.state||"off"]}),S.peers!==void 0&&S.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",S.peers," peer",S.peers!==1?"s":"",")"]})]}),S&&H>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),H>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[j.map(A=>{const I=Lb(A.type),$=A.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:I.icon}),s.jsx("span",{children:I.name}),$!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${$?"bg-green-400":"animate-pulse"}`,style:$?void 0:{background:"var(--status-warning)"},title:$?"CDP connected":"CDP connecting..."})]},A.id)}),v.map(A=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:A.cliName||"CLI"})]},A.id)),g.map(A=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:A.cliName||"ACP"})]},A.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(c||w)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||p==="error"?"text-red-400":o==="done"||p==="done"?"text-green-400":"text-text-muted"}`,children:w||c})]}),m==="disconnect"&&s.jsx(xl,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
44
+
45
+ This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
46
+
47
+ Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:C,onCancel:()=>u(null)}),m==="revoke"&&s.jsx(xl,{title:"⚠️ Remove Machine",message:`Remove "${y}" from your dashboard?
48
+
49
+ This will:
50
+ • Immediately disconnect the machine
51
+ • Delete the machine registration
52
+ • Require restarting ADHDev on that machine
53
+
54
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:N,onCancel:()=>u(null)})]})}const Rb=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function Db({daemonId:e,knownCliTypes:t=Rb}){const{sendCommand:r}=lt(),[n,a]=l.useState({}),[o,i]=l.useState({}),[c,d]=l.useState(!0),[m,u]=l.useState(null),[p,x]=l.useState(null),[w,b]=l.useState(""),f=l.useCallback(async()=>{if(e){d(!0),x(null);try{const h=await r(e,"list_coordinator_prompts",{}),j=h!=null&&h.result&&typeof h.result=="object"?h.result:h;if(!(j!=null&&j.success)){x((j==null?void 0:j.error)||"Failed to load");return}const v=j.entries||{};b(j.dir||"");const g={};for(const S of t)g[S]=v[S]||{override:"",append:""};for(const S of Object.keys(v))g[S]||(g[S]=v[S]);a(g),i(JSON.parse(JSON.stringify(g)))}catch(h){x((h==null?void 0:h.message)||String(h))}finally{d(!1)}}},[r,e,t]);l.useEffect(()=>{f()},[f]);const k=l.useCallback(async(h,j)=>{var v;if(e){u(`${h}:${j}`),x(null);try{const g=((v=n[h])==null?void 0:v[j])||"",S=await r(e,"write_coordinator_prompt",{key:h,kind:j,content:g}),M=S!=null&&S.result&&typeof S.result=="object"?S.result:S;if(!(M!=null&&M.success)){x((M==null?void 0:M.error)||"Save failed");return}i(C=>({...C,[h]:{...C[h]||{override:"",append:""},[j]:g}}))}catch(g){x((g==null?void 0:g.message)||String(g))}finally{u(null)}}},[r,e,n]),y=l.useMemo(()=>(h,j)=>{var v,g;return(((v=n[h])==null?void 0:v[j])||"")!==(((g=o[h])==null?void 0:g[j])||"")},[n,o]);return e?s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",children:[s.jsxs("p",{children:["Customize the coordinator prompt this daemon's mesh coordinator sessions get. ",s.jsx("span",{className:"font-mono text-[11px]",children:w||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx("strong",{children:"Override"})," replaces the daemon's built-in base prompt for that CLI."," ",s.jsx("strong",{children:"Append"})," stacks after whichever base wins. Leave a field empty + Save to remove it (reset to default). Supports placeholders: ","{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}",", etc."]})]}),p&&s.jsx("div",{className:"text-[12px] text-red-400 bg-red-500/10 border border-red-500/20 rounded px-3 py-2",children:p}),c&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(n).map(([h,j])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-2",children:h}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Override"}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:4,value:j.override,onChange:v=>a(g=>({...g,[h]:{...g[h],override:v.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:m===`${h}:override`}),s.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void k(h,"override"),disabled:m===`${h}:override`||!y(h,"override"),children:m===`${h}:override`?"Saving…":y(h,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Append"}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:3,value:j.append,onChange:v=>a(g=>({...g,[h]:{...g[h],append:v.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:m===`${h}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void k(h,"append"),disabled:m===`${h}:append`||!y(h,"append"),children:m===`${h}:append`?"Saving…":y(h,"append")?"Save append":"Saved"})})]},h))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const Eb=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function $b(){const{preference:e,setPreference:t}=Us();return s.jsx("div",{className:"flex gap-2",children:Eb.map(r=>s.jsxs("button",{onClick:()=>t(r.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx("span",{children:r.icon}),r.label]},r.id))})}function Bb(e){const t=e.trim();return/^#[0-9a-fA-F]{6}$/.test(t)?t:/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:null}function Ob(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Sa(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function bl(e){const{r:t,g:r,b:n}=Ob(e);return .2126*Sa(t)+.7152*Sa(r)+.0722*Sa(n)}function gl(e,t){const r=bl(e),n=bl(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function Td(e){const t=Bb(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return gl(t,r)>=gl(t,n)?r:n}const wo={bgPrimary:"#0a0e1a",bgSecondary:"#0f1320",surfacePrimary:"#111726",textPrimary:"#f0f0f5",textSecondary:"#9ca3af",textMuted:"#6b7280",borderSubtle:"#1d2536",borderDefault:"#313c52",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#111726",assistantText:"#f0f0f5",containerBg:"#0f1320",sendButton:"#d97706",inputBorder:"#313c52",bubbleRadius:16},jo={bgPrimary:"#fff8ee",bgSecondary:"#fff1de",surfacePrimary:"#ffffff",textPrimary:"#24160f",textSecondary:"#6f6255",textMuted:"#938374",borderSubtle:"#e7d3ba",borderDefault:"#d7b892",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#fffaf4",assistantText:"#24160f",containerBg:"#fff8ee",sendButton:"#d97706",inputBorder:"#d7b892",bubbleRadius:16},Fb=[{id:"midnight",name:"Midnight",description:"Classic violet theme",preview:{dark:{userBubble:"#8b5cf6",assistantBubble:"#18181d",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0f0f13",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#7c3aed",assistantBubble:"#ffffff",assistantBorder:"1px solid rgba(0,0,0,0.08)",containerBg:"#f0f1f5",textColor:"#52525b"}}},{id:"ember",name:"Ember",description:"Default landing-inspired amber theme",preview:{dark:{userBubble:"#f59e0b",assistantBubble:"#111726",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0a0e1a",textColor:"#9ca3af"},light:{userBubble:"#f59e0b",assistantBubble:"#fffaf4",assistantBorder:"1px solid rgba(146,64,14,0.10)",containerBg:"#fff8ee",textColor:"#6f6255"}}},{id:"aurora",name:"Aurora",description:"Pink accent theme",preview:{dark:{userBubble:"#ec4899",assistantBubble:"#1e1b2e",assistantBorder:"1px solid rgba(236,72,153,0.12)",containerBg:"#0f0d17",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#ec4899",assistantBubble:"#fef2f8",assistantBorder:"1px solid rgba(236,72,153,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}},{id:"honey",name:"Honey",description:"Warm yellow accents",preview:{dark:{userBubble:"#fbbf24",assistantBubble:"#1c1c1e",assistantBorder:"1px solid rgba(255,255,255,0.06)",containerBg:"#111113",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#fbbf24",assistantBubble:"#fffbeb",assistantBorder:"1px solid rgba(251,191,36,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}}],Ad="adhdev-chat-theme",_d="adhdev-chat-theme-custom";function vn(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Ad)||"ember"}catch{return"ember"}}function Et(e){try{const t=localStorage.getItem(_d);if(t){const r=JSON.parse(t);return{...e==="dark"?wo:jo,...r[e]}}}catch{}return e==="dark"?wo:jo}function tn(e,t){try{localStorage.setItem(_d,JSON.stringify({dark:e,light:t}))}catch{}}function Mt(e,t){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${t})`}function Gn(e,t){const r=Math.min(255,parseInt(e.slice(1,3),16)+t),n=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const Hb={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function gr(e,t){var a;const r=(a=Hb[e])==null?void 0:a[t];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",Gn(r,24)),n.style.setProperty("--accent-on-primary",Td(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Gn(r,18)})`),n.style.setProperty("--border-accent",Mt(r,.35)),n.style.setProperty("--nav-active-bg",Mt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Mt(r,.06)}`)}function hs(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Mt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Mt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Mt(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",Mt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Mt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Gn(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Td(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Gn(e.accentColor,40)})`),t.style.setProperty("--border-accent",Mt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Mt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Mt(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${Mt(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function Zo(){const e=document.documentElement;["--bg-primary","--bg-secondary","--bg-card","--surface-primary","--surface-secondary","--bg-glass","--bg-glass-hover","--text-primary","--text-secondary","--text-muted","--border-subtle","--border-default","--accent-primary","--accent-primary-light","--accent-on-primary","--accent-gradient","--border-accent","--nav-active-bg","--nav-active-shadow","--chat-user-bg","--chat-user-color","--chat-user-radius","--chat-assistant-bg","--chat-assistant-color","--chat-assistant-radius","--chat-assistant-border","--chat-container-bg","--dashboard-pane-bg","--chat-thought-accent","--chat-tool-accent","--chat-action-color","--chat-send-bg","--chat-input-border"].forEach(r=>e.style.removeProperty(r))}function Wb(e){try{localStorage.setItem(Ad,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ps()?"dark":"light";hs(Et(t))}else Zo(),gr(e,ps()?"dark":"light")}function Kb(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=vn();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ps()?"dark":"light";hs(Et(t))}else Zo(),gr(e,ps()?"dark":"light")}function ps(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function vt({label:e,value:t,onChange:r}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function sr({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function Ub({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=l.useState(()=>Et(r));l.useEffect(()=>{a(Et(r))},[r]);const o=l.useCallback((i,c)=>{a(d=>{const m={...d,[i]:c},p=Et(r==="dark"?"light":"dark");return r==="dark"?tn(m,p):tn(p,m),hs(m),t(m),m})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",s.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(sr,{title:"App Background",children:[s.jsx(vt,{label:"Background",value:n.bgPrimary,onChange:i=>o("bgPrimary",i)}),s.jsx(vt,{label:"Surface",value:n.bgSecondary,onChange:i=>o("bgSecondary",i)}),s.jsx(vt,{label:"Card",value:n.surfacePrimary,onChange:i=>o("surfacePrimary",i)})]}),s.jsxs(sr,{title:"App Text",children:[s.jsx(vt,{label:"Primary",value:n.textPrimary,onChange:i=>o("textPrimary",i)}),s.jsx(vt,{label:"Secondary",value:n.textSecondary,onChange:i=>o("textSecondary",i)}),s.jsx(vt,{label:"Muted",value:n.textMuted,onChange:i=>o("textMuted",i)})]}),s.jsxs(sr,{title:"Borders & Accent",children:[s.jsx(vt,{label:"Border subtle",value:n.borderSubtle,onChange:i=>o("borderSubtle",i)}),s.jsx(vt,{label:"Border default",value:n.borderDefault,onChange:i=>o("borderDefault",i)}),s.jsx(vt,{label:"Accent",value:n.accentColor,onChange:i=>o("accentColor",i)})]})]}),s.jsxs("div",{children:[s.jsxs(sr,{title:"Chat Bubbles",children:[s.jsx(vt,{label:"User bubble",value:n.userBubble,onChange:i=>o("userBubble",i)}),s.jsx(vt,{label:"User text",value:n.userText,onChange:i=>o("userText",i)}),s.jsx(vt,{label:"Agent bubble",value:n.assistantBubble,onChange:i=>o("assistantBubble",i)}),s.jsx(vt,{label:"Agent text",value:n.assistantText,onChange:i=>o("assistantText",i)})]}),s.jsxs(sr,{title:"Chat Layout",children:[s.jsx(vt,{label:"Chat BG",value:n.containerBg,onChange:i=>o("containerBg",i)}),s.jsx(vt,{label:"Send button",value:n.sendButton,onChange:i=>o("sendButton",i)}),s.jsx(vt,{label:"Input border",value:n.inputBorder,onChange:i=>o("inputBorder",i)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:i=>o("bubbleRadius",Number(i.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const i=e?wo:jo,d=Et(e?"light":"dark");e?tn(i,d):tn(d,i),a(i),hs(i),t(i)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function zb(){const[e,t]=l.useState(vn),[r,n]=l.useState(!0),[a,o]=l.useState(()=>Et("dark"));l.useEffect(()=>{n(ps());const d=new MutationObserver(()=>{const p=ps();n(p);const x=vn();x==="custom"?hs(Et(p?"dark":"light")):gr(x,p?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const p=ps();n(p);const x=vn();x==="custom"?hs(Et(p?"dark":"light")):gr(x,p?"dark":"light")};return m.addEventListener("change",u),()=>{d.disconnect(),m.removeEventListener("change",u)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?hs(Et(r?"dark":"light")):(Zo(),gr(e,r?"dark":"light"))},[e,r]),l.useEffect(()=>{o(Et(r?"dark":"light"))},[r]);const i=d=>{t(d),Wb(d)},c=[...Fb,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:c.map(d=>{const m=e===d.id,u=r?d.preview.dark:d.preview.light,p=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>i(d.id),className:"text-left rounded-xl p-3 transition-all",style:{background:m?"var(--bg-glass-hover)":"var(--bg-glass)",border:m?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:m?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:u.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:p},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[m&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:d.id==="custom"?"🎨 Custom":d.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:d.description})]})]})]},d.id)})}),e==="custom"&&s.jsx(Ub,{dark:r,onColorsChange:d=>o(d)})]})}const ei="adhdev_mobileDashboardMode_v1",ko="adhdev:mobile-dashboard-mode-change";function ti(){try{return localStorage.getItem(ei)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Gb(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??ti())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==ei||t()};return window.addEventListener(ko,r),window.addEventListener("storage",n),()=>{window.removeEventListener(ko,r),window.removeEventListener("storage",n)}}function Vb(e){try{localStorage.setItem(ei,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ko,{detail:e}))}function qb(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(ti()==="chat")},[]),s.jsx(ls,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ws,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{t(r),Vb(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Na=new Map,yl=new Map;function Yb(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t,n=r.machine;return!n||typeof n!="object"?null:{machine:n,timestamp:typeof r.timestamp=="number"?r.timestamp:void 0}}function Xb(e,t,r,n){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n,platform:r.platform,machine:r}}function Ld(){const{sendCommand:e}=lt(),{injectEntries:t,getIdes:r}=wr();return l.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??Lf,i=yl.get(n)||0;if(!(a!=null&&a.force)&&i>0&&Date.now()-i<o)return;const c=Na.get(n);if(c)return c;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=Yb(m);if(!u)return;const p=r().find(w=>w.id===n),x=Xb(p,n,u.machine,u.timestamp||Date.now());t([x]),yl.set(n,Date.now())})().finally(()=>{Na.delete(n)});return Na.set(n,d),d},[r,t,e])}function Jb(e,t,r){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r.timestamp,platform:r.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...r.machine}}}function Qb(e,t){const{sendData:r}=lt(),{injectEntries:n,getIdes:a}=wr(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(d=>Gt.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const p=a().find(w=>w.id===d),x=Jb(p,d,u);n([x])}));return()=>{c.forEach(d=>d())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function Zb(e,t){const{sendData:r}=lt(),[n,a]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){a(null),i(!1);return}if(!(t!=null&&t.enabled)||!r){i(!1);return}a(null),i(!0);let c=null;const d=Gt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},m=>{c&&(clearTimeout(c),c=null),a(m.diagnostics),i(!1)});return d.initialSendAccepted?c=setTimeout(()=>{i(!1)},Ef):i(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:o,applyDiagnostics:a}}function eg(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Pd(e){const{sendData:t}=lt(),[r,n]=l.useState({});return l.useEffect(()=>{const a=eg(e);if(!a||!e.sessionId||!t){n({});return}const o=Gt.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{n({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),Ds.record({interactionId:i.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:i.status,modalButtonCount:Array.isArray(i.modalButtons)?i.modalButtons.length:0}})});return o.initialSendAccepted||n({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const Rd="adhdev_hiddenTabs",Dd="adhdev_autoHiddenMeshTabs";function tg(){try{const e=localStorage.getItem(Rd);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function os(e){try{localStorage.setItem(Rd,JSON.stringify([...e]))}catch{}}function sg(){try{const e=localStorage.getItem(Dd);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function vl(e){try{localStorage.setItem(Dd,JSON.stringify([...e]))}catch{}}function dr(e){return Sr(e)}function aa(e,t){return Vt(t).some(r=>e.has(r))}function Ed(e){var t,r,n;return((t=e.settings)==null?void 0:t.launchedByCoordinator)===!0&&typeof((r=e.settings)==null?void 0:r.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0&&((n=e.settings)==null?void 0:n.spawnedSessionVisibility)==="hidden"}function rg(e,t,r=new Set){return e.filter(n=>{if(!Ed(n))return!1;const a=dr(n);return r.has(a)?!1:!aa(t,n)})}function ng(){const[e,t]=l.useState(tg),[r,n]=l.useState(sg),a=l.useCallback(x=>{const w=dr(x);t(b=>{const f=new Set(b);return f.has(w)?f.delete(w):f.add(w),os(f),f})},[]),o=l.useCallback(x=>{const w=dr(x);t(b=>{if(b.has(w))return b;const f=new Set(b);return f.add(w),os(f),f})},[]),i=l.useCallback(x=>{const w=dr(x);t(b=>{if(b.has(w))return b;const f=new Set(b);return f.add(w),os(f),f}),n(b=>{if(b.has(w))return b;const f=new Set(b);return f.add(w),vl(f),f})},[]),c=l.useCallback(x=>{const w=dr(x);t(b=>{if(!b.has(w))return b;const f=new Set(b);return f.delete(w),os(f),f}),n(b=>{if(b.has(w))return b;const f=new Set(b);return f.add(w),vl(f),f})},[]),d=l.useCallback(()=>{t(x=>{if(x.size===0)return x;const w=new Set;return os(w),w})},[]),m=l.useCallback((x,w)=>{t(b=>{const f=new Set(b);for(const k of w)f.add(k);return os(f),f})},[]),u=l.useCallback((x,w)=>{t(b=>{const f=new Set(b);for(const k of w)f.delete(k);return os(f),f})},[]),p=l.useCallback(x=>aa(e,x),[e]);return{hiddenTabs:e,autoHiddenTabs:r,toggleTarget:a,hideTarget:o,autoHideTarget:i,showTarget:c,showAllTabs:d,hideAllForDaemon:m,showAllForDaemon:u,isHidden:p}}const sn="adhdev_mutedConversations",Ca="adhdev_autoMutedMeshConversations";function wl(e){try{const t=localStorage.getItem(e);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function rr(e,t){try{localStorage.setItem(e,JSON.stringify([...t]))}catch{}}function ag(e,t){return Vt(t).some(r=>e.has(r))}function og(){const[e,t]=l.useState(()=>wl(sn)),[r,n]=l.useState(()=>wl(Ca)),a=l.useCallback(m=>{const u=Sr(m);t(p=>{if(p.has(u))return p;const x=new Set(p);return x.add(u),rr(sn,x),x})},[]),o=l.useCallback(m=>{const u=Vt(m);t(p=>{let x=!1;const w=new Set(p);for(const b of u)w.delete(b)&&(x=!0);return x?(rr(sn,w),w):p}),n(p=>{let x=!1;const w=new Set(p);for(const b of u)w.delete(b)&&(x=!0);return x?(rr(Ca,w),w):p})},[]),i=l.useCallback(m=>{Vt(m).some(x=>e.has(x))?o(m):a(m)},[e,a,o]),c=l.useCallback(m=>{if(!Ed(m))return;const u=Sr(m);r.has(u)||(n(p=>{if(p.has(u))return p;const x=new Set(p);return x.add(u),rr(Ca,x),x}),t(p=>{if(p.has(u))return p;const x=new Set(p);return x.add(u),rr(sn,x),x}))},[r]),d=l.useCallback(m=>ag(e,m),[e]);return{mutedTargets:e,autoMutedTargets:r,muteTarget:a,unmuteTarget:o,toggleTarget:i,autoMuteIfCoordinator:c,isMuted:d}}function $d(e){return e instanceof Error?e.message:String(e||"")}function ig(e){const t=$d(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function lg(e){const t=$d(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Bd({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!Ye(e)||Ve(e))return;const o=Ks(e);if(o===t)return;const i=e.sessionId;i&&a(c=>({...c,[i]:t}));try{await n(js(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Kt(e),mode:t})}catch(c){const d=lg(c);i&&!d&&a(m=>{const u={...m};return o===Od(r,i)?delete u[i]:u[i]=o,u}),ig(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function jl(e,t){const r=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!r||e.transport!=="pty")return e;const n=t[r];return!n||e.mode===n?e:{...e,mode:n}}function cg(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let r=!1;const n=e.map(a=>{const o=jl(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(d=>jl(d,t)):a.childSessions,c=i!==a.childSessions;return o!==a||c?(r=!0,{...o,...c?{childSessions:i}:{}}):a});return r?n:e}function Od(e,t){if(!t)return null;for(const r of e){if(r.sessionId===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function dg(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,o]of Object.entries(e))Od(t,a)===o&&(delete n[a],r=!0);return r?n:e}function ug({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){l.useEffect(()=>{Hc()},[]);const a=l.useMemo(()=>e.map(o=>({id:o.tabKey,name:md(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return Ep(a),l.useEffect(()=>{if(Object.keys(t).length===0)return;const i=setTimeout(()=>{r(c=>{const d=Date.now(),m={};for(const[u,p]of Object.entries(c))d-p<5e3&&(m[u]=p);return Object.keys(m).length===Object.keys(c).length?c:m})},5500);return()=>clearTimeout(i)},[t,r]),l.useEffect(()=>{const o=setInterval(()=>{const i=Date.now()-3e5;n(c=>{const d=c.filter(m=>m.timestamp>i).slice(-100);return d.length===c.length?c:d})},6e4);return()=>clearInterval(o)},[n]),null}function kl(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function fs(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],r=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,n=kl(t==null?void 0:t.receivedAt)||kl(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function So(e,t=0){return fs(e)||e.lastUpdated||t||0}function Fd(e){return fs(e)||e.lastUpdated||0}function Hd(e,t,r=Fd){const n=r(t)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const o=e.displayPrimary.localeCompare(t.displayPrimary);if(o!==0)return o;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function No(e){var r;const t=Tt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function mg(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!No(e)&&!e.title.trim()}function hg(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(No(r))-Number(No(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:Hd(t,r)})[0]||null}function $t(e,t){const r=e.filter(i=>i.routeId===t);if(r.length===0)return null;const n=r.find(i=>i.streamSource==="native")||null,a=r.filter(i=>i.streamSource==="agent-stream"),o=hg(a);return n?o&&mg(n)?o:n:o||r[0]||null}function pg(e){const t=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return!t||r.startsWith(`${t}:`)?r:`${t}:${r}`}function fg(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=pg(n),o=r.get(a);if(!o){r.set(a,n);continue}const i=(o.workspace?1:0)+(o.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(o.timestamp||0))&&r.set(a,n)}return Array.from(r.values())}function Ma(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function xg(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function Sl(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?xg(Es(r.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((r==null?void 0:r.id)||""),String((r==null?void 0:r.index)??""),String((r==null?void 0:r.receivedAt)??(r==null?void 0:r.timestamp)??""),n].join(":")}function bg(e){const t=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),Sl(e.activeChat),...t.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastMessageAt||""),r.lastMessagePreview||"",r.lastMessageRole||"",String(r.lastUpdated||""),Sl(r.activeChat)].join(":"))].join("|")}function gg(e,t){const r=Date.now();return e.map(n=>{const a=t[n.tabKey];return a&&r-a<5e3?{...n,messages:[],title:""}:n})}function yg(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of Vt({routeId:n.routeId}))r.set(o,a);for(const o of Vt({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Vt({tabKey:n.tabKey}))r.set(o,n)}return r}function vg(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function wg(e){const t=vg(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const r=String(t.role||""),n=Es(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function jg({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=l.useMemo(()=>fg(e),[e]),o=l.useMemo(()=>wd(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),m=l.useRef(new Map),u=l.useRef(new Map),p=l.useMemo(()=>{const v=new Map,g=[];for(const N of a){const{connectionState:O="new",machineName:_}=jd(N,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),T=bg(N),H=m.current.get(N.id);if(H&&H.ide===N&&H.sourceSignature===T&&H.connectionState===O&&H.machineName===_){v.set(N.id,H),g.push(...H.conversations);continue}const R=Jo(N,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),F={ide:N,sourceSignature:T,connectionState:O,machineName:_,conversations:R};v.set(N.id,F),g.push(...R)}m.current=v;const S=new Map,M=N=>{const O=wg(N),_=u.current.get(N.tabKey);if(_&&_.signature===O)return S.set(N.tabKey,_),_.timestamp;const T={signature:O,timestamp:Fd(N)||(_==null?void 0:_.timestamp)||0};return S.set(N.tabKey,T),T.timestamp},C=[...g].sort((N,O)=>Hd(N,O,M));return u.current=S,C},[a,t,o]),x=l.useMemo(()=>{const v=gg(p,r);return Ma(i.current,v)?i.current:(i.current=v,v)},[p,r]),w=l.useMemo(()=>{const v=new Map,g=Array.from(new Set(x.map(S=>S.routeId)));for(const S of g){const M=$t(x,S);M&&v.set(S,M)}return v},[x]),b=l.useMemo(()=>{const v=new Map;for(const g of x){const S=w.get(g.routeId),M=g.streamSource==="native"&&S?S:g;for(const C of Vt({providerSessionId:g.providerSessionId,sessionId:g.sessionId,tabKey:g.tabKey}))v.set(C,M)}return v},[x,w]),f=l.useMemo(()=>yg(x,w),[x,w]),k=l.useCallback(v=>{if(v)return b.get(v)},[b]),y=l.useCallback(v=>{if(v)return f.get(v)},[f]),h=l.useMemo(()=>{const v=x.filter(g=>!aa(n,g));return Ma(c.current,v)?c.current:(c.current=v,v)},[x,n]),j=l.useMemo(()=>{const v=h.map(g=>g.tabKey);return Ma(d.current,v)?d.current:(d.current=v,v)},[h]);return{chatIdes:a,conversations:x,visibleConversations:h,visibleTabKeys:j,resolveConversationBySessionId:k,resolveConversationByTarget:y}}function kg({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=l.useMemo(()=>{var c;return e||!t?null:((c=r(t))==null?void 0:c.tabKey)??null},[e,r,t]),o=l.useMemo(()=>{var c;return!e||!t?null:((c=r(t))==null?void 0:c.tabKey)??null},[e,r,t]),i=l.useCallback(()=>{t&&n(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function Sg({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){l.useEffect(()=>{Je.setIdes(e)},[e]),l.useEffect(()=>{Je.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=Je.onToast(o=>{r(c=>c.some(m=>m.message===o.message&&o.timestamp-m.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>r(c=>c.filter(d=>d.id!==o.id)),i)});return()=>{a()}},[r]),l.useEffect(()=>{const a=cd.on("status_event",o=>{Je.handleRawEvent(o,"ws")});return()=>{a()}},[]),l.useEffect(()=>{var o;const a=i=>{var f;const c=i.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,m=n(d),u=(m==null?void 0:m.routeId)||c.daemonId;if(!u)return;const p=Number(c.buttonIndex),x=c.button||((f=m==null?void 0:m.modalButtons)==null?void 0:f[p])||"Approve",w=String(x).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),b=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(w);t(u,"resolve_action",{action:b?"approve":"reject",button:x,...Number.isFinite(p)&&{buttonIndex:p},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(k=>console.error("[SW Action] approval failed:",k))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",a)}},[n,t])}const Ng="adhdev_dashboardLayout_v1",Cg="adhdev_dashboardDockview_v1",Mg="adhdev_dashboardDockviewHiddenRestore_v1",nr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function si(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Ig(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Wd(e){return`${Ng}:${e}`}function Tg(e){const t=Wd(e);return si(t,null)}function Ag(e,t){try{const r=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,n=Wd(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Kd(e){return`${Cg}:${e}`}function _g(e){const t=Kd(e);return si(t,null)}function Lg(e,t){try{const r=Kd(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Ud(e){return`${Mg}:${e}`}function Pg(e){const t=Ud(e);return si(t,{})}function Rg(e,t){try{const r=Ud(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Dg(){return{groupAssignments:[...nr.groupAssignments],focusedGroup:nr.focusedGroup,groupActiveTabIds:{...nr.groupActiveTabIds},groupTabOrders:{...nr.groupTabOrders},groupSizes:[...nr.groupSizes]}}function Eg(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function $g(){const[e]=l.useState(()=>Ig(typeof window<"u"?window.innerWidth:1280)),[t,r]=l.useState(()=>new Map),[n,a]=l.useState(0),[o,i]=l.useState({}),[c,d]=l.useState({}),[m,u]=l.useState([]),[p,x]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[w,b]=l.useState(!1),f=l.useCallback(()=>{if(w)return;const N=Tg(e)??Dg();r(new Map(N.groupAssignments)),a(N.focusedGroup),i(N.groupActiveTabIds),d(N.groupTabOrders),u(N.groupSizes),b(!0)},[w,e]);l.useEffect(()=>{w&&Ag(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:c,groupSizes:m})},[w,e,t,n,o,c,m]),l.useEffect(()=>{const N=window.matchMedia("(max-width: 767px)"),O=_=>x(_.matches);return N.addEventListener("change",O),()=>N.removeEventListener("change",O)},[]);const k=l.useCallback(N=>{r(N)},[]),y=l.useCallback(N=>{a(N)},[]),h=l.useCallback(N=>{i(N)},[]),j=l.useCallback(N=>{d(N)},[]),v=l.useCallback(N=>{u(N)},[]),g=l.useCallback(N=>{y(N)},[y]),S=l.useCallback((N,O)=>{i(_=>(_[N]??null)===(O??null)?_:{..._,[N]:O})},[]),M=l.useCallback((N,O)=>{d(_=>{const T=_[N];return Eg(T,O)?_:{..._,[N]:O}})},[]),C=l.useCallback((N,O)=>{const _=O.get(N)??0;return S(_,N),g(_),_},[g,S]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:k,focusedGroup:n,updateFocusedGroup:y,focusGroup:g,groupActiveTabIds:o,updateGroupActiveTabIds:h,setGroupActiveTab:S,groupTabOrders:c,updateGroupTabOrders:j,setGroupTabOrder:M,groupSizes:m,updateGroupSizes:v,isMobile:p,hasHydratedStoredLayout:w,hydrateStoredLayout:f,focusConversationTab:C}}function Bg(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=na(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Og({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,ides:p,handleRefreshHistory:x}){const w=l.useRef(!1),b=l.useRef(!1),f=l.useRef(null),k=l.useRef(!1);l.useEffect(()=>{if(!e||w.current||t.length===0)return;if(!a){o();return}const y=r(e);y&&(i(y.tabKey,n),w.current=!0,b.current=!0,f.current!=null&&(window.clearTimeout(f.current),f.current=null),c(h=>{const j=new URLSearchParams(h);return j.delete("activeTab"),j},{replace:!0}))},[e,t,r,n,a,o,i,c]),l.useEffect(()=>{if(!(b.current||a)&&t.length!==0){if(!e){o(),b.current=!0;return}if(w.current){b.current=!0;return}if(f.current==null)return f.current=window.setTimeout(()=>{f.current=null,!(b.current||a)&&(o(),b.current=!0)},1500),()=>{f.current!=null&&(window.clearTimeout(f.current),f.current=null)}}},[e,t.length,a,o]),l.useEffect(()=>{if(!d){k.current=!1;return}if(!m||k.current||u)return;const y=p.find(h=>h.id===m.routeId);y&&(!y.chats||y.chats.length===0||Bg(y.chats,m))&&(k.current=!0,x())},[d,m,u,p,x])}function Ia(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=na(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function zd({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[i,c]=l.useState(!1),[d,m]=l.useState(!1),u=l.useCallback(async b=>{try{await e("standalone","launch_ide",{ideType:b,enableCdp:!0})}catch(f){console.error("Launch failed",f)}},[e]),p=l.useCallback(async(b,f)=>{try{const k=b||(t==null?void 0:t.daemonId)||"",y=await e(k,"switch_chat",{id:f,sessionId:f,...ds(t)}),h=y==null?void 0:y.result;if((y==null?void 0:y.success)===!0||h==="switched"||h==="switched-by-title")return;h===!1||h==="not_found"?Zs(a,"⚠️ Session tab not found — try refreshing history"):typeof h=="string"&&h.startsWith("error:")?Zs(a,`⚠️ Switch error: ${h}`):Zs(a,"⚠️ Session switch failed")}catch(k){console.error("Switch failed",k),Zs(a,`❌ Switch failed: ${k.message||"connection error"}`)}},[t,e,a]),x=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const b=us(t);await e(b,"new_chat",{...ds(t)}),tx(b,t.sessionId,na(t)[0]),o(f=>({...f,[t.tabKey]:Date.now()}))}catch(b){console.error("New chat failed",b)}finally{c(!1)}}},[t,i,e,o]),w=l.useCallback(async()=>{var b,f;if(!(!t||d)){m(!0);try{const k=us(t),y=async()=>e(k,"list_chats",{forceExpand:!0,...ds(t)});let h=await y(),j=(h==null?void 0:h.chats)||((b=h==null?void 0:h.result)==null?void 0:b.chats);Ia(j,t)&&(await new Promise(v=>setTimeout(v,450)),h=await y(),j=(h==null?void 0:h.chats)||((f=h==null?void 0:h.result)==null?void 0:f.chats)),h!=null&&h.success&&Array.isArray(j)&&(n(t.routeId,j),Ia(j,t)&&!Ia(r,t)&&Zs(a,"⚠️ History dialog did not fully open — try once more"))}catch(k){console.error("Refresh history failed",k)}finally{m(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:p,handleNewChat:x,handleRefreshHistory:w}}function Fg(e,t){if(e.size!==t.size)return!1;for(const[r,n]of e)if(t.get(r)!==n)return!1;return!0}function Hg(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Nl(e,t){const r=Object.keys(e),n=Object.keys(t);return r.length!==n.length?!1:r.every(a=>t[Number(a)]===e[Number(a)])}function rn(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[i,c]of e)!r.has(i)||c<=0||n.includes(c)||n.push(c);n.sort((i,c)=>i-c);const a={};n.forEach((i,c)=>{a[i]=c}),n.length===0&&(a[0]=0);const o=new Map;for(const[i,c]of e){if(!r.has(i)||c<=0)continue;const d=a[c];typeof d=="number"&&d>0&&o.set(i,d)}return{assignments:o,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function Cl(e,t){const r={};for(const[n,a]of Object.entries(e)){const o=t[Number(n)];typeof o=="number"&&(r[o]=a)}return r}function Wg(e,t,r){if(t.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...t].reverse().find(a=>a<e)??t[0];return r[n]??0}function Kg(e,t,r){if(t.length<=1)return[];const n=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),a=n.length===t.length?n:Array(r).fill(100/r),o=a.reduce((i,c)=>i+c,0);return o>0?a.map(i=>i/o*100):Array(r).fill(100/r)}function Ml(e,t){const r={};for(const[n,a]of Object.entries(e)){const o=Number(n);r[o>=t?o+1:o]=a}return r}function Il(e){return Array(e).fill(100/e)}function Ug({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:m}){const u=l.useRef(null),p=l.useMemo(()=>rn(e,m),[e,m]),x=p.assignments,w=l.useMemo(()=>c?1:p.groupCount,[p.groupCount,c]),b=w>1,f=l.useCallback((g,S)=>{t(M=>{const C=new Map(rn(M,m).assignments);return S===0?C.delete(g):C.set(g,S),C}),n(M=>({...M,[S]:g})),r(S)},[t,m,n,r]),k=l.useCallback(g=>{t(S=>{const M=rn(S,m).assignments,C=new Map;for(const[N,O]of M)O!==g&&(O>g?C.set(N,O-1):C.set(N,O));return C}),i(S=>{if(S.length<=1)return[];const M=[...S];M.splice(g,1);const C=M.reduce((N,O)=>N+O,0);return C>0?M.map(N=>N/C*100):[]}),r(0)},[t,m,i,r]),y=l.useCallback((g,S)=>{S.preventDefault();const M=u.current;if(!M)return;const C=S.clientX,N=M.offsetWidth,O=o.length===w?[...o]:Il(w),_=H=>{const F=(H.clientX-C)/N*100,A=[...O];A[g]=Math.max(15,O[g]+F),A[g+1]=Math.max(15,O[g+1]-F),i(A)},T=()=>{document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",T),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",_),document.addEventListener("mouseup",T)},[o,w,i]),h=l.useCallback((g,S,M)=>{if(w>=4)return;const C=M==="left"?S:S+1;t(N=>{const O=rn(N,m).assignments,_=new Map;for(const T of d){const H=O.get(T.tabKey)??0,R=H>=C?H+1:H;R>0&&_.set(T.tabKey,R)}return C>0&&_.set(g,C),_}),i(N=>{const O=N.length===w?[...N]:Il(w),_=O[S]??100/w,T=Math.max(15,_/2),H=Math.max(15,_/2),R=[...O];R[S]=T,R.splice(C,0,H);const F=R.reduce((A,I)=>A+I,0);return R.map(A=>A/F*100)}),n(N=>{const O=Ml(N,C);return O[C]=g,O}),a(N=>{const O=Ml(N,C);return O[C]=[g],O}),r(C)},[w,t,m,d,i,n,a,r]);l.useEffect(()=>{Fg(e,x)||t(x)},[e,x,t]),l.useEffect(()=>{const{mapping:g,usedGroups:S}=p;n(M=>{const C=Cl(M,g);return Nl(M,C)?M:C}),a(M=>{const C=Cl(M,g);return Nl(M,C)?M:C}),r(M=>{const C=c?0:Wg(M,S,g);return M===C?M:C}),i(M=>{const C=c?[]:Kg(M,S,p.groupCount);return Hg(M,C)?M:C})},[p,c,n,a,r,i]);const j=l.useMemo(()=>{const g=Array.from({length:w},()=>[]);for(const S of d){const M=x.get(S.tabKey)??0,C=Math.min(M,w-1);g[C].push(S)}return g},[d,x,w]),v=l.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:x,numGroups:w,isSplitMode:b,groupedConvs:j,moveTabToGroup:f,closeGroup:k,handleResizeStart:y,splitTabRelative:h,clearAllSplits:v}}function Ta(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="stable"||t==="latest"?"stable":t==="preview"||t==="next"?"preview":null}function zg(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="latest"||t==="stable"?"latest":t==="next"||t==="preview"?"next":null}function nn(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function ri(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=Ta(t.channel)||Ta(e.updateChannel)||Ta(e.releaseChannel)||void 0,n=zg(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=nn(t.targetVersion)||nn(e.serverVersion)||void 0,o=nn(t.minVersion)||void 0,i=nn(t.updateCommand)||(r?`adhdev update --channel ${r}`:void 0);return{...r?{channel:r}:{},...n?{npmTag:n}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...i?{updateCommand:i}:{}}}function Ts(e,t=null){return ri(e).targetVersion||t}function Gd(e){return ri(e).channel||null}function Vd(e){const t=ri(e);return{...t.channel?{channel:t.channel}:{},...t.npmTag?{npmTag:t.npmTag}:{},...t.targetVersion?{targetVersion:t.targetVersion}:{},...Object.keys(t).length>0?{updatePolicy:t}:{}}}function Gg({ides:e,sendDaemonCommand:t}){const r="0.9.81",n=l.useMemo(()=>e.filter(p=>p.type!=="adhdev-daemon"?!1:Qo(p,Ts(p,r))).sort((p,x)=>Number(br(x,Ts(x,r)))-Number(br(p,Ts(p,r)))),[r,e]),a=l.useMemo(()=>n.some(p=>br(p,Ts(p,r))),[r,n]),o=l.useMemo(()=>n.map(p=>Ts(p,r)).find(p=>typeof p=="string"&&p.trim().length>0)||r,[r,n]),[i,c]=l.useState(!1),[d,m]=l.useState({}),u=l.useCallback(async p=>{var w,b;const x=e.find(f=>f.id===p);if(x){m(f=>({...f,[p]:"upgrading"}));try{const f=await t(p,"daemon_upgrade",Vd(x));(w=f==null?void 0:f.result)!=null&&w.upgraded||(b=f==null?void 0:f.result)!=null&&b.success?m(k=>({...k,[p]:"done"})):m(k=>({...k,[p]:"error"}))}catch{m(f=>({...f,[p]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const qd=80;function wn(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function Vg(e){return{...e,createdAt:wn(e.createdAt),updatedAt:wn(e.updatedAt,e.createdAt),lastEventAt:wn(e.lastEventAt,e.updatedAt||e.createdAt)}}function qg(e){const t=Sr(e);return t==="unknown:"?e.id:t}function Yg(e){return[e.type,rd(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Xg(e,t=qd){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=qg(n),o=r.get(a);if(!o){r.set(a,n);continue}(n.updatedAt>o.updatedAt||n.updatedAt===o.updatedAt&&n.createdAt>o.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const o=a.updatedAt-n.updatedAt;return o!==0?o:a.createdAt-n.createdAt}).slice(0,Math.max(0,t))}function Jg(e,t){const r=Date.now(),n=[];for(const a of e){const o=a.sessionId?t.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden)continue;const i=ta(a,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=wn(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),m=Yg({type:c,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||a.lastUpdated});n.push(Vg({id:m,dedupKey:m,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Vc(a),preview:hf(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return Xg(n)}function Qg(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function Zg(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=qd}=e,a=l.useMemo(()=>Jg(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=l.useMemo(()=>Qg(a),[a]);return{notifications:a,unreadCount:o}}function ey({notifications:e,sendDaemonCommand:t}){const r=l.useCallback(o=>{const i=e.find(d=>d.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),n=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}const ty=l.createContext(null);function Yd(){return l.useContext(ty)}function ni(...e){const t=new Set,r=[],n=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),r.push(o))};for(const a of e){if(Array.isArray(a)){for(const o of a)n(o);continue}n(a)}return r}function sy(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const r=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function ai(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=sy(r);if(n)return n}return"C:\\"}for(const r of t){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function ry(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const r=t.includes("\\")?"\\":"/",n=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(n[0]||"")?n.length<=2?`${n[0]}\\`:n.slice(0,-1).join("\\"):n.length<=2?r:n.slice(0,-1).join(r)||r}function ny(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function oi(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=ny(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const o=typeof(a==null?void 0:a.path)=="string"?a.path:r,i=o.includes("\\")?"\\":"/",c=(m,u)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${u}`:m==="/"||m==="\\"?`${i}${u}`:`${m.replace(/[\\/]+$/,"")}${i}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(m=>(m==null?void 0:m.type)==="directory"&&typeof(m==null?void 0:m.name)=="string").map(m=>({name:m.name,path:typeof(m==null?void 0:m.path)=="string"&&m.path.trim()?m.path:c(o,m.name)})).sort((m,u)=>m.name.localeCompare(u.name)):[];return{path:o,directories:d}}function ay(e,t){const r={meshId:t.meshId||"",workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp"};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand)\s*\}\}/g,(n,a)=>r[a]||"")}function Xd(e,t={}){const r=e==null?void 0:e.mcpConfig;return(r==null?void 0:r.mode)!=="manual"?null:{serverName:r.serverName||"adhdev-mesh",configFormat:r.format,configPathCommand:r.configPathCommand,requiresRestart:r.requiresRestart===!0,instructions:r.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:ay(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function oy(e){if(!e||typeof e!="object")return null;const t=e,r=typeof t.instructions=="string"?t.instructions:"",n=typeof t.template=="string"?t.template:"";return!r&&!n?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:r||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:n}}function Nr(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Jd(e){return Pr(e)||e.tabKey||e.routeId||null}function Qd(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",a=e.conversations.find(o=>{if(n&&o.routeId!==n)return!1;const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||r&&i.includes(r)||n&&o.routeId===n)});if(a!=null&&a.tabKey)return a.tabKey;if(n){const o=$t(e.conversations,n)||e.conversations.find(i=>i.routeId===n);if(o!=null&&o.tabKey)return o.tabKey}return t||r||n||null}function Jt(e){return String(e||"").trim()}function Zd(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Vn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function iy(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function ly(e,t){const r=Jt(e.providerSessionId),n=Jt(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Jt).filter(Boolean);return!!(r&&i.includes(r)||n&&i.includes(n))});return a?a.tabKey:n||r||null}function cy(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=Zd(t.daemonId);if(n&&n!==e.machineId)return null;const a=Jt(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=Jt(e.resumeSessionId),i=Jt(e.launchedSessionId),c=Jt(t.providerSessionId),d=Jt(t.targetSessionId);if(o&&o!==c&&o!==d||i&&i!==c&&i!==d)return null;const m=Vn(e.workspacePath);if(m){const u=Vn(t.workspaceName);if(u&&!iy(u,m))return null}return ly(t,r)}function Tl(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function dy({ides:e,conversations:t,onOpenSession:r}){const[n,a]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,a(null)},[]),c=l.useCallback(d=>{o.current=d,a(d)},[]);return l.useEffect(()=>{if(!n)return;const d=Vn(n.workspacePath),m=e.find(p=>{var k,y,h,j;if(!p||p.type==="adhdev-daemon"||Zd(p.daemonId||p.id)!==n.machineId||(kr(p)?"cli":Ls(p)?"acp":"ide")!==n.kind)return!1;const b=String(p.agentType||p.type||"");if(n.providerType&&b!==n.providerType)return!1;if(n.resumeSessionId)return String(p.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const v=String(n.launchedSessionId||"");return[p.providerSessionId,p.sessionId,p.instanceId,p.id].map(S=>String(S||"")).filter(Boolean).includes(v)}if(d){const v=Vn(p.workspace||p.runtimeWorkspaceLabel);return v?v===d:!1}return Number(p.lastUpdated||p._lastUpdate||p.timestamp||((j=(h=(y=(k=p.activeChat)==null?void 0:k.messages)==null?void 0:y.at)==null?void 0:h.call(y,-1))==null?void 0:j.timestamp)||0)>=n.startedAt-5e3});if(!m)return;const u=Qd({entrySessionId:m.sessionId,entryInstanceId:m.instanceId,entryRouteId:m.id,conversations:t});u&&(i(),r(u))},[i,t,e,r,n]),l.useEffect(()=>Je.onStatusEvent(d=>{const m=o.current;if(!m)return;const u=cy(m,d,t);u&&(i(),r(u))}),[i,t,r]),l.useEffect(()=>{if(!n)return;const d=window.setTimeout(()=>{a(m=>!m||m.startedAt!==n.startedAt?m:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[n]),{trackPendingLaunch:c}}function uy({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const i=Yd(),c=l.useCallback(async(f,k)=>oi(e,f,k),[e]),d=l.useCallback(async(f,k)=>{if(!k.trim())return{ok:!1,error:"Choose a workspace path first."};try{const y=await e(f,"workspace_add",{path:k.trim()});return y!=null&&y.success?{ok:!0}:{ok:!1,error:(y==null?void 0:y.error)||"Could not save workspace"}}catch(y){return{ok:!1,error:y instanceof Error?y.message:"Could not save workspace"}}},[e]),m=l.useCallback(async(f,k,y)=>{var h;try{const j={ideType:k,enableCdp:!0};(h=y==null?void 0:y.workspacePath)!=null&&h.trim()&&(j.workspace=y.workspacePath.trim());const v=await e(f,"launch_ide",j);return!(v!=null&&v.success)&&(v==null?void 0:v.success)!==void 0?{ok:!1,error:(v==null?void 0:v.error)||"Could not launch IDE"}:(t({machineId:f,kind:"ide",providerType:k,workspacePath:(y==null?void 0:y.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(j){return{ok:!1,error:j instanceof Error?j.message:"Could not launch IDE"}}},[e,t]),u=l.useCallback(async(f,k,y,h)=>{var v,g,S;const j=Date.now();try{const M={cliType:y};(v=h==null?void 0:h.workspacePath)!=null&&v.trim()?M.dir=h.workspacePath.trim():h!=null&&h.workspaceId&&(M.workspaceId=h.workspaceId),(g=h==null?void 0:h.resumeSessionId)!=null&&g.trim()&&(M.resumeSessionId=h.resumeSessionId.trim()),Array.isArray(h==null?void 0:h.cliArgs)&&h.cliArgs.length>0&&(M.cliArgs=h.cliArgs),(S=h==null?void 0:h.initialModel)!=null&&S.trim()&&(M.initialModel=h.initialModel.trim());const C=await e(f,"launch_cli",M),N=(C==null?void 0:C.result)||C,O=(N==null?void 0:N.sessionId)||(N==null?void 0:N.id);return C!=null&&C.success&&O?(t({machineId:f,kind:k,providerType:y,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,launchedSessionId:O,startedAt:j}),{ok:!0}):C!=null&&C.success?(t({machineId:f,kind:k,providerType:y,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:(C==null?void 0:C.error)||(N==null?void 0:N.error)||`Could not launch ${k.toUpperCase()} session`}}catch(M){return Tl(M)?(t({machineId:f,kind:k,providerType:y,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:M instanceof Error?M.message:`Could not launch ${k.toUpperCase()} session`}}},[r,e,t]),p=l.useCallback(async f=>{var k;if(i!=null&&i.listMeshes)return i.listMeshes(f);if(!f)return[];try{const y=await e(f,"list_meshes",{}),h=(y==null?void 0:y.result)??y;if((h==null?void 0:h.success)===!1)throw new Error((h==null?void 0:h.error)||"Could not load meshes");return(Array.isArray(h==null?void 0:h.meshes)?h.meshes:Array.isArray((k=h==null?void 0:h.result)==null?void 0:k.meshes)?h.result.meshes:[]).map(v=>{var g;return{id:String((v==null?void 0:v.id)||""),name:String((v==null?void 0:v.name)||(v==null?void 0:v.id)||"Untitled mesh"),repoIdentity:(v==null?void 0:v.repoIdentity)||(v==null?void 0:v.repo_identity)||null,workspace:Array.isArray(v==null?void 0:v.nodes)&&v.nodes.length>0?String(((g=v.nodes[0])==null?void 0:g.workspace)||""):null,nodesCount:Array.isArray(v==null?void 0:v.nodes)?v.nodes.length:void 0,status:(v==null?void 0:v.status)||null}}).filter(v=>v.id)}catch(y){throw console.error("List meshes failed",y),y}},[i,e]),x=l.useCallback(async(f,k,y)=>{if(!k.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(f,k,y);const h=Date.now();try{const j={meshId:k.trim()};y.trim()&&(j.cliType=y.trim());const v=await e(f,"launch_mesh_coordinator",j),g=(v==null?void 0:v.result)??v;if((g==null?void 0:g.success)===!1||(v==null?void 0:v.success)===!1){const M=String((g==null?void 0:g.code)||(v==null?void 0:v.code)||""),C=oy((g==null?void 0:g.meshCoordinatorSetup)||(g==null?void 0:g.manualSetup)||(v==null?void 0:v.meshCoordinatorSetup)||(v==null?void 0:v.manualSetup));return{ok:!1,error:(g==null?void 0:g.error)||(v==null?void 0:v.error)||"Could not launch mesh coordinator",code:M||void 0,manualSetup:C}}const S=(g==null?void 0:g.sessionId)||(g==null?void 0:g.id);return S?r(S):t({machineId:f,kind:"cli",providerType:(g==null?void 0:g.cliType)||y.trim()||void 0,workspacePath:(g==null?void 0:g.workspace)||null,startedAt:h}),{ok:!0}}catch(j){return Tl(j)?(t({machineId:f,kind:"cli",providerType:y.trim()||void 0,startedAt:h}),{ok:!0}):{ok:!1,error:j instanceof Error?j.message:"Could not launch mesh coordinator"}}},[i,r,e,t]),w=l.useCallback(async(f,k)=>{if(!f||!k)return[];try{const y=await e(f,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),h=(y==null?void 0:y.result)??y;return Array.isArray(h==null?void 0:h.sessions)?h.sessions:[]}catch(y){return console.error("List saved sessions failed",y),[]}},[e]),b=l.useCallback(async f=>{await Bd({conversation:n,mode:f,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:d,handleLaunchMachineIde:m,handleLaunchMachineProvider:u,handleListMachineMeshes:p,handleLaunchMeshCoordinator:x,handleListMachineSavedSessions:w,setActiveCliViewMode:b}}function my(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":return!0;case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function hy(e,t,r=Date.now()){return!e||!my(t)?null:{tabKey:e,nonce:r}}function py({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:i}){const[c,d]=l.useState(null),[m,u]=l.useState(null),p=l.useMemo(()=>{var k,y;if(!e){if(c){const h=t.find(j=>j.tabKey===c);if(h)return h}return r[0]}const f=n[a];if(f){const h=t.find(j=>j.tabKey===f);if(h)return h}return((k=o[a])==null?void 0:k[0])||((y=o[0])==null?void 0:y[0])},[t,c,a,n,o,e,r]),x=l.useCallback(f=>{d(f)},[]),w=l.useCallback(f=>{d(f.tabKey),i(k=>{const y=new URLSearchParams(k),h=ff(f);return h?y.set("activeTab",h):y.delete("activeTab"),y},{replace:!0})},[i]),b=l.useCallback((f,k)=>{const y=hy(f,k);y&&u(y)},[]);return{activeConv:p,openDesktopConversation:w,requestScrollToBottom:b,scrollToBottomRequest:m,setDesktopActiveTab:x}}function fy(e){const t=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:r===e.autoReadKey?r:null}:r===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:r}:{shouldSchedule:!0,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!r,nextPendingKey:null}}function xy(e){const t=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&(!t||t!==r)),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function by({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),d=l.useRef(null);l.useEffect(()=>{const m=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const u=Pn(e,r),p=xy({tabKey:e.tabKey,historySessionId:Pr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:fs(e),liveState:u}),x=p.autoReadKey,w=fy({autoReadKey:x,shouldMarkSeen:p.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!p.shouldMarkSeen){w.shouldCancelPending&&m(),a.current=x;return}if(!w.shouldSchedule)return;w.shouldCancelPending&&m();const b=()=>{if(document.visibilityState!=="visible"||a.current===x)return;a.current=x,o.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const k=p.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:k,completionMarker:p.completionMarker}).catch(()=>{})};if(o.current=w.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(b,1500);const k=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=k,document.addEventListener("visibilitychange",k);return}const f=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(b,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=f,document.addEventListener("visibilitychange",f)},[e,t,r,n]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function Aa(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const r=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(r)?r:""}function gy({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var I;const[m,u]=l.useState(!1),[p,x]=l.useState([]),[w,b]=l.useState(()=>jt()),[f,k]=l.useState(!1),[y,h]=l.useState(null),j=l.useRef(null),v=l.useMemo(()=>r||t||e,[e,r,t]),g=!!v&&Ye(v)&&!Ve(v),S=l.useMemo(()=>{if(!v||!g)return null;const $=v.daemonId||v.routeId||"",E=Kt(v),L=Aa(v);return`${$}:${E}:${v.providerSessionId||""}:${L}`},[v,g]),M=l.useMemo(()=>!v||!g?"":Aa(v),[v,g]),{isCreatingChat:C,isRefreshingHistory:N,handleSwitchSession:O,handleNewChat:_,handleRefreshHistory:T}=zd({sendDaemonCommand:a,activeConv:v,chats:(I=n.find($=>$.id===(v==null?void 0:v.routeId)))==null?void 0:I.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),H=l.useCallback(()=>{u(!0)},[]),R=l.useCallback(()=>{u(!1)},[]),F=l.useCallback(async()=>{if(!(!v||!g||f)){k(!0);try{const $=v.daemonId||v.routeId,E=Kt(v),L=Aa(v),U=await a($,"list_saved_sessions",{agentType:E,providerType:E,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},...L?{workspace:L}:{}}),B=(U==null?void 0:U.result)??U;x(Array.isArray(B==null?void 0:B.sessions)?B.sessions:[])}catch($){console.error("Refresh saved sessions failed",$),x([])}finally{k(!1)}}},[v,f,g,a]);l.useEffect(()=>{if(!m){j.current=null;return}if(!g){j.current=null,x([]),k(!1);return}!S||f||j.current!==S&&(j.current=S,F())},[F,m,f,g,S]);const A=l.useCallback(async $=>{if(!v||!g||!$.providerSessionId||!$.workspace)return;const E=v.daemonId||v.routeId,L=Kt(v);try{h($.providerSessionId);const U=await a(E,"launch_cli",{cliType:L,dir:$.workspace,resumeSessionId:$.providerSessionId,initialModel:Oc($.summaryMetadata,"model",{preferShortValue:!0})||void 0}),B=(U==null?void 0:U.result)??U,K=typeof(B==null?void 0:B.sessionId)=="string"?B.sessionId:typeof(B==null?void 0:B.id)=="string"?B.id:"";K&&d(J=>{const X=new URLSearchParams(J);return X.set("activeTab",K),X},{replace:!0}),R()}catch(U){console.error("Resume saved session failed",U)}finally{h(null)}},[R,v,g,a,d]);return{historyModalOpen:m,openHistoryModal:H,closeHistoryModal:R,historyTargetConv:v,isSavedSessionHistoryTarget:g,isHistoryCreatingChat:C,isHistoryRefreshingHistory:N,handleHistorySwitchSession:O,handleHistoryNewChat:_,handleHistoryRefresh:T,savedHistorySessions:p,savedHistoryFilters:w,setSavedHistoryFilters:b,missingWorkspaceResumePath:M,isSavedHistoryLoading:f,resumingSavedHistorySessionId:y,handleRefreshSavedHistory:F,handleResumeSavedHistorySession:A}}function yy({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}){const[d,m]=l.useState(null),[u,p]=l.useState(null),x=l.useMemo(()=>{if(e||!n)return null;const y=c(n);return y&&!Ye(y)&&!Ve(y)?y:null},[e,n,c]),w=l.useMemo(()=>{const y=d==null?void 0:d.routeId;if(!y)return null;const h=d!=null&&d.tabKey?o.find(j=>j.tabKey===d.tabKey):a?o.find(j=>j.tabKey===a):null;return(h==null?void 0:h.routeId)===y?h:$t(o,y)},[o,d,a]),b=l.useMemo(()=>{if(w)return i.find(y=>y.id===w.routeId)},[i,w]);l.useEffect(()=>{x&&(m({routeId:x.routeId,tabKey:Ji(x)}),p(x),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,x]);const f=l.useCallback(y=>{y&&(m({routeId:y.routeId,tabKey:Ji(y)}),p(y))},[]),k=l.useCallback(()=>{m(null),p(null)},[]);return{remoteDialogConv:w,remoteDialogIdeEntry:b,remoteDialogActiveConv:u,setRemoteDialogActiveConv:p,openRemoteDialog:f,closeRemoteDialog:k}}function vy({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:p,remoteDialogActiveConv:x,setRemoteDialogActiveConv:w,openRemoteDialog:b,closeRemoteDialog:f}=yy({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}),[k,y]=l.useState(!1),[h,j]=l.useState(null),v=l.useCallback(async M=>{const C=M||d;!C||!Ye(C)&&!Ve(C)||(j(C),y(!0))},[d]),g=l.useCallback(()=>{y(!1),j(null)},[]),S=l.useCallback(async M=>{const C=h||d;if(!C||!Ye(C)&&!Ve(C)){g();return}y(!1);try{const N=Kt(C),O=C.routeId||C.daemonId||"";await m(O,"stop_cli",{cliType:N,targetSessionId:C.sessionId,mode:M})}catch(N){console.error("Stop CLI failed:",N)}finally{j(null)}},[d,g,h,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:p,remoteDialogActiveConv:x,setRemoteDialogActiveConv:w,openRemoteDialog:b,closeRemoteDialog:f,cliStopDialogOpen:k,cliStopTargetConv:h,requestCliStop:v,cancelCliStop:g,confirmCliStop:S}}function eu({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var j,v,g;const i=Ir(),c=js(e),d=o?null:Gc(e),m=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!o&&e.streamSource==="agent-stream"&&!!e.agentName,p=!o&&!u&&(e.transport==="pty"||e.transport==="acp"),x=Os(e),w=pf(e),b=(j=e.settings)==null?void 0:j.meshNodeFor,f=e.meshQueueStats,k=((v=e.coordinator)==null?void 0:v.meshId)||((g=e.settings)==null?void 0:g.meshCoordinatorFor);if(!m&&!u&&!p&&!d&&!b&&!f)return null;const y=l.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),h=l.useCallback(()=>{if(r){r();return}const S=Jd(e);S&&i(Nr(S))},[e,i,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[m&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:h,title:w,children:[s.jsx(Bt,{size:12}),s.jsx("span",{children:w})]}):s.jsxs("span",{className:"conversation-meta-chip",title:w,children:[s.jsx(Bt,{size:12}),s.jsx("span",{children:w})]})),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(Bs,{size:12}),s.jsx("span",{children:x})]}),p&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(Bs,{size:12}),s.jsx("span",{children:x})]}),d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:y,title:d,children:[s.jsx(es,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(es,{size:12}),s.jsx("span",{children:d})]})),b&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(es,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),k&&f&&s.jsxs("span",{className:`conversation-meta-chip ${f.pending>0?"is-active":""}`,style:f.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${f.pending} pending, ${f.assigned} assigned, ${f.completed} completed, ${f.failed} failed`,children:[s.jsx(mh,{size:12}),s.jsxs("span",{children:[f.pending," Pending"]})]})]})}function _a(e,t=!0){return(e??!0)&&t}const ii=l.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:d,handleForceSendChat:m,isSendingChat:u,sendFeedbackMessage:p=null,handleFocusAgent:x,isFocusingAgent:w,actionLogs:b,userName:f,scrollToBottomRequestNonce:k,isInputActive:y=!0,isVisible:h=!0}){const j=n,v=!n,g=_a(h,j),S=_a(h,v),M=_a(h),C=Pd(t),N=C.status||C.modalMessage||C.modalButtons?{...t,...C.status?{status:C.status}:{},...C.modalMessage!==void 0?{modalMessage:C.modalMessage}:{},...C.modalButtons!==void 0?{modalButtons:C.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Dc,{activeConv:N,onModalButton:i}),s.jsx(eu,{conversation:N,className:"chat-pane-meta-row mx-3 mt-1",meshOnly:!0}),N.transport!=="pty"&&N.transport!=="acp"&&N.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(jr,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:c,children:"Relaunch with CDP"})]})}):null,N.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:j?"visible":"hidden",pointerEvents:j?"auto":"none"},children:s.jsx(Dx,{activeConv:N,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:p,isVisible:g,isInputActive:y&&g})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:v?"visible":"hidden",pointerEvents:v?"auto":"none"},children:s.jsx(go,{activeConv:N,ideEntry:a,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:p,handleFocusAgent:x,isFocusingAgent:w,actionLogs:b,userName:f,scrollToBottomRequestNonce:k,isInputActive:y&&S,isVisible:S})})]}):s.jsx(go,{activeConv:N,ideEntry:a,handleSendChat:d,handleForceSendChat:m,isSendingChat:u,sendFeedbackMessage:p,handleFocusAgent:x,isFocusingAgent:w,actionLogs:b,userName:f,scrollToBottomRequestNonce:k,isInputActive:y&&M,isVisible:M})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.handleForceSendChat===t.handleForceSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function wy({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:m,onOpenNativeConversation:u,onOpenMachine:p,onOpenHistory:x,onOpenRemote:w,onOpenMeshGraph:b,onStopCli:f,cliViewMode:k,onSetCliViewMode:y,handleSendChat:h,handleForceSendChat:j,handleFocusAgent:v,handleModalButton:g,handleRelaunch:S}){var T,H;const M=l.useRef(null),C=Ye(e)&&!t,N=C&&k==="terminal",O=!!e.daemonId&&!!((T=e.coordinator)!=null&&T.meshId||(H=e.settings)!=null&&H.meshCoordinatorFor),_=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${_} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx(Po,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:nt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(eu,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>p(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[C&&k&&s.jsx(pd,{mode:k,onChange:y,compact:!0}),C&&f&&s.jsx("button",{onClick:()=>{f(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(gt,{size:14})}),O&&b&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>b(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(Qt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),type:"button",children:s.jsx(Ro,{size:14})}),!t&&!C&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:s.jsx(Bt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(ii,{activeConv:e,clearToken:0,isCliTerminal:N,ideEntry:n,terminalRef:M,handleModalButton:g,handleRelaunch:S,handleSendChat:h,handleForceSendChat:j,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:v,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const La={unix:{cmd:"curl -fsSL https://adhf.dev/install | sh",shell:"Terminal",prompt:"$ "},powershell:{cmd:"irm https://adhf.dev/install.ps1 | iex",shell:"PowerShell",prompt:"PS> "},cmd:{cmd:"curl -fsSL https://adhf.dev/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd",shell:"CMD",prompt:"> "}};function jy(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function tu(){const[e,t]=l.useState("unix"),[r,n]=l.useState("powershell"),[a,o]=l.useState(!1),i=e==="unix"?"unix":r;l.useEffect(()=>{t(jy())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(La[i].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[i]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:c,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:La[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:La[i].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function su({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Bt},{key:"chats",label:"Chats",icon:ws}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:a,icon:o})=>{const i=e===n;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${i?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(n),type:"button","aria-pressed":i,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${i?"text-accent-primary":"bg-transparent text-current"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(o,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function an({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function Ns({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function ar({icon:e,title:t,subtitle:r,children:n}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function ky({conversation:e,onCancel:t,onConfirm:r}){const n=nt(e),a=ys(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",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"fade-in relative w-full sm:w-[min(92vw,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] border border-border-subtle bg-bg-primary shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border-subtle bg-[var(--surface-primary)] px-4 py-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base font-extrabold text-text-primary",children:"Hide this chat from the inbox?"}),s.jsx("div",{className:"mt-1 text-[13px] leading-relaxed text-text-muted",children:"This only collapses the chat locally. You can restore it from Hidden tabs."})]}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary text-text-secondary transition-colors hover:bg-surface-primary hover:text-text-primary",onClick:t,"aria-label":"Cancel hide chat",children:s.jsx(gt,{size:16})})]}),s.jsx("div",{className:"px-4 py-4",children:s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary/60 px-3.5 py-3",children:[s.jsx("div",{className:"truncate text-sm font-bold text-text-primary",children:n}),s.jsx("div",{className:"mt-1 truncate text-xs text-text-muted",children:a})]})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-border-subtle bg-bg-secondary px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))]",children:[s.jsx("button",{type:"button",className:"btn btn-secondary min-h-[40px] px-4 text-sm",onClick:t,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary min-h-[40px] px-4 text-sm",onClick:r,children:"Hide tab"})]})]})]})}function on({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onOpenMeshGraph:o,onCollectChatDebugBundle:i,isMuted:c,onToggleMute:d}){var T,H;const m=t==="needs_attention"||t==="task_complete",u=t==="working",p=t==="earlier",x=t==="task_complete",{isReconnecting:w,isConnecting:b}=Ws(e.conversation),f=nt(e.conversation),k=ys(e.conversation),y=ud(e.conversation,{requiresAction:t==="needs_attention"}),h=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":u?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":p?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",j=m?"bg-accent-primary shadow-glow":u?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":p?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",v=p?"text-text-secondary":"text-text-primary",g=p?"text-text-muted":"text-text-secondary",S=p?"text-text-secondary opacity-80":"text-text-muted",M=p?"text-text-muted opacity-80":"text-text-muted",C=!u&&!x,N=!!e.conversation.daemonId&&!!((T=e.conversation.coordinator)!=null&&T.meshId||(H=e.conversation.settings)!=null&&H.meshCoordinatorFor),O="text-[color:var(--status-warning)]",_=R=>{if(!i)return;R.preventDefault(),R.stopPropagation();const F=i==null?void 0:i(e.conversation);Promise.resolve(F).catch(A=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",A)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${h}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||u?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${j}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:r(f)}),a&&s.jsxs("button",{type:"button",className:"mobile-inbox-hide-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-border-subtle bg-bg-primary/70 px-2 text-[10px] font-semibold text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:R=>{R.preventDefault(),R.stopPropagation(),a()},"aria-label":`Hide ${f}`,title:"Hide conversation",children:[s.jsx(Do,{size:11}),s.jsx("span",{children:"Hide"})]}),d&&s.jsxs("button",{type:"button",className:`mobile-inbox-mute-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border px-2 text-[10px] font-semibold transition-colors ${c?"border-amber-500/40 bg-amber-500/10 text-amber-300 hover:bg-amber-500/20":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:R=>{R.preventDefault(),R.stopPropagation(),d()},"aria-label":c?`Unmute ${f}`:`Mute ${f}`,title:c?"Unmute (resume notifications)":"Mute notifications",children:[s.jsx(Tr,{size:11}),s.jsx("span",{children:c?"Muted":"Mute"})]}),N&&o&&s.jsxs("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-border-subtle bg-bg-primary/70 px-2 text-[10px] font-semibold text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:R=>{R.preventDefault(),R.stopPropagation(),o(e.conversation)},"aria-label":`Open mesh graph for ${f}`,title:"Open live repo mesh graph",children:[s.jsx(Qt,{size:11}),s.jsx("span",{children:"Graph"})]})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:_,type:"button",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${v}`,children:f}),C&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${M}`,children:Rc(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${g}`,children:[s.jsx("span",{className:"truncate",children:k}),s.jsx(Bn,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),w?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${O} animate-pulse`,children:"Reconnecting…"})]}):b?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):y==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:O,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${S}`,children:e.preview})]}),m&&!x&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),x&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),u&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]})},e.conversation.tabKey)}function Al({size:e=32}){return s.jsx("div",{className:"flex flex-col items-center gap-2.5",children:s.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}})})}function Sy({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:p,onHideConversation:x,onOpenMeshGraph:w,onOpenNewSession:b,onOpenMachine:f,onOpenSettings:k,onSectionChange:y,wsStatus:h="connected",isStandalone:j=!1,onCollectChatDebugBundle:v,isConversationMuted:g,onToggleMuteConversation:S}){const[M,C]=l.useState(null),N=h==="disconnected"||h==="reconnecting"||h==="offline"||h==="auth_failed",O=i.length>0,_=t.length>0||r.length>0||n.length>0||a.length>0,T=e==="machines"?"Machines":"Chats",H=j?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",R=j?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",F=l.useCallback(async $=>{const E=us($);if(!E)return;const L=Array.isArray($.messages)?$.messages:[],U=Qc({activeConv:$,visibleMessages:L,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:L.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),B=await m(E,"get_chat_debug_bundle",{...ds($),delivery:"daemon_file",frontendSnapshot:U}),K=pr(B),J=td(K),X=await ed(J);X==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),Je.showToast(Zc(K,{locatorCopyStatus:X}),X==="failed"?"warning":"success")},[d,m]),A=v||F,I=l.useCallback(()=>{M&&(x==null||x(M),C(null))},[M,x]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${H}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:T}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||r.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(Tr,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:k,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(Qn,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${R}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:N?s.jsx(ar,{icon:s.jsx(Al,{}),title:h==="offline"?"Network offline":h==="auth_failed"?"Session expired":"Reconnecting",subtitle:h==="offline"?"Waiting for network…":h==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):i.length===0?s.jsx(ar,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:j?"Waiting for your daemon":"Connect your machines",subtitle:j?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can launch sessions with any installed provider.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!j&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(tu,{})})}):s.jsx(Ns,{children:i.map(($,E)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${E>0?"border-t border-border-subtle/70":""}`,onClick:()=>f($.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:c($.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:$.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:$.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[$.unread," new"]}):$.total>0?`${$.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:$.subtitle}),$.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[$.total," chat",$.total!==1?"s":"",$.unread>0?` · ${$.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},$.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(an,{title:"Needs attention",className:"mb-0"}),s.jsx(Ns,{children:t.map(($,E)=>s.jsx("div",{className:E>0?"border-t border-border-subtle/70":"",children:s.jsx(on,{item:$,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:x?()=>C($.conversation):void 0,onOpenMeshGraph:w,onCollectChatDebugBundle:A,isMuted:g==null?void 0:g($.conversation),onToggleMute:S?()=>S($.conversation):void 0})},$.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(an,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(Ns,{children:r.map(($,E)=>s.jsx("div",{className:E>0?"border-t border-border-subtle/70":"",children:s.jsx(on,{item:$,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:x?()=>C($.conversation):void 0,onOpenMeshGraph:w,onCollectChatDebugBundle:A,isMuted:g==null?void 0:g($.conversation),onToggleMute:S?()=>S($.conversation):void 0})},$.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(an,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(Ns,{children:n.map(($,E)=>s.jsx("div",{className:E>0?"border-t border-border-subtle/70":"",children:s.jsx(on,{item:$,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:x?()=>C($.conversation):void 0,onOpenMeshGraph:w,onCollectChatDebugBundle:A,isMuted:g==null?void 0:g($.conversation),onToggleMute:S?()=>S($.conversation):void 0})},$.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(an,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(Ns,{children:a.map(($,E)=>s.jsx("div",{className:E>0?"border-t border-border-subtle/70":"",children:s.jsx(on,{item:$,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:x?()=>C($.conversation):void 0,onOpenMeshGraph:w,onCollectChatDebugBundle:A,isMuted:g==null?void 0:g($.conversation),onToggleMute:S?()=>S($.conversation):void 0})},$.conversation.tabKey))}):_?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):N?s.jsx(ar,{icon:s.jsx(Al,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):O?s.jsx(ar,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(ws,{size:20})}),title:"No conversations yet",subtitle:fd,children:b&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:b,"aria-label":Ht,title:Ht,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:Ht})]})}):s.jsx(ar,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&o.length>0&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(Ns,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[o.length," collapsed ",o.length===1?"conversation":"conversations"]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:p,children:"Restore all"})]})})})]}),e==="chats"&&b&&_&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:b,"aria-label":Ht,title:Ht,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),M&&s.jsx(ky,{conversation:M,onCancel:()=>C(null),onConfirm:I}),s.jsx(su,{section:e,onSectionChange:y})]})}function Ny(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function ru(e){const t=[e.workspace||"Workspace unknown"],r=gs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Ny(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function li({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:d,onConfirm:m}){const[u,p]=l.useState(r);l.useEffect(()=>{p(r)},[r]);const x=ry(r),w=u.trim();return 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":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] 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-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),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:c,"aria-label":"Close folder browser",children:s.jsx(gt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!x||a||d(x)},disabled:!x||a,children:[s.jsx(Po,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:b=>p(b.target.value),onKeyDown:b=>{b.key!=="Enter"||!w||a||(b.preventDefault(),d(w))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!w||a||d(w)},disabled:!w||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):n.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:n.map(b=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(b.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx($s,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:b.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:b.path})]})]},b.path))})}),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:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(w||r),disabled:!w&&!r||a,children:i})]})]})})}function nu({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:i="Launch",busyLabel:c="Launching…",busy:d=!1,showArgsInput:m,argsValue:u,onArgsChange:p,showModelInput:x,modelValue:w,onModelChange:b,historyProviderNode:f,onConfirm:k,onCancel:y}){const h=n==null?void 0:n.find(j=>j.key===a);return 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":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] 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-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),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:y,"aria-label":"Close launch confirmation",children:s.jsx(gt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:j=>o(j.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:d,children:n.map(j=>s.jsx("option",{value:j.key,children:j.label},j.key))}),(h==null?void 0:h.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h.description})]}),f,r.map(j=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:j.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:j.value})]},`${j.label}:${j.value}`)),x&&b&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:w||"",onChange:j=>b(j.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),m&&p&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:j=>p(j.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),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:y,disabled:d,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:k,disabled:d,children:[s.jsx(kc,{size:14}),d?c:i]})]})]})})}function _l(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function au(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,o=[];a&&o.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])o.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${_l(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const i=(r==null?void 0:r.trim())||"",c=i?(t.workspaces||[]).find(d=>d.path===i):null;if(i&&!c&&o.push({key:`custom:${i}`,label:_l(i),description:i,workspaceId:null,workspacePath:i}),n){const d=`saved:${n}`;if(o.some(m=>m.key===d))return{options:o,selectedKey:d}}return c?{options:o,selectedKey:`saved:${c.id}`}:i?{options:o,selectedKey:`custom:${i}`}:{options:o,selectedKey:"__home__"}}function Cy(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function My(e){return[Cy(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Iy(e){return e.lastLaunchedAt?ea(e.lastLaunchedAt):""}function ou(e){return{metaText:My(e),updatedLabel:Iy(e)}}function Pa(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Ty({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var et,ct,Xe,pt;const i=Lr(),[c,d]=l.useState(!1),m=(((et=e.detectedIdes)==null?void 0:et.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(Ae=>({id:Ae.id,path:Ae.path,label:Ae.label})),[e]),p=e.defaultWorkspaceId||null,[x,w]=l.useState(p||((ct=u[0])==null?void 0:ct.id)||""),[b,f]=l.useState(""),[k,y]=l.useState(""),[h,j]=l.useState([]),[v,g]=l.useState(!1),[S,M]=l.useState(""),[C,N]=l.useState(!1),[O,_]=l.useState(Pa(m,t.length,r.length)),T=l.useRef(null),[H,R]=l.useState(null),F=l.useRef("__home__"),[A,I]=l.useState("__home__"),[$,E]=l.useState(""),[L,U]=l.useState(""),[B,K]=l.useState(""),[J,X]=l.useState([]),[ae,de]=l.useState(()=>jt().textQuery),[ke,q]=l.useState(()=>jt().workspaceQuery),[ve,be]=l.useState(()=>jt().modelQuery),[we,xe]=l.useState(()=>jt().resumableOnly),[Ce,Q]=l.useState(()=>jt().sortMode),[ge,ce]=l.useState(!1),[ye,me]=l.useState(!1),fe=l.useRef(null),le=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const pe=x==="__custom__"?b.trim():((Xe=u.find(Ae=>Ae.id===x))==null?void 0:Xe.path)||"",oe=x==="__custom__"&&!!pe&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),P=x!=="__custom__"&&((pt=u.find(Ae=>Ae.id===x))==null?void 0:pt.path)||"",ue=l.useMemo(()=>(e.recentLaunches||[]).map(Ae=>Ae.workspace),[e]),Se=l.useCallback(async Ae=>{g(!0),M("");try{const Fe=await a(Ae);y(Fe.path),f(Fe.path),j(Fe.directories)}catch(Fe){M(Fe instanceof Error?Fe.message:"Could not load folder")}finally{g(!1)}},[a]),Ie=l.useCallback(()=>{var Fe;w("__custom__"),N(!0);const Ae=ai(e.platform,ni(b.trim(),P,ue,e.defaultWorkspacePath,(Fe=u.find(st=>st.id===p))==null?void 0:Fe.path,u.map(st=>st.path)));Se(Ae)},[b,p,Se,ue,P,e.platform,u]),te=l.useCallback(Ae=>{if(Ae!=null&&Ae.workspaceId){w(Ae.workspaceId),f("");return}if(Ae!=null&&Ae.workspacePath){w("__custom__"),f(Ae.workspacePath);return}w(""),f("")},[]),Ne=l.useCallback(Ae=>{if(w(Ae),Ae==="__custom__"){Ie();return}f("")},[Ie]),De=l.useCallback(Ae=>{w("__custom__"),f(Ae)},[]),Ee=l.useCallback((Ae,Fe)=>{T.current=Fe,F.current=Ae.selectedWorkspaceKey||"__home__",I(Ae.selectedWorkspaceKey||"__home__"),E(Ae.initialArgs||""),U(Ae.initialModel||""),K(""),X([]);const st=Ae.providerType?`${e.id}:${Ae.providerType}`:null;if(Gx(le.current,st)){const qe=jt();de(qe.textQuery),q(qe.workspaceQuery),be(qe.modelQuery),xe(qe.resumableOnly),Q(qe.sortMode)}le.current=st,R(Ae),Ae.providerType&&o&&(ce(!0),o(Ae.providerType).then(qe=>X(qe||[])).catch(qe=>console.warn("Failed to load saved sessions",qe)).finally(()=>ce(!1)))},[o,e.id]),ze=l.useMemo(()=>xd(J,{textQuery:ae,workspaceQuery:ke,modelQuery:ve,resumableOnly:we,sortMode:Ce}),[ve,we,J,Ce,ae,ke]);l.useEffect(()=>{B&&(ze.some(Ae=>Ae.providerSessionId===B)||K(""))},[ze,B]);const Qe=l.useCallback(()=>{T.current&&(me(!0),T.current().finally(()=>{T.current=null,me(!1),R(null)}))},[]),Ze=l.useCallback(()=>{T.current=null,R(null)},[]),rt=l.useCallback(Ae=>{F.current=Ae,I(Ae)},[]);return l.useEffect(()=>{var Ae;fe.current!==e.id&&(fe.current=e.id,w(p||((Ae=u[0])==null?void 0:Ae.id)||"__custom__"),f(""),y(""),j([]),M(""),N(!1),de(jt().textQuery),q(jt().workspaceQuery),be(jt().modelQuery),xe(jt().resumableOnly),Q(jt().sortMode),le.current=null,_(Pa(m,t.length,r.length)))},[r.length,t.length,p,m,e.id,u]),l.useEffect(()=>{var Ae;x!=="__custom__"&&(x&&u.some(Fe=>Fe.id===x)||w(p||((Ae=u[0])==null?void 0:Ae.id)||"__custom__"))},[p,x,u]),l.useEffect(()=>{O==="ide"&&m||O==="cli"&&t.length>0||O==="acp"&&r.length>0||_(Pa(m,t.length,r.length))},[O,r.length,t.length,m]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:m,workspaceRows:u,defaultWorkspaceId:p,workspaceChoice:x,customWorkspacePath:b,browseCurrentPath:k,browseDirectories:h,browseBusy:v,browseError:S,browseDialogOpen:C,activeLauncherKind:O,launchConfirm:H,launchConfirmWorkspaceKeyRef:F,launchConfirmWorkspaceKey:A,launchConfirmArgs:$,launchConfirmModel:L,launchConfirmResumeId:B,launchConfirmSavedSessions:J,launchConfirmTextFilter:ae,launchConfirmWorkspaceFilter:ke,launchConfirmModelFilter:ve,launchConfirmResumableOnly:we,launchConfirmSortMode:Ce,filteredLaunchConfirmSavedSessions:ze,launchConfirmSessionsLoading:ge,launchConfirmBusy:ye,resolvedWorkspacePath:pe,canCreateMissingWorkspace:oe,openBrowseDialog:Ie,loadBrowsePath:Se,handleWorkspaceChoiceChange:Ne,chooseCustomWorkspacePath:De,setCustomWorkspacePath:f,setBrowseDialogOpen:N,setActiveLauncherKind:_,openLaunchConfirm:Ee,handleConfirmLaunch:Qe,closeLaunchConfirm:Ze,setWorkspaceSelectionFromOption:te,setLaunchConfirmWorkspaceKeyAndSync:rt,setLaunchConfirmArgs:E,setLaunchConfirmModel:U,setLaunchConfirmResumeId:K,setLaunchConfirmTextFilter:de,setLaunchConfirmWorkspaceFilter:q,setLaunchConfirmModelFilter:be,setLaunchConfirmResumableOnly:xe,setLaunchConfirmSortMode:Q}}function Ay({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:d,section:m,showBottomNav:u,onBack:p,onSectionChange:x,onOpenConversation:w,onOpenRecent:b,onOpenMachineDetails:f,onMachineUpgrade:k,onLaunchDetectedIde:y,onAddWorkspace:h,onBrowseDirectory:j,onLaunchWorkspaceProvider:v,onListSavedSessions:g}){const S=A=>A==="ide"?"Workspace":A==="cli"?"CLI":"ACP",M=r.slice(0,4),C=t.slice(0,3),N=Ty({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:c,onBrowseDirectory:j,onListSavedSessions:g}),O=l.useMemo(()=>M.map(A=>{const{metaText:I,updatedLabel:$}=ou(A);return{key:`recent-launch:${A.id}`,primary:A.label,secondary:I,updatedLabel:$,onClick:()=>{const{options:E,selectedKey:L}=au({machine:{workspaces:N.workspaceRows,defaultWorkspaceId:N.defaultWorkspaceId},currentWorkspacePath:A.workspace});N.openLaunchConfirm({title:A.kind==="ide"?Fn("restart-ide",A.label):A.providerSessionId?bd(A.label):Fn("start-fresh",A.label),description:A.kind==="ide"?Hn("restart-ide"):A.providerSessionId?gd():Hn("start-fresh"),confirmLabel:A.kind==="ide"?Wn("restart-ide"):A.providerSessionId?On(!0):Wn("start-fresh"),busyLabel:A.kind==="ide"?Kn("restart-ide"):A.providerSessionId?Yo(!0):Kn("start-fresh"),workspaceOptions:E,selectedWorkspaceKey:L,details:[{label:"Mode",value:S(A.kind)},...A.providerType?[{label:"Provider",value:A.providerType}]:[]]},async()=>{const U=E.find(B=>B.key===N.launchConfirmWorkspaceKeyRef.current);N.setWorkspaceSelectionFromOption(U),await b({...A,workspace:(U==null?void 0:U.workspacePath)??null})})}}}),[N,b,M]),_=l.useMemo(()=>C.map(A=>({key:`recent-chat:${A.conversation.tabKey}`,primary:nt(A.conversation),secondary:_x(A.conversation,{timestampLabel:A.timestamp?Rc(A.timestamp):null}),unread:A.unread,onClick:()=>w(A.conversation)})),[w,C]),T=N.showAllRecent?O:O.slice(0,4),H=O.length>0,R=_.length>0,F=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${F} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(Po,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Ct(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[R&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:_.map(A=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${A.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:A.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:A.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:A.secondary})]},A.key))})]}),H&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:T.map(A=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:A.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:A.primary}),A.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:A.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:A.secondary})]},A.key))}),O.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>N.setShowAllRecent(A=>!A),children:N.showAllRecent?"Show fewer":`Show ${O.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:k,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:f,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),N.browseDialogOpen&&s.jsx(li,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:N.browseCurrentPath,directories:N.browseDirectories,busy:N.browseBusy,error:N.browseError,confirmLabel:"Use this folder",onClose:()=>N.setBrowseDialogOpen(!1),onNavigate:A=>{N.loadBrowsePath(A)},onConfirm:A=>{N.chooseCustomWorkspacePath(A),N.setBrowseDialogOpen(!1)}}),N.launchConfirm&&s.jsx(nu,{title:N.launchConfirm.title,description:N.launchConfirm.description,details:N.launchConfirm.details,workspaceOptions:N.launchConfirm.workspaceOptions,selectedWorkspaceKey:N.launchConfirmWorkspaceKey,onWorkspaceChange:N.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:N.launchConfirm.providerType?On(!!N.launchConfirmResumeId):N.launchConfirm.confirmLabel,busyLabel:N.launchConfirm.providerType?void 0:N.launchConfirm.busyLabel,busy:N.launchConfirmBusy,showArgsInput:N.launchConfirm.showArgsInput,argsValue:N.launchConfirmArgs,onArgsChange:N.setLaunchConfirmArgs,showModelInput:N.launchConfirm.showModelInput,modelValue:N.launchConfirmModel,onModelChange:N.setLaunchConfirmModel,historyProviderNode:N.launchConfirm.providerType&&(N.launchConfirmSessionsLoading||N.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),N.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:Xo()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:N.launchConfirmTextFilter,onChange:A=>N.setLaunchConfirmTextFilter(A.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:N.launchConfirmBusy||N.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:N.launchConfirmWorkspaceFilter,onChange:A=>N.setLaunchConfirmWorkspaceFilter(A.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:N.launchConfirmBusy||N.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:N.launchConfirmModelFilter,onChange:A=>N.setLaunchConfirmModelFilter(A.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:N.launchConfirmBusy||N.launchConfirmSessionsLoading}),s.jsxs("select",{value:N.launchConfirmSortMode,onChange:A=>N.setLaunchConfirmSortMode(A.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:N.launchConfirmBusy||N.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:N.launchConfirmResumableOnly,onChange:A=>N.setLaunchConfirmResumableOnly(A.target.checked),disabled:N.launchConfirmBusy||N.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:N.launchConfirmResumeId,onChange:A=>N.setLaunchConfirmResumeId(A.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:N.launchConfirmBusy||N.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Yx()}),N.filteredLaunchConfirmSavedSessions.map(A=>s.jsxs("option",{value:A.providerSessionId,disabled:!A.canResume,children:[A.title||A.providerSessionId," ",A.canResume?"":"(workspace missing)"]},A.providerSessionId))]}),!N.launchConfirmSessionsLoading&&N.launchConfirmSavedSessions.length>0&&N.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),N.launchConfirmResumeId&&(()=>{const A=N.filteredLaunchConfirmSavedSessions.find($=>$.providerSessionId===N.launchConfirmResumeId);if(!A)return null;const I=ru(A);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:I.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:I.providerSessionId}),s.jsx("div",{className:"mt-1",children:I.metaLine}),I.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:I.updatedLabel}),I.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:I.preview})]})})()]}),onConfirm:N.handleConfirmLaunch,onCancel:N.closeLaunchConfirm}),u&&s.jsx(su,{section:m,onSectionChange:x})]})}function jn(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function _y(e,t=[]){const r=new Map(e.map(a=>[a.conversation.tabKey,a])),n=t.map(a=>r.get(a)).filter(a=>!!a);return n.length===e.length?n:jn(e)}function Ly(e){var r;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":"Offline"}function Py(e,t){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:gs(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var i;const a=kr(n)?"cli":Ls(n)?"acp":"ide",o=gs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||(kr(n)?n.cliName||n.type:Ls(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ls(n)?o||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:n.lastMessageAt||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Ry(e,t){const r=new Map;for(const n of t){const a=js(n.conversation),o=r.get(a);o?o.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],o=[...a].sort((p,x)=>x.timestamp-p.timestamp)[0]||null,i=(o==null?void 0:o.conversation)||null,c=uo(n),d=a.filter(p=>p.unread||p.requiresAction).length,m=Ly(n),u=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:Ct(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:i,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:c,preview:i?Lx(i):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,a)=>{const o=n.latestTimestamp||n.fallbackActivityAt||0,i=a.latestTimestamp||a.fallbackActivityAt||0;return i!==o?i-o:n.label.localeCompare(a.label)})}function Dy(e){return e==="chat"}function ln(e,t){var r;if(!(typeof window>"u"))try{if(!(!!((r=import.meta.env)!=null&&r.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function Ey({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:x,onRequestedMobileSectionConsumed:w,setSelectedTabKey:b,setScreen:f,setSelectedMachineId:k,setSection:y,setMachineBackTarget:h,resetMachineAction:j}){const v=l.useRef(null),g=l.useCallback(S=>{if(!(S!=null&&S.sessionId))return;const M=Pn(S,i),C=Math.max(Date.now(),fs(S),M.lastUpdated||0);ln("mark_read:start",{tabKey:S.tabKey,sessionId:S.sessionId,displayPrimary:nt(S),inboxBucket:M.inboxBucket,unread:M.unread,lastSeenAt:M.lastSeenAt,lastUpdated:M.lastUpdated,activityAt:fs(S),readAt:C}),c(js(S)||S.routeId,"mark_session_seen",{sessionId:S.sessionId,providerSessionId:S.providerSessionId,seenAt:C,completionMarker:M.completionMarker}).then(N=>{ln("mark_read:result",{tabKey:S.tabKey,sessionId:S.sessionId,result:N})}).catch(N=>{ln("mark_read:error",{tabKey:S.tabKey,sessionId:S.sessionId,error:N instanceof Error?N.message:String(N)})})},[i,c]);return l.useEffect(()=>{var M;if(!n){Dy(o)&&f("inbox"),b(((M=e[0])==null?void 0:M.tabKey)||null),v.current=null;return}if(o!=="chat"){v.current=null;return}const S=`${n.tabKey}:${n.sessionId||""}`;v.current!==S&&(v.current=S,g(n))},[e,g,o,n,f,b]),l.useEffect(()=>{if(!d)return;const S=e.find(M=>M.tabKey===d);S&&(b(S.tabKey),f("chat"),m==null||m())},[e,m,d,f,b]),l.useEffect(()=>{if(!u)return;const S=t.find(M=>M.id===u);S&&(k(S.id),j(),y("machines"),h("inbox"),f("machine"),p==null||p())},[t,p,u,j,h,f,y,k]),l.useEffect(()=>{x&&(y(x),f("inbox"),w==null||w())},[w,x,f,y]),l.useEffect(()=>{const S=r.filter(M=>M.inboxBucket==="task_complete"||M.unread);S.length!==0&&ln("inbox_state",{screen:o,selectedTabKey:a,items:S.map(M=>{const C=Pn(M.conversation,i);return{liveState:C,tabKey:M.conversation.tabKey,sessionId:M.conversation.sessionId,displayPrimary:nt(M.conversation),serverBucket:C.inboxBucket,computedBucket:M.inboxBucket,serverUnread:C.unread,computedUnread:M.unread,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,activityAt:fs(M.conversation)}})})},[r,i,o,a]),{markConversationRead:g}}function $y(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Ll(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function By(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Oy({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,o]=l.useState("idle"),[i,c]=l.useState(""),[d,m]=l.useState(null),u=l.useCallback(()=>{o("idle"),c(""),m(null)},[]),p=l.useCallback(async(h,j,v)=>{var g;try{o("loading"),c(`Launching ${j}…`);const S={ideType:j,enableCdp:!0};(g=v==null?void 0:v.workspacePath)!=null&&g.trim()&&(S.workspace=v.workspacePath.trim()),await e(h,"launch_ide",S),o("done"),c(`${j} launch requested`)}catch(S){o("error"),c(S instanceof Error?S.message:"Launch IDE failed"),console.error("Launch IDE failed",S)}},[e]),x=l.useCallback(async(h,j,v)=>{if(j.trim())try{o("loading"),c(v!=null&&v.createIfMissing?"Creating folder…":"Saving workspace…");const g=await e(h,"workspace_add",{path:j.trim(),createIfMissing:(v==null?void 0:v.createIfMissing)===!0});if(g!=null&&g.success){o("done"),c(v!=null&&v.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}o("error"),c((g==null?void 0:g.error)||"Could not save workspace")}catch(g){o("error"),c(g instanceof Error?g.message:"Could not save workspace")}},[e]),w=l.useCallback(async h=>{var j,v,g,S,M,C;try{o("loading"),c("Starting daemon upgrade…");const N=await e(h,"daemon_upgrade",{});if((j=N==null?void 0:N.result)!=null&&j.alreadyLatest){o("done"),c(`Already on v${((v=N==null?void 0:N.result)==null?void 0:v.version)||"latest"}.`);return}if((g=N==null?void 0:N.result)!=null&&g.upgraded||(S=N==null?void 0:N.result)!=null&&S.success){o("done"),c(`Upgrade to v${((M=N==null?void 0:N.result)==null?void 0:M.version)||"latest"} started. Daemon is restarting…`);return}o("error"),c(((C=N==null?void 0:N.result)==null?void 0:C.error)||"Upgrade failed")}catch(N){o("error"),c(N instanceof Error?N.message:"Upgrade failed")}},[e]),b=l.useCallback(async(h,j,v,g)=>{var C,N,O;const S=Date.now(),M={machineId:h,kind:j,providerType:v,workspaceId:(g==null?void 0:g.workspaceId)||null,workspacePath:(g==null?void 0:g.workspacePath)||null,resumeSessionId:(g==null?void 0:g.resumeSessionId)||null,startedAt:S};try{o("loading"),c(`Launching ${v}…`),m(M);const _={cliType:v};(C=g==null?void 0:g.workspacePath)!=null&&C.trim()?_.dir=g.workspacePath.trim():g!=null&&g.workspaceId&&(_.workspaceId=g.workspaceId),g!=null&&g.resumeSessionId&&(_.resumeSessionId=g.resumeSessionId),(N=g==null?void 0:g.args)!=null&&N.trim()&&(_.cliArgs=g.args.trim().split(/\s+/).filter(Boolean)),(O=g==null?void 0:g.model)!=null&&O.trim()&&(_.initialModel=g.model.trim());const T=await e(h,"launch_cli",_),H=(T==null?void 0:T.result)||T,R=(H==null?void 0:H.sessionId)||(H==null?void 0:H.id);if(T!=null&&T.success&&R){m(null),o("done"),c(`${v} launched`),t(Nr(R));return}if(T!=null&&T.success){o("loading"),c(`${v} launch requested — waiting for session…`);return}m(null),o("error"),c((T==null?void 0:T.error)||(H==null?void 0:H.error)||`Could not launch ${j.toUpperCase()} workspace`)}catch(_){if(By(_)){o("loading"),c(`${v} launch requested — waiting for session…`);return}m(null),o("error"),c(_ instanceof Error?_.message:`Could not launch ${j.toUpperCase()} workspace`)}},[t,e]),f=l.useCallback(async(h,j)=>{try{const v=await e(h,"list_saved_sessions",{providerType:j,kind:"cli",limit:30}),g=(v==null?void 0:v.result)??v;return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]}catch(v){return console.error("Failed to list saved sessions on mobile:",v),[]}},[e]),k=l.useCallback(async(h,j)=>oi(e,h,j),[e]);l.useEffect(()=>{if(!d)return;const h=Ll(d.workspacePath),j=r.find(g=>{var _,T,H,R;if(!g||g.type==="adhdev-daemon"||$y(g.daemonId||g.id)!==d.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==d.kind||String(g.agentType||g.type||"")!==d.providerType)return!1;const N=String(g.providerSessionId||"");if(d.resumeSessionId&&N)return N===d.resumeSessionId;if(h){const F=Ll(g.workspace||g.runtimeWorkspaceLabel);return F?F===h:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((R=(H=(T=(_=g.activeChat)==null?void 0:_.messages)==null?void 0:T.at)==null?void 0:H.call(T,-1))==null?void 0:R.timestamp)||0)>=d.startedAt-5e3});if(!j)return;const v=Qd({entrySessionId:j.sessionId,entryInstanceId:j.instanceId,entryRouteId:j.id,conversations:n});v&&(m(null),o("done"),c(`${d.providerType} launched`),t(Nr(v)))},[n,r,t,d]),l.useEffect(()=>{if(!d)return;const h=window.setTimeout(()=>{m(j=>!j||j.startedAt!==d.startedAt?j:(o("error"),c("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[d]);const y=l.useCallback(async(h,j)=>{if(j.kind==="ide"&&j.providerType){await p(h,j.providerType,{workspacePath:j.workspace||null});return}(j.kind==="cli"||j.kind==="acp")&&j.providerType&&await b(h,j.kind,j.providerType,{workspacePath:j.workspace||null,resumeSessionId:j.providerSessionId||null})},[p,b]);return{machineAction:{state:a,message:i},resetMachineAction:u,handleLaunchDetectedIde:p,handleAddWorkspace:x,handleMachineUpgrade:w,handleLaunchWorkspaceProvider:b,handleListSavedSessions:f,handleBrowseDirectory:k,handleOpenRecent:y}}function Fy({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:m}){const u=l.useCallback(y=>{o(y.tabKey),i("chat"),n(y)},[n,i,o]),p=l.useCallback(y=>{const h=e.find(j=>j.routeId===y.routeId&&j.streamSource==="native");h&&(o(h.tabKey),i("chat"),n(h))},[e,n,i,o]),x=l.useCallback(()=>{n(t),i("inbox")},[n,t,i]),w=l.useCallback((y,h="inbox")=>{c(y),a(),d("machines"),m(h),i("machine")},[a,m,i,d,c]),b=l.useCallback(y=>{const h=js(y);h&&w(h,"chat")},[w]),f=l.useCallback(()=>{a(),i(r)},[r,a,i]),k=l.useCallback(y=>{d(y),i("inbox")},[i,d]);return{openConversation:u,openNativeConversation:p,backFromConversation:x,openMachine:w,openConversationMachine:b,backFromMachine:f,changeMachineSection:k}}function Fs(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function Hy(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Wy({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:x,onRequestedMobileSectionConsumed:w,onOpenHistory:b,onOpenRemote:f,onStopCli:k,wsStatus:y,isConnected:h,onShowAllHiddenConversations:j,onHideConversation:v,onOpenMeshGraph:g,onOpenNewSession:S,liveSessionInboxState:M,setCliViewModeOverrides:C}){const[N,O]=l.useState(()=>{var te;return((te=e[0])==null?void 0:te.tabKey)||null}),[_,T]=l.useState(()=>e[0]?"chat":"inbox"),[H,R]=l.useState("chats"),[F,A]=l.useState(null),[I,$]=l.useState("inbox"),E=l.useRef([]),L=Ir(),U="0.9.81",B=l.useMemo(()=>e.find(te=>te.tabKey===N)||e[0]||null,[e,N]),K=l.useMemo(()=>B?r.find(te=>te.id===B.routeId):void 0,[r,B]),J=l.useMemo(()=>!B||Ve(B)||!Ye(B)?null:Ks(B),[B]),X=l.useMemo(()=>r.filter(te=>te.type==="adhdev-daemon").sort(Ho),[r]),ae=l.useMemo(()=>X.find(te=>te.id===F)||null,[X,F]),de=ra({sendDaemonCommand:a,activeConv:B||void 0,setActionLogs:o,isStandalone:i}),ke=Oy({sendDaemonCommand:a,navigate:L,ides:r,conversations:e}),q=l.useMemo(()=>e.map(te=>{const Ne=_==="chat"&&(B==null?void 0:B.tabKey)===te.tabKey,De=ta(te,M,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ne}),Ee=fs(te),ze=dd(te);return{conversation:te,timestamp:Ee,preview:ze,unread:De.unread,requiresAction:De.requiresAction,isWorking:De.isWorking,inboxBucket:De.inboxBucket}}),[e,M,_,B]),{markConversationRead:ve}=Ey({conversations:e,machineEntries:X,items:q,selectedConversation:B,selectedTabKey:N,screen:_,liveSessionInboxState:M,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:x,onRequestedMobileSectionConsumed:w,setSelectedTabKey:O,setScreen:T,setSelectedMachineId:A,setSection:R,setMachineBackTarget:$,resetMachineAction:ke.resetMachineAction}),be=Fy({conversations:e,selectedConversation:B,machineBackTarget:I,markConversationRead:ve,resetMachineAction:ke.resetMachineAction,setSelectedTabKey:O,setScreen:T,setSelectedMachineId:A,setSection:R,setMachineBackTarget:$}),{isMuted:we,autoMuteIfCoordinator:xe,toggleTarget:Ce}=og();l.useEffect(()=>{if(i)for(const te of q)xe(te.conversation)},[q,i,xe]);const Q=l.useMemo(()=>jn(q.filter(te=>te.requiresAction&&!we(te.conversation))),[q,we]),ge=l.useMemo(()=>jn(q.filter(te=>te.unread&&!te.requiresAction&&!we(te.conversation))),[q,we]),ce=l.useMemo(()=>_y(q.filter(te=>!te.unread&&!te.requiresAction&&te.isWorking),E.current),[q]);l.useEffect(()=>{E.current=ce.map(te=>te.conversation.tabKey)},[ce]);const ye=l.useMemo(()=>jn(q.filter(te=>!te.unread&&!te.requiresAction&&!te.isWorking)),[q]),me=l.useMemo(()=>ae?q.filter(te=>js(te.conversation)===ae.id):[],[q,ae]),fe=l.useMemo(()=>Py(ae,r),[r,ae]),le=(ae==null?void 0:ae.version)||null,pe=!!ae&&!!le&&!0&&le!==U,oe=l.useMemo(()=>(ae==null?void 0:ae.availableProviders)||[],[ae]),P=l.useMemo(()=>oe.filter(te=>Fs(te,"cli")).map(te=>({type:te.type,displayName:te.displayName||te.type,icon:te.icon})),[oe]),ue=l.useMemo(()=>oe.filter(te=>Fs(te,"acp")).map(te=>({type:te.type,displayName:te.displayName||te.type,icon:te.icon})),[oe]),Se=l.useMemo(()=>Ry(X,q),[q,X]),Ie=l.useCallback(async te=>{ae&&await ke.handleOpenRecent(ae.id,te)},[ke,ae]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:_==="chat"&&B?s.jsx(wy,{selectedConversation:B,isAcp:Ve(B),isStandalone:i,selectedIdeEntry:K,actionLogs:n,userName:c,isSendingChat:de.isSendingChat,sendFeedbackMessage:de.sendFeedbackMessage,isFocusingAgent:de.isFocusingAgent,handleModalButton:de.handleModalButton,handleRelaunch:de.handleRelaunch,onBack:be.backFromConversation,onOpenNativeConversation:be.openNativeConversation,onOpenMachine:be.openConversationMachine,onOpenHistory:b,onOpenRemote:f,onOpenMeshGraph:g,onStopCli:k,cliViewMode:J,onSetCliViewMode:async te=>{await Bd({conversation:B,mode:te,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:C})},handleSendChat:de.handleSendChat,handleForceSendChat:de.handleForceSendChat,handleFocusAgent:de.handleFocusAgent}):_==="machine"&&ae?s.jsx(Ay,{selectedMachineEntry:ae,selectedMachineConversations:me,selectedMachineRecentLaunches:fe,cliProviders:P,acpProviders:ue,selectedMachineNeedsUpgrade:pe,appVersion:U,machineAction:ke.machineAction,isStandalone:i,section:H,showBottomNav:I==="inbox",onBack:be.backFromMachine,onSectionChange:be.changeMachineSection,onOpenConversation:be.openConversation,onOpenRecent:Ie,onOpenMachineDetails:()=>L(`/machines/${ae.id}`),onMachineUpgrade:()=>ke.handleMachineUpgrade(ae.id),onLaunchDetectedIde:(te,Ne)=>ke.handleLaunchDetectedIde(ae.id,te,Ne),onAddWorkspace:(te,Ne)=>ke.handleAddWorkspace(ae.id,te,Ne),onBrowseDirectory:te=>ke.handleBrowseDirectory(ae.id,te),onLaunchWorkspaceProvider:(te,Ne,De)=>ke.handleLaunchWorkspaceProvider(ae.id,te,Ne,De),onListSavedSessions:te=>ke.handleListSavedSessions(ae.id,te)}):s.jsx(Sy,{section:H,attentionItems:Q,unreadItems:ge,workingItems:ce,completedItems:ye,hiddenConversations:t,machineCards:Se,getAvatarText:Hy,actionLogs:n,sendDaemonCommand:a,onOpenConversation:be.openConversation,onShowAllHidden:j,onHideConversation:v,onOpenMeshGraph:g,onOpenNewSession:S,onOpenMachine:be.openMachine,onOpenSettings:()=>L("/settings"),onSectionChange:R,wsStatus:y,isConnected:h,isStandalone:i,isConversationMuted:i?we:void 0,onToggleMuteConversation:i?Ce:void 0})})}function Ra(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Ky({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const i=l.useRef(0),[c,d]=l.useState(!1),[m,u]=l.useState(null),p=l.useCallback(()=>{i.current=0,d(!1),u(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",p),window.addEventListener("drop",p),()=>{window.removeEventListener("dragend",p),window.removeEventListener("drop",p)}),[p]);const x=l.useCallback(k=>{k.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),w=l.useCallback(k=>{if(!k.dataTransfer.types.includes("text/tab-key"))return;if(k.preventDefault(),!Ra(t,r)){u("merge");return}const y=k.currentTarget.getBoundingClientRect(),h=k.clientX-y.left,j=y.width/3;h<j?u("split-left"):h>j*2?u("split-right"):u("merge")},[t,r]),b=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),u(null))},[]),f=l.useCallback(k=>{i.current=0,d(!1);const y=k.dataTransfer.getData("text/tab-key"),h=y?e.some(v=>v.tabKey===y):!1,j=m;if(u(null),o(),!!y){if(k.preventDefault(),j==="split-left"&&Ra(t,r)){r==null||r(y,"split-left");return}if(j==="split-right"&&Ra(t,r)){r==null||r(y,"split-right");return}if(h){a(y);return}n==null||n(y)}},[e,m,t,r,n,a,o]);return{dragOver:c,dropAction:m,resetDragState:p,handleDragEnter:x,handleDragOver:w,handleDragLeave:b,handleDrop:f}}function Uy(e,t){const r=new Set(t.map(o=>o.tabKey)),n=e.filter(o=>r.has(o)),a=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...n,...a]}function zy({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,i]=l.useState(t??null),[c,d]=l.useState(r??[]),[m,u]=l.useState(null),p=l.useRef(null),x=l.useRef(null),w=l.useRef(n),b=l.useRef(a);l.useEffect(()=>{w.current=n},[n]),l.useEffect(()=>{b.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(M=>{const C=Uy(M,e);return C.length===M.length&&C.every((N,O)=>N===M[O])?M:C})},[e]);const f=l.useMemo(()=>{const M=m??c;if(M.length===0)return e;const C=new Map(M.map((N,O)=>[N,O]));return[...e].sort((N,O)=>{const _=C.get(N.tabKey)??999,T=C.get(O.tabKey)??999;return _-T})},[e,m,c]);l.useEffect(()=>{var C,N;if(f.length===0){o!==null&&(i(null),(C=w.current)==null||C.call(w,null));return}if(o&&f.some(O=>O.tabKey===o))return;const M=f[0].tabKey;M!==o&&(i(M),(N=w.current)==null||N.call(w,M))},[f,o]);const k=l.useMemo(()=>f.find(M=>M.tabKey===o),[f,o]),y=l.useCallback(M=>{var C;i(M),(C=w.current)==null||C.call(w,M)},[]),h=l.useCallback((M,C,N)=>{d(O=>{var R;const _=O.filter(F=>F!==M),T=_.indexOf(C);if(T<0)return O;const H=N==="left"?T:T+1;return _.splice(H,0,M),(R=b.current)==null||R.call(b,_),_}),u(null)},[]),j=l.useCallback((M,C,N)=>{const _=(c.length>0?c:e.map(R=>R.tabKey)).filter(R=>R!==M),T=_.indexOf(C);if(T<0)return;const H=N==="left"?T:T+1;_.splice(H,0,M),p.current=_,u(_)},[c,e]),v=l.useCallback(()=>{var C;const M=p.current;M&&(d(M),(C=b.current)==null||C.call(b,M))},[]),g=l.useCallback(()=>{p.current=null,u(null)},[]),S=l.useCallback(M=>{d(C=>{var O;const N=C.filter(_=>_!==M);return N.push(M),(O=b.current)==null||O.call(b,N),N})},[]);return{activeTabId:o,activeConv:k,sortedConversations:f,previewOrderRef:p,draggingTabRef:x,selectTab:y,handleTabReorder:h,updatePreviewOrder:j,commitPreviewOrder:v,clearPreviewOrder:g,moveTabToEnd:S,setDraggingTabKey:M=>{x.current=M}}}function Gy({dropAction:e,canSplit:t}){return s.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),s.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function ci({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:o}){if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const i=!r&&!n,c=n&&!!o,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?fd:r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can launch sessions with any installed provider.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),c&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Ht,"aria-label":Ht,children:[s.jsx(Sc,{size:14}),s.jsx("span",{children:Ht})]})}),i&&s.jsx(tu,{}),i&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const iu="adhdev-tab-shortcuts";function lu(){try{return JSON.parse(localStorage.getItem(iu)||"{}")}catch{return{}}}function cu({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>lu()),[c,d]=l.useState(null),m=l.useCallback(p=>{const x=[];return p.metaKey&&x.push(a?"⌘":"Meta"),p.ctrlKey&&x.push("Ctrl"),p.altKey&&x.push(a?"⌥":"Alt"),p.shiftKey&&x.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(x.push(p.key.length===1?p.key.toUpperCase():p.key),x.join("+"))},[a]),u=l.useCallback(p=>{i(p);try{localStorage.setItem(iu,JSON.stringify(p))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const p=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){d(null);return}const w=m(x);if(!w)return;const b={...o};for(const[f,k]of Object.entries(b))k===w&&delete b[f];b[c]=w,u(b),d(null)};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[e,c,o,u,m]),l.useEffect(()=>{if(!e)return;const p=x=>{if(!(!x.ctrlKey&&!x.metaKey&&!x.altKey)){for(const[w,b]of Object.entries(o))if(t.includes(w)&&m(x)===b){x.preventDefault(),r(),n(w);return}}};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[e,o,t,r,n,m]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const Da=e=>{e.preventDefault()},Vy=l.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:p,onReorderTab:x,onCommitPreviewOrder:w,onClearPreviewOrder:b,onDragStateReset:f,onDragTabKeyChange:k,onReceiveTab:y,onOpenContextMenu:h,longPressTimer:j,isGroupActive:v}){const g=Ws(t),S=g.isGenerating?"agent-tab-generating":g.isWaiting?"agent-tab-waiting":"",M=g.isReconnecting,C=l.useCallback(I=>{c.current=t.tabKey,k(t.tabKey),I.dataTransfer.setData("text/tab-key",t.tabKey),I.dataTransfer.effectAllowed="move"},[t.tabKey,c,k]),N=l.useCallback(()=>{c.current=null,k(null),w(),b(),f()},[c,k,w,b,f]),O=l.useCallback(I=>{const $=c.current;if(!(!$||$===t.tabKey)&&I.dataTransfer.types.includes("text/tab-key")){I.preventDefault(),I.stopPropagation();const E=I.currentTarget.getBoundingClientRect(),L=I.clientX<E.left+E.width/2?"left":"right";p($,t.tabKey,L)}},[t.tabKey,c,p]),_=l.useCallback(I=>{I.preventDefault(),I.stopPropagation();const $=I.dataTransfer.getData("text/tab-key");if($&&$!==t.tabKey){const E=I.currentTarget.getBoundingClientRect(),L=I.clientX<E.left+E.width/2?"left":"right";i.includes($)?x($,t.tabKey,L):y&&y($)}b()},[t.tabKey,i,x,y,b]),T=l.useCallback(I=>{I.stopPropagation(),d(),m(t.tabKey),u(t)},[t,u,d,m]),H=l.useCallback(I=>{I.preventDefault(),h(I.clientX,I.clientY,t.tabKey)},[t.tabKey,h]),R=l.useCallback(I=>{const $=I.touches[0];j.current=setTimeout(()=>{h($.clientX,$.clientY,t.tabKey)},600)},[t.tabKey,j,h]),F=l.useCallback(()=>{j.current&&clearTimeout(j.current)},[j]),A=["adhdev-dockview-tab",S,r&&"is-active",v&&"is-group-active",M&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:A,draggable:!0,onDragStart:C,onDragEnd:N,onDragOver:O,onDrop:_,onClick:T,onContextMenu:H,onTouchStart:R,onTouchEnd:F,onTouchMove:F,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:g.isGenerating?s.jsx("div",{className:"tab-spinner"}):g.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):M?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):g.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:nt(t),children:nt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[M?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:ms(t)}):g.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[ms(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:ms(t)}),s.jsx(Bn,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),o&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${o}`,children:o})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function qy({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:p,onDragStateReset:x,onDragTabKeyChange:w,onReceiveTab:b,onHideTab:f,isGroupActive:k,allowTabShortcuts:y=!0}){const[h,j]=l.useState(null),v=l.useRef(null),g=l.useRef(null),S=l.useMemo(()=>e.map(H=>H.tabKey),[e]);Ar("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:M,tabShortcuts:C,shortcutListening:N,setShortcutListening:O,saveShortcuts:_}=cu({enabled:y,sortedTabKeys:e.map(H=>H.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!h)return;const H=R=>{const F=document.querySelector("[data-pane-context-menu]");F&&F.contains(R.target)||j(null)};return window.addEventListener("mousedown",H,!0),()=>window.removeEventListener("mousedown",H,!0)},[h]),l.useEffect(()=>{const H=g.current;if(!H)return;const R=F=>{Math.abs(F.deltaY)<=Math.abs(F.deltaX)||(F.preventDefault(),H.scrollLeft+=F.deltaY)};return H.addEventListener("wheel",R,{passive:!1}),()=>H.removeEventListener("wheel",R)},[]);const T=l.useCallback((H,R,F)=>{j({x:H,y:R,tabKey:F})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:g,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(H=>s.jsx(Vy,{conv:H,isActive:t===H.tabKey,isDraggedTab:a.current===H.tabKey,isTaskCompleteUnread:n.has(H.tabKey),shortcut:y?C[H.tabKey]:void 0,conversationKeys:S,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:p,onDragStateReset:x,onDragTabKeyChange:w,onReceiveTab:b,onOpenContextMenu:T,longPressTimer:v,isGroupActive:k},H.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),h&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:h.x,top:h.y},children:[y&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:Da,onClick:H=>{H.stopPropagation(),O(h.tabKey),j(null)},children:["⌨ ",C[h.tabKey]?`Change shortcut (${C[h.tabKey]})`:"Set shortcut"]}),C[h.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:Da,onClick:()=>{const H={...C};delete H[h.tabKey],_(H),j(null)},children:"✕ Remove shortcut"})]}),f&&s.jsxs(s.Fragment,{children:[y&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:Da,onClick:()=>{f(h.tabKey),j(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&N&&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:()=>O(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:H=>H.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. ",M?"⌘+1":"Ctrl+1",", ",M?"⌥+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"})]})})]})}function Yy({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,userName:d,groupIndex:m,onFocus:u,isSplitMode:p,numGroups:x,onMoveTab:w,onReceiveTab:b,style:f,onActiveTabChange:k,initialActiveTabId:y,initialTabOrder:h,onTabOrderChange:j,onHideTab:v,isFocused:g,allowTabShortcuts:S=!0,onOpenNewSession:M,liveSessionInboxState:C}){const{sendCommand:N}=lt(),O=l.useRef(null),{activeTabId:_,activeConv:T,sortedConversations:H,draggingTabRef:R,selectTab:F,handleTabReorder:A,updatePreviewOrder:I,commitPreviewOrder:$,clearPreviewOrder:E,moveTabToEnd:L,setDraggingTabKey:U}=zy({conversations:e,initialActiveTabId:y,initialTabOrder:h,onActiveTabChange:k,onTabOrderChange:j}),B=ra({sendDaemonCommand:a,activeConv:T,setActionLogs:o,isStandalone:i}),{dragOver:K,dropAction:J,resetDragState:X,handleDragEnter:ae,handleDragOver:de,handleDragLeave:ke,handleDrop:q}=Ky({conversations:e,numGroups:x,onMoveTab:w,onReceiveTab:b,onOwnTabDrop:L,onClearPreviewOrder:E}),ve=T&&!Ve(T)&&Ks(T)==="terminal",be=l.useMemo(()=>T?t.find(Q=>Q.id===T.routeId):void 0,[t,T]),we=l.useMemo(()=>T?n.filter(Q=>Q.routeId===T.tabKey):[],[n,T]),xe=l.useMemo(()=>new Set(H.filter(Q=>dp(Q,C,{isOpenConversation:Q.tabKey===_})).map(Q=>Q.tabKey)),[_,C,H]);Ar("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:_,dragOver:K});const Ce=l.useCallback(Q=>{Q.streamSource==="agent-stream"&&Q.agentType&&N(Q.routeId,Jc(),{agentType:Q.agentType,...Q.sessionId&&{targetSessionId:Q.sessionId}}).catch(()=>{})},[N]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...f,outline:K?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(qy,{conversations:H,activeTabId:_,groupIndex:m,numGroups:x,unreadTabKeys:xe,draggingTabRef:R,onFocus:u,onSelectTab:F,onConversationActivated:Ce,onPreviewReorder:I,onReorderTab:A,onCommitPreviewOrder:$,onClearPreviewOrder:E,onDragStateReset:X,onDragTabKeyChange:U,onMoveTab:w,onReceiveTab:b,onHideTab:v,isGroupActive:g??!1,allowTabShortcuts:S}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ae,onDragOver:de,onDragLeave:ke,onDrop:q,children:[K&&s.jsx(Gy,{dropAction:J,canSplit:!!(x<4&&w)}),T?s.jsx(ii,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!ve,ideEntry:be,terminalRef:O,handleModalButton:B.handleModalButton,handleRelaunch:B.handleRelaunch,handleSendChat:B.handleSendChat,handleForceSendChat:B.handleForceSendChat,isSendingChat:B.isSendingChat,sendFeedbackMessage:B.sendFeedbackMessage,handleFocusAgent:B.handleFocusAgent,isFocusingAgent:B.isFocusingAgent,actionLogs:we,userName:d,isInputActive:!p||!!g}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(ci,{conversationsCount:e.length,isSplitMode:p,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:M})})]})]})}function Xy({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:p,userName:x,focusedGroup:w,focusGroup:b,moveTabToGroup:f,splitTabRelative:k,closeGroup:y,handleResizeStart:h,groupActiveTabIds:j,setGroupActiveTab:v,groupTabOrders:g,setGroupTabOrder:S,toggleHiddenTab:M,onOpenNewSession:C,allowTabShortcuts:N=!0,liveSessionInboxState:O}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((_,T)=>{const H=t&&n.length===r?`${n[T]}%`:void 0;return s.jsxs(ft.Fragment,{children:[t&&T>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:R=>h(T-1,R),onDoubleClick:()=>y(T),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(Yy,{style:t?{flexBasis:H??`${100/r}%`,flexGrow:H?0:1,flexShrink:H?0:1}:void 0,conversations:_,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:p,userName:x,groupIndex:T,isFocused:t&&w===T,onFocus:()=>b(T),isSplitMode:t,numGroups:r,onMoveTab:(R,F)=>{F==="left"&&T>0?f(R,T-1):F==="right"&&T<r-1?f(R,T+1):F==="split-left"&&r<4?k(R,T,"left"):F==="split-right"&&r<4&&k(R,T,"right")},onReceiveTab:R=>f(R,T),onActiveTabChange:R=>v(T,R),initialActiveTabId:j[T],initialTabOrder:g[T],onTabOrderChange:R=>S(T,R),onHideTab:M,onOpenNewSession:C,allowTabShortcuts:N,liveSessionInboxState:O})]},T)})})}function du({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?at.onScreenshot("ide-page",(u,p)=>{if(u!==e)return;const x=new FileReader;x.onload=()=>o(x.result),x.readAsDataURL(p)}):void 0,[e]),l.useEffect(()=>{r!=="connected"&&o(null)},[r]),l.useEffect(()=>{var u;return e?((u=at.onStatus)==null?void 0:u.call(at,(p,x)=>{p===e&&x!=null&&x.screenshotUsage&&c(x.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const m=e?at.get(e):null;if(!(!m||r!=="connected"))return n!=="chat"&&t?m.startScreenshots(t):m.stopScreenshots(t),()=>{m.stopScreenshots(t)}},[n,r,t,e]);const d=l.useCallback(async(m,u)=>{const p=e?at.get(e):null;return!p||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):p.sendInput(m,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:i,handleRemoteAction:d}}const uu="adhdev-dashboard-action-shortcuts",Jy=1200,Qy=[["toggleHiddenTabs","G H"],["openNewSession","N"],["setActiveTabShortcut","G S"],["selectPreviousGroupTab","G K"],["selectPreviousGroupTab","T ←"],["selectPreviousGroupTab","⌥+["],["selectPreviousGroupTab","Ctrl+Alt+["],["selectNextGroupTab","G J"],["selectNextGroupTab","T →"],["selectNextGroupTab","⌥+]"],["selectNextGroupTab","Ctrl+Alt+]"],["splitActiveTabDown","S ↓"],["splitActiveTabDown","⌘+⌥+-"],["splitActiveTabDown","Ctrl+Alt+-"],["splitActiveTabRight","S →"],["splitActiveTabRight","⌘+⌥+\\"],["splitActiveTabRight","⌘+⌥+="],["splitActiveTabRight","Ctrl+Alt+\\"],["focusLeftPane","F ←"],["focusLeftPane","⌘+⌥+←"],["focusLeftPane","⌘+⌥+["],["focusLeftPane","Ctrl+Alt+←"],["focusRightPane","F →"],["focusRightPane","⌘+⌥+→"],["focusRightPane","⌘+⌥+]"],["focusRightPane","Ctrl+Alt+→"],["focusUpPane","F ↑"],["focusUpPane","⌘+⌥+U"],["focusUpPane","Ctrl+Alt+↑"],["focusDownPane","F ↓"],["focusDownPane","⌘+⌥+J"],["focusDownPane","Ctrl+Alt+↓"],["moveActiveTabToLeftPane","M ←"],["moveActiveTabToLeftPane","⌘+⌥+⇧+←"],["moveActiveTabToLeftPane","⌘+⌥+,"],["moveActiveTabToLeftPane","Ctrl+Alt+Shift+←"],["moveActiveTabToRightPane","M →"],["moveActiveTabToRightPane","⌘+⌥+⇧+→"],["moveActiveTabToRightPane","⌘+⌥+."],["moveActiveTabToRightPane","Ctrl+Alt+Shift+→"],["moveActiveTabToUpPane","M ↑"],["moveActiveTabToUpPane","⌘+⌥+I"],["moveActiveTabToUpPane","Ctrl+Alt+Shift+↑"],["moveActiveTabToDownPane","M ↓"],["moveActiveTabToDownPane","⌘+⌥+K"],["moveActiveTabToDownPane","Ctrl+Alt+Shift+↓"],["triggerPrimaryApprovalAction","⌥+A"],["triggerSecondaryApprovalAction","⌥+D"],["toggleCliView","T"]];function Zy(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function tt(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function mu(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:tt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:tt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:tt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:tt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:tt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:tt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:tt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:tt("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:tt("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:tt("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:tt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:tt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:tt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:tt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:tt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:tt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:tt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:tt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:tt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:tt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:tt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:tt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:tt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:tt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:tt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:tt("toggleCliView",e)}]}function Co(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function qn(e){const t=Object.fromEntries(mu(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(uu)||"{}"),n={...t,...r};for(const[a,o]of Qy)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function hu(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function e0({enabled:e=!0,onTrigger:t}){const r=Zy(),[n,a]=l.useState(()=>qn(r)),[o,i]=l.useState(null),[c,d]=l.useState([]),m=l.useRef({parts:[],timer:null}),u=l.useCallback(f=>{const k=[];return f.metaKey&&k.push(r?"⌘":"Meta"),f.ctrlKey&&k.push("Ctrl"),f.altKey&&k.push(r?"⌥":"Alt"),f.shiftKey&&f.key.length!==1&&k.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(k.push(hu(f.key)),k.join("+"))},[r]),p=l.useCallback(f=>{a(f);try{localStorage.setItem(uu,JSON.stringify(f))}catch{}},[]);l.useEffect(()=>{const f=qn(r),k=Object.entries(n),y=Object.entries(f);k.length===y.length&&k.every(([h,j])=>f[h]===j)||p(f)},[n,r,p]);const x=l.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),w=l.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},Jy))},[]);l.useEffect(()=>{if(!o)return;const f=k=>{if(k.preventDefault(),k.stopPropagation(),k.key==="Escape"){i(null),d([]);return}const y=u(k);if(!y)return;const j=!(k.metaKey||k.ctrlKey||k.altKey)&&/^[A-Z0-9]$/.test(y);if(c.length===0&&j){d([y]);return}const g=[...c,y].slice(0,2).join(" "),S={...n};for(const[M,C]of Object.entries(S))C===g&&delete S[M];S[o]=g,p(S),i(null),d([])};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[n,u,p,o,c]),l.useEffect(()=>{if(!e||o)return;const f=k=>{if(k.defaultPrevented)return;const y=u(k);if(!y)return;const h=k.metaKey||k.ctrlKey||k.altKey;if(Co(k.target))return;const j=m.current.parts,v=h?[y]:[...j.slice(-1),y].slice(-2),g=v.join(" "),S=v[v.length-1],M=Object.entries(n).filter(([,T])=>!!T),C=M.find(([,T])=>T===g);if(C){k.preventDefault(),x(),t(C[0]);return}if(M.some(([,T])=>T.startsWith(`${g} `))){k.preventDefault(),m.current.parts=v,w();return}const O=M.find(([,T])=>T===S);if(O){k.preventDefault(),x(),t(O[0]);return}if(M.some(([,T])=>T.startsWith(`${S} `))){k.preventDefault(),m.current.parts=[S],w();return}x()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[n,w,e,u,t,x,o]),l.useEffect(()=>()=>x(),[x]);const b=l.useMemo(()=>mu(r),[r]);return{isMac:r,actionDefinitions:b,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:p}}function t0({isTabInPopout:e,isTabFloating:t,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(t&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):t?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:r?`Change shortcut (${r})`:"Set shortcut",shortcut:n.setActiveTabShortcut}),r&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:n.hideCurrentTab,tone:"muted"}),a}function pu(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Pl({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!pu(n):!0}function s0({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:pu(r)}const fu=1e3,r0=4;function Rl(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Dl(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function n0({detachDelayMs:e=fu,stillnessThresholdPx:t=r0,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,d=null,m=null,u=!1;const p=()=>{m!=null&&(a(m),m=null)},x=()=>{p(),c=null},w=()=>{p(),o=null,i=null,c=null,d=null,u=!1},b=()=>{!o||!c||!d||u||m!=null||(m=n(()=>{m=null,!(!o||!c||!d||u)&&Rl(d,i)&&(Dl(c,d,t)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},f=y=>{if(!(!o||u)){if(!Rl(y,i)){d={clientX:y.clientX,clientY:y.clientY},x();return}(!c||Dl(c,y,t))&&(p(),c={clientX:y.clientX,clientY:y.clientY}),d={clientX:y.clientX,clientY:y.clientY},b()}},k=y=>{!o||u||(y&&(d={clientX:y.clientX,clientY:y.clientY}),x())};return{startDrag:y=>{p(),o=y.panelId,i=y.selfPanelBounds??null,c=null,d={clientX:y.clientX,clientY:y.clientY},u=!1},markSelfPanel:f,markNonSelfPanel:k,markNoDropTarget:k,markDockTarget:k,endDrag:w,isDragging:()=>o!=null,hasDetached:()=>u,dispose:w}}function a0(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function cn(e){return e.isActive}function El(e){return e.isVisible}const xu=l.createContext(null);function oa(){const e=l.useContext(xu);if(!e)throw new Error("DashboardDockviewContext missing");return e}function kn(e){return nt(e)||e.tabKey}function o0(e){return`remote:${e}`}function Rt(e){return e.startsWith("remote:")}function $l(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function i0(e){e.preventDefault()}function Ea(e){var n;const t=e==null?void 0:e.defaultView;if(!t)return;const r=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),r(e==null?void 0:e.body),r(e==null?void 0:e.documentElement),(n=t.requestAnimationFrame)==null||n.call(t,()=>{try{t.focus(),r(e==null?void 0:e.body)}catch{}})}catch{}}function $a(e,t){e.classList.remove(so.className,ro.className),e.classList.add(t==="light"?so.className:ro.className)}function Bl(e){return e?Array.from(new Set(e.groups.map(t=>{var r,n;return(n=(r=t.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(t=>!!t&&t!==window))):[]}function l0(e){const[,t]=l.useState(0);l.useEffect(()=>{const r=()=>t(a=>a+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const a of n)a.dispose()}},[e.api,e.containerApi])}function c0(e,t,r){var i;const n=[t];let a;for(const c of n){let d;for(const m of c){const u=e.addPanel({id:m.tabKey,component:"conversation",title:kn(m),params:{kind:"conversation",tabKey:m.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=u.id)}a=d??a}return r??((i=t[0])==null?void 0:i.tabKey)??null}function Ol(e,t){const r=new Set(t.map(a=>a.tabKey)),n=new Map;for(const a of t)n.set(a.tabKey,(n.get(a.tabKey)||0)+1);for(const a of[...e.panels])Rt(a.id)||r.has(a.id)||e.removePanel(a);for(const a of t){const o=e.getPanel(a.tabKey);if(o){(n.get(a.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:a.tabKey,daemonId:a.daemonId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,panelId:o.id}),o.update({params:{tabKey:a.tabKey}}),o.title!==kn(a)&&o.api.setTitle(kn(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:kn(a),params:{kind:"conversation",tabKey:a.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function Fl(e,t,r){var d,m;const n=r?o0(r):null;for(const u of[...e.panels])Rt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=$t(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),i=hd(a);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((m=e.panels.find(u=>!Rt(u.id)))==null?void 0:m.id);e.addPanel({id:n,component:"remote",title:i,params:{kind:"remote",routeId:r},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function d0({params:e,api:t}){var w;const r=oa(),n=l.useRef(null),[a,o]=l.useState(()=>cn(t)),[i,c]=l.useState(()=>El(t)),d=r.conversationsByTabKey.get(e.tabKey),m=ra({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});l.useEffect(()=>{o(cn(t)),c(El(t));const b=[t.onDidActiveChange(f=>o(f.isActive)),t.onDidActiveGroupChange(f=>{if(!cn(t)&&!f.isActive){o(!1);return}o(cn(t))}),t.onDidVisibilityChange(f=>c(f.isVisible))];return()=>{for(const f of b)f.dispose()}},[t]);const u=l.useMemo(()=>d?r.ides.find(b=>b.id===d.routeId):void 0,[r.ides,d]),p=l.useMemo(()=>d?r.actionLogs.filter(b=>b.routeId===d.tabKey):[],[r.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(ci,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const x=!Ve(d)&&Ks(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(ii,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:x,ideEntry:u,terminalRef:n,handleModalButton:m.handleModalButton,handleRelaunch:m.handleRelaunch,handleSendChat:m.handleSendChat,handleForceSendChat:m.handleForceSendChat,isSendingChat:m.isSendingChat,handleFocusAgent:m.handleFocusAgent,isFocusingAgent:m.isFocusingAgent,actionLogs:p,userName:r.userName,scrollToBottomRequestNonce:((w=r.scrollToBottomRequest)==null?void 0:w.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:i})})}function u0({params:e}){var d;const t=oa(),r=l.useMemo(()=>$t([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=l.useMemo(()=>t.ides.find(m=>m.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((d=r==null?void 0:r.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=du({doId:a,targetSessionId:r?Xc(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(Pc,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:o,screenshotUsage:i,transportType:r.transport,onAction:c})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function m0(){const e=oa();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(ci,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function h0(e){var h,j;l0(e);const t=oa(),r=l.useCallback(v=>{"button"in v&&v.button!==0||e.api.setActive()},[e.api]),n=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),a=n==null?void 0:n.sessionId,o=l.useCallback(v=>fx(v),[]),i=l.useCallback(()=>px(a),[a]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const v=$t([...t.conversationsByTabKey.values()],e.params.routeId),g=((h=e.api.group.activePanel)==null?void 0:h.id)===e.api.id,S=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${g?" is-active":""}${S?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(v==null?void 0:v.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:v!=null&&v.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:v.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const d=t.conversationsByTabKey.get(e.params.tabKey);if(!d)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const m=((j=e.api.group.activePanel)==null?void 0:j.id)===e.api.id,u=e.api.isGroupActive,p=ta(d,t.liveSessionInboxState,{isOpenConversation:m}),x=p.isReconnecting,w=p.isConnecting,b=p.isGenerating||c,f=p.isWaiting,k=p.unread,y=t.tabShortcuts[d.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${m?" is-active":""}${u?" is-group-active":""}${x?" is-reconnecting":""}`,title:nt(d),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:v=>{var g;v.preventDefault(),r(v),t.openTabContextMenu({x:v.clientX,y:v.clientY,tabKey:d.tabKey,sourceDocument:((g=v.target)==null?void 0:g.ownerDocument)??document})},children:[k&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:b?s.jsx("div",{className:"tab-spinner"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):x?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):w?s.jsx("div",{className:"tab-connecting-spinner"}):d.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:nt(d)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:x?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ms(d)}):w?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ms(d)}):s.jsx("span",{children:ms(d)})})]}),y&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:y,children:y})]})}function p0({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:m,toggleHiddenTab:u,actionShortcuts:p,registerActionHandlers:x,onActiveTabChange:w,onOpenNewSession:b,onRequestScrollToBottom:f,requestedActiveTabKey:k,requestedRemoteIdeId:y,onRequestedActiveTabConsumed:h,scrollToBottomRequest:j,liveSessionInboxState:v,layoutProfile:g}){var st,qe,Ke;const{theme:S}=Us(),{sendCommand:M}=lt(),C=l.useRef(null),N=l.useRef(null),O=l.useRef(null),_=l.useRef(!1),T=l.useRef(!1),H=l.useRef(!1),R=l.useRef(null),F=l.useRef([]),[A,I]=l.useState(null),[$,E]=l.useState(0),L=l.useRef(typeof window>"u"?{}:Pg(g)),U=l.useMemo(()=>new Map(e.map(z=>[z.tabKey,z])),[e]),B=l.useMemo(()=>{const z=C.current;return z?z.groups.some(G=>{try{const Y=G.model.location.type;return Y!=="floating"&&Y!=="popout"?!1:G.panels.some(se=>U.has(se.id))}catch{return!1}}):!1},[U,$,e]),K=l.useCallback(()=>{var z;(z=C.current)==null||z.focus()},[]),J=l.useCallback((z,G)=>{f==null||f(z,G)},[f]),X=l.useCallback(z=>{const G=document,Y=z.document;for(const ne of G.querySelectorAll('link[rel="stylesheet"]')){const D=Y.createElement("link");D.rel="stylesheet",D.href=ne.href,ne.crossOrigin&&(D.crossOrigin=ne.crossOrigin),Y.head.appendChild(D)}for(const ne of G.querySelectorAll("style")){const D=Y.createElement("style");D.textContent=ne.textContent,Y.head.appendChild(D)}const se=[];for(const ne of G.styleSheets)try{for(const D of ne.cssRules)D instanceof CSSStyleRule&&(D.selectorText===":root"||D.selectorText==="html")&&se.push(D.cssText)}catch{}if(se.length>0){const ne=Y.createElement("style");ne.textContent=se.join(`
55
+ `),Y.head.appendChild(ne)}const W=G.documentElement.getAttribute("data-theme");W&&Y.documentElement.setAttribute("data-theme",W),Y.documentElement.style.colorScheme=W==="light"?"light":"dark",Y.body.className=G.body.className;const V=G.documentElement.getAttribute("style");V&&Y.documentElement.setAttribute("style",V);const ee=Y.getElementById("dv-popout-window");ee instanceof HTMLElement&&(ee.classList.add("adhdev-dockview"),$a(ee,S))},[S]),ae=l.useCallback(()=>{var G;const z=C.current;if(z)for(const Y of z.groups)try{const se=(G=Y.element)==null?void 0:G.ownerDocument;if(!se||se===document)continue;const W=se.getElementById("dv-popout-window");W instanceof HTMLElement&&(W.classList.add("adhdev-dockview"),$a(W,S));const V=document.documentElement.getAttribute("data-theme");V&&se.documentElement.setAttribute("data-theme",V),se.documentElement.style.colorScheme=V==="light"?"light":"dark",se.body.className=document.body.className;const ee=document.documentElement.getAttribute("style");ee?se.documentElement.setAttribute("style",ee):se.documentElement.removeAttribute("style")}catch{}},[S]),de=l.useCallback(z=>{const G=C.current;if(!G)return;const Y=G.getPanel(z);Y&&G.addPopoutGroup(Y,{popoutUrl:"/popout.html",onDidOpen:({window:se})=>{X(se),ge();const W=U.get(z);se.document.title=W?`${nt(W)} — ADHDev`:"ADHDev — Popout"}})},[U,X]),ke=l.useCallback(z=>{const G=C.current,Y=G==null?void 0:G.getPanel(z);if(!G||!Y)return;const se=G.groups.filter(W=>{var V;try{return((V=W.element)==null?void 0:V.ownerDocument)===document}catch{return!0}});se.length>0?Y.api.moveTo({group:se[0],position:"center"}):Y.api.moveTo({position:"center"}),Y.api.setActive()},[]),q=l.useCallback(z=>{var se;const G=C.current;if(!G)return!1;const Y=G.getPanel(z);if(!Y)return!1;try{return((se=Y.group.element)==null?void 0:se.ownerDocument)!==document}catch{return!1}},[]),ve=l.useCallback(z=>{q(z)&&ke(z),u(z)},[q,ke,u]),be=l.useCallback(z=>{const G=C.current,Y=G==null?void 0:G.getPanel(z);!G||!Y||G.addFloatingGroup(Y,{width:600,height:500})},[]),we=l.useCallback(z=>{var Y;const G=(Y=C.current)==null?void 0:Y.getPanel(z);if(!G)return!1;try{return G.group.model.location.type==="floating"}catch{return!1}},[]),xe=l.useCallback(()=>{var G,Y;const z=(Y=(G=C.current)==null?void 0:G.activePanel)==null?void 0:Y.id;return!z||Rt(z)?null:U.has(z)?z:null},[U]),Ce=l.useCallback(z=>{const G=C.current,Y=G==null?void 0:G.getPanel(z);if(!G||!Y)return;const se=G.groups.filter(W=>{try{return W.model.location.type==="grid"}catch{return!0}});se.length>0?Y.api.moveTo({group:se[0],position:"center"}):Y.api.moveTo({position:"center"}),Y.api.setActive()},[]),Q=l.useCallback(()=>{var V;const z=C.current;if(!z)return;const Y=z.groups.filter(ee=>{var ne;try{return((ne=ee.element)==null?void 0:ne.ownerDocument)===document&&ee.model.location.type==="grid"}catch{return!1}})[0]||null,se=[...z.panels];for(const ee of se){const ne=(V=ee.group.element)==null?void 0:V.ownerDocument,D=ee.group.model.location.type;ne===document&&D==="grid"||(Y&&Y.id!==ee.group.id?ee.api.moveTo({group:Y,position:"center"}):ee.api.moveTo({position:"center"}))}const W=z.activePanel;W&&(W.group.model.openPanel(W),W.api.setActive()),Ea(document)},[]),ge=l.useCallback(()=>{var G,Y;const z=C.current;if(z)for(const se of z.groups){const W=(G=se.element)==null?void 0:G.ownerDocument;if(!W||W===document)continue;const V=W.getElementById("dv-popout-window");if(!(V instanceof HTMLElement))continue;let ee=null,ne=W.title||"ADHDev",D="Popout workspace";const ie=se.activePanel;if(ie)if(ee=ie.id,Rt(ie.id)){const Te=((Y=ie.params)==null?void 0:Y.routeId)||ie.id.slice(7),Le=$t([...U.values()],Te);ne=hd(Le),D=Le!=null&&Le.machineName?`Remote view · ${Le.machineName}`:"Remote view"}else{const Te=U.get(ie.id);ne=Te?nt(Te):ie.title||ie.id,D=Te?ms(Te):"Dockview panel"}W.title=`${ne} — ADHDev`;const he=Array.from(W.querySelectorAll("#adhdev-popout-header"));for(const Te of he)Te.remove();const je=W.createElement("div");je.id="adhdev-popout-header",W.body.appendChild(je),je.setAttribute("style",["position:absolute","top:0","left:0","right:0","height:52px","display:flex","align-items:center","justify-content:space-between","gap:12px","padding:0 14px","box-sizing:border-box","background:var(--surface-secondary)","border-bottom:1px solid var(--border-subtle)","z-index:5","backdrop-filter:blur(14px)"].join(";")),je.innerHTML=`
56
+ <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
57
+ <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
58
+ <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${$l(ne)}</div>
59
+ <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${$l(D)}</div>
60
+ </div>
61
+ <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
62
+ <button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
63
+ <button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
64
+ </div>
65
+ `,V.style.top="52px",V.style.height="calc(100% - 52px)";const Me=je.querySelector("[data-adhdev-popout-focus]");Me&&(Me.onclick=()=>{window.focus()});const $e=je.querySelector("[data-adhdev-popout-dock]");$e&&($e.disabled=!ee,$e.style.opacity=ee?"1":"0.5",$e.style.cursor=ee?"pointer":"default",$e.onclick=()=>{var Te;ee&&ke(ee),(Te=W.defaultView)==null||Te.focus()})}},[U,ke]),ce=l.useCallback(z=>{var se;const G=C.current,Y=G==null?void 0:G.getPanel(z);if(!(!G||!Y)){Y.group.model.openPanel(Y),Y.api.setActive(),J(z,"dockview-shortcut");try{const W=Y.group.model.location;W.type==="popout"?W.getWindow().focus():Ea((se=Y.group.element)==null?void 0:se.ownerDocument)}catch{}}},[J]),ye=l.useCallback(z=>{const G=C.current,Y=G==null?void 0:G.activePanel,se=(G==null?void 0:G.activeGroup)||(Y==null?void 0:Y.group);if(!G||!Y||!se)return;const W=se.panels||[];if(W.length<=1)return;const V=W.findIndex(D=>D.id===Y.id);if(V<0)return;const ee=(V+z+W.length)%W.length,ne=W[ee];ne&&(ne.group.model.openPanel(ne),ne.api.setActive(),Rt(ne.id)||J(ne.id,"dockview-shortcut"))},[J]),me=l.useCallback(z=>{var Me;const G=C.current,Y=(G==null?void 0:G.activeGroup)||((Me=G==null?void 0:G.activePanel)==null?void 0:Me.group);if(!G||!Y)return;const se=G.groups||[],W=se.find($e=>$e.id===Y.id);if(!W)return;const V=W.element.getBoundingClientRect(),ee=V.left+V.width/2,ne=V.top+V.height/2,D=($e,Te,Le,Ue)=>Math.max(0,Math.min(Te,Ue)-Math.max($e,Le)),ie=$e=>{const Te=$e.element.getBoundingClientRect(),Le=Te.left+Te.width/2,Ue=Te.top+Te.height/2;let dt=0,yt=0,ut=0,mt=!1;if(z==="left"?(mt=Le<ee,dt=Math.max(0,V.left-Te.right),yt=Math.abs(Ue-ne),ut=D(V.top,V.bottom,Te.top,Te.bottom)):z==="right"?(mt=Le>ee,dt=Math.max(0,Te.left-V.right),yt=Math.abs(Ue-ne),ut=D(V.top,V.bottom,Te.top,Te.bottom)):z==="above"?(mt=Ue<ne,dt=Math.max(0,V.top-Te.bottom),yt=Math.abs(Le-ee),ut=D(V.left,V.right,Te.left,Te.right)):(mt=Ue>ne,dt=Math.max(0,Te.top-V.bottom),yt=Math.abs(Le-ee),ut=D(V.left,V.right,Te.left,Te.right)),!mt)return Number.POSITIVE_INFINITY;const Oe=ut>0?0:120;return dt*3+yt+Oe};let he=null,je=Number.POSITIVE_INFINITY;for(const $e of se){if($e.id===W.id)continue;const Te=ie($e);Number.isFinite(Te)&&(Te>=je||(je=Te,he=$e))}return he||void 0},[]),fe=l.useCallback(z=>{var se;const G=me(z);if(!G)return;const Y=G.activePanel||G.panels[0];Y&&(G.model.openPanel(Y),Y.api.setActive(),Rt(Y.id)||J(Y.id,"dockview-focus"),Ea((se=G.element)==null?void 0:se.ownerDocument))},[me,J]),le=l.useCallback((z,G)=>{const Y=C.current,se=Y==null?void 0:Y.activePanel,W=(Y==null?void 0:Y.activeGroup)||(se==null?void 0:se.group);if(!Y||!se||!W)return;let V=me(z);!V&&(G!=null&&G.createGroupIfMissing)&&(V=Y.addGroup({referenceGroup:W,direction:z})),V&&(se.api.moveTo({group:V,position:"center"}),se.group.model.openPanel(se),se.api.setActive(),Rt(se.id)||J(se.id,G!=null&&G.createGroupIfMissing?"dockview-split":"dockview-move"))},[me,J]),{isMac:pe,tabShortcuts:oe,shortcutListening:P,setShortcutListening:ue,saveShortcuts:Se}=cu({sortedTabKeys:e.map(z=>z.tabKey),onFocus:K,onSelectTab:ce}),Ie=l.useCallback(()=>{var Y;const z=C.current;if(!z)return;const G=z.activePanel;if(G){if(Rt(G.id)){const se=((Y=G.params)==null?void 0:Y.routeId)||G.id.slice(7),W=$t(e,se);W!=null&&W.tabKey&&ue(W.tabKey);return}U.has(G.id)&&ue(G.id)}},[U,ce,ue,e]),te=l.useCallback(z=>{const G=[];return z.metaKey&&G.push(pe?"⌘":"Meta"),z.ctrlKey&&G.push("Ctrl"),z.altKey&&G.push(pe?"⌥":"Alt"),z.shiftKey&&z.key.length!==1&&G.push(pe?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(z.key)?null:(G.push(hu(z.key)),G.join("+"))},[pe]),Ne=l.useCallback(z=>{var G,Y;switch(z){case"splitActiveTabRight":le("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":le("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const se=xe();se&&be(se);return}case"popoutActiveTab":{const se=xe();se&&de(se);return}case"dockActiveTab":{const se=xe();if(!se)return;q(se)?ke(se):we(se)&&Ce(se);return}case"focusLeftPane":fe("left");return;case"focusRightPane":fe("right");return;case"focusUpPane":fe("above");return;case"focusDownPane":fe("below");return;case"moveActiveTabToLeftPane":le("left");return;case"moveActiveTabToRightPane":le("right");return;case"moveActiveTabToUpPane":le("above");return;case"moveActiveTabToDownPane":le("below");return;case"selectPreviousGroupTab":ye(-1);return;case"selectNextGroupTab":ye(1);return;case"setActiveTabShortcut":Ie();return;case"hideCurrentTab":{const se=(Y=(G=C.current)==null?void 0:G.activePanel)==null?void 0:Y.id;se&&!Rt(se)&&ve(se);return}default:return}},[ye,Ce,fe,be,xe,ve,we,q,ke,le,de,Ie]);l.useEffect(()=>{if(!A)return;const z=A.sourceDocument,G=z.defaultView??window,Y=se=>{const W=z.querySelector("[data-dockview-tab-context-menu]");W&&W.contains(se.target)||I(null)};return G.addEventListener("mousedown",Y,!0),G!==window&&window.addEventListener("mousedown",()=>I(null),!0),()=>{G.removeEventListener("mousedown",Y,!0),G!==window&&window.removeEventListener("mousedown",()=>I(null),!0)}},[A]);const De=l.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:U,hasDetachedConversationPanels:B,ides:r,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:b,liveSessionInboxState:v,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:ve,userName:m,scrollToBottomRequest:j,tabShortcuts:oe,openTabContextMenu:({x:z,y:G,tabKey:Y,sourceDocument:se})=>I({x:z,y:G,tabKey:Y,sourceDocument:se??document}),popoutTab:de,moveTabBackToMain:ke,isTabInPopout:q,floatTab:be,isTabFloating:we}),[n,t,U,B,r,i,c,b,v,a,o,ve,m,j,oe,de,ke,q,be,we]),Ee=A?t0({isTabInPopout:q(A.tabKey),isTabFloating:we(A.tabKey),tabShortcut:oe[A.tabKey],actionShortcuts:p}):[],ze=l.useCallback(z=>{var se;const G=C.current;if((((se=G==null?void 0:G.activePanel)==null?void 0:se.id)??null)===z.id){z.group.model.openPanel(z);return}z.group.model.openPanel(z),z.api.setActive()},[]),Qe=l.useCallback((z,G="requested-tab")=>{if(!z)return!1;const Y=C.current;if(!Y)return!1;const se=Y.getPanel(z);return se?(ze(se),J(z,G),h==null||h(),!0):!1},[ze,h,J]),Ze=l.useCallback(()=>{if(H.current)return!1;const z=Qe(R.current,"stored-layout-restore");return z&&(H.current=!0),z},[Qe]),rt=l.useCallback(()=>{var G;const z=C.current;z&&Lg(g,{activeTabId:((G=z.activePanel)==null?void 0:G.id)??null,layout:z.toJSON()})},[g]),et=l.useCallback(()=>{Rg(g,L.current)},[g]),ct=l.useCallback(z=>{var se,W,V,ee;const G=C.current;if(!G)return{kind:"grid"};const Y=G.toJSON();for(const ne of Y.floatingGroups||[])if((W=(se=ne.data)==null?void 0:se.views)!=null&&W.includes(z)&&ne.position)return{kind:"floating",position:ne.position};for(const ne of Y.popoutGroups||[])if((ee=(V=ne.data)==null?void 0:V.views)!=null&&ee.includes(z))return{kind:"popout",position:ne.position,popoutUrl:ne.url};return{kind:"grid"}},[]),Xe=l.useCallback(z=>{const G=C.current;if(!G)return;const Y=G.getPanel(z),se=L.current[z];if(!Y||!se||se.kind==="grid")return;if(Y.group.model.location.type===se.kind){delete L.current[z],et();return}if(se.kind==="floating"){G.addFloatingGroup(Y,{x:se.position.left??24,y:se.position.top??24,width:se.position.width,height:se.position.height}),delete L.current[z],et();return}delete L.current[z],et()},[et]);l.useEffect(()=>(x==null||x({setShortcutForActiveTab:Ie,restoreHiddenTabToSavedLocation:Xe,activateConversationTab:ce,resetAllPanelsToMain:Q,activatePreviousTabInGroup:()=>ye(-1),activateNextTabInGroup:()=>ye(1),floatActiveTab:()=>{const z=xe();z&&be(z)},popoutActiveTab:()=>{const z=xe();z&&de(z)},dockActiveTab:()=>{const z=xe();z&&(q(z)?ke(z):we(z)&&Ce(z))},splitActiveTabRight:()=>le("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>le("below",{createGroupIfMissing:!0}),focusLeftPane:()=>fe("left"),focusRightPane:()=>fe("right"),focusUpPane:()=>fe("above"),focusDownPane:()=>fe("below"),moveActiveTabToLeftPane:()=>le("left"),moveActiveTabToRightPane:()=>le("right"),moveActiveTabToUpPane:()=>le("above"),moveActiveTabToDownPane:()=>le("below")}),()=>x==null?void 0:x(null)),[ye,Ce,be,fe,xe,we,q,le,ke,de,x,Q,Xe,ce,Ie]),l.useEffect(()=>()=>{var z;(z=O.current)==null||z.call(O),O.current=null},[]);const pt=l.useCallback(z=>{var Y,se;C.current=z.api,(Y=O.current)==null||Y.call(O),O.current=null;const G=_g(g);if(R.current=(G==null?void 0:G.activeTabId)??null,G!=null&&G.layout&&z.api.fromJSON(G.layout,{reuseExistingPanels:!1}),T.current=Pl({hasStoredLayout:!!(G!=null&&G.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),T.current||(Ol(z.api,e),Fl(z.api,e,y)),z.api.totalPanels===0&&e.length>0){const W=c0(z.api,e,k);if(W){const V=z.api.getPanel(W);V&&ze(V)}}else!T.current&&!Qe(k)&&Ze();if(_.current=!0,z.api.onDidActivePanelChange(W=>{var ee;if(R.current=(W==null?void 0:W.id)??null,H.current=!0,ge(),W&&Rt(W.id)){const ne=((ee=W.params)==null?void 0:ee.routeId)||W.id.slice(7),D=$t(e,ne);w((D==null?void 0:D.tabKey)??null),rt();return}if(w((W==null?void 0:W.id)??null),rt(),!W)return;const V=U.get(W.id);(V==null?void 0:V.streamSource)==="agent-stream"&&V.agentType&&M(V.routeId,Jc(),{agentType:V.agentType,...V.sessionId&&{targetSessionId:V.sessionId}}).catch(()=>{})}),z.api.onDidLayoutChange(()=>{rt(),ge(),E(W=>W+1)}),a0()){const W=je=>({clientX:je.clientX,clientY:je.clientY}),V=je=>{const Me=je==null?void 0:je.getBoundingClientRect();return Me?{left:Me.left,right:Me.right,top:Me.top,bottom:Me.bottom}:null},ee=je=>{var $e;const Me=($e=N.current)==null?void 0:$e.getBoundingClientRect();return Me?je.clientX<Me.left||je.clientX>Me.right||je.clientY<Me.top||je.clientY>Me.bottom:!1},ne=n0({detachDelayMs:fu,onDetach:({panelId:je,clientX:Me,clientY:$e})=>{var ut,mt;const Te=z.api.getPanel(je);if(!Te)return;try{if(Te.group.model.location.type!=="grid")return}catch{return}const Le=(ut=N.current)==null?void 0:ut.getBoundingClientRect(),Ue=(mt=Te.group.element)==null?void 0:mt.getBoundingClientRect(),dt=Math.round(Math.min(Math.max((Ue==null?void 0:Ue.width)??600,360),720)),yt=Math.round(Math.min(Math.max((Ue==null?void 0:Ue.height)??500,260),640));z.api.addFloatingGroup(Te,{x:Le?Math.max(0,Me-Le.left-32):void 0,y:Le?Math.max(0,$e-Le.top-18):void 0,width:dt,height:yt}),Te.api.setActive(),rt(),ge(),E(Oe=>Oe+1)}}),D=[z.api.onWillDragPanel(je=>{if(!(je.nativeEvent.defaultPrevented||je.nativeEvent.shiftKey)){try{if(je.panel.group.model.location.type!=="grid")return}catch{return}ne.startDrag({panelId:je.panel.id,selfPanelBounds:V(je.panel.group.element),...W(je.nativeEvent)})}}),z.api.onWillShowOverlay(je=>{if(ne.hasDetached()){je.preventDefault();return}ne.markDockTarget(W(je.nativeEvent))}),z.api.onWillDrop(je=>{if(ne.hasDetached()){je.preventDefault(),ne.endDrag();return}ne.markDockTarget(W(je.nativeEvent))}),z.api.onDidDrop(()=>ne.endDrag()),z.api.onUnhandledDragOverEvent(je=>{ne.isDragging()&&ne.markSelfPanel(W(je.nativeEvent))})],ie=je=>{if(!ne.isDragging())return;const Me=W(je);ee(Me)&&ne.markNonSelfPanel(Me)},he=()=>ne.endDrag();window.addEventListener("dragover",ie,!0),window.addEventListener("drop",he,!0),window.addEventListener("dragend",he,!0),O.current=()=>{ne.dispose();for(const je of D)je.dispose();window.removeEventListener("dragover",ie,!0),window.removeEventListener("drop",he,!0),window.removeEventListener("dragend",he,!0)}}z.api.onDidAddGroup(W=>{requestAnimationFrame(()=>{var V,ee;try{const ne=(V=W.element)==null?void 0:V.ownerDocument;if(!ne||ne===document)return;(ee=ne.getElementById("dv-popout-window"))==null||ee.classList.add("adhdev-dockview");const D=document.documentElement.getAttribute("data-theme");D&&ne.documentElement.setAttribute("data-theme",D),ne.body.className=document.body.className;const ie=document.documentElement.getAttribute("style");ie&&ne.documentElement.setAttribute("style",ie)}catch{}ge(),E(ne=>ne+1)})}),w(((se=z.api.activePanel)==null?void 0:se.id)??null)},[ze,Qe,U,r,d,g,w,rt,k,y,M,ge,e]);l.useLayoutEffect(()=>{const z=C.current;if(!z||!_.current||T.current&&Pl({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;T.current&&(T.current=!1);const G=F.current,Y=new Set(G),se=e.map(he=>he.tabKey),W=new Set(se),V=s0({previousVisibleConversationCount:G.length,visibleConversationCount:e.length,ides:r});let ee=!1;for(const he of G)W.has(he)||V||(L.current[he]=ct(he),ee=!0);ee&&et(),V||(Ol(z,e),Fl(z,e,y));const ne=se.filter(he=>!Y.has(he));let D=!1;for(const he of ne){const je=z.getPanel(he),Me=L.current[he];if(!je||!Me||Me.kind==="grid")continue;if(je.group.model.location.type===Me.kind){delete L.current[he],D=!0;continue}if(Me.kind==="floating"){z.addFloatingGroup(je,{x:Me.position.left??24,y:Me.position.top??24,width:Me.position.width,height:Me.position.height}),delete L.current[he],D=!0;continue}}if(D&&et(),F.current=se,k&&Qe(k))return;!z.activePanel&&z.panels[0]&&ze(z.panels[0]),!!(z.activePanel&&z.getPanel(z.activePanel.id))||Ze()},[ze,Qe,Ze,r,d,et,ct,k,y,e]),l.useEffect(()=>{_.current&&Qe(k)},[Qe,k]),l.useEffect(()=>{const z=Y=>{const se=Y.target;if(!se)return;const W=se.querySelector("[data-tab-key]")||se.closest("[data-tab-key]");if(W){const V=W.getAttribute("data-tab-key");if(V&&Y.dataTransfer){const ee=se.closest(".dv-tab")||W.closest(".dv-tab")||W;Y.dataTransfer.effectAllowed="move",Y.dataTransfer.setData("text/tab-key",V),ee instanceof HTMLElement&&Y.dataTransfer.setDragImage(ee,Math.max(12,Math.round(ee.clientWidth/2)),Math.max(10,Math.round(ee.clientHeight/2)))}}};window.addEventListener("dragstart",z);const G=Bl(C.current);for(const Y of G)Y.addEventListener("dragstart",z);return()=>{window.removeEventListener("dragstart",z);for(const Y of G)Y.removeEventListener("dragstart",z)}},[$]),l.useEffect(()=>{var G;const z=(G=N.current)==null?void 0:G.querySelector(".adhdev-dockview");z instanceof HTMLElement&&$a(z,S),ae(),ge()},[ge,ae,S]),l.useEffect(()=>{ge()},[ge]),l.useEffect(()=>{const z=G=>{if(G.defaultPrevented||P)return;const Y=te(G);if(!Y)return;const se=G.metaKey||G.ctrlKey||G.altKey;Co(G.target)&&!se||qn(pe).setActiveTabShortcut!==Y||(G.preventDefault(),G.stopPropagation(),Ie())};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[te,pe,P,Ie]),l.useEffect(()=>{const z=N.current;if(!z)return;const G=Y=>{var ne,D;if(!Y.isTrusted)return;const se=(D=(ne=Y.target)==null?void 0:ne.closest)==null?void 0:D.call(ne,".dv-scrollable");if(!se)return;Y.preventDefault(),Y.stopPropagation();const W=Math.abs(Y.deltaX),V=Math.abs(Y.deltaY),ee=W>V?Y.deltaX:Y.deltaY;se.dispatchEvent(new WheelEvent("wheel",{deltaY:ee,deltaMode:Y.deltaMode,bubbles:!1,cancelable:!0}))};return z.addEventListener("wheel",G,{passive:!1,capture:!0}),()=>z.removeEventListener("wheel",G,{capture:!0})},[]),l.useEffect(()=>{const z=Bl(C.current);if(z.length===0)return;const G=z.map(Y=>{let se=[],W=null;const V=()=>{W!=null&&Y.clearTimeout(W),W=null,se=[]},ee=()=>{W!=null&&Y.clearTimeout(W),W=Y.setTimeout(()=>{W=null,se=[]},1200)},ne=ie=>{if(!ie.ctrlKey&&!ie.metaKey&&!ie.altKey)return;const he=te(ie);if(!he)return;const je=lu();for(const[Me,$e]of Object.entries(je))if(e.some(Te=>Te.tabKey===Me)&&$e===he){ie.preventDefault(),ce(Me);return}},D=ie=>{if(ie.defaultPrevented||P)return;const he=te(ie);if(!he)return;const je=ie.metaKey||ie.ctrlKey||ie.altKey;if(Co(ie.target))return;const Me=qn(pe),$e=Object.entries(Me).filter(([Oe,Yt])=>!!Yt&&(Oe==="splitActiveTabRight"||Oe==="splitActiveTabDown"||Oe==="floatActiveTab"||Oe==="popoutActiveTab"||Oe==="dockActiveTab"||Oe==="focusLeftPane"||Oe==="focusRightPane"||Oe==="focusUpPane"||Oe==="focusDownPane"||Oe==="moveActiveTabToLeftPane"||Oe==="moveActiveTabToRightPane"||Oe==="moveActiveTabToUpPane"||Oe==="moveActiveTabToDownPane"||Oe==="selectPreviousGroupTab"||Oe==="selectNextGroupTab"||Oe==="setActiveTabShortcut"||Oe==="hideCurrentTab")),Te=je?[he]:[...se.slice(-1),he].slice(-2),Le=Te.join(" "),Ue=Te[Te.length-1],dt=$e.find(([,Oe])=>Oe===Le);if(dt){ie.preventDefault(),V(),Ne(dt[0]);return}if($e.some(([,Oe])=>Oe.startsWith(`${Le} `))){ie.preventDefault(),se=Te,ee();return}const ut=$e.find(([,Oe])=>Oe===Ue);if(ut){ie.preventDefault(),V(),Ne(ut[0]);return}if($e.some(([,Oe])=>Oe.startsWith(`${Ue} `))){ie.preventDefault(),se=[Ue],ee();return}V()};return Y.addEventListener("keydown",ne),Y.addEventListener("keydown",D),()=>{V(),Y.removeEventListener("keydown",ne),Y.removeEventListener("keydown",D)}});return()=>{for(const Y of G)Y()}},[te,pe,$,ce,P,Ne,e]);const Ae=S==="light"?so:ro,Fe=((Ke=(qe=(st=C.current)==null?void 0:st.activePanel)==null?void 0:qe.group.element)==null?void 0:Ke.ownerDocument)??document;return s.jsxs(xu.Provider,{value:De,children:[s.jsx("div",{ref:N,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(vm,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:d0,remote:u0},defaultTabComponent:h0,watermarkComponent:m0,onReady:pt,singleTabMode:"default",tabAnimation:"smooth",theme:Ae,popoutUrl:"/popout.html"})}),A&&vr.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:A.x,top:A.y},children:Ee.map(z=>{if(z.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},z.id);let G=s.jsx(Ih,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{};switch(z.id){case"dockInWindow":case"dockBackToGrid":G=s.jsx(Ah,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{Ce(A.tabKey),I(null)};break;case"moveBackToMain":G=s.jsx(Mh,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{ke(A.tabKey),I(null)};break;case"floatAsPanel":G=s.jsx(Th,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{be(A.tabKey),I(null)};break;case"openInNewWindow":G=s.jsx(Ch,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{de(A.tabKey),I(null)};break;case"setShortcut":Y=se=>{se.stopPropagation(),ue(A.tabKey),I(null)};break;case"removeShortcut":G=s.jsx(gt,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{const se={...oe};delete se[A.tabKey],Se(se),I(null)};break;case"hideTab":G=s.jsx(Do,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{ve(A.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 ${z.tone==="muted"?"text-text-muted":""}`,onMouseDown:i0,onClick:Y,children:[G,s.jsx("span",{className:"flex-1 min-w-0",children:z.label}),z.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:z.shortcut}):null]},z.id)})}),A.sourceDocument.body),P&&vr.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:()=>ue(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:z=>z.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",pe?"⌘+1":"Ctrl+1",", ",pe?"⌥+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"})]})}),Fe.body)]})}const bu="adhdev-recent-launch-args-v1",f0=8;function x0(e){return String(e||"").trim().replace(/\s+/g," ")}function gu(e,t){return`${e.trim()}::${t.trim()}`}function yu(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(bu)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function b0(e){if(!(typeof window>"u"))try{window.localStorage.setItem(bu,JSON.stringify(e))}catch{}}function g0(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=yu().byKey[gu(r,n)])==null?void 0:o.items)||[]}function y0(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=x0(r);if(!n||!a||!o)return;const i=yu(),c=gu(n,a),d=((u=i.byKey[c])==null?void 0:u.items)||[],m=[o,...d.filter(p=>p!==o)].slice(0,f0);i.byKey[c]={items:m},b0(i)}function v0(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Sn({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 w0({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 j0({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:i,onOpenHistory:c,onClearSelection:d}){const m=o?ru(o):null,u=w0({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Sn,{title:"Saved history",description:Xo(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:i,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:c,children:Zx()})]}),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 vu({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 k0({workspaceMode:e,activeKind:t,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:o,onSelect:i}){return e==="mesh"?null:s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:r},{id:"ide",label:"Workspace",enabled:n},{id:"acp",label:"ACP",enabled:a}].map(c=>s.jsx("button",{type:"button",className:`btn btn-sm ${t===c.id?"btn-primary":"btn-secondary"}`,onClick:()=>i(c.id),disabled:!c.enabled||o,children:c.label},c.id))})]})}function Ba(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>Fs(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>Fs(a,"acp"))?"acp":null}function dn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function S0({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Oe,Yt;const u=Lr(),p=l.useMemo(()=>[...e].sort(Ho),[e]),[x,w]=l.useState(((Oe=p[0])==null?void 0:Oe.id)||""),b=l.useMemo(()=>p.find(Z=>Z.id===x)||p[0],[x,p]),f=l.useMemo(()=>((b==null?void 0:b.workspaces)||[]).map(Z=>({id:Z.id,path:Z.path,label:Z.label})),[b]),k=(b==null?void 0:b.defaultWorkspaceId)||null,[y,h]=l.useState("workspace"),[j,v]=l.useState(""),[g,S]=l.useState(""),[M,C]=l.useState([]),[N,O]=l.useState(""),[_,T]=l.useState(!1),[H,R]=l.useState(null),[F,A]=l.useState(""),[I,$]=l.useState(Ba(p[0])),[E,L]=l.useState(""),[U,B]=l.useState(""),[K,J]=l.useState([]),[X,ae]=l.useState(""),[de,ke]=l.useState([]),[q,ve]=l.useState(!1),[be,we]=l.useState(!1),[xe,Ce]=l.useState(""),[Q,ge]=l.useState(!1),[ce,ye]=l.useState(()=>jt()),[me,fe]=l.useState(null),[le,pe]=l.useState(!1),[oe,P]=l.useState(""),[ue,Se]=l.useState(null),[Ie,te]=l.useState(!1),[Ne,De]=l.useState(""),[Ee,ze]=l.useState([]),[Qe,Ze]=l.useState(!1),[rt,et]=l.useState(""),[ct,Xe]=l.useState(!1),pt=l.useRef(null),Ae=l.useRef(0);l.useEffect(()=>{var Z;!x&&((Z=p[0])!=null&&Z.id)&&w(p[0].id)},[x,p]),l.useEffect(()=>{!b||!(!b.workspaces||!b.availableProviders||!b.detectedIdes||!b.recentLaunches)||u(b.id,{minFreshMs:3e4}).catch(()=>{})},[u,b]);const Fe=l.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(Z=>Fs(Z,"cli")),[b]),st=l.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(Z=>Fs(Z,"acp")),[b]),qe=l.useMemo(()=>((b==null?void 0:b.detectedIdes)||[]).map(Z=>({id:Z.type,label:Z.name||Z.type,meta:Z.running?"Detected locally":"Available to open"})),[b]),Ke=l.useMemo(()=>I==="cli"?Fe.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"CLI provider"})):I==="acp"?st.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"ACP provider"})):qe,[st,I,Fe,qe]),z=l.useMemo(()=>M.find(Z=>Z.id===N)||null,[M,N]),G=l.useMemo(()=>Fe.find(Z=>Z.type===E)||null,[Fe,E]),Y=l.useMemo(()=>Xd(G==null?void 0:G.meshCoordinator,{meshId:(z==null?void 0:z.id)||"",workspace:(z==null?void 0:z.workspace)||""}),[G,z]),se=ue||Y,W=l.useCallback(async Z=>{T(!0),A("");try{const Pe=await c(Z);C(Pe),O(re=>{var Re;return Pe.some(kt=>kt.id===re)?re:((Re=Pe[0])==null?void 0:Re.id)||""}),R(Z)}catch(Pe){C([]),O(""),R(Z),A(Pe instanceof Error?Pe.message:"Could not load meshes")}finally{T(!1)}},[c]);l.useEffect(()=>{var Pe;if(!b)return;if(pt.current!==b.id){pt.current=b.id,h("workspace"),v(k||((Pe=f[0])==null?void 0:Pe.id)||"__home__"),S(""),C([]),O(""),R(null),A(""),$(Ba(b)),L(""),B(""),ae(""),ke([]),we(!1),Ce(""),ye(jt()),P(""),Se(null);return}v(re=>{var Re;return re==="__custom__"||re==="__home__"||f.some(kt=>kt.id===re)?re:k||((Re=f[0])==null?void 0:Re.id)||"__home__"}),$(re=>re==="ide"&&qe.length>0||re==="cli"&&Fe.length>0||re==="acp"&&st.length>0?re:Ba(b))},[st.length,Fe.length,k,qe.length,b,f]),l.useEffect(()=>{!b||y!=="mesh"||H===b.id||_||W(b.id)},[W,H,_,b,y]),l.useEffect(()=>{y==="mesh"&&I!=="cli"&&Fe.length>0&&$("cli")},[I,Fe.length,y]),l.useEffect(()=>{var Z;I&&(Ke.some(Pe=>Pe.id===E)||L(((Z=Ke[0])==null?void 0:Z.id)||""))},[I,Ke,E]),l.useEffect(()=>{Se(null)},[b==null?void 0:b.id,N,E,y]);const V=l.useCallback(async(Z,Pe)=>{const re=Ae.current+1;return Ae.current=re,ve(!0),Ce(""),m(Z,Pe).then(Re=>{Ae.current===re&&ke(Re)}).catch(Re=>{Ae.current===re&&(ke([]),Ce(Re instanceof Error?Re.message:"Could not load saved sessions"))}).finally(()=>{Ae.current===re&&(ve(!1),we(!0))})},[m]),ee=l.useCallback((Z,Pe)=>{J(g0(Z,Pe))},[]);l.useEffect(()=>{Ae.current+=1,ae(""),ye(jt()),!b||!E||I==="ide"?J([]):ee(b.id,E),we(!1),ke([]),Ce(""),ve(!1)},[I,ee,V,b,E]),l.useEffect(()=>{if(!X)return;const Z=de.find(Pe=>Pe.providerSessionId===X);Z!=null&&Z.canResume||ae("")},[de,X]);const ne=j==="__custom__"?g.trim():j==="__home__"?"":((Yt=f.find(Z=>Z.id===j))==null?void 0:Yt.path)||"",D=l.useMemo(()=>b?t.filter(Z=>Z.id!==b.id&&Z.daemonId===b.id).map(Z=>Z.workspace):[],[t,b]),ie=l.useMemo(()=>((b==null?void 0:b.recentLaunches)||[]).map(Z=>Z.workspace),[b]),he=l.useCallback(Z=>{const Pe=String(Z.workspace||"").trim();if(!Pe)return;const re=f.find(Re=>dn(Re.path)===dn(Pe));if(re){v(re.id),S("");return}v("__custom__"),S(Pe)},[f]),je=l.useCallback(Z=>{const Pe=String(Z.workspace||"").trim();if(!Pe)return{workspaceId:null,workspacePath:null};const re=f.find(Re=>dn(Re.path)===dn(Pe));return re?{workspaceId:re.id,workspacePath:null}:{workspaceId:null,workspacePath:Pe}},[f]),Me=l.useMemo(()=>de.find(Z=>Z.providerSessionId===X)||null,[de,X]),$e=l.useMemo(()=>{var Pe;if(I!=="cli"||!b||!E)return null;const Z=((Pe=Fe.find(re=>re.type===E))==null?void 0:Pe.displayName)||E;return{routeId:b.id,daemonId:b.id,providerSessionId:X||void 0,transport:"pty",mode:"chat",agentName:Z,agentType:E,status:"idle",title:Z,messages:[],ideType:E,workspaceName:ne,workspacePath:ne,displayPrimary:Z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${b.id}:${E}`,machineName:Ct(b,{fallbackId:b.id})}},[I,Fe,ne,b,X,E]),Te=l.useCallback(()=>{var Pe;if(!b)return;v("__custom__"),te(!0),et("");const Z=ai(b.platform,ni(g.trim(),ne,D,ie,b.defaultWorkspacePath,(Pe=f.find(re=>re.id===k))==null?void 0:Pe.path,f.map(re=>re.path)));Ze(!0),n(b.id,Z).then(re=>{De(re.path),S(re.path),ze(re.directories)}).catch(re=>{et(re instanceof Error?re.message:"Could not load folder")}).finally(()=>Ze(!1))},[g,k,ie,D,n,ne,b,f]),Le=l.useCallback(Z=>{b&&(Ze(!0),et(""),n(b.id,Z).then(Pe=>{De(Pe.path),S(Pe.path),ze(Pe.directories)}).catch(Pe=>{et(Pe instanceof Error?Pe.message:"Could not load folder")}).finally(()=>Ze(!1)))},[n,b]),Ue=l.useCallback(async()=>{if(!b||!ne)return;Xe(!0),P("");const Z=await a(b.id,ne);if(Xe(!1),!Z.ok){P(Z.error||"Could not save workspace");return}P("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,ne,b]),dt=l.useCallback(async()=>{if(!b)return;if(y==="mesh"){if(!N||!E)return;pe(!0),P(""),Se(null);const re=await d(b.id,N,E);if(pe(!1),!re.ok){if(re.code==="mesh_coordinator_manual_mcp_setup_required"&&re.manualSetup){Se(re.manualSetup),P("Manual MCP setup required before this provider can act as mesh coordinator.");return}P(re.error||"Could not start mesh coordinator");return}r();return}if(!I||!E)return;pe(!0),P("");const Z=U.trim()?U.trim().split(/\s+/).filter(Boolean):[],Pe=I==="ide"?await o(b.id,E,{workspacePath:ne||null}):await i(b.id,I,E,{workspaceId:j!=="__home__"&&j!=="__custom__"?j:null,workspacePath:j==="__custom__"&&ne||null,resumeSessionId:I==="cli"&&X?X:null,cliArgs:Z});if(pe(!1),!Pe.ok){P(Pe.error||"Could not start session");return}I!=="ide"&&U.trim()&&(y0(b.id,E,U),ee(b.id,E)),r()},[I,U,ee,r,o,d,i,ne,b,N,X,E,j,y]),yt=y==="mesh"?"Start mesh coordinator":I?Xx(I,I==="cli"&&!!X):"Start",ut=y==="mesh"?"Starting coordinator…":I?Jx(I,I==="cli"&&!!X):"Starting…",mt=p.length>5;return b?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(gt,{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:[p.length>1&&s.jsx(Sn,{title:"Machine",children:mt?s.jsx("select",{"aria-label":"Machine",value:b.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:le,children:p.map(Z=>s.jsx("option",{value:Z.id,children:Ct(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 Pe=Ct(Z,{fallbackId:Z.id}),re=b.id===Z.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${Pe}`,"aria-pressed":re,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${re?"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:le,title:Pe,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:Pe})]},Z.id)})})}),s.jsxs(Sn,{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:Te,disabled:le,children:"Browse…"}):void 0,children:[s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":"Launch target type",children:[{id:"workspace",label:"Workspace",desc:"Normal session"},{id:"mesh",label:"Mesh",desc:"Coordinator session"}].map(Z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":y===Z.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${y===Z.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{h(Z.id),P(""),Z.id==="mesh"&&b&&H!==b.id&&!_&&W(b.id)},disabled:le,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:j,onChange:Z=>{const Pe=Z.target.value;v(Pe),Pe==="__custom__"?Te():P("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:le,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),f.map(Z=>s.jsxs("option",{value:Z.id,children:[Z.id===k?"⭐ ":"",Ec(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:j==="__home__"?"Launch without a workspace.":ne||"Select a workspace folder."}),j==="__custom__"&&ne&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Te,disabled:le,children:[s.jsx($s,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ue,disabled:le||ct,children:ct?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[_&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!_&&F&&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:F}),!_&&!F&&M.length===0&&s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker."}),M.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:M.map(Z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":N===Z.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${N===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>O(Z.id),disabled:le,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))}),z&&s.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),s.jsx(k0,{workspaceMode:y,activeKind:I,cliEnabled:Fe.length>0,ideEnabled:qe.length>0,acpEnabled:st.length>0,busy:le,onSelect:$}),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:[Ke.map(Z=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${E===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>L(Z.id),disabled:le,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)),Ke.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(vu,{setup:se,providerName:(G==null?void 0:G.displayName)||(G==null?void 0:G.name)||E}),y!=="mesh"&&I!=="ide"&&s.jsxs(Sn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:U,onChange:Z=>B(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:le}),K.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:K.map(Z=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>B(Z),disabled:le,title:Z,children:Z},Z))})]}),y!=="mesh"&&I==="cli"&&s.jsx(j0,{busy:le,savedSessionsLoading:q,savedSessionsError:xe,selectedSession:Me,onRefresh:()=>{!b||!E||V(b.id,E)},onOpenHistory:()=>{!b||!E||(ge(!0),v0({hasLoadedInitialResults:be,isLoading:q})&&V(b.id,E))},onClearSelection:()=>ae("")}),oe&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${oe.includes("saved")||oe.includes("requested")||oe.includes("Manual MCP setup")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:oe})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:r,disabled:le,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:dt,disabled:le||(y==="mesh"?!N||!E||I!=="cli"||_:!I||!E||j==="__custom__"&&!ne),children:[s.jsx(kc,{size:14}),le?ut:yt]})]})]})}),Ie&&s.jsx(li,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:Ne,directories:Ee,busy:Qe,error:rt,onClose:()=>te(!1),onNavigate:Le,onConfirm:Z=>{S(Z),De(Z),v("__custom__"),te(!1)}}),Q&&$e&&s.jsx(yd,{activeConv:$e,ides:[],isCreatingChat:!1,isRefreshingHistory:q,savedSessions:de,isSavedSessionsLoading:q,isResumingSavedSessionId:me,savedHistoryFilters:ce,missingWorkspaceResumePath:ne||null,onSavedHistoryFiltersChange:ye,onClose:()=>ge(!1),onNewChat:()=>{ae(""),ge(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!b||!E||V(b.id,E)},onResumeSavedSession:Z=>{if(!b||!E||me||!Z.canResume)return;const Pe=je(Z);ae(Z.providerSessionId),he(Z),fe(Z.providerSessionId),ge(!1),pe(!0),P(""),i(b.id,"cli",E,{workspaceId:Pe.workspaceId,workspacePath:Pe.workspacePath,resumeSessionId:Z.providerSessionId}).then(re=>{if(!re.ok){P(re.error||"Could not resume session");return}r()}).finally(()=>{pe(!1),fe(re=>re===Z.providerSessionId?null:re)})}})]}):null}function wu(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 Yn(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=wu(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 di(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function ju(e){var t;return!di(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 un(e){return[...new Set(e.filter(t=>!!t))]}function N0(e){const t=e.nodes.find(i=>i.type==="defaultBranchNode")??null,r=(t==null?void 0:t.branch)??null,n=e.nodes.filter(i=>i.type!=="defaultBranchNode"&&i.type!=="submoduleNode"&&!i.isOrphan&&!!r&&i.branch===r),a=e.nodes.filter(i=>i.type!=="submoduleNode"&&!i.isOrphan),o=e.nodes.filter(i=>i.type!=="submoduleNode");return t||n.length>0?un([t==null?void 0:t.id,...n.map(i=>i.id)]):a.length>0?un(a.map(i=>i.id)):o.length>0?un(o.map(i=>i.id)):un(e.nodes.map(i=>i.id))}function ku(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 C0(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${ku(e)}::${n}x${a}`}const M0={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"},I0={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"},T0={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"},A0={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=>I0[t],actionButton:t=>A0[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=>M0[t],actionButton:t=>T0[t]}}const xs={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,layerGap:220,nodeGap:82,edgeLabelBuffer:180,placeholderTopOffset:0},Rs={worktreeCardWidth:188,submoduleCardWidth:164,minWorktreeCardHeight:68,minSubmoduleCardHeight:56,maxEstimatedCardHeight:120,layerGap:160,nodeGap:52,edgeLabelBuffer:120},_0={maxWidth:180},L0="RIGHT",ui={"elk.algorithm":"layered","elk.direction":L0,"elk.edgeRouting":"ORTHOGONAL","elk.spacing.nodeNode":String(xs.nodeGap),"elk.layered.spacing.nodeNodeBetweenLayers":String(xs.layerGap),"elk.layered.spacing.edgeNodeBetweenLayers":String(xs.edgeLabelBuffer),"elk.layered.layering.strategy":"NETWORK_SIMPLEX","elk.layered.nodePlacement.strategy":"NETWORK_SIMPLEX","elk.layered.crossingMinimization.strategy":"LAYER_SWEEP","elk.layered.considerModelOrder.strategy":"NODES_AND_EDGES","elk.layered.cycleBreaking.strategy":"GREEDY","elk.layered.mergeEdges":"false","elk.randomSeed":"1"},P0={...ui,"elk.spacing.nodeNode":String(Rs.nodeGap),"elk.layered.spacing.nodeNodeBetweenLayers":String(Rs.layerGap),"elk.layered.spacing.edgeNodeBetweenLayers":String(Rs.edgeLabelBuffer)},R0=new wm;function mn(e,t,r){const n=(e||"").trim();return n?Math.max(1,Math.min(r,Math.ceil(n.length/t))):0}const D0=6.2,E0=20;function $0(e){return Math.ceil(e.length*D0)+E0}function B0(e,t){const r=t-32,n=[];n.push(e.health.replace(/_/g," ")),e.type==="submoduleNode"?n.push("submodule"):n.push(e.locality==="remote"?"remote":"local"),e.branch&&e.type!=="submoduleNode"&&n.push(e.branch),e.submoduleCommit&&e.type==="submoduleNode"&&n.push(e.submoduleCommit.slice(0,7)),e.dirty&&n.push(e.type==="submoduleNode"?"local changes":`${e.dirtyFiles} dirty`),e.outOfSync&&n.push("out of sync"),e.hasConflicts&&n.push("conflicts"),e.type!=="submoduleNode"&&e.upstream&&e.upstreamStatus!=="fresh"&&n.push("upstream unverified"),e.isOrphan&&n.push("needs follow-up");let a=0,o=0;for(const i of n){const c=$0(i)+6;o>0&&o+c>r?(a+=1,o=c):o+=c}return o>0&&(a+=1),Math.max(1,a)}function Cr(e,t=!1){const r=t?Rs:xs;return e.type==="submoduleNode"?r.submoduleCardWidth:r.worktreeCardWidth}function Nn(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=wu(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 Su(e,t=!1){const r=t?Rs:xs;if(t){const b=Yn(e),f=e.type==="defaultBranchNode",k=!b&&e.branch&&e.type!=="submoduleNode",y=36+(f?0:14)+(b?24:k?16:0),h=e.type==="submoduleNode"?r.minSubmoduleCardHeight:r.minWorktreeCardHeight;return Math.min(r.maxEstimatedCardHeight,Math.max(h,Math.ceil(y)))}const n=Cr(e),a=e.type==="submoduleNode"?24:30,o=B0(e,n),i=mn(e.label,a,2),c=mn(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,a,2),d=mn(Nn(e),a+4,3),m=Yn(e),u=ju(e)?di(e):null,p=mn(u,Math.max(24,Math.floor(n/8)),4),x=52+i*18+c*14+(m?30:0)+o*24+Math.max(22,d*18)+(p>0?22+p*16:0),w=e.type==="submoduleNode"?r.minSubmoduleCardHeight:r.minWorktreeCardHeight;return Math.min(r.maxEstimatedCardHeight,Math.max(w,Math.ceil(x)))}function O0(e,t){return e.type==="defaultBranchNode"&&t.type!=="defaultBranchNode"?-1:t.type==="defaultBranchNode"&&e.type!=="defaultBranchNode"||e.type==="submoduleNode"&&t.type!=="submoduleNode"?1:t.type==="submoduleNode"&&e.type!=="submoduleNode"?-1:e.branch&&t.branch&&e.branch!==t.branch?e.branch.localeCompare(t.branch):e.branch&&!t.branch?-1:!e.branch&&t.branch?1:e.label.localeCompare(t.label)||e.id.localeCompare(t.id)}function F0(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function H0(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 W0(e,t,r){return{id:e.id,x:t,y:r,width:Cr(e),height:Su(e)}}function K0(e,t){return{id:`${e.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:t.repoIdentity,branch:e.branch,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:null,locality:"unknown",health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],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 Nu(e){const t=[...e.nodes].sort(O0),r=t.find(a=>a.type==="defaultBranchNode")??null,n=t.some(a=>a.id!==(r==null?void 0:r.id)&&a.type!=="submoduleNode");return!r||n?t:[...t,K0(r,e)]}function U0(e,t=ui,r=!1){const n=Nu(e),a=new Set(n.map(c=>c.id)),o=n.map(c=>({id:c.id,width:Cr(c,r),height:Su(c,r)})),i=e.edges.filter(c=>a.has(c.source)&&a.has(c.target)).sort(F0).map(c=>({id:c.id,sources:[c.source],targets:[c.target]}));return{id:`${e.meshId||"mesh"}__elk_root`,layoutOptions:{...t},children:o,edges:i}}function z0(e,t=!1){const r=[...new Set(e.map(a=>Math.round(a.x)))].sort((a,o)=>a-o),n=t?Rs.layerGap:xs.layerGap;return r.length<2?n:Math.min(...r.slice(1).map((a,o)=>a-r[o]))}async function G0(e,t=!1){const r=t?P0:ui,n=Nu(e),a=new Map(n.map(m=>[m.id,m])),i=((await R0.layout(U0(e,r,t))).children??[]).map(m=>{const u=a.get(m.id);return u?H0(u,Math.round(m.x??0),Math.round(m.y??xs.placeholderTopOffset),!m.id.endsWith("__placeholder")):null}).filter(Boolean),c=new Map(n.map((m,u)=>[m.id,u]));i.sort((m,u)=>(c.get(m.id)??0)-(c.get(u.id)??0));const d=i.map(m=>W0(m.graphNode,m.position.x,m.position.y));return{nodes:i,bounds:d,columnGap:z0(d,t),layoutOptions:{...r}}}function V0(e){var t,r;return[e.id,e.type,e.label,e.branch??"",e.upstream??"",e.upstreamStatus??"",e.daemonId??"",e.machineId??"",e.machineLabel??"",e.locality,e.health,e.ahead,e.behind,e.dirty?1:0,e.dirtyFiles,e.hasConflicts?1:0,e.activeSessionCount,e.isOrphan?1:0,e.outOfSync?1:0,e.snapshotCompleteness,((t=e.branchConvergence)==null?void 0:t.status)??"",(r=e.branchConvergence)!=null&&r.needsConvergence?1:0,e.nextStepHint??"",e.error??"",e.parentNodeId??"",e.submodulePath??"",e.submoduleCommit??""].join("|")}function Cu(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function q0(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(V0),...e.edges.map(Cu)].join("::")}function Y0(e){return[e.meshId,e.nodes.length,e.edges.length,...e.nodes.map(t=>{var r,n;return[t.id,t.type,t.label,t.branch??"",t.machineLabel??"",t.locality,t.health,t.dirty?1:0,t.dirtyFiles,t.hasConflicts?1:0,t.activeSessionCount,t.isOrphan?1:0,t.outOfSync?1:0,t.snapshotCompleteness,((r=t.branchConvergence)==null?void 0:r.status)??"",(n=t.branchConvergence)!=null&&n.needsConvergence?1:0,t.nextStepHint??"",t.parentNodeId??"",t.submodulePath??"",t.submoduleCommit??""].join("|")}),...e.edges.map(Cu)].join("::")}const X0=7,mi=l.createContext(zs("dark")),Mu=l.createContext(!1),Iu={overflowWrap:"anywhere",wordBreak:"break-word"},J0={...Iu,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},Q0={...Iu,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function Tu(e){return e.activeSessionCount>0}function Z0(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function Hl(e,t,r){const n=Tu(e),a=Z0(e);let o;t?o="border-cyan-400/70 shadow-[0_0_0_1px_rgba(34,211,238,0.35),0_24px_60px_rgba(8,145,178,0.18)]":n?o=r?"border-emerald-400/40 shadow-[0_0_0_1px_rgba(52,211,153,0.18),0_18px_48px_rgba(3,7,18,0.22)]":"border-emerald-400/60 shadow-[0_0_0_1px_rgba(52,211,153,0.2),0_18px_48px_rgba(148,163,184,0.20)]":a?o=r?"border-white/6 shadow-[0_12px_32px_rgba(3,7,18,0.16)] opacity-60":"border-slate-200/70 shadow-[0_12px_32px_rgba(148,163,184,0.14)] opacity-60":o=r?"border-white/10 shadow-[0_18px_48px_rgba(3,7,18,0.22)]":"border-slate-300/90 shadow-[0_18px_48px_rgba(148,163,184,0.20)]";const i=Yn(e);if((i==null?void 0:i.tone)==="danger")return`${o} ${r?"bg-rose-500/12":"bg-rose-50/95"}`;if((i==null?void 0:i.tone)==="warn")return`${o} ${r?"bg-amber-500/10":"bg-amber-50/95"}`;if((i==null?void 0:i.tone)==="info")return`${o} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;switch(e.health){case"online":return`${o} ${r?n?"bg-emerald-500/10":"bg-emerald-500/8":n?"bg-emerald-50":"bg-emerald-50/95"}`;case"dirty":return`${o} ${r?"bg-amber-500/8":"bg-amber-50/95"}`;case"degraded":return`${o} ${r?"bg-rose-500/10":"bg-rose-50/95"}`;case"wrong_branch":return`${o} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;case"offline":return`${o} ${r?"bg-slate-500/10":"bg-slate-100/90"}`;default:return`${o} ${r?"bg-slate-950/78":"bg-white/96"}`}}function Pt(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 Wl(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 Kl(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 ev(e){return e.replace(/_/g," ")}function Oa(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function tv(e){return e.locality==="remote"?"meta":"health"}function sv({data:e,selected:t}){const r=l.useContext(mi),n=l.useContext(Mu),a=e.graphNode,o=a.type==="defaultBranchNode",i=a.type==="submoduleNode",c=ju(a),d=o?"default branch anchor":i?a.submodulePath||"submodule checkout":[a.machineLabel,Oa(a.locality)].filter(Boolean).join(" · ")||a.workspace,m=a.submoduleCommit?a.submoduleCommit.slice(0,7):null,u=Yn(a),p=di(a),x=Tu(a);return n?s.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${Hl(a,t,r.isDark)}`,style:{width:Cr(a,!0)},title:[a.label,a.branch?`Branch: ${a.branch}`:null,a.machineLabel?`Machine: ${a.machineLabel}`:null,a.workspace?`Workspace: ${a.workspace}`:null,u?`Status: ${u.label}`:null,Nn(a)].filter(Boolean).join(`
66
+ `),children:[s.jsx(Vr,{type:"target",position:qr.Left,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-xs font-semibold leading-4 ${r.textPrimary}`,children:a.label}),!o&&s.jsx("div",{className:`truncate text-[10px] leading-3.5 ${r.textMuted}`,children:d})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[x&&s.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${r.isDark?"bg-emerald-400":"bg-emerald-500"} animate-pulse`,"aria-label":"active session"}),s.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full",style:{backgroundColor:Kl(a.health)},"aria-hidden":!0})]})]}),u&&s.jsx("div",{className:`mt-1.5 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[9px] font-semibold uppercase tracking-[0.14em] ${Wl(u.tone,r.isDark)}`,title:u.label,children:s.jsx("span",{className:"truncate",children:u.label})}),!u&&a.branch&&!i&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[10px] ${Pt("meta",r.isDark)} rounded-full border px-2 py-0.5 inline-block`,title:a.branch,children:a.branch}),s.jsx(Vr,{type:"source",position:qr.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]}):s.jsxs("div",{className:`rounded-2xl border px-4 py-3.5 backdrop-blur-sm transition-all ${Hl(a,t,r.isDark)}`,style:{width:Cr(a)},title:[a.machineLabel?`Machine: ${a.machineLabel}`:null,a.machineId?`Machine id: ${a.machineId}`:null,a.daemonId?`Daemon: ${a.daemonId}`:null,`Locality: ${Oa(a.locality)}`,a.workspace?`Workspace: ${a.workspace}`:null].filter(Boolean).join(`
67
+ `),children:[s.jsx(Vr,{type:"target",position:qr.Left,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${r.textPrimary}`,children:a.label}),s.jsx("div",{className:`truncate text-[11px] ${r.textMuted}`,children:d})]}),s.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 shrink-0",children:[x&&s.jsx("span",{className:`h-2 w-2 rounded-full ${r.isDark?"bg-emerald-400":"bg-emerald-500"} animate-pulse`,"aria-label":"active session"}),s.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:Kl(a.health)},"aria-hidden":!0})]})]}),u&&s.jsx("div",{className:`mt-3 inline-flex min-w-0 max-w-full items-center rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] ${Wl(u.tone,r.isDark)}`,title:u.label,children:s.jsx("span",{className:"truncate",children:u.label})}),s.jsxs("div",{className:"mt-3 flex min-w-0 flex-wrap gap-1.5 text-[10px]",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${Pt("health",r.isDark)}`,children:ev(a.health)}),i&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Pt("submodule",r.isDark)}`,children:"submodule"}),!o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Pt(tv(a),r.isDark)}`,children:Oa(a.locality)}),a.branch&&!i&&s.jsx("span",{className:`min-w-0 max-w-full rounded-full border px-2 py-0.5 ${Pt("meta",r.isDark)}`,title:a.branch,children:s.jsx("span",{className:"block truncate",children:a.branch})}),m&&i&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Pt("meta",r.isDark)}`,children:m}),a.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Pt("dirty",r.isDark)}`,children:i?"local changes":`${a.dirtyFiles} dirty`}),a.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Pt("conflict",r.isDark)}`,children:"out of sync"}),a.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Pt("conflict",r.isDark)}`,children:"conflicts"}),!i&&a.upstream&&a.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Pt("orphan",r.isDark)}`,children:"upstream unverified"}),a.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Pt("orphan",r.isDark)}`,children:"needs follow-up"})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,style:J0,title:Nn(a),children:Nn(a)}),c&&p&&s.jsx("div",{className:`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${r.isDark?"border-cyan-400/15 bg-cyan-500/8 text-cyan-50/90":"border-sky-300 bg-sky-50 text-sky-700"}`,style:Q0,title:p,children:p}),s.jsx(Vr,{type:"source",position:qr.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const rv={meshNode:sv};function nv(e){const t={sourceX:e.sourceX,sourceY:e.sourceY,sourcePosition:e.sourcePosition,targetX:e.targetX,targetY:e.targetY,targetPosition:e.targetPosition},r=e.data.graphEdge;return r.type==="parentBranch"?Lm(t):r.type==="worktreeLink"||r.type==="submoduleLink"||r.type==="cloneLink"?Pm(t):Rm(t)}function av(e,t){const r="nodrag nopan rounded-md border px-2 py-1 text-[10px] font-semibold shadow-sm backdrop-blur-sm";switch(e.type){case"orphanLink":return t?`${r} border-orange-400/35 bg-orange-500/14 text-orange-100`:`${r} border-orange-300 bg-orange-50 text-orange-700`;case"submoduleLink":return t?`${r} border-violet-400/30 bg-violet-500/14 text-violet-100`:`${r} border-violet-300 bg-violet-50 text-violet-700`;case"sessionLink":return t?`${r} border-emerald-400/30 bg-emerald-500/14 text-emerald-100`:`${r} border-emerald-300 bg-emerald-50 text-emerald-700`;case"cloneLink":return t?`${r} border-teal-400/30 bg-teal-500/14 text-teal-100`:`${r} border-teal-300 bg-teal-50 text-teal-700`;default:return t?`${r} border-sky-400/25 bg-slate-950/78 text-sky-100`:`${r} border-sky-300 bg-white/95 text-sky-700`}}function ov(e){const t=l.useContext(mi),r=e.data.graphEdge,[n,a,o]=nv(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(Im,{id:e.id,path:n,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(Tm,{children:s.jsx("div",{className:av(r,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${a}px, ${o}px)`,pointerEvents:"none",maxWidth:_0.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const iv={meshEdge:ov};async function lv(e,t=zs("dark"),r=!1){const n=await G0(e,r),a=new Set(n.nodes.map(c=>c.id)),o=n.nodes.map(c=>({id:c.id,type:c.type,position:c.position,data:{graphNode:c.graphNode,compact:r},selected:c.selected,draggable:c.draggable,selectable:c.selectable})),i=e.edges.filter(c=>a.has(c.source)&&a.has(c.target)).map(c=>({id:c.id,source:c.source,target:c.target,label:c.label,type:"meshEdge",data:{graphEdge:c},animated:c.type==="orphanLink",markerEnd:c.direction==="directed"?{type:Mm.ArrowClosed,width:c.type==="submoduleLink"?16:18,height:c.type==="submoduleLink"?16:18,color:Ul(c)}:void 0,style:{stroke:Ul(c),strokeWidth:c.type==="orphanLink"?2.25:c.type==="submoduleLink"?1.7:c.type==="worktreeLink"?1.8:c.type==="cloneLink"?1.6:2,strokeDasharray:c.type==="orphanLink"?"5 4":c.type==="submoduleLink"?"4 3":c.type==="cloneLink"?"6 3":void 0},labelStyle:{fill:t.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:t.edgeLabelBackgroundColor,fillOpacity:1,stroke:t.edgeLabelBorderColor},labelBgPadding:[6,4],labelBgBorderRadius:7}));return{nodes:o,edges:i}}function Ul(e){switch(e.type){case"parentBranch":return"#38bdf8";case"worktreeLink":return"#a78bfa";case"sessionLink":return"#34d399";case"orphanLink":return"#f97316";case"submoduleLink":return"#c084fc";case"cloneLink":return"#2dd4bf";default:return"#64748b"}}function cv(e){const t=e.data.graphNode;if(t.locality==="local")return"#38bdf8";switch(t.health){case"online":return"#34d399";case"dirty":return"#fbbf24";case"degraded":case"offline":return"#fb7185";case"wrong_branch":return"#a78bfa";default:return"#94a3b8"}}function dv(e){const t=e.data.graphNode;return["mesh-minimap-node",`mesh-minimap-node--${t.type}`,`mesh-minimap-node--${t.health}`,t.isOrphan?"mesh-minimap-node--attention":null,t.dirty?"mesh-minimap-node--dirty":null,t.outOfSync?"mesh-minimap-node--out-of-sync":null].filter(Boolean).join(" ")}function uv({data:e,viewportKey:t}){const r=Am(),n=_m(),a=l.useRef(null),o=l.useMemo(()=>ku(e),[e]),i=l.useMemo(()=>N0(e),[e]);return l.useEffect(()=>{if(!r||e.nodes.length===0||a.current===t)return;let c=!1;const d=requestAnimationFrame(()=>{if(c)return;const m=i.length>0&&i.length<e.nodes.length;n.fitView({nodes:m?i.map(u=>({id:u})):void 0,padding:m?.24:.2,maxZoom:m?.98:.9,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(d)}},[e.nodes.length,i,o,r,n,t]),null}function mv(e){return e>=16?"h-[720px] min-h-[720px] sm:h-[860px] xl:h-[980px]":e>=10?"h-[580px] min-h-[580px] sm:h-[700px] xl:h-[820px]":"h-[460px] min-h-[460px] sm:h-[560px] xl:h-[680px]"}function hv({data:e,selectedNodeId:t=null,onNodeClick:r}){const{theme:n}=Us(),a=l.useMemo(()=>zs(n),[n]),o=l.useMemo(()=>q0(e),[e]),i=l.useMemo(()=>Y0(e),[e]),c=e.nodes.length>=X0,[d,m]=l.useState({nodes:[],edges:[]}),u=l.useRef(null),[p,x]=l.useState({width:0,height:0}),w=l.useMemo(()=>C0(e,p.width,p.height),[o,e,p.height,p.width]);l.useEffect(()=>{let k=!1;return lv(e,a,c).then(y=>{k||m(y)}),()=>{k=!0}},[e,i,a,c]);const b=l.useMemo(()=>d.nodes.map(k=>({...k,selected:k.id===t})),[d.nodes,t]);l.useEffect(()=>{const k=u.current;if(!k)return;const y=()=>{const j=Math.max(0,Math.round(k.clientWidth)),v=Math.max(0,Math.round(k.clientHeight));x(g=>g.width===j&&g.height===v?g:{width:j,height:v})};y();const h=typeof ResizeObserver=="function"?new ResizeObserver(()=>y()):null;return h==null||h.observe(k),window.addEventListener("resize",y),()=>{h==null||h.disconnect(),window.removeEventListener("resize",y)}},[]);const f=mv(e.nodes.length);return s.jsx(mi.Provider,{value:a,children:s.jsx(Mu.Provider,{value:c,children:s.jsxs("div",{ref:u,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"]}),e.stats.totalActiveSessions>0&&s.jsxs("span",{className:a.isDark?"rounded-full border border-emerald-400/25 bg-emerald-500/12 px-3 py-1 text-emerald-100":"rounded-full border border-emerald-300 bg-emerald-50 px-3 py-1 text-emerald-700",children:[e.stats.totalActiveSessions," active session",e.stats.totalActiveSessions===1?"":"s"]}),e.stats.orphanNodes>0&&s.jsxs("span",{className: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"]}),c&&s.jsx("span",{className:a.isDark?"rounded-full border border-white/8 bg-white/[0.03] px-3 py-1 text-slate-400":"rounded-full border border-slate-200 bg-slate-50/80 px-3 py-1 text-slate-500",children:"dense view · hover for details"})]}),s.jsx("div",{className:a.graphHintChipClass,children:c?"drag or scroll to pan":"Focused on the main path first · drag or scroll to pan"})]}),s.jsx("div",{className:`w-full min-w-0 ${f}`,children:s.jsxs(jm,{nodes:b,edges:d.edges,nodeTypes:rv,edgeTypes:iv,minZoom:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(k,y)=>r==null?void 0:r(y.data.graphNode),className:"h-full w-full",colorMode:a.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(uv,{data:e,viewportKey:w}),s.jsx(km,{className:a.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),s.jsx(Sm,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:cv,nodeClassName:dv,nodeStrokeWidth:3,className:a.isDark?"overflow-hidden rounded-xl border border-white/10 bg-slate-950/85":"overflow-hidden rounded-xl border border-slate-200 bg-white/95"}),s.jsx(Nm,{variant:Cm.Dots,gap:18,size:1.2,color:a.graphBackgroundDotColor})]})})]})})})}function ot(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function _e(...e){for(const t of e){if(typeof t!="string")continue;const r=t.trim();if(r)return r}}function Nt(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function At(...e){for(const t of e)if(typeof t=="boolean")return t}function Fa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function hi(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 pv(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 fv(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=ot(n),o=_e(a.path),i=_e(a.commit),c=_e(a.repoPath,a.repo_root)??pv(t,o);return!o||!i||!c?null:{path:o,commit:i,repoPath:c,dirty:At(a.dirty)??!1,outOfSync:At(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:Nt(a.lastCheckedAt,a.last_checked_at)??Date.now(),..._e(a.error)?{error:_e(a.error)}:{}}}).filter(n=>n!==null);return r.length>0?r:void 0}function xv(e){return At(e.isGitRepo)!==void 0||!!_e(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||Nt(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 Cn(e,t,r){const n=At(e.isGitRepo);if(!Object.keys(e).length||!xv(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(b=>typeof b=="string"):[],i=Nt(e.conflicts)??o.length,c=At(e.hasConflicts)??i>0,d=_e(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,m=fv(e.submodules,d),u=_e(e.upstreamStatus,e.upstream_status),p=Nt(e.upstreamFetchedAt,e.upstream_fetched_at),x=_e(e.upstreamFetchError,e.upstream_fetch_error),w=_e(e.error);return{workspace:_e(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:a,branch:_e(e.branch)??null,headCommit:_e(e.headCommit)??null,headMessage:_e(e.headMessage)??null,upstream:_e(e.upstream)??null,upstreamStatus:u??"unchecked",...p!==void 0?{upstreamFetchedAt:p}:{},...x?{upstreamFetchError:x}:{},ahead:Nt(e.ahead)??0,behind:Nt(e.behind)??0,staged:Nt(e.staged)??0,modified:Nt(e.modified)??0,untracked:Nt(e.untracked)??0,deleted:Nt(e.deleted)??0,renamed:Nt(e.renamed)??0,hasConflicts:c,conflictFiles:o,stashCount:Nt(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??Nt(e.lastCheckedAt,e.last_checked_at)??Date.now(),...m?{submodules:m}:{},...w?{error:w}:{}}}function bv(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+=hi(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 gv(e){const t=ot(e.lastGit??e.last_git),r=ot(t.result),n=ot(t.status),a=ot(r.status),o=ot(e.lastProbe??e.last_probe),i=ot(o.git),c=ot(i.result),d=ot(i.status),m=ot(c.status);let u=null;for(const p of[n,a,d,m]){const x=Cn(p,e,{lastCheckedAt:Date.now()});if(!x)continue;const w=bv(x);(!u||w>u.score)&&(u={git:x,score:w})}return u==null?void 0:u.git}function yv(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 vv(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 Xn(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=yv(e);return t.outOfSync?"degraded":t.dirty||vv(e)?"dirty":"online"}function wv(e,t){const r=t?Xn(t):void 0;return!e||e==="unknown"?r:e}function jv(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 i=ot(o),c=_e(i.sessionId,i.session_id,i.id);return c?{sessionId:c,..._e(i.providerType,i.provider)?{providerType:_e(i.providerType,i.provider)}:{},..._e(i.state,i.status)?{state:_e(i.state,i.status)}:{},..._e(i.lifecycle)?{lifecycle:_e(i.lifecycle)}:{},..._e(i.surfaceKind,i.surface_kind)?{surfaceKind:_e(i.surfaceKind,i.surface_kind)}:{},..._e(i.recoveryState,i.recovery_state)?{recoveryState:_e(i.recoveryState,i.recovery_state)}:{},..._e(i.workspace)?{workspace:_e(i.workspace)}:{},..._e(i.title)?{title:_e(i.title)}:{},..._e(i.lastActivityAt,i.last_activity_at)?{lastActivityAt:_e(i.lastActivityAt,i.last_activity_at)}:{},...At(i.isCached,i.is_cached)!==void 0?{isCached:At(i.isCached,i.is_cached)}:{}}:null}).filter(o=>o!==null);if(a.length>0)return a}const r=ot(e.activeSession??e.active_session),n=_e(r.id,r.sessionId,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id);if(n)return[{sessionId:n,..._e(r.providerType,r.provider)?{providerType:_e(r.providerType,r.provider)}:{},..._e(r.state,r.status)?{state:_e(r.state,r.status)}:{}}]}function kv(e){const t=ot(e.connection);return Object.keys(t).length>0?t:void 0}function Sv(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 pi(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 zl(e){var n,a,o,i,c,d;let t=0;const r=e.git;return pi(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+=hi(r==null?void 0:r.upstreamStatus),typeof(r==null?void 0:r.lastCheckedAt)=="number"&&(t+=6),t+=(((n=r==null?void 0:r.submodules)==null?void 0:n.length)??0)*6),(a=e.branchConvergence)!=null&&a.status&&(t+=12),(((o=e.connection)==null?void 0:o.state)==="connected"||((i=e.connection)==null?void 0:i.state)==="self")&&(t+=8),((c=e.connection)==null?void 0:c.transport)==="direct"&&(t+=4),((d=e.connection)==null?void 0:d.source)==="mesh_peer_status"&&(t+=4),e.health==="online"&&(t+=4),e.health==="dirty"&&(t+=3),e.health==="degraded"&&(t+=2),e.launchReady&&(t+=2),e.gitProbePending&&(t-=40),e.error&&(t-=10),t}function Nv(e,t){var b,f,k,y;const r=zl(e),a=zl(t)>r?t:e,o=a===t?e:t,i=a.git??o.git,c=(((b=a.providers)==null?void 0:b.length)??0)>0?a.providers:o.providers,d=(((f=a.activeSessions)==null?void 0:f.length)??0)>0?a.activeSessions:o.activeSessions,m=(((k=a.activeSessionDetails)==null?void 0:k.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:i&&(!a.health||a.health==="unknown")?Xn(i):a.health,providers:c??[],activeSessions:d??[],...m&&m.length>0?{activeSessionDetails:m}:{},...u&&u.length>0?{providerPriority:u}:{},...p?{connection:p}:{},...i?{git:i}:{}},w=ot(a.branchConvergence);return Object.keys(w).length>0?Object.assign(x,{branchConvergence:w}):delete x.branchConvergence,i&&(delete x.gitProbePending,delete x.error),x}function Cv(e){const t=ot(e),r=_e(t.nodeId,t.id);if(!r)return null;const n=ot(t.cachedStatus),a=gv(t),o=a?void 0:Cn(ot(t.git),t)??Cn(t,t),i=a??o,c=i?void 0:Cn(ot(n.git),t),d=i??c,m=_e(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),u=_e(t.health),p=a?Xn(d):wv(u,i)||(d?Xn(d):void 0)||_e(n.health)||m||_e(t.status)||"unknown",w=(a?void 0:_e(t.error))??(i?void 0:_e(n.error)),b=jv(t),f=Fa(t.activeSessions),k=(b==null?void 0:b.map(C=>C.sessionId))??[],y=Fa(t.providerPriority),h=At(t.gitProbePending,t.git_probe_pending),j=i?void 0:h,v=kv(t),g=ot(t.branchConvergence??t.branch_convergence),S=v==null?void 0:v.state,M=a&&(!(v!=null&&v.reported)||S==="unknown")?Sv(v):v;return{nodeId:r,machineLabel:_e(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:_e(t.workspace,d==null?void 0:d.workspace)||"",..._e(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:_e(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},..._e(t.daemonId,t.daemon_id)?{daemonId:_e(t.daemonId,t.daemon_id)}:{},..._e(t.machineId,t.machine_id)?{machineId:_e(t.machineId,t.machine_id)}:{},...m?{machineStatus:m}:{},...At(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:At(t.isLocalWorktree,t.is_local_worktree)}:{},..._e(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:_e(t.worktreeBranch,t.worktree_branch)}:{},health:p,...d?{git:d}:{},...j!==void 0?{gitProbePending:j}:{},providers:Fa(t.providers),activeSessions:f.length>0?f:k,...b&&b.length>0?{activeSessionDetails:b}:{},...y.length>0?{providerPriority:y}:{},...At(t.launchReady)!==void 0?{launchReady:At(t.launchReady)}:a?{launchReady:!0}:{},..._e(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:_e(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},..._e(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:_e(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...M?{connection:M}:{},...Object.keys(g).length>0?{branchConvergence:g}:{},...w?{error:w}:{}}}function Au(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=Nv(a,n);t.set(n.nodeId,o);const i=r.findIndex(c=>c.nodeId===n.nodeId);i>=0&&(r[i]=o)}return r}function _u(e){return{...e,nodes:Au(e.nodes??[])}}function Mv(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:pi(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 Iv(e){const t=_e(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(d=>Cv(d)).filter(d=>d!==null):null;if(!t||!n)return null;const a=Au(n),o=_e(e.meshName,e.mesh_name,e.name),i=_e(e.repoIdentity,e.repo_identity),c=_e(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!o||!i||!c?null:{...e,meshId:t,meshName:o,repoIdentity:i,refreshedAt:c,nodes:a}}function Tv(e){var o;let t=0;const r=ot(e.sourceOfTruth),n=ot(r.directPeerTruth);_e(r.currentStatus)==="live_git_and_session_probes"&&(t+=100),r.coordinatorOwnsLiveTruth===!0&&(t+=25),n.satisfied===!0&&(t+=15);for(const i of e.nodes){const c=i.git;if(!c){i.gitProbePending&&(t-=8);continue}t+=10,c.isGitRepo===!0&&(t+=5),c.isGitRepo===!1&&(t+=1),c.branch&&(t+=4),c.upstream&&(t+=3),c.headCommit&&(t+=3),t+=hi(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 Gl(e){let t=null;for(const r of e){const n=Iv(ot(r));if(!n)continue;const a=Tv(n);(!t||a>t.score)&&(t={status:n,score:a})}return(t==null?void 0:t.status)??null}function Lu(e){const r=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,n=Gl([r==null?void 0:r.status,r]);return n||Gl([e==null?void 0:e.status,e])}const Av=5*60*1e3;function Pu(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function Ru(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function _v(e){var t,r,n;return((t=e.connection)==null?void 0:t.state)==="self"||e.isLocalWorktree===!0?"local":((r=e.connection)==null?void 0:r.transport)==="direct"||((n=e.connection)==null?void 0:n.transport)==="relay"||Pu(e)||Ru(e)?"remote":"unknown"}function Lv(e){return pi(e)}function Du(e){var t;return Lv(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function Pv(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function Eu(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function $u(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function fi(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function Rv(e){return fi(e)?"degraded":$u(e)?"dirty":"online"}function Dv(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function Vl(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 Ha(e){return e.length===0?"unknown":e.reduce((t,r)=>Vl(r)>Vl(t)?r:t)}function Ev(e){var o,i,c,d,m;const t=new Map,r=new Map;for(const u of e){const p=(i=(o=u.git)==null?void 0:o.branch)==null?void 0:i.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]),b=x.indexOf(p[0]);return w!==-1||b!==-1?w===-1?1:b===-1?-1:w-b: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 $v(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 ql(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 Bv(e){return e.reduce((t,r)=>ql(r.status)>ql(t.status)?r:t)}function Ov(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 Fv(e){var a,o,i;const t=e.sourceOfTruth,r=[],n=(a=t==null?void 0:t.fallback)==null?void 0:a.warning;return typeof n=="string"&&n.trim()&&r.push(n.trim()),(t==null?void 0:t.currentStatus)==="bootstrap_inventory_fallback"&&((o=t.directPeerTruth)==null?void 0:o.required)===!0&&((i=t.directPeerTruth)==null?void 0:i.satisfied)!==!0&&!r.some(c=>c.includes("direct mesh truth"))&&r.push("Direct mesh truth is not confirmed yet; this graph is drawn from setup inventory only."),r}function Hv(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 Wv(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 Kv(e,t){if(Du(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=Eu(a)||$u(a),i=!!(a!=null&&a.hasConflicts)||fi(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??i}}function Uv(e,t){const r=Kv(e,t);return r?{...r,defaultBranch:r.defaultBranch??t}:null}function zv(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function Gv(e){var d,m,u;const{nodeStatus:t,expectedSubmodulePaths:r,refreshedAtMs:n}=e,a=[],o=t.machineLabel||t.nodeId,i=t.git;if(!i){if(Du(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((i.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 i.lastCheckedAt=="number"&&n-i.lastCheckedAt>Av&&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 Vv(e){var H;const t=_u(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??Ev(t.nodes),a=Pv(t.refreshedAt),o=new Set(t.nodes.flatMap(R=>{var F;return(((F=R.git)==null?void 0:F.submodules)??[]).map(A=>A.path)})),i=[],c=[],d=Fv(t),m=new Map;for(const R of t.nodes){const F=R.git,A=(F==null?void 0:F.branch)??null,I=Rv(F),$=Eu(F)||I==="dirty",E=$v(R,n),L=Uv(R,n),U=Gv({nodeStatus:R,expectedSubmodulePaths:o,refreshedAtMs:a}),B=typeof R.clonedFromNodeId=="string"?R.clonedFromNodeId:null,K={id:R.nodeId,type:E.length>0?"orphanNode":"worktreeNode",label:R.machineLabel||R.nodeId.slice(0,8),workspace:R.workspace,branch:A,upstream:(F==null?void 0:F.upstream)??null,upstreamStatus:(F==null?void 0:F.upstreamStatus)??null,daemonId:Pu(R),machineId:Ru(R),machineLabel:R.machineLabel||null,locality:_v(R),health:Ha([R.health,I]),ahead:(F==null?void 0:F.ahead)??0,behind:(F==null?void 0:F.behind)??0,dirty:$,dirtyFiles:Dv(F),hasConflicts:(F==null?void 0:F.hasConflicts)??!1,activeSessionCount:((H=R.activeSessions)==null?void 0:H.length)??0,activeSessions:R.activeSessions??[],providers:R.providers??[],isOrphan:E.length>0,orphanReasons:E,error:R.error,nextStepHint:U.snapshotWarnings[0]??E[0]??(L==null?void 0:L.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:B,worktreeBranch:R.worktreeBranch??null,submodulePath:null,submoduleCommit:(F==null?void 0:F.headCommit)??null,outOfSync:fi(F),snapshotCompleteness:U.snapshotCompleteness,snapshotWarnings:U.snapshotWarnings,branchConvergence:L,source:R};if(i.push(K),A){const J=m.get(A)??[];J.push(K.id),m.set(A,J)}for(const J of(F==null?void 0:F.submodules)??[]){const X=`${K.id}::submodule::${J.path}`,ae=J.path.split("/").filter(Boolean).pop()||J.path;i.push({id:X,type:"submoduleNode",label:ae,workspace:J.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:K.daemonId,machineId:K.machineId,machineLabel:K.machineLabel,locality:K.locality,health:zv(J),ahead:0,behind:0,dirty:J.dirty,dirtyFiles:J.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],error:J.error,nextStepHint:J.error||(J.outOfSync?`${J.path} is out of sync with the parent checkout`:J.dirty?`${J.path} has local changes`:`${J.path} is in sync with the parent checkout`),parentNodeId:K.id,submodulePath:J.path,submoduleCommit:J.commit,outOfSync:J.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:K.id,parentWorkspace:R.workspace,submodule:J}}),c.push({id:`${K.id}--${X}`,source:K.id,target:X,type:"submoduleLink",label:J.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const u=n?`__branch_${n}`:null;if(u&&n){const F=(m.get(n)??[]).map(B=>i.find(K=>K.id===B)).filter(Boolean),A=F.map(B=>B.branchConvergence).filter(Boolean),I=Ov(t),$=F.length>0&&F.every(B=>Hv(B,n)),E=(I==null?void 0:I.length)===0&&$?Wv(n,F):A.length>0?Bv(A):null,L=(I==null?void 0:I.length)===0&&$?0:A.filter(B=>B.needsConvergence).length,U={id:u,type:"defaultBranchNode",label:n,workspace:t.repoIdentity,branch:n,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:"default branch",locality:"unknown",health:Ha(F.map(B=>B.health)),ahead:0,behind:0,dirty:F.some(B=>B.dirty),dirtyFiles:F.reduce((B,K)=>B+K.dirtyFiles,0),hasConflicts:F.some(B=>B.hasConflicts),activeSessionCount:F.reduce((B,K)=>B+K.activeSessionCount,0),activeSessions:F.flatMap(B=>B.activeSessions),providers:[...new Set(F.flatMap(B=>B.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:L>0?`${L} workspace(s) on ${n} still need follow-up`:F.length>0?`${F.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:E,source:{nodeId:u,machineLabel:n,workspace:t.repoIdentity,health:Ha(F.map(B=>B.health)),providers:[],activeSessions:[]}};i.push(U);for(const B of i)if(!(B.id===u||B.type==="submoduleNode")){if(B.branch===n){c.push({id:`${u}--${B.id}`,source:u,target:B.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(B.branch){c.push({id:`${u}--${B.id}`,source:u,target:B.id,type:B.isOrphan?"orphanLink":"parentBranch",label:B.branch,direction:"undirected"});continue}B.isOrphan&&c.push({id:`${u}--${B.id}`,source:u,target:B.id,type:"orphanLink",label:"detached",direction:"undirected"})}}for(const[R,F]of m){if(F.length<2)continue;const A=F.map(I=>i.find($=>$.id===I)).filter(Boolean);A.sort((I,$)=>I.label.localeCompare($.label));for(let I=1;I<A.length;I+=1)c.push({id:`wt_${A[I-1].id}--${A[I].id}`,source:A[I-1].id,target:A[I].id,type:"worktreeLink",label:I===1?`${R} peers`:void 0,direction:"undirected"})}const p=new Set(i.map(R=>R.id)),x=new Set;for(const R of i){if(!R.clonedFromNodeId||R.type==="submoduleNode"||!p.has(R.clonedFromNodeId))continue;const F=`clone_${R.clonedFromNodeId}--${R.id}`;if(x.has(F))continue;x.add(F);const A=R.worktreeBranch??R.branch??void 0;c.push({id:F,source:R.clonedFromNodeId,target:R.id,type:"cloneLink",label:A?`cloned · ${A}`:"cloned",direction:"directed"})}const w=i.filter(R=>R.type!=="defaultBranchNode"),b=w.filter(R=>R.isOrphan).length,f=w.filter(R=>R.hasConflicts).length,k=w.filter(R=>R.health==="offline").length,y=w.filter(R=>R.type==="submoduleNode"&&R.outOfSync).length,h=w.filter(R=>{var F;return R.type!=="submoduleNode"&&((F=R.branchConvergence)==null?void 0:F.needsConvergence)}).length,j=w.filter(R=>{var F;return((F=R.branchConvergence)==null?void 0:F.status)==="blocked_review"}).length,v=w.filter(R=>{var F;return((F=R.branchConvergence)==null?void 0:F.status)==="pushed_feature_branch_needs_merge"}).length,g=w.filter(R=>{var F;return((F=R.branchConvergence)==null?void 0:F.status)==="cleanup_candidate"}).length,S=w.filter(R=>{var F;return((F=R.branchConvergence)==null?void 0:F.status)==="not_mergeable"}).length,M=w.filter(R=>R.snapshotWarnings.length>0).length,C=w.filter(R=>R.snapshotCompleteness==="pending_git").length,N=w.filter(R=>R.snapshotCompleteness==="missing_git").length,O=w.filter(R=>R.snapshotCompleteness==="missing_submodule_report").length,_=w.filter(R=>R.snapshotCompleteness==="stale").length,T=[C>0?`${C} node(s) are still waiting for a live peer git snapshot`:null,N>0?`${N} node(s) have no visible peer git snapshot`:null,O>0?`${O} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,_>0?`${_} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return h>0&&d.push(`${h} workspace(s) still need follow-up before the mesh is converged`),b>0&&d.push(`${b} workspace(s) need attention before safe coordination`),j>0&&d.push(`${j} workspace(s) are blocked on branch convergence or upstream sync`),v>0&&d.push(`${v} clean feature branch workspace(s) still need merge follow-up`),g>0&&d.push(`${g} worktree workspace(s) are ready for refine / cleanup`),S>0&&d.push(`${S} workspace(s) have local changes or conflicts blocking convergence`),f>0&&d.push(`${f} workspace(s) report merge conflicts`),k>0&&d.push(`${k} node(s) are currently offline`),y>0&&d.push(`${y} submodule(s) are out of sync with their parent checkout`),d.push(...T),n||d.push("Could not infer a default branch from live mesh status"),{meshId:t.meshId,meshName:t.meshName,repoIdentity:t.repoIdentity,refreshedAt:t.refreshedAt,nodes:i,edges:c,stats:{totalNodes:w.length,onlineNodes:w.filter(R=>R.health==="online").length,dirtyNodes:w.filter(R=>R.dirty).length,orphanNodes:b,errorNodes:w.filter(R=>!!R.error||R.outOfSync).length,offlineNodes:k,followUpNodes:h,blockedReviewNodes:j,mergeReadyNodes:v,cleanupCandidateNodes:g,notMergeableNodes:S,incompleteSnapshotNodes:M,missingGitSnapshotNodes:N,missingSubmoduleSnapshotNodes:O,staleGitSnapshotNodes:_,totalActiveSessions:w.reduce((R,F)=>R+F.activeSessionCount,0)},warnings:d,snapshotWarnings:T}}const qv={recentFailures:0,taskCompleted:0,taskFailed:0,sessionLaunched:0},xi=l.createContext(zs("dark"));function Ge({label:e,tone:t="default"}){const r=l.useContext(xi);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 wt({label:e,value:t}){const r=l.useContext(xi);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 Yv(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 Wa(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 Xv(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 Jv(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 Qv(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 Zv(e){return e.assignedNodeId||e.targetNodeId||null}function Yl(e){return e?e.slice(0,7):null}function ew(e,t){var o,i,c;const r=Yl((o=e==null?void 0:e.git)==null?void 0:o.headCommit),n=((c=(i=e==null?void 0:e.git)==null?void 0:i.headMessage)==null?void 0:c.trim())||"";if(r||n)return[r,n].filter(Boolean).join(" · ");const a=t[0];return a?[Yl(a.commit),a.message].filter(Boolean).join(" · "):null}function tw(e,t){const r=ew(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function sw(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 rw(e){var r,n,a,o,i,c;const t=((r=e.selectedSessionEntry)==null?void 0:r.session.workspace)||((n=e.selectedSessionEntry)==null?void 0:n.workspace)||((o=(a=e.selectedNodeStatus)==null?void 0:a.git)==null?void 0:o.workspace)||((i=e.selectedNodeStatus)==null?void 0:i.workspace)||null;if(t&&e.selectedSessionEntry){const d=((c=e.selectedNodeStatus)==null?void 0:c.daemonId)||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}if(t&&e.selectedNodeStatus){const d=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}return null}function nw(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":Jv(e.connection)}function aw(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 ow(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function iw(e){var t,r,n,a;return[e.meshId,e.refreshedAt,e.nodes.length,((r=(t=e.queue)==null?void 0:t.summary)==null?void 0:r.active)??"",((a=(n=e.ledger)==null?void 0:n.summary)==null?void 0:a.recentFailures)??"",...e.nodes.map(o=>{var i,c,d,m,u,p,x,w,b,f,k,y,h,j,v,g,S,M,C,N,O;return[o.nodeId,o.daemonId??"",o.machineId??"",o.machineLabel,o.machineStatus??"",((i=o.connection)==null?void 0:i.state)??"",((c=o.connection)==null?void 0:c.transport)??"",((d=o.connection)==null?void 0:d.source)??"",o.health,o.gitProbePending?1:0,((m=o.git)==null?void 0:m.branch)??"",((u=o.git)==null?void 0:u.upstream)??"",((p=o.git)==null?void 0:p.upstreamStatus)??"",((x=o.git)==null?void 0:x.ahead)??"",((w=o.git)==null?void 0:w.behind)??"",((b=o.git)==null?void 0:b.headCommit)??"",((f=o.git)==null?void 0:f.staged)??"",((k=o.git)==null?void 0:k.modified)??"",((y=o.git)==null?void 0:y.untracked)??"",((h=o.git)==null?void 0:h.deleted)??"",((j=o.git)==null?void 0:j.renamed)??"",(v=o.git)!=null&&v.hasConflicts?1:0,((g=o.git)==null?void 0:g.lastCheckedAt)??"",((S=o.activeSessions)==null?void 0:S.join(","))??"",((M=o.activeSessionDetails)==null?void 0:M.length)??"",((C=o.providers)==null?void 0:C.join(","))??"",((N=o.providerPriority)==null?void 0:N.join(","))??"",o.error??"",(((O=o.git)==null?void 0:O.submodules)??[]).map(_=>[_.path,_.commit,_.dirty?1:0,_.outOfSync?1:0,_.error??""].join("/")).join(",")].join("|")})].join("::")}function Bu({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null}){var $,E,L,U,B;const{theme:a}=Us(),o=l.useMemo(()=>zs(a),[a]),i=l.useMemo(()=>_u(e),[e]),c=l.useMemo(()=>iw(i),[i]),d=l.useMemo(()=>Vv(i),[c]),[m,u]=l.useState(null),[p,x]=l.useState(null),[w,b]=l.useState({}),f=l.useMemo(()=>new Map(i.nodes.map(K=>[K.nodeId,K])),[i.nodes]),k=l.useMemo(()=>new Map(d.nodes.map(K=>[K.id,K])),[d.nodes]),y=(($=i.queue)==null?void 0:$.summary)??null,h=((E=i.ledger)==null?void 0:E.summary)??qv,j=l.useMemo(()=>Qv(i),[i]),v=l.useMemo(()=>{const K=new Map;for(const J of j){const X=J.session.state||J.session.lifecycle||"unknown";K.set(X,(K.get(X)??0)+1)}return[...K.entries()].sort((J,X)=>X[1]-J[1])},[j]);l.useEffect(()=>{m&&(k.has(m)||(u(null),x(K=>!K||"nodeId"in K&&K.nodeId===m?null:K)))},[k,m]);const g=m?f.get(m)??null:null,S=ow(d,m);l.useEffect(()=>{var K,J,X;if(m)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:i.meshId,selectedNodeId:m,canonicalNode:Mv(g),graphNode:S?{id:S.id,branch:S.branch,upstream:S.upstream,headCommit:S.submoduleCommit,submoduleCount:((J=(K=g==null?void 0:g.git)==null?void 0:K.submodules)==null?void 0:J.length)??0,snapshotCompleteness:S.snapshotCompleteness,snapshotWarnings:S.snapshotWarnings,branchConvergence:((X=S.branchConvergence)==null?void 0:X.status)??null}:null})}catch{}},[i.meshId,S,m,g]);const M=(p==null?void 0:p.kind)==="session"?j.find(K=>K.nodeId===p.nodeId&&K.session.sessionId===p.sessionId)??null:null,C=l.useMemo(()=>j.filter(K=>K.nodeId===m),[m,j]),N=rw({coordinatorDaemonId:r,selectedNodeStatus:g,selectedSessionEntry:M}),O=(N==null?void 0:N.workspace)??null,_=O?w[O]??null:null,T=tw(g,(_==null?void 0:_.entries)??[]),H=l.useCallback(()=>{u(null),x(null)},[]);l.useEffect(()=>{if(!S)return;const K=J=>{J.key==="Escape"&&H()};return window.addEventListener("keydown",K),()=>window.removeEventListener("keydown",K)},[H,S]),l.useEffect(()=>{if(!N||!n)return;const{daemonId:K,workspace:J}=N,X=w[J];if(X!=null&&X.loading||X&&(X.entries.length>0||X.error))return;let ae=!1;return b(de=>{var ke;return{...de,[J]:{loading:!0,error:null,entries:((ke=de[J])==null?void 0:ke.entries)??[]}}}),n(K,"git_log",{workspace:J,limit:5}).then(de=>{ae||b(ke=>({...ke,[J]:{loading:!1,error:null,entries:sw(de)}}))}).catch(de=>{ae||b(ke=>({...ke,[J]:{loading:!1,error:de instanceof Error?de.message:"git_log failed",entries:[]}}))}),()=>{ae=!0}},[w,N,n]);const R=[...d.warnings??[],...i.nodes.filter(K=>K.machineStatus&&K.machineStatus!=="online").map(K=>`${K.machineLabel}: ${K.machineStatus}`)],F=d.stats.incompleteSnapshotNodes>0,A=d.stats.followUpNodes>0?`${d.stats.followUpNodes} need follow-up`:F?"mesh visibility incomplete":"mesh converged",I=d.stats.followUpNodes>0?"danger":F?"warn":"good";return s.jsx(xi.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(Ge,{label:A,tone:I}),d.stats.blockedReviewNodes>0&&s.jsx(Ge,{label:`${d.stats.blockedReviewNodes} blocked review`,tone:"danger"}),d.stats.notMergeableNodes>0&&s.jsx(Ge,{label:`${d.stats.notMergeableNodes} not mergeable`,tone:"danger"}),d.stats.mergeReadyNodes>0&&s.jsx(Ge,{label:`${d.stats.mergeReadyNodes} need merge`,tone:"warn"}),d.stats.cleanupCandidateNodes>0&&s.jsx(Ge,{label:`${d.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),d.stats.offlineNodes>0&&s.jsx(Ge,{label:`${d.stats.offlineNodes} offline`,tone:"danger"}),d.stats.incompleteSnapshotNodes>0&&s.jsx(Ge,{label:`${d.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),d.stats.missingGitSnapshotNodes>0&&s.jsx(Ge,{label:`${d.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),d.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Ge,{label:`${d.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),d.stats.staleGitSnapshotNodes>0&&s.jsx(Ge,{label:`${d.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((y==null?void 0:y.active)??0)>0&&s.jsx(Ge,{label:`${(y==null?void 0:y.active)??0} active queue`,tone:"info"}),s.jsx(Ge,{label:`${d.stats.totalNodes} nodes`,tone:"default"}),d.stats.totalActiveSessions>0&&s.jsx(Ge,{label:`${d.stats.totalActiveSessions} 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(Ge,{label:`${d.stats.dirtyNodes} dirty`,tone:d.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Ge,{label:`${d.stats.orphanNodes} orphan`,tone:d.stats.orphanNodes>0?"warn":"good"}),s.jsx(Ge,{label:`${h.recentFailures} recent failures`,tone:h.recentFailures>0?"danger":"good"}),v.length===0?s.jsx(Ge,{label:"no session metadata"}):v.slice(0,2).map(([K,J])=>s.jsx(Ge,{label:`${J} ${K}`,tone:Wa(K)},K))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ge,{label:"Anchor = default branch",tone:"info"}),s.jsx(Ge,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Ge,{label:"Submodule link = child checkout",tone:"warn"})]}),R.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:R.map(K=>s.jsx("span",{className:o.isDark?"rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1 text-xs text-amber-100":"rounded-full border border-amber-300 bg-amber-50 px-3 py-1 text-xs text-amber-700",children:K},K))}),s.jsx("div",{className:`text-xs ${o.textMuted}`,children:"Click a node only when you want drill-down details. The graph itself now carries the convergence state."})]})]})]}),d.nodes.length>0?s.jsx(hv,{data:d,selectedNodeId:m,onNodeClick:K=>{if((p==null?void 0:p.kind)==="node"&&m===K.id){u(null),x(null);return}u(K.id),x({kind:"node",nodeId:K.id})}}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:t}),S&&(p==null?void 0:p.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:H,role:"presentation",children:s.jsxs("section",{role:"dialog","aria-modal":"false","aria-label":"Selected node",className:o.isDark?"max-h-[min(72vh,540px)] w-full max-w-[min(28rem,calc(100vw-2.5rem))] overflow-y-auto rounded-2xl border border-white/12 bg-slate-950/96 p-4 shadow-2xl shadow-black/40 backdrop-blur-xl":"max-h-[min(72vh,540px)] w-full max-w-[min(28rem,calc(100vw-2.5rem))] overflow-y-auto rounded-2xl border border-slate-200 bg-white/96 p-4 shadow-2xl shadow-slate-900/15 backdrop-blur-xl",onClick:K=>K.stopPropagation(),children:[s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${o.textPrimary}`,children:S.label}),s.jsx("div",{className:`mt-1 font-mono text-[11px] ${o.textMuted}`,children:S.id.slice(0,16)})]}),s.jsx("button",{type:"button",onClick:H,className:o.isDark?"rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-xs text-slate-200 transition hover:bg-white/[0.08]":"rounded-full border border-slate-200 bg-white px-2.5 py-1 text-xs text-slate-600 transition hover:bg-slate-50",children:"Close"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[s.jsx(Ge,{label:(g==null?void 0:g.health)??S.health,tone:Yv((g==null?void 0:g.health)??S.health)}),S.branch&&s.jsx(Ge,{label:S.branch,tone:"default"}),S.ahead>0&&s.jsx(Ge,{label:`ahead ${S.ahead}`,tone:"warn"}),S.behind>0&&s.jsx(Ge,{label:`behind ${S.behind}`,tone:"warn"}),S.dirtyFiles>0&&s.jsx(Ge,{label:`${S.dirtyFiles} dirty`,tone:"warn"}),(g==null?void 0:g.connection)&&s.jsx(Ge,{label:nw(g),tone:Xv(g.connection)}),C.length>0&&s.jsx(Ge,{label:`${C.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[s.jsx(wt,{label:"Machine",value:S.machineLabel??"not reported"}),s.jsx(wt,{label:"Locality",value:S.locality}),s.jsx(wt,{label:"Machine id",value:S.machineId??(g==null?void 0:g.machineId)??"not reported"}),s.jsx(wt,{label:"Daemon id",value:S.daemonId??(g==null?void 0:g.daemonId)??"not reported"}),s.jsx(wt,{label:"Workspace",value:(g==null?void 0:g.workspace)??S.workspace}),s.jsx(wt,{label:"Branch",value:S.branch??"unknown"}),s.jsx(wt,{label:"HEAD",value:T??(g!=null&&g.gitProbePending?"Pending live git probe":"not reported")}),s.jsx(wt,{label:"Upstream",value:S.upstream??"none"}),s.jsx(wt,{label:"Dirty/ahead/behind",value:`${S.dirtyFiles} dirty · ↑${S.ahead}/↓${S.behind}`}),s.jsx(wt,{label:"Source",value:String(((L=g==null?void 0:g.connection)==null?void 0:L.source)??aw(S))}),s.jsx(wt,{label:"Transport",value:((U=g==null?void 0:g.connection)==null?void 0:U.transport)??"unknown"}),s.jsx(wt,{label:"Sessions",value:C.length>0?C.map(K=>K.session.state||K.session.lifecycle||"unknown").join(", "):"none active"})]}),C.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${o.textMuted}`,children:"Active Sessions"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:C.map(K=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${o.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`font-mono ${o.textMuted}`,children:K.session.sessionId.slice(0,14)}),s.jsx(Ge,{label:K.session.state||K.session.lifecycle||"unknown",tone:Wa(K.session.state||K.session.lifecycle)})]}),s.jsxs("div",{className:`mt-0.5 truncate ${o.textMuted}`,children:[(K.session.workspace||K.workspace).slice(0,32),K.branch?` · ${K.branch}`:""]})]},K.session.sessionId))})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${o.textMuted}`,children:"Ledger (mesh-wide)"}),s.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[s.jsx(wt,{label:"Completed",value:String(h.taskCompleted)}),s.jsx(wt,{label:"Failed",value:s.jsx("span",{className:h.taskFailed>0?o.isDark?"text-rose-300":"text-rose-600":"",children:h.taskFailed})}),s.jsx(wt,{label:"Launched",value:String(h.sessionLaunched)}),s.jsx(wt,{label:"Recent failures",value:s.jsx("span",{className:h.recentFailures>0?o.isDark?"text-amber-300":"text-amber-600":"",children:h.recentFailures})})]})]}),(()=>{var X,ae;const K=((X=i.queue)==null?void 0:X.tasks)??((ae=i.queue)==null?void 0:ae.items)??null;if(!Array.isArray(K)||K.length===0)return null;const J=K.filter(de=>Zv(de)===m).slice(0,3);return J.length===0?null:s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${o.textMuted}`,children:"Queue tasks"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:J.map(de=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${o.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`font-mono ${o.textMuted}`,children:de.id.slice(0,12)}),s.jsx(Ge,{label:de.status??"unknown",tone:Wa(de.status)})]}),de.message&&s.jsx("div",{className:`mt-0.5 truncate ${o.textMuted}`,children:de.message.slice(0,48)})]},de.id))})]})})(),S.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:S.snapshotWarnings[0]})]}),((B=S.branchConvergence)==null?void 0:B.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:S.branchConvergence.nextStep})]})]})})]})})})})}const hn=new Map;function lw(e,t){return!e||!t?null:`${e}::${t}`}function cw({activeConv:e,sendDaemonCommand:t,onClose:r}){var M,C;const n=((M=e.coordinator)==null?void 0:M.meshId)??(typeof((C=e.settings)==null?void 0:C.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),a=e.daemonId??null,o=lw(a,n),i=o?hn.get(o)??null:null,c=Yd(),{theme:d}=Us(),m=l.useMemo(()=>zs(d),[d]),[u,p]=l.useState(i),[x,w]=l.useState(!1),[b,f]=l.useState(null),[k,y]=l.useState((i==null?void 0:i.refreshedAt)??null),h=l.useRef(i!==null);l.useEffect(()=>{h.current=u!==null},[u]),l.useEffect(()=>{const N=o?hn.get(o)??null:null;p(N),y((N==null?void 0:N.refreshedAt)??null),h.current=N!==null,f(null)},[o]);const j=l.useCallback(async(N=!1)=>{if(!a||!n){f("This coordinator does not expose a live mesh id."),p(null);return}if(!N&&o){const O=hn.get(o);if(O){p(O),y(O.refreshedAt||null),h.current=!0,w(!1),f(null);return}}w(!h.current),f(null);try{const O=c!=null&&c.loadMeshStatus?await c.loadMeshStatus(a,n,{refresh:N,retryProfile:N?"settled":"interactive"}):await t(a,"mesh_status",{meshId:n,refresh:N}),_=Lu(O);if(!_){f("mesh_status returned an unexpected payload.");return}o&&hn.set(o,_),p(_),h.current=!0,y(_.refreshedAt||new Date().toISOString())}catch(O){f(O instanceof Error?O.message:"Failed to load live mesh status")}finally{w(!1)}},[o,a,n,c,t]);l.useEffect(()=>{j(!1)},[j]),l.useEffect(()=>{const N=O=>{O.key==="Escape"&&r()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[r]);const v=(u==null?void 0:u.meshName)||n||"Repo Mesh",g=k?new Date(k).toLocaleTimeString():null,S=l.useMemo(()=>x?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[x]);return s.jsx("div",{className:m.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:m.dialogShellClass,onClick:N=>N.stopPropagation(),children:[s.jsxs("div",{className:m.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(Qt,{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:m.dialogTitleClass,children:v}),s.jsx("span",{className:m.dialogKickerClass,children:"Mesh observability"})]}),s.jsxs("p",{className:m.dialogSubtitleClass,children:[nt(e),e.workspaceName?` · ${e.workspaceName}`:"",u!=null&&u.repoIdentity?` · ${u.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[g&&s.jsxs("span",{className:m.dialogRefreshedChipClass,children:["Refreshed ",g]}),s.jsx("button",{type:"button",onClick:()=>{j(!0)},disabled:x,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:x?"Refreshing…":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:m.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:s.jsx(gt,{size:16})})]})]}),b&&s.jsx("div",{className:m.isDark?"shrink-0 border-b border-rose-400/20 bg-rose-500/12 px-4 py-2 text-sm text-rose-200 md:px-5":"shrink-0 border-b border-rose-300 bg-rose-50 px-4 py-2 text-sm text-rose-700 md:px-5",children:b}),s.jsx("div",{className:m.dialogBodyClass,children:u?s.jsx(Bu,{status:u,emptyMessage:S,daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:m.dialogEmptyClass,children:S})})]})})}function dw(e,t){const{sendCommand:r}=lt(),[n,a]=l.useState(null),[o,i]=l.useState(!1);l.useEffect(()=>{if(!e||!t){a(null);return}i(!0),r(e,"git_remote_url",{workspace:t}).then(d=>{const m=(d==null?void 0:d.result)??d;a(typeof(m==null?void 0:m.remoteUrl)=="string"?m.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>i(!1))},[e,t,r]);const c=uw(n);return{remoteUrl:n,githubUrl:c,loading:o}}function uw(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 Ou=5e3;function mw(e){return`git:${e}`}function hw({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Ou}){return{type:"subscribe",topic:"workspace.git",key:mw(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function bi(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function vs(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 pw(e){const t=bi(e);return(t==null?void 0:t.success)===!1?{status:null,error:vs(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:vs(t,"Git status response did not include status")}}function fw(e){const t=bi(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:vs(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:vs(t,"Git diff summary response did not include diffSummary")}}function Ka(e){return e===void 0||typeof e=="boolean"}function xw(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Ka(t.binary)&&Ka(t.truncated)&&Ka(t.staged)}function bw(e){const t=bi(e);return(t==null?void 0:t.success)===!1?{diff:null,error:vs(t,"Git file diff request failed")}:xw(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:vs(t,"Git file diff response did not include a valid diff object")}}function gw({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Ou}){const{sendCommand:o,sendData:i}=lt(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[m,u]=l.useState(null),[p,x]=l.useState(null),[w,b]=l.useState(!1),[f,k]=l.useState(null),y=l.useCallback(async()=>{if(!(!d||!e||!c)){b(!0),k(null);try{const j=pw(await o(e,"git_status",{workspace:c}));if(j.error){u(null),x(null),k(j.error);return}if(u(j.status),!n){x(null);return}const v=fw(await o(e,"git_diff_summary",{workspace:c}));if(v.error){x(null),k(v.error);return}x(v.diffSummary)}catch(j){k(vs(j,"Git status request failed"))}finally{b(!1)}}},[d,e,n,o,c]),h=l.useMemo(()=>c?hw({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return l.useEffect(()=>{if(!d||!e||!c||!h){u(null),x(null),b(!1),k(null);return}const j=i?Gt.subscribe({sendData:i},e,h,v=>{var g,S;v.workspace===c&&(u(v.status),x(v.diffSummary??null),k(((g=v.status)==null?void 0:g.error)||((S=v.diffSummary)==null?void 0:S.error)||null),b(!1))},{retryIntervalMs:1e3}):null;return y(),()=>{j==null||j()}},[d,e,y,h,i,c]),{status:m,diffSummary:p,loading:w,error:f,refresh:y}}const yw={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},vw={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 Xl(e){return e.split("/").pop()??e}function ww(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function jw({files:e,truncated:t,onFileClick:r,selectedPath:n,className:a=""}){return e.length===0?s.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:"No changed files."}):s.jsxs("div",{className:`flex flex-col ${a}`,children:[s.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(o=>{const i=n===o.path,c=yw[o.status]??"?",d=vw[o.status]??"text-zinc-400",m=ww(o.path),u=Xl(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 ${i?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(o),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:o.status,children:c}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&s.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),s.jsx("span",{className:"text-text-primary",children:u}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",Xl(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 kw(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 Sw({diff:e,binary:t,truncated:r,loading:n,error:a,className:o=""}){const i=l.useRef(null);if(l.useEffect(()=>{i.current&&(i.current.scrollTop=0)},[e]),n)return s.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${o}`,children:"Loading diff…"});if(a)return s.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${o}`,children:a});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"No diff available."});const c=e.split(`
68
+ `);return s.jsxs("div",{ref:i,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((d,m)=>kw(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 Nw(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(`
69
+ `)}function Fu({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=lt(),{status:a,diffSummary:o,loading:i,error:c,refresh:d}=gw({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=l.useState(null),[p,x]=l.useState(null),[w,b]=l.useState(""),[f,k]=l.useState(!1),[y,h]=l.useState(!1),[j,v]=l.useState(null),[g,S]=l.useState(null),{githubUrl:M}=dw(e,t),C=l.useCallback(async R=>{if(!((m==null?void 0:m.path)===R.path&&!m.loading)){u({path:R.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const F=await n(e,"git_diff_file",{workspace:t,path:R.path,staged:R.staged}),A=bw(F);if(A.error||!A.diff){u({path:R.path,diff:"",binary:!1,truncated:!1,loading:!1,error:A.error??"Failed to load diff"});return}u({path:R.path,diff:A.diff.diff,binary:A.diff.binary??!1,truncated:A.diff.truncated??!1,loading:!1,error:null})}catch(F){const A=F instanceof Error?F.message:"Failed to load diff";u({path:R.path,diff:"",binary:!1,truncated:!1,loading:!1,error:A})}}},[e,n,m,t]),N=l.useCallback(R=>{b(""),k(!1),v(null),S(null),x(R)},[]),O=l.useCallback(()=>{x(null),v(null),h(!1)},[]),_=l.useCallback(async()=>{var R,F,A;if(p){h(!0),v(null);try{let I;p==="checkpoint"?I=await n(e,"git_checkpoint",{workspace:t,message:w,includeUntracked:f}):p==="stash"?I=await n(e,"git_stash_push",{workspace:t,message:w,includeUntracked:f}):p==="stash_pop"?I=await n(e,"git_stash_pop",{workspace:t}):p==="checkout_files"&&m&&(I=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const $=(I==null?void 0:I.result)??I;if(($==null?void 0:$.success)===!1||$!=null&&$.error){v(($==null?void 0:$.error)??"Action failed"),h(!1);return}p==="checkpoint"?S(`Checkpoint created: ${((F=(R=$==null?void 0:$.checkpoint)==null?void 0:R.commit)==null?void 0:F.slice(0,7))??"done"}`):p==="stash"?S(`Stashed as ${((A=$==null?void 0:$.stash)==null?void 0:A.stashRef)??"stash@{0}"}`):p==="stash_pop"?S("Stash restored"):(S("File reverted"),u(null)),x(null),await d()}catch(I){v(I instanceof Error?I.message:"Action failed")}finally{h(!1)}}},[p,n,e,t,w,f,m,d]),T=!!(a!=null&&a.hasConflicts),H=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:R=>{R.target===R.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}),M&&s.jsx("a",{href:`${M}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-sky-400 underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:d,disabled:i,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),s.jsx("button",{onClick:r,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(gt,{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"}),H===0&&!a.error&&s.jsx("span",{className:"text-emerald-500",children:"clean"}),o&&o.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[o.files.length," file",o.files.length!==1?"s":"",o.totalInsertions>0&&s.jsxs("span",{className:"text-emerald-500",children:[" +",o.totalInsertions]}),o.totalDeletions>0&&s.jsxs("span",{className:"text-red-400",children:[" -",o.totalDeletions]})]})]}),c&&s.jsx("div",{className:"shrink-0 border-b border-border/50 bg-red-500/10 px-4 py-2 text-xs text-red-400",children:c}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[i&&!o&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),o&&s.jsx(jw,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:C}),!i&&!o&&!c&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:m?s.jsx(Sw,{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"})})]}),g&&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:g}),s.jsx("button",{onClick:()=>S(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:()=>N("checkpoint"),disabled:T,title:T?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),s.jsx("button",{onClick:()=>N("stash"),disabled:T,title:T?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),s.jsx("button",{onClick:()=>N("stash_pop"),disabled:T||!(a!=null&&a.stashCount),title:T?"Resolve conflicts before restoring a stash":a!=null&&a.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),s.jsx("button",{onClick:()=>N("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 R=Nw((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(R),S("Copied to clipboard"),setTimeout(()=>S(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:R=>b(R.target.value),maxLength:200,placeholder:"Message (required)",className:"rounded border border-border bg-surface-alt px-2 py-1 text-xs text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-border",autoFocus:!0}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:f,onChange:R=>k(R.target.checked)}),"Include untracked files"]})]}),j&&s.jsx("p",{className:"text-xs text-red-400",children:j}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:O,disabled:y,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),s.jsx("button",{onClick:_,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 Cw({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=l.useState(!1),[o,i]=l.useState(!1),[c,d]=l.useState(!1),[m,u]=l.useState(!1),[p,x]=l.useState(!1),[w,b]=l.useState("quickstart"),[f,k]=l.useState("workspace"),y=l.useMemo(()=>!t&&!e,[t,e]),h=l.useCallback(C=>{a(C),C&&i(!1)},[]),j=l.useCallback(C=>{i(C),C&&a(!1)},[]),v=l.useCallback(()=>{b(r===0?"quickstart":"shortcuts"),k("workspace"),d(!0),a(!1),i(!1)},[r]),g=l.useCallback(()=>{d(!1)},[]),S=l.useCallback(()=>{u(!0)},[]),M=l.useCallback(()=>{u(!1)},[]);return l.useEffect(()=>{if(!y){x(!1);return}x(!0);const C=window.setTimeout(()=>{x(!1)},1e4);return()=>window.clearTimeout(C)},[y]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:m,guideNudgeVisible:p,guideTab:w,shortcutSection:f,isDesktopDashboard:y,setGuideTab:b,setShortcutSection:k,handleInboxOpenChange:h,handleHiddenOpenChange:j,handleOpenShortcutHelp:v,closeShortcutHelp:g,openNewSession:S,closeNewSession:M}}function Mw(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 Iw(e){return e instanceof Error?e.message:String(e||"")}function Tw(e){const t=Iw(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Aw({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:i,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:p,ides:x,actionLogs:w,sendDaemonCommand:b,setActionLogs:f,setCliViewModeOverrides:k,isStandalone:y,initialDataLoaded:h,userName:j,requestedMobileTabKey:v,onRequestedMobileTabConsumed:g,requestedMachineId:S,onRequestedMachineConsumed:M,requestedMobileSection:C,onRequestedMobileSectionConsumed:N,containerRef:O,isSplitMode:_,numGroups:T,groupSizes:H,groupedConvs:R,clearedTabs:F,focusedGroup:A,focusGroup:I,moveTabToGroup:$,splitTabRelative:E,closeGroup:L,handleResizeStart:U,groupActiveTabIds:B,setGroupActiveTab:K,groupTabOrders:J,setGroupTabOrder:X,toggleHiddenTab:ae,visibleConversations:de,requestedDesktopTabKey:ke,onRequestedDesktopTabConsumed:q,onDesktopActiveTabChange:ve,onRequestScrollToBottom:be,onHideConversation:we,onShowHiddenConversation:xe,onShowAllHiddenConversations:Ce,scrollToBottomRequest:Q,machineEntries:ge,layoutProfile:ce,onBrowseMachineDirectory:ye,onSaveMachineWorkspace:me,onLaunchMachineIde:fe,onLaunchMachineProvider:le,onListMachineMeshes:pe,onLaunchMeshCoordinator:oe,onListMachineSavedSessions:P,notifications:ue,notificationUnreadCount:Se,liveSessionInboxState:Ie,onMarkNotificationRead:te,onMarkNotificationUnread:Ne,onDeleteNotification:De}){const Ee=ft.useRef(null),{inboxOpen:ze,hiddenOpen:Qe,shortcutHelpOpen:Ze,newSessionOpen:rt,guideNudgeVisible:et,guideTab:ct,shortcutSection:Xe,isDesktopDashboard:pt,setGuideTab:Ae,setShortcutSection:Fe,handleInboxOpenChange:st,handleHiddenOpenChange:qe,handleOpenShortcutHelp:Ke,closeShortcutHelp:z,openNewSession:G,closeNewSession:Y}=Cw({isMobile:t,showMobileChatMode:e,visibleConversationCount:de.length}),[se,W]=ft.useState(null),[V,ee]=ft.useState(null),ne=ft.useCallback((re,Re)=>{W({daemonId:re,workspace:Re})},[]),D=ft.useCallback(re=>{ee(re)},[]),ie=ft.useCallback(re=>{var Re;vr.flushSync(()=>{xe(re)}),(Re=Ee.current)==null||Re.restoreHiddenTabToSavedLocation(re.tabKey)},[xe]),he=ft.useCallback(re=>{var kt;const Re=u.find(St=>po(St,re))||p.find(St=>po(St,re));Re&&(p.some(St=>St.tabKey===Re.tabKey)&&ie(Re),ve(Re.tabKey),(kt=Ee.current)==null||kt.activateConversationTab(Re.tabKey),be(Re.tabKey,"notification-open")),te(re.id),st(!1)},[ie,p,u,ve,te,be]),je=ft.useCallback(()=>{var Re;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Re=Ee.current)==null||Re.resetAllPanelsToMain(),qe(!1))},[qe]),Me=ft.useCallback(async re=>{var rs;if(!r)return;const Re=(rs=r.modalButtons)==null?void 0:rs[re];if(!Re)return;const kt=us(r);if(!kt)return;const St=Re.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),ks=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(St);try{await b(kt,"resolve_action",{button:Re,action:ks?"approve":"reject",buttonIndex:re,...ds(r)})}catch(ns){Tw(ns)||console.error("[Shortcut approval] Failed:",ns)}},[r,b]),{isMac:$e,actionDefinitions:Te,actionShortcuts:Le,shortcutListening:Ue,shortcutListeningDraft:dt,setShortcutListening:yt,setShortcutListeningDraft:ut,saveShortcuts:mt}=e0({enabled:pt&&!Ze,onTrigger:re=>{var Re,kt,St,ks,rs,ns,Er,$r,Br,Or,Fr,Hr,Wr,Kr,Ur,zr;if(re==="openShortcutHelp"){Ke();return}if(re==="openNewSession"){G();return}if(re==="hideCurrentTab"){r&&we(r);return}if(re==="toggleHiddenTabs"){qe(!Qe);return}if(re==="openHistoryForActiveTab"){r&&!Ve(r)&&o(r);return}if(re==="openRemoteForActiveTab"){r&&!Ye(r)&&!Ve(r)&&i(r);return}if(re==="splitActiveTabRight"){(Re=Ee.current)==null||Re.splitActiveTabRight();return}if(re==="splitActiveTabDown"){(kt=Ee.current)==null||kt.splitActiveTabDown();return}if(re==="floatActiveTab"){(St=Ee.current)==null||St.floatActiveTab();return}if(re==="popoutActiveTab"){(ks=Ee.current)==null||ks.popoutActiveTab();return}if(re==="dockActiveTab"){(rs=Ee.current)==null||rs.dockActiveTab();return}if(re==="focusLeftPane"){(ns=Ee.current)==null||ns.focusLeftPane();return}if(re==="focusRightPane"){(Er=Ee.current)==null||Er.focusRightPane();return}if(re==="focusUpPane"){($r=Ee.current)==null||$r.focusUpPane();return}if(re==="focusDownPane"){(Br=Ee.current)==null||Br.focusDownPane();return}if(re==="moveActiveTabToLeftPane"){(Or=Ee.current)==null||Or.moveActiveTabToLeftPane();return}if(re==="moveActiveTabToRightPane"){(Fr=Ee.current)==null||Fr.moveActiveTabToRightPane();return}if(re==="moveActiveTabToUpPane"){(Hr=Ee.current)==null||Hr.moveActiveTabToUpPane();return}if(re==="moveActiveTabToDownPane"){(Wr=Ee.current)==null||Wr.moveActiveTabToDownPane();return}if(re==="triggerPrimaryApprovalAction"){Me(0);return}if(re==="triggerSecondaryApprovalAction"){Me(1);return}if(re==="triggerTertiaryApprovalAction"){Me(2);return}if(re==="setActiveTabShortcut"){(Kr=Ee.current)==null||Kr.setShortcutForActiveTab();return}if(re==="selectPreviousGroupTab"){(Ur=Ee.current)==null||Ur.activatePreviousTabInGroup();return}if(re==="selectNextGroupTab"){(zr=Ee.current)==null||zr.activateNextTabInGroup();return}!r||!Ye(r)||Ve(r)||re==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),Oe=ft.useCallback(()=>{z(),yt(null),ut([])},[z,yt,ut]),Yt=ft.useMemo(()=>Xe==="all"?Te:Te.filter(re=>Mw(re)===Xe),[Te,Xe]),Z=ft.useCallback(()=>{const re=Object.fromEntries(Te.map(Re=>[Re.id,""]));mt(re)},[Te,mt]),Pe=ft.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const re=Object.fromEntries(Te.map(Re=>[Re.id,Re.defaultShortcut]));mt(re)},[Te,mt]);return ft.useEffect(()=>{const re=Re=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Re.metaKey&&Re.key.toLowerCase()==="w":Re.ctrlKey&&Re.key.toLowerCase()==="w")&&(Re.preventDefault(),r&&we&&we(r))};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[r,we]),ft.useEffect(()=>{if(!Ze||Ue)return;const re=Re=>{Re.key==="Escape"&&(Re.preventDefault(),Oe())};return window.addEventListener("keydown",re,!0),()=>window.removeEventListener("keydown",re,!0)},[Oe,Ze,Ue]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(zx,{activeConv:r,wsStatus:n,isConnected:a,conversations:de,hiddenConversations:p,onOpenHistory:o,onHideConversation:we,onShowConversation:ie,onShowAllHidden:Ce,onResetPanelsToMain:je,notifications:ue,notificationUnreadCount:Se,onOpenNotification:he,onMarkNotificationRead:te,onMarkNotificationUnread:Ne,onDeleteNotification:De,inboxOpen:ze,onInboxOpenChange:st,hiddenOpen:Qe,onHiddenOpenChange:qe,onOpenNewSession:t?void 0:G,onOpenDashboardGuide:Ke,guideNudgeVisible:et,actionShortcuts:Le,onOpenRemote:()=>{!r||Ye(r)||Ve(r)||i(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:ne,onOpenMeshGraph:D}),e?s.jsx(Wy,{conversations:u,hiddenConversations:p,ides:x,actionLogs:w,sendDaemonCommand:b,setActionLogs:f,setCliViewModeOverrides:k,isStandalone:y,userName:j,requestedActiveTabKey:v,onRequestedActiveTabConsumed:g,requestedMachineId:S,onRequestedMachineConsumed:M,requestedMobileSection:C,onRequestedMobileSectionConsumed:N,onOpenHistory:o,onOpenRemote:i,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Ce,onHideConversation:we,onOpenMeshGraph:D,onOpenNewSession:G,liveSessionInboxState:Ie}):t?s.jsx(Xy,{containerRef:O,isSplitMode:_,numGroups:T,groupSizes:H,groupedConvs:R,clearedTabs:F,ides:x,actionLogs:w,sendDaemonCommand:b,setActionLogs:f,isStandalone:y,hasRegisteredMachines:ge.length>0,userName:j,focusedGroup:A,focusGroup:I,moveTabToGroup:$,splitTabRelative:E,closeGroup:L,handleResizeStart:U,groupActiveTabIds:B,setGroupActiveTab:K,groupTabOrders:J,setGroupTabOrder:X,toggleHiddenTab:ae,onOpenNewSession:G,allowTabShortcuts:!1,liveSessionInboxState:Ie}):s.jsx(p0,{visibleConversations:de,clearedTabs:F,ides:x,actionLogs:w,sendDaemonCommand:b,setActionLogs:f,isStandalone:y,hasRegisteredMachines:ge.length>0,initialDataLoaded:h,userName:j,toggleHiddenTab:ae,actionShortcuts:Le,registerActionHandlers:re=>{Ee.current=re},onActiveTabChange:ve,requestedActiveTabKey:ke,onRequestedActiveTabConsumed:q,onRequestScrollToBottom:be,scrollToBottomRequest:Q,onOpenNewSession:G,liveSessionInboxState:Ie,layoutProfile:ce}),rt&&s.jsx(S0,{machines:ge,ides:x,onClose:Y,onBrowseDirectory:ye,onSaveWorkspace:me,onLaunchIde:fe,onLaunchProvider:le,onListMeshes:pe,onLaunchMeshCoordinator:oe,onListSavedSessions:P}),V&&s.jsx(cw,{activeConv:V,sendDaemonCommand:b,onClose:()=>ee(null)}),se&&s.jsx(Fu,{daemonId:se.daemonId,workspace:se.workspace,onClose:()=>W(null)}),Ze&&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:Oe,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:re=>re.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:Oe,"aria-label":"Close dashboard guide",children:s.jsx(gt,{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(re=>s.jsx("button",{type:"button",className:`btn btn-sm ${ct===re.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ae(re.id),children:re.label},re.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 ",$e?"⌥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(re=>s.jsx("button",{type:"button",className:`btn btn-sm ${Xe===re.id?"btn-primary":"btn-secondary"}`,onClick:()=>Fe(re.id),children:re.label},re.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:Pe,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Yt.map(re=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Ue===re.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:re.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:re.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:re.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:Ue===re.id?dt.length>0?`${dt.join(" ")} ...`:"Listening...":Le[re.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{yt(re.id),ut([])},children:Ue===re.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Re={...Le};Re[re.id]="",mt(Re)},children:"Disable"})]})]})},re.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",$e?"⌘⇧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 Ua=[{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 _w({onClose:e}){const[t,r]=l.useState(0),n=Ua[t],a=t===Ua.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(gt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Ua.map((o,i)=>s.jsx("div",{style:{width:i===t?24:8,height:8,borderRadius:4,background:i===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},i))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx("span",{children:n.icon})," ",n.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&s.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>a?e():r(o=>o+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
70
+ @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
71
+ @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
72
+ `})]})}function Lw({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 i=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 ${i?"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 Pw({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,i]=l.useState(()=>a||"native"),c=l.useMemo(()=>wd(t),[t]),d=l.useMemo(()=>e?Jo(e,{machineNames:c,connectionStates:r,defaultConnectionState:"new"}):[],[e,c,r]),m=l.useMemo(()=>d.find(f=>f.streamSource==="native"),[d]),u=l.useMemo(()=>d.filter(f=>f.streamSource==="agent-stream"),[d]),p=l.useMemo(()=>e?$t(d,e.id):null,[d,e]);l.useEffect(()=>{a&&i(a)},[a]),l.useEffect(()=>{if(a||!p)return;const f=p.streamSource==="native"?"native":p.tabKey;!f||o===f||o==="native"&&i(f)},[o,p,a]),l.useEffect(()=>{var f;o!=="native"&&(u.some(k=>k.tabKey===o)||i(((f=u[0])==null?void 0:f.tabKey)||"native"))},[o,u]),l.useEffect(()=>{o==="native"&&(m||u[0]&&i(u[0].tabKey))},[o,m,u]);const x=l.useMemo(()=>o==="native"&&m?m:u.find(f=>f.tabKey===o)||p||m||u[0],[o,m,p,u]),w=l.useMemo(()=>u.map(f=>({tabKey:f.tabKey,title:md(f)||n,status:f.status})),[u,n]),b=l.useCallback(f=>{if(f)return d.find(k=>po(k,{sessionId:f,routeId:f,tabKey:f,providerSessionId:f}))},[d]);return{activeChatTab:o,setActiveChatTab:i,activeConv:x,conversations:d,extensionTabs:w,hasExtensions:w.length>0,resolveConversationByTarget:b}}function Rw({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:i,isStandalone:c,userName:d,onOpenHistory:m,onConversationChange:u,onClose:p}){const[x,w]=l.useState("split"),[b,f]=l.useState(()=>ts(e)?"native":e.tabKey),k=l.useRef(null),y=l.useMemo(()=>t||r.find(I=>I.id===e.routeId),[e.routeId,t,r]),h=l.useMemo(()=>xt((y==null?void 0:y.type)||""),[y==null?void 0:y.type]),{conversations:j,extensionTabs:v,hasExtensions:g}=Pw({ideData:y,allIdes:r,connectionStates:n,ideName:h||"IDE",preferredTabKey:ts(e)?void 0:e.tabKey}),S=l.useMemo(()=>y?$t(j,y.id):null,[y,j]);l.useEffect(()=>{const I=k.current,$={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(k.current=$,!(I&&I.routeId===$.routeId&&I.tabKey===$.tabKey&&I.streamSource===$.streamSource)){if(ts(e)){f("native");return}f(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),l.useEffect(()=>{if(b==="native"){if(j.some(I=>I.streamSource==="native"))return;(S==null?void 0:S.streamSource)==="agent-stream"&&f(S.tabKey);return}if(!j.some(I=>I.tabKey===b)){if((S==null?void 0:S.streamSource)==="agent-stream"){f(S.tabKey);return}f("native")}},[j,b,S]);const M=l.useMemo(()=>b==="native"?j.find(I=>I.streamSource==="native")||e:j.find(I=>I.tabKey===b)||e,[e,j,b]),C=Pd(M),N=l.useMemo(()=>C.status||C.modalMessage||C.modalButtons?{...M,...C.status?{status:C.status}:{},...C.modalMessage!==void 0?{modalMessage:C.modalMessage}:{},...C.modalButtons!==void 0?{modalButtons:C.modalButtons}:{}}:M,[M,C]),O=_r(N),_=ra({sendDaemonCommand:o,activeConv:N,setActionLogs:i,isStandalone:c}),{connScreenshot:T,screenshotUsage:H,handleRemoteAction:R}=du({doId:O,targetSessionId:Xc(N),connState:N.connectionState||"new",viewMode:x}),F=l.useMemo(()=>a.filter(I=>I.routeId===N.tabKey),[a,N.tabKey]);l.useEffect(()=>{u==null||u(N)},[N,u]),l.useEffect(()=>{const I=$=>{$.key==="Escape"&&p()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[p]);const A=l.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:A,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(Bt,{size:16})}),s.jsx("span",{className:"truncate",children:Uo(M)||"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 $=x===I;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${$?"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(ph,{size:15}):s.jsx(Bt,{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(M),title:"Chat History",children:[s.jsx(Ro,{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(Lw,{hasExtensions:g,ideName:h||"IDE",activeChatTab:b,extensionTabs:v,onSelectTab:f}),s.jsx(Dc,{activeConv:N,onModalButton:_.handleModalButton}),s.jsx(go,{activeConv:N,ideEntry:y,showMetaChips:!1,handleSendChat:_.handleSendChat,handleForceSendChat:_.handleForceSendChat,isSendingChat:_.isSendingChat,sendFeedbackMessage:_.sendFeedbackMessage,handleFocusAgent:_.handleFocusAgent,isFocusingAgent:_.isFocusingAgent,actionLogs:F,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(Pc,{addLog:()=>{},connState:N.connectionState||"new",connScreenshot:T,screenshotUsage:H,transportType:N.transport,onAction:R})})]})]})})}function Dw({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=Rx(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 Ew({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o}){var i;return s.jsxs(s.Fragment,{children:[s.jsx(Ox,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(yd,{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(Rw,{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&&(Ye(r.targetConv)||Ve(r.targetConv))&&s.jsx(Dw,{activeConv:r.targetConv,canSaveAndStop:Ye(r.targetConv)&&!Ve(r.targetConv)&&!!((i=r.targetConv.resume)!=null&&i.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(vd,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),o.open&&s.jsx(_w,{onClose:o.onClose})]})}function $w({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(Zn,{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(i=>{const c=Ct(i,{fallbackId:i.id}),d=n[i.id],m=i.version||i.daemonVersion||"unknown",u=i.versionUpdateRequired===!0,x=Gd(i)==="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(i.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(i.id),children:x})]},i.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:s.jsx(gt,{size:16})})]})}function Bw(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function Ow(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 Fw(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>Ow(t)).map(t=>t.id)}}function Hw(){var Si,Ni,Ci,Mi;const{sendCommand:e}=lt(),t=Lr(),r=Ld(),n=_o(),a=Ir(),[o,i]=Dm(),c=o.get("activeTab"),d=((Si=n.state)==null?void 0:Si.openRemoteForTabKey)||null,m=((Ni=n.state)==null?void 0:Ni.openMachineId)||null,u=((Ci=n.state)==null?void 0:Ci.mobileSection)||null,p=ld(),x=p.ides||[],w=p.initialLoaded??!0,{updateRouteChats:b,setToasts:f}=p,[k,y]=l.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),h=p.toasts||[],j=p.wsStatus||"connected",v=p.isConnected??!0,g=p.connectionStates||{},S=p.showReconnected||!1,{layoutProfile:M,groupAssignments:C,updateGroupAssignments:N,focusedGroup:O,updateFocusedGroup:_,focusGroup:T,groupActiveTabIds:H,updateGroupActiveTabIds:R,setGroupActiveTab:F,groupTabOrders:A,updateGroupTabOrders:I,setGroupTabOrder:$,groupSizes:E,updateGroupSizes:L,isMobile:U,hasHydratedStoredLayout:B,hydrateStoredLayout:K,focusConversationTab:J}=$g(),[X,ae]=l.useState(()=>ti());l.useEffect(()=>Gb(ae),[]);const de=l.useMemo(()=>Bw({isMobile:U,mobileViewMode:X}),[U,X]),[ke,q]=l.useState([]),[ve,be]=l.useState({}),[we,xe]=l.useState({});Ar("Dashboard",{ideCount:x.length,toastCount:h.length,focusedGroup:O,groupCount:Object.keys(C).length,actionLogCount:ke.length});const Ce=l.useMemo(()=>x.filter(He=>He.type==="adhdev-daemon").sort(Ho),[x]),Q=Ce[0],ge=!!Q;l.useEffect(()=>{const{metadataDaemonIds:He,runtimeDaemonIds:_t}=Fw(Ce);for(const Gs of He)t(Gs,{minFreshMs:3e4}).catch(()=>{});for(const Gs of _t)r(Gs,{minFreshMs:3e4}).catch(()=>{})},[t,r,Ce]);const ce=(Q==null?void 0:Q.terminalBackend)||null,ye=Q?Ct(Q,{fallbackId:Q.id}):null,me=(Q==null?void 0:Q.id)||null,fe=l.useMemo(()=>cg(x,ve),[x,ve]),{hiddenTabs:le,autoHiddenTabs:pe,autoHideTarget:oe,hideTarget:P,toggleTarget:ue,showTarget:Se,showAllTabs:Ie}=ng(),{conversations:te,visibleConversations:Ne,visibleTabKeys:De,resolveConversationBySessionId:Ee,resolveConversationByTarget:ze}=jg({ides:fe,connectionStates:g,clearedTabs:we,hiddenTabs:le}),Qe=l.useMemo(()=>new Map(te.map(He=>[He.tabKey,He])),[te]),Ze=l.useMemo(()=>rg(te,le,pe),[te,le,pe]);l.useEffect(()=>{for(const He of Ze)oe(He)},[Ze,oe]),lx(Ne,de),l.useEffect(()=>{Object.keys(ve).length!==0&&be(He=>dg(He,x))},[x,ve]);const rt=l.useMemo(()=>cp(x),[x]),{notifications:et,unreadCount:ct}=Zg({conversations:te,liveSessionInboxState:rt}),{handleMarkDashboardNotificationRead:Xe,handleMarkDashboardNotificationUnread:pt,handleDeleteDashboardNotification:Ae}=ey({notifications:et,sendDaemonCommand:e}),{containerRef:Fe,normalizedGroupAssignments:st,numGroups:qe,isSplitMode:Ke,groupedConvs:z,moveTabToGroup:G,closeGroup:Y,handleResizeStart:se,splitTabRelative:W}=Ug({groupAssignments:C,updateGroupAssignments:N,updateFocusedGroup:_,updateGroupActiveTabIds:R,updateGroupTabOrders:I,groupSizes:E,updateGroupSizes:L,isMobile:U,visibleConversations:Ne,visibleTabKeys:De}),{activeConv:V,openDesktopConversation:ee,requestScrollToBottom:ne,scrollToBottomRequest:D,setDesktopActiveTab:ie}=py({isMobile:U,conversations:te,visibleConversations:Ne,groupActiveTabIds:H,focusedGroup:O,groupedConvs:z,setSearchParams:i});by({activeConv:V,isMobile:U,liveSessionInboxState:rt,sendDaemonCommand:e});const{requestedDesktopTabKey:he,requestedMobileTabKey:je,consumeRequestedActiveTab:Me}=kg({isMobile:U,urlActiveTab:c,resolveConversationBySessionId:Ee,setSearchParams:i}),{remoteDialogConv:$e,remoteDialogIdeEntry:Te,remoteDialogActiveConv:Le,setRemoteDialogActiveConv:Ue,openRemoteDialog:dt,closeRemoteDialog:yt,cliStopDialogOpen:ut,cliStopTargetConv:mt,requestCliStop:Oe,cancelCliStop:Yt,confirmCliStop:Z}=vy({isMobile:U,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:he,conversations:te,ides:x,resolveConversationByTarget:ze,activeConv:V,sendDaemonCommand:e}),{historyModalOpen:Pe,openHistoryModal:re,closeHistoryModal:Re,historyTargetConv:kt,isSavedSessionHistoryTarget:St,isHistoryCreatingChat:ks,isHistoryRefreshingHistory:rs,handleHistorySwitchSession:ns,handleHistoryNewChat:Er,handleHistoryRefresh:$r,savedHistorySessions:Br,savedHistoryFilters:Or,setSavedHistoryFilters:Fr,missingWorkspaceResumePath:Hr,isSavedHistoryLoading:Wr,resumingSavedHistorySessionId:Kr,handleRefreshSavedHistory:Ur,handleResumeSavedHistorySession:zr}=gy({activeConv:V,remoteDialogConv:$e,remoteDialogActiveConv:Le,ides:x,sendDaemonCommand:e,updateRouteChats:b,setToasts:f,setClearedTabs:xe,setSearchParams:i}),Gu=l.useMemo(()=>Ne,[Ne]),Gr=U&&X==="chat",Vu=l.useMemo(()=>te.filter(He=>aa(le,He)),[te,le]),wi=l.useCallback(He=>{const _t=new URLSearchParams(o);_t.set("activeTab",He),i(_t,{replace:!0})},[o,i]),{trackPendingLaunch:qu}=dy({ides:x,conversations:te,onOpenSession:wi}),{handleBrowseMachineDirectory:Yu,handleSaveMachineWorkspace:Xu,handleLaunchMachineIde:Ju,handleLaunchMachineProvider:Qu,handleListMachineMeshes:Zu,handleLaunchMeshCoordinator:em,handleListMachineSavedSessions:tm,setActiveCliViewMode:sm}=uy({sendDaemonCommand:e,trackPendingLaunch:qu,onOpenSession:wi,activeConv:V,ides:x,setCliViewModeOverrides:be});ug({visibleConversations:Ne,clearedTabs:we,setClearedTabs:xe,setActionLogs:q}),Sg({ides:x,sendDaemonCommand:e,setToasts:f,resolveConversationByTarget:ze});const{isRefreshingHistory:rm,handleRefreshHistory:nm}=zd({sendDaemonCommand:e,activeConv:V,chats:(Mi=x.find(He=>He.id===(V==null?void 0:V.routeId)))==null?void 0:Mi.chats,updateRouteChats:b,setToasts:f,setClearedTabs:xe});Og({urlActiveTab:U&&!Gr?c:null,conversations:te,resolveConversationBySessionId:Ee,normalizedGroupAssignments:st,hasHydratedStoredLayout:U&&!Gr?B:!0,hydrateStoredLayout:U&&!Gr?K:()=>{},focusConversationTab:J,setSearchParams:i,historyModalOpen:Pe,activeConv:V,isRefreshingHistory:rm,ides:x,handleRefreshHistory:nm});const am=l.useMemo(()=>!V||!Ye(V)||Ve(V)?null:Ks(V),[V]),{versionMismatchDaemons:om,hasRequiredVersionDaemons:ji,targetVersion:im,versionBannerDismissed:lm,setVersionBannerDismissed:cm,upgradingDaemons:dm,handleBannerUpgrade:um}=Gg({ides:x,sendDaemonCommand:e}),ki=l.useCallback(He=>{Se(He),ee(He)},[ee,Se]),mm=l.useCallback(He=>{P(He)},[P]);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(Fx,{terminalBackend:ce,isStandalone:ge,machineLabel:ye,machineKey:me}),(!lm||ji)&&s.jsx($w,{daemons:om,targetVersion:im,required:ji,upgradingDaemons:dm,onUpgrade:um,onDismiss:()=>cm(!0)}),s.jsx(Aw,{showMobileChatMode:Gr,isMobile:U,activeConv:V,wsStatus:j,isConnected:v,onOpenHistory:He=>{He&&Ue(He),re()},onOpenRemote:dt,onStopCli:Oe,activeCliViewMode:am,onSetActiveCliViewMode:sm,mobileChatConversations:Gu,ides:x,actionLogs:ke,sendDaemonCommand:e,setActionLogs:q,setCliViewModeOverrides:be,isStandalone:ge,initialDataLoaded:w,userName:p.userName,requestedMobileTabKey:je,onRequestedMobileTabConsumed:Me,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:Fe,isSplitMode:Ke,numGroups:qe,groupSizes:E,groupedConvs:z,clearedTabs:we,focusedGroup:O,focusGroup:T,moveTabToGroup:G,splitTabRelative:W,closeGroup:Y,handleResizeStart:se,groupActiveTabIds:H,setGroupActiveTab:F,groupTabOrders:A,setGroupTabOrder:$,toggleHiddenTab:He=>ue(Qe.get(He)||{tabKey:He}),visibleConversations:Ne,hiddenConversations:Vu,requestedDesktopTabKey:he,onRequestedDesktopTabConsumed:Me,onDesktopActiveTabChange:ie,onRequestScrollToBottom:ne,onHideConversation:mm,onShowHiddenConversation:ki,onShowAllHiddenConversations:Ie,scrollToBottomRequest:D,machineEntries:Ce,layoutProfile:M,onBrowseMachineDirectory:Yu,onSaveMachineWorkspace:Xu,onLaunchMachineIde:Ju,onLaunchMachineProvider:Qu,onListMachineMeshes:Zu,onLaunchMeshCoordinator:em,onListMachineSavedSessions:tm,notifications:et,notificationUnreadCount:ct,liveSessionInboxState:rt,onMarkNotificationRead:Xe,onMarkNotificationUnread:pt,onDeleteNotification:Ae}),s.jsx("style",{children:`
73
+ body { overflow: hidden; overscroll-behavior: none; }
74
+ `}),s.jsx(Ew,{historyModal:{open:Pe,targetConv:kt,ides:x,isCreatingChat:ks,isRefreshingHistory:St?!1:rs,savedSessions:Br,savedHistoryFilters:Or,missingWorkspaceResumePath:Hr||null,onSavedHistoryFiltersChange:Fr,isSavedSessionsLoading:Wr,isResumingSavedSessionId:Kr,onClose:Re,onNewChat:Er,onSwitchSession:ns,onRefreshHistory:St?Ur:$r,onResumeSavedSession:zr},remoteDialog:{conversation:$e,ideEntry:Te,ides:x,connectionStates:g,actionLogs:ke,sendDaemonCommand:e,setActionLogs:q,isStandalone:ge,userName:p.userName,onOpenHistory:He=>{He&&Ue(He),re()},onConversationChange:Ue,onClose:yt},cliStopDialog:{open:ut,targetConv:mt,onCancel:Yt,onStopNow:async()=>{await Z("hard")},onSaveAndStop:async()=>{await Z("save")}},connectionBanner:{wsStatus:j,showReconnected:S,loginUrl:p.connectionLoginUrl,onReconnect:p.retryServerConnection},toastOverlay:{toasts:h,onDismiss:He=>f(_t=>_t.filter(Gs=>Gs.id!==He)),onClick:He=>{if(He.targetKey){const _t=ze(He.targetKey);_t&&(J(_t.tabKey,st),ki(_t),ne(_t.tabKey,"toast-open"))}}},onboarding:{open:k,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}y(!1)}}})]})}function Ww({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[o,i]=l.useState([]),[c,d]=l.useState(null),[m,u]=l.useState(null),[p,x]=l.useState(!1),[w,b]=l.useState(null),[f,k]=l.useState(!1),[y,h]=l.useState(""),j=l.useRef(null),v=l.useCallback(E=>{j.current=E},[]),g=l.useCallback((E,L,U=!1)=>{i(B=>[...B.slice(-100),{timestamp:Date.now(),level:E,message:L}]),setTimeout(()=>{var B;return(B=a.current)==null?void 0:B.scrollIntoView({behavior:"smooth"})},100),U&&Je.showToast(L,E==="error"||E==="warn"?"warning":"success")},[a]),S=l.useCallback(E=>{const L=E instanceof Error?E.message:String(E||"");return L.includes("P2P command timeout")||L.includes("P2P not connected")||L.includes("P2P not available")},[]),M=l.useCallback(async(E,L)=>{var U;if(!e||c)return!1;d(E),g("info",`Launching ${xt(E)}${L!=null&&L.workspace?` in ${L.workspace}`:""}...`);try{const B={ideType:E,enableCdp:!0};(U=L==null?void 0:L.workspace)!=null&&U.trim()?B.workspace=L.workspace.trim():L!=null&&L.useDefaultWorkspace&&(B.useDefaultWorkspace=!0);const K=await r(e,"launch_ide",B);return g(K!=null&&K.success?"info":"error",K!=null&&K.success?`${xt(E)} launched`:`Failed: ${K==null?void 0:K.error}`,!0),!!(K!=null&&K.success)}catch(B){return g("error",`Launch error: ${B.message}`,!0),!1}finally{d(null)}},[e,c,g,r]),C=l.useCallback(async E=>{if(!e)return{success:!1};const{cliType:L,dir:U,workspaceId:B,useDefaultWorkspace:K,useHome:J,argsStr:X,model:ae,resumeSessionId:de}=E;if(!L)return g("warn","Select a CLI or ACP provider first",!0),{success:!1};const ke=X?X.split(/\s+/).filter(Boolean):void 0,q=(U==null?void 0:U.trim())||(B?"(saved id)":K?"(default workspace)":J?"(home)":"");g("info",`Launching ${L}${q?` in ${q}`:""}${ae?` (model: ${ae})`:""}...`),u(L);try{const ve={cliType:L,cliArgs:ke,initialModel:ae||void 0};U!=null&&U.trim()?ve.dir=U.trim():B?ve.workspaceId=B:K?ve.useDefaultWorkspace=!0:J&&(ve.useHome=!0),de&&(ve.resumeSessionId=de);const be=await r(e,"launch_cli",ve),we=(be==null?void 0:be.result)||be;return be!=null&&be.success?(g("info",`${L} launched`,!0),(we==null?void 0:we.launchSource)==="home"?g("info","📂 Running in home directory (explicit choice)"):(we==null?void 0:we.launchSource)==="defaultWorkspace"&&g("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:we==null?void 0:we.sessionId}):(g("error",`Failed: ${(be==null?void 0:be.error)||(we==null?void 0:we.error)}`,!0),(be==null?void 0:be.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&b({cliType:L,argsStr:X,model:ae}),{success:!1,sessionId:we==null?void 0:we.sessionId})}catch(ve){return S(ve)?(g("warn",`${L} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(g("error",`Launch error: ${ve.message}`,!0),{success:!1})}finally{u(null)}},[e,g,S,r]),N=l.useCallback(async(E,L,U,B)=>e?E?L.trim()?C({cliType:E,dir:L,argsStr:U,model:B}):(b({cliType:E,argsStr:U,model:B}),{success:!1}):(g("warn","Select a provider",!0),{success:!1}):{success:!1},[e,g,C]),O=l.useCallback(async(E,L,U)=>{if(e&&window.confirm(`Stop ${E}?
75
+ This will terminate the process.`))try{const B=await r(e,"stop_cli",{cliType:E,dir:L,targetSessionId:U});B!=null&&B.success?g("info",`${E} stopped`,!0):g("error",`Stop failed: ${(B==null?void 0:B.error)||"Unknown error"}`,!0)}catch(B){g("error",`Stop failed: ${B.message}`,!0)}},[e,g,r]),_=l.useCallback(async E=>{try{await r(E.daemonId,"restart_ide",{ideType:E.type}),g("info",`${xt(E.type)} restart initiated`,!0)}catch(L){g("error",`Restart failed: ${L.message}`,!0)}},[g,r]),T=l.useCallback(async E=>{if(window.confirm(`Stop ${xt(E.type)}?
76
+ This will disconnect CDP and optionally kill the process.`))try{const L=await r(E.daemonId,"stop_ide",{ideType:E.type,killProcess:!0});L!=null&&L.success?g("info",`${xt(E.type)} stopped`,!0):g("error",`Stop failed: ${(L==null?void 0:L.error)||"Unknown error"}`,!0)}catch(L){g("error",`Stop failed: ${L.message}`,!0)}},[g,r]),H=l.useCallback(async()=>{if(e)try{const E=await r(e,"detect_ides",{});g("info",`Found ${((E==null?void 0:E.result)||[]).length} IDE(s)`,!0)}catch(E){g("error",`Detection failed: ${E.message}`,!0)}},[e,g,r]),R=l.useCallback(async E=>{if(!e||!E.trim())return!1;x(!0);try{const L=await r(e,"workspace_add",{path:E.trim()});return L!=null&&L.success?(g("info",`Workspace added: ${E.trim()}`),!0):(g("error",(L==null?void 0:L.error)||"workspace_add failed"),!1)}catch(L){return g("error",L.message),!1}finally{x(!1)}},[e,g,r]),F=l.useCallback(async E=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){x(!0);try{const L=await r(e,"workspace_remove",{id:E});L!=null&&L.success?g("info","Workspace removed",!0):g("error",(L==null?void 0:L.error)||"workspace_remove failed",!0)}catch(L){g("error",L.message,!0)}finally{x(!1)}}},[e,g,r]),A=l.useCallback(async E=>{var L;if(e){x(!0);try{const U=await r(e,"workspace_set_default",E===null?{clear:!0}:{id:E});if(U!=null&&U.success){g("info",E?"Default workspace updated":"Default workspace cleared",!0);const B=typeof U.defaultWorkspacePath=="string"?U.defaultWorkspacePath:"";B&&((L=j.current)==null||L.call(j,B))}else g("error",(U==null?void 0:U.error)||"workspace_set_default failed",!0)}catch(U){g("error",U.message,!0)}finally{x(!1)}}},[e,g,r]),I=l.useCallback(async E=>{var U;if(!e||!E.trim())return;const L=E.trim();x(!0);try{const B=await r(e,"workspace_set_default",{path:L});B!=null&&B.success?(g("info","Default workspace set from history"),(U=j.current)==null||U.call(j,L)):g("error",(B==null?void 0:B.error)||"Could not set default (path missing on disk?)")}catch(B){g("error",B.message)}finally{x(!1)}},[e,g,r]),$=l.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(E){g("warn",`Live nickname updated, but account sync failed: ${E.message}`)}g("info",`Nickname set to "${y||"(cleared)"}"`),k(!1)}catch(E){g("error",`Failed: ${E.message}`)}},[e,y,t,g,n,r]);return{logs:o,launchingIde:c,launchingAgentType:m,workspaceBusy:p,launchPick:w,setLaunchPick:b,editingNickname:f,setEditingNickname:k,nicknameInput:y,setNicknameInput:h,addLog:g,handleLaunchIde:M,runLaunchCliCore:C,handleLaunchCli:N,handleStopCli:O,handleRestartIde:_,handleStopIde:T,handleDetectIdes:H,handleWorkspaceAdd:R,handleWorkspaceRemove:F,handleWorkspaceSetDefault:A,handleWorkspaceResumePath:I,handleSaveNickname:$,setOnDefaultWorkspaceChanged:v}}function Kw({machine:e,ideSessions:t,cliSessions:r,acpSessions:n}){var d;const a=typeof e.uptime=="number"||typeof e.freeMem=="number"||typeof e.availableMem=="number"||Array.isArray(e.loadavg)&&e.loadavg.length>0,o=e.availableMem??e.freeMem??e.totalMem,i=a&&e.totalMem>0?Math.min(100,Math.max(0,Math.round((e.totalMem-o)/e.totalMem*100))):0,c=((d=e.loadavg)==null?void 0:d[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(Xr,{icon:s.jsx(jc,{size:16}),label:"Uptime",value:typeof e.uptime=="number"?fp(e.uptime):"Waiting…"}),s.jsx(Xr,{icon:s.jsx(Bt,{size:16}),label:"IDEs",value:`${t.length}`}),s.jsx(Xr,{icon:s.jsx(Eo,{size:16}),label:"CLIs",value:`${r.length}`}),s.jsx(Xr,{icon:s.jsx(xh,{size:16}),label:"ACPs",value:`${n.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(Hi,{value:a?Math.min(Math.round(c/e.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:a?`${c.toFixed(2)} avg / ${e.cpus} cores`:"Polled from machine page"}),s.jsx(Hi,{value:i,max:100,label:"Memory",color:"#3b82f6",detail:a?`${fa(e.totalMem-o)} / ${fa(e.totalMem)}${e.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${fa(e.totalMem)} total`})]})]})]})}function Uw(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 zw(e,t,r){const n=[];for(const[a,o]of Object.entries(e.settings)){const i=r!=null&&r.filterSchema?r.filterSchema(o):o;if(i.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:i,values:e.values[a]||{}})}return n}function za(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 Jl(e){if(!e||typeof e!="object")return null;if(za(e))return e;const t=e,r=t.result;return za(r)?r:za(t.sourceConfig)?t.sourceConfig:null}function Gw(e){const t=e.trim();return t||null}function Vw({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var g;const o=t.filter(S=>S.category==="ide"),[i,c]=l.useState(((g=o[0])==null?void 0:g.type)||""),[d,m]=l.useState(""),[u,p]=l.useState(""),[x,w]=l.useState(!1),[b,f]=l.useState(""),[k,y]=l.useState(!1),h=S=>{const M=S.toLowerCase().replace(/[^a-z0-9-]/g,"");m(M),(!u||u===j(d))&&p(j(M))},j=S=>S.split("-").map(M=>M.charAt(0).toUpperCase()+M.slice(1)).join(" "),v=async()=>{if(!(!d||!u||!i)){w(!0),f("");try{const S=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:i});S!=null&&S.success||S!=null&&S.created?(y(!0),a==null||a(d)):f((S==null?void 0:S.error)||"Failed to create provider")}catch(S){f((S==null?void 0:S.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:S=>S.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:k?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(S=>s.jsxs("button",{onClick:()=>c(S.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:i===S.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:i===S.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:S.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:i===S.type?"#a78bfa":"var(--text-secondary)"},children:S.displayName})]},S.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:S=>h(S.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:S=>p(S.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),b&&s.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:b})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:k?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:v,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"})]})})]})})}const Ga=24,qw={verified:"Verified","declarative-only":"Declarative",extended:"Extended","extended-legacy":"Legacy"},Yw={cli:"CLI",ide:"IDE",extension:"EXT",acp:"ACP"};function Xw(){if(typeof window>"u")return"https://api.adhf.dev/api/v1/registry";const e=window.location.hostname;return window.location.port==="3847"?"https://api.adhf.dev/api/v1/registry":e==="localhost"||e==="127.0.0.1"?"/registry":e==="adhf.dev"||e==="adhdev-web.pages.dev"?"https://api.adhf.dev/api/v1/registry":"https://api-preview.adhf.dev/api/v1/registry"}function Jw({machineId:e,sendDaemonCommand:t,installedTypes:r,onInstalled:n}){const[a,o]=l.useState(!1),[i,c]=l.useState([]),[d,m]=l.useState(0),[u,p]=l.useState(!1),[x,w]=l.useState(!1),[b,f]=l.useState(null),[k,y]=l.useState("all"),[h,j]=l.useState(""),[v,g]=l.useState(""),[S,M]=l.useState("popular"),[C,N]=l.useState(0),[O,_]=l.useState(new Set),[T,H]=l.useState(null),R=l.useRef(null);l.useEffect(()=>{const L=setTimeout(()=>g(h),250);return()=>clearTimeout(L)},[h]),l.useEffect(()=>{N(0)},[k,S,v]);const F=l.useCallback(L=>{const U=Xw(),B=new URL(`${U}/providers`,window.location.origin);return k!=="all"&&B.searchParams.set("category",k),v&&B.searchParams.set("search",v),B.searchParams.set("sort",S),B.searchParams.set("limit",String(Ga)),B.searchParams.set("offset",String(L)),B.toString()},[k,v,S]);l.useEffect(()=>{if(!a)return;p(!0),f(null);let L=!1;return fetch(F(0)).then(async U=>{if(!U.ok)throw new Error(`HTTP ${U.status}`);const B=U.headers.get("content-type")||"";if(!B.includes("json"))throw new Error(`registry returned ${B||"unknown"} (expected JSON). Check that the registry endpoint is reachable from this host.`);return U.json()}).then(U=>{var B;L||(c(U.providers??[]),m(U.total??((B=U.providers)==null?void 0:B.length)??0),N(Ga))}).catch(U=>{L||f(U instanceof Error?U.message:String(U))}).finally(()=>{L||p(!1)}),()=>{L=!0}},[F,a]),l.useEffect(()=>{if(!a)return;const L=R.current;if(!L)return;const U=new IntersectionObserver(async B=>{var K;if((K=B[0])!=null&&K.isIntersecting&&!(u||x)&&!(i.length>=d)){w(!0);try{const J=await fetch(F(C));if(!J.ok)throw new Error(`HTTP ${J.status}`);const X=J.headers.get("content-type")||"";if(!X.includes("json"))throw new Error(`registry returned ${X||"unknown"}`);const ae=await J.json();c(de=>[...de,...ae.providers??[]]),m(ae.total??d),N(de=>de+Ga)}catch{}finally{w(!1)}}},{rootMargin:"200px"});return U.observe(L),()=>U.disconnect()},[a,F,C,i.length,d,u,x]);const A=l.useCallback(async L=>{var U,B;if(!O.has(L.type)){H(null),_(K=>new Set(K).add(L.type));try{const K=await t(e,"install_provider_manifest",{type:L.type});if(!((K==null?void 0:K.success)??((U=K==null?void 0:K.result)==null?void 0:U.success))){const X=(K==null?void 0:K.error)??((B=K==null?void 0:K.result)==null?void 0:B.error)??"install failed";throw new Error(X)}n==null||n()}catch(K){H({type:L.type,message:K instanceof Error?K.message:String(K)})}finally{_(K=>{const J=new Set(K);return J.delete(L.type),J})}}},[O,e,t,n]),I=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],$=[{key:"popular",label:"Popular"},{key:"newest",label:"Newest"},{key:"name",label:"Name"}],E=l.useMemo(()=>i,[i]);return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[s.jsxs("button",{onClick:()=>o(L=>!L),className:"flex items-center justify-between w-full text-left gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Add provider"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Browse the registry and install provider manifests on this daemon."})]}),s.jsx("span",{className:"text-text-muted text-xs",children:a?"▾":"▸"})]}),a&&s.jsxs("div",{className:"mt-3 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[s.jsx("div",{className:"flex gap-1 flex-wrap",children:I.map(L=>s.jsx("button",{onClick:()=>y(L.key),className:`machine-btn text-[10px] px-2 py-0.5 ${k===L.key?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:L.label},L.key))}),s.jsxs("div",{className:"flex gap-1.5 sm:ml-auto items-center",children:[s.jsx("select",{value:S,onChange:L=>M(L.target.value),className:"machine-input text-[11px]",children:$.map(L=>s.jsx("option",{value:L.key,children:L.label},L.key))}),s.jsx("input",{type:"text",placeholder:"Search…",value:h,onChange:L=>j(L.target.value),className:"machine-input text-[11px] min-w-[140px]"})]})]}),u&&s.jsx("div",{className:"text-text-muted text-[11px] py-6 text-center",children:"Loading registry…"}),!u&&b&&s.jsxs("div",{className:"rounded-xl border border-red-500/30 bg-red-500/5 px-3 py-2 text-[11px] text-red-400",children:["Failed to load registry: ",b]}),!u&&!b&&E.length===0&&s.jsx("div",{className:"text-text-muted text-[11px] py-6 text-center",children:v?`No providers matching "${v}".`:"No providers found."}),!u&&!b&&E.length>0&&s.jsx("div",{className:"grid gap-2 sm:grid-cols-2 xl:grid-cols-3",children:E.map(L=>{const U=r.has(L.type),B=O.has(L.type),K=L.manifest,J=typeof K.icon=="string"?K.icon:"📦",X=typeof K.details=="string"?K.details:"",ae=K.links??{},de=ae.docs||ae.homepage||ae.repo;return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-3 py-2.5 flex flex-col gap-2",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("span",{className:"text-base shrink-0",children:J}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[12px] font-semibold text-text-primary truncate",children:L.displayName}),X&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:X})]}),s.jsx("div",{className:"shrink-0",children:U?s.jsx("span",{className:"text-[9px] px-1.5 py-px rounded border bg-green-500/10 border-green-500/25 text-green-400 font-semibold",children:"Installed"}):s.jsx("button",{onClick:()=>void A(L),disabled:B,className:"machine-btn text-[10px] px-2 py-0.5 bg-violet-500/[0.08] border-violet-500/30 text-violet-300 hover:bg-violet-500/[0.16]",children:B?"…":"Install"})})]}),s.jsxs("div",{className:"flex flex-wrap gap-1 items-center text-[9px]",children:[s.jsx("span",{className:"px-1.5 py-px rounded border border-border-subtle text-text-muted",children:Yw[L.category]??L.category}),s.jsx("span",{className:"px-1.5 py-px rounded border border-border-subtle text-text-muted",children:qw[L.tier]??L.tier}),s.jsxs("span",{className:"text-text-muted",children:["v",L.version]}),s.jsxs("span",{className:"text-text-muted ml-auto",children:["⬇ ",(L.downloadCount??0).toLocaleString()]}),de&&s.jsx("a",{href:de,target:"_blank",rel:"noopener noreferrer",className:"text-violet-400 hover:text-violet-300 ml-1",onClick:ke=>ke.stopPropagation(),children:"↗"})]}),(T==null?void 0:T.type)===L.type&&s.jsx("div",{className:"text-[10px] text-red-400 break-all",children:T.message})]},L.id)})}),!u&&!b&&s.jsxs(s.Fragment,{children:[s.jsx("div",{ref:R,className:"h-1"}),s.jsx("div",{className:"text-[10px] text-text-muted text-center",children:x?"Loading more…":`${E.length} of ${d} provider${d!==1?"s":""}`})]})]})]})}const Qw={detected:"Detected",not_detected:"Not detected",enabled_unchecked:"Enabled (unchecked)",disabled:"Disabled"},Ql={detected:"bg-green-500/[0.10] border-green-500/25 text-green-400",not_detected:"bg-red-500/[0.10] border-red-500/25 text-red-400",enabled_unchecked:"bg-yellow-500/[0.10] border-yellow-500/25 text-yellow-400",disabled:"bg-white/[0.04] border-white/[0.10] text-text-muted"},Zw={acp:"bg-violet-500/10 text-violet-300 border-violet-500/20",cli:"bg-blue-500/10 text-blue-300 border-blue-500/20",ide:"bg-green-500/10 text-green-300 border-green-500/20",extension:"bg-yellow-500/10 text-yellow-300 border-yellow-500/20"};function Zl(e){if(!e)return"—";const t=e.ok?"OK":"Failed",r=e.message||e.path||e.command||"";return r?`${t} — ${r}`:t}function ej(e){return e==="cli"||e==="acp"}function tj({prov:e,providerInfo:t,savingKey:r,onSetSetting:n,onEnableToggle:a,onDetect:o,onResetCommand:i,onUninstall:c}){const[d,m]=l.useState(!1),u=(t==null?void 0:t.enabled)===!0||e.values.enabled===!0,p=t==null?void 0:t.machineStatus,x=u&&p==="disabled"?"enabled_unchecked":p||(u?"enabled_unchecked":"disabled"),w=ej(e.category);return s.jsxs("div",{className:"rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("button",{onClick:()=>m(b=>!b),className:"w-full px-4 py-2.5 flex items-center gap-3 text-left",children:[s.jsx("span",{className:"text-base shrink-0",children:e.icon}),s.jsx("span",{className:"text-[13px] font-semibold text-text-primary truncate",children:e.displayName}),s.jsx("span",{className:`text-[9px] font-semibold px-1.5 py-px rounded border ${Zw[e.category]??"border-border-subtle text-text-muted"}`,children:e.category.toUpperCase()}),w&&s.jsx("span",{className:`text-[9px] font-semibold px-1.5 py-px rounded border ${Ql[x]??Ql.disabled}`,children:Qw[x]??x}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[w&&s.jsx("button",{onClick:b=>{b.stopPropagation(),a(e.type,!u)},disabled:r===`${e.type}.enabled`,className:`machine-btn text-[10px] px-2 py-0.5 ${u?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:u?"Disable":"Enable"}),s.jsx("span",{className:"text-text-muted text-xs",children:d?"▾":"▸"})]})]}),d&&s.jsxs("div",{className:"border-t border-border-subtle px-4 py-3 flex flex-col gap-3",children:[w&&s.jsxs("div",{className:"grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Detection:"})," ",Zl(t==null?void 0:t.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Verification:"})," ",Zl(t==null?void 0:t.lastVerification)]})]}),e.schema.length>0&&s.jsx("div",{className:"flex flex-col gap-1.5",children:e.schema.map(b=>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-[11px] font-medium text-text-primary",children:[b.label||b.key,r===`${e.type}.${b.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving…"})]}),b.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:b.description})]}),s.jsx("div",{className:"shrink-0",children:b.type==="boolean"?s.jsx("button",{onClick:()=>void n(e.type,b.key,!(e.values[b.key]??b.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:e.values[b.key]??b.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[b.key]??b.default?21:3}})}):b.type==="number"?s.jsx("input",{type:"number",value:Number(e.values[b.key]??b.default??0)||0,min:b.min,max:b.max,onChange:f=>{const k=parseInt(f.target.value)||0;b.min!==void 0&&k<b.min||b.max!==void 0&&k>b.max||n(e.type,b.key,k)},className:"machine-input w-20 text-center text-[11px]"}):b.type==="select"&&b.options?s.jsx("select",{value:String(e.values[b.key]??b.default??""),onChange:f=>void n(e.type,b.key,f.target.value),className:"machine-input text-[11px]",children:b.options.map(f=>s.jsx("option",{value:f,children:f},f))}):s.jsx("input",{type:"text",defaultValue:String(e.values[b.key]??b.default??""),onBlur:f=>void n(e.type,b.key,f.target.value),className:"machine-input w-[180px] text-[11px]"})})]},b.key))}),s.jsxs("div",{className:"flex gap-1.5 flex-wrap pt-1 border-t border-border-subtle",children:[w&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>void o(e.type),disabled:!u||r===`${e.type}.detect`,className:`machine-btn text-[10px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${u?"":"opacity-40 cursor-not-allowed"}`,title:u?"Run detection for the configured executable":"Enable provider before detection",children:"Detect"}),s.jsx("button",{onClick:()=>void i(e.type),className:"machine-btn text-[10px] px-2 py-0.5",children:"Reset command"})]}),s.jsx("button",{onClick:()=>void c(e.type,e.category),className:"machine-btn text-[10px] px-2 py-0.5 text-red-400 border-red-500/25 ml-auto",title:"Remove manifest from ~/.adhdev/marketplace/",children:"Uninstall"})]})]})]})}function sj({machineId:e,providers:t,sendDaemonCommand:r}){var A;const[n,a]=l.useState([]),[o,i]=l.useState(!1),[c,d]=l.useState(null),[m,u]=l.useState("all"),[p,x]=l.useState(!1),[w,b]=l.useState(!1),[f,k]=l.useState(null),[y,h]=l.useState("normal"),[j,v]=l.useState(""),[g,S]=l.useState(!1),M=l.useCallback(async()=>{if(e)try{const I=await r(e,"get_provider_source_config",{}),$=Jl(I);$&&(k($),h($.sourceMode),v($.explicitProviderDir||""))}catch{}},[e,r]),C=l.useCallback(async()=>{if(e){i(!0);try{const I=await r(e,"get_provider_settings",{}),$=Uw(I);if($){const E=zw($,t,{filterSchema:L=>L.filter(U=>U.key!=="enabled")});E.sort((L,U)=>L.category.localeCompare(U.category)||L.displayName.localeCompare(U.displayName)),a(E)}}catch{}i(!1)}},[e,t,r]);l.useEffect(()=>{n.length===0&&C(),f||M()},[]);const N=async(I,$,E)=>{d(`${I}.${$}`),a(L=>L.map(U=>U.type===I?{...U,values:{...U.values,[$]:E}}:U));try{const L=await r(e,"set_provider_setting",{providerType:I,key:$,value:E});L!=null&&L.success||C()}catch{C()}d(null)},O=async(I,$)=>{await N(I,"enabled",$),await C()},_=async I=>{d(`${I}.detect`);try{await r(e,"detect_provider",{providerType:I})}finally{await C(),d(null)}},T=async I=>{await N(I,"executablePath",""),await N(I,"executableArgs",""),await C()},H=async(I,$)=>{if(confirm(`Uninstall ${I}? This removes the manifest from ~/.adhdev/marketplace/.`))try{await r(e,"uninstall_provider_manifest",{type:I,category:$})}finally{await C()}},R=async()=>{S(!0);try{const I=await r(e,"set_provider_source_config",{providerSourceMode:y,providerDir:Gw(j)}),$=Jl(I);$?(k($),h($.sourceMode),v($.explicitProviderDir||"")):await M(),await C()}catch{await M()}S(!1)},F=n.filter(I=>m==="all"||I.category===m);return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Jw,{machineId:e,sendDaemonCommand:r,installedTypes:new Set(n.map(I=>I.type)),onInstalled:()=>{C()}}),s.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",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(I=>s.jsx("button",{onClick:()=>u(I),className:`machine-btn text-[10px] px-2 py-0.5 ${m===I?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:I.toUpperCase()},I))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>x(!0),className:"machine-btn text-[10px]",title:"Create a new provider from an existing one",children:"✨ Create"}),s.jsxs("button",{onClick:C,disabled:o,className:"machine-btn text-[10px]",children:[o?"⏳":"↻"," Refresh"]}),s.jsx("button",{onClick:()=>b(I=>!I),className:"machine-btn text-[10px]",title:"Show source configuration (advanced)",children:"⚙ Advanced"})]})]}),w&&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 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:"Where the daemon looks for provider manifests. Affects resolution and reloads."})]}),s.jsx("button",{onClick:M,className:"machine-btn text-[10px]",children:"↻ Refresh"})]}),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:I=>h(I.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:j,onChange:I=>v(I.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void R(),disabled:g,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:g?"Applying…":"Apply + Reload"})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"User root:"})," ",(f==null?void 0:f.userDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Upstream root:"})," ",(f==null?void 0:f.upstreamDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Provider roots:"})," ",((A=f==null?void 0:f.providerRoots)==null?void 0:A.join(" → "))||"—"]})]})]}),o&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings…"}):F.length===0?s.jsx("div",{className:"px-4.5 py-8 rounded-xl border border-border-subtle bg-bg-secondary text-center",children:s.jsx("div",{className:"text-[12px] text-text-muted",children:m==="all"?'No providers installed yet. Open "Add provider" above to install one.':`No ${m.toUpperCase()} providers installed.`})}):s.jsx("div",{className:"flex flex-col gap-1.5",children:F.map(I=>s.jsx(tj,{prov:I,providerInfo:t.find($=>$.type===I.type),savingKey:c,onSetSetting:N,onEnableToggle:O,onDetect:_,onResetCommand:T,onUninstall:H},I.type))}),p&&s.jsx(Vw,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>x(!1),onCreated:()=>{x(!1),C()}})]})}const rj=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function nj({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function aj(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function oj(e){return e.trim().toLowerCase()}function ia(e,t){const r=oj(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function gi(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Hs(e,t=220){const r=gi(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function ij(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 lj(e,t){return e.filter(r=>ia([r.level,r.message],t))}function ec(e){return`${e.timestamp}:${e.level}:${e.message}`}function cj(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const i of e.entries)n.set(ec(i),i);for(const i of t.entries)n.set(ec(i),i);const a=Array.from(n.values()).sort((i,c)=>i.timestamp-c.timestamp).slice(-r),o=a.reduce((i,c)=>Math.max(i,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 dj(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 uj(e,t){return e.split(`
77
+ `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>ia([r],t))}function mj(e,t){return e.filter(r=>ia([r.level,r.category,r.stage,r.interactionId,gi(r.payload)],t))}function hj(e,t){return e.filter(r=>ia([r.kind,r.topic,r.interactionId,gi(r.payload)],t))}function tc(e){return e==="warn"||e==="error"}function pj({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=>tc(a.level)).length+r.filter(a=>tc(a.level)).length}}function fj({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(`
78
+ `)):t.length>0&&a.push(["[daemon logs]",...t].join(`
79
+ `)),r.length>0&&a.push(["[trace]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${Hs(o.payload,500)}`.trim())].join(`
80
+ `)),n.length>0&&a.push(["[browser events]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${Hs(o.payload,500)}`.trim())].join(`
81
+ `)),a.join(`
82
+
83
+ `)}function xj({machineId:e,sendDaemonCommand:t}){const[r,n]=l.useState([]),[a,o]=l.useState("empty"),[i,c]=l.useState(""),[d,m]=l.useState([]),[u,p]=l.useState([]),[x,w]=l.useState(null),[b,f]=l.useState(!0),[k,y]=l.useState("info"),[h,j]=l.useState("all"),[v,g]=l.useState(!0),[S,M]=l.useState(!0),[C,N]=l.useState(""),[O,_]=l.useState(""),[T,H]=l.useState(0),R=l.useRef(0),F=l.useRef(0),A=l.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),I=l.useRef([]),$=l.useCallback(()=>{const X={entries:[],kind:"empty",rawText:"",lastTs:0};A.current=X,R.current=0,n([]),c(""),o("empty"),g(!0)},[]),E=l.useCallback(()=>{I.current=[],F.current=0,m([]),M(!0)},[]),L=l.useCallback(X=>{X!==k&&($(),y(X))},[k,$]),U=l.useCallback(X=>{j(ae=>ae===X?ae:X)},[]),B=l.useCallback(()=>{$(),E(),p([]),w(null),N(""),_(""),Ds.clear()},[$,E]),K=l.useCallback(()=>{H(X=>X+1)},[]),J=l.useCallback(async()=>{if(!e)return;const X=R.current,ae=F.current,[de,ke]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:k,since:X}),t(e,"get_debug_trace",nj({count:120,since:ae,category:h}))]);if(de.status==="fulfilled"){const q=de.value,ve=(q==null?void 0:q.result)||q,be=ij(ve),we=cj(A.current,be,300);A.current=we,R.current=we.lastTs,g(!1),N((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 g(!1),N(de.reason instanceof Error?de.reason.message:"Could not load daemon logs");if(ke.status==="fulfilled"){const q=ke.value,ve=(q==null?void 0:q.result)||q;if((q==null?void 0:q.success)===!1)_(String((q==null?void 0:q.error)||"Could not load daemon trace"));else if(Array.isArray(ve==null?void 0:ve.trace)){const be=ve.trace,we=dj(I.current,be,120),xe=be.reduce((Ce,Q)=>Math.max(Ce,Number(Q.ts||0)),ae);I.current=we,xe>ae&&(F.current=xe),_(""),m(we)}else _("");M(!1)}else M(!1),_(ke.reason instanceof Error?ke.reason.message:"Could not load daemon trace");p(Ds.list({limit:120})),w(Date.now())},[k,e,t,h]);return l.useEffect(()=>{E()},[E,h]),l.useEffect(()=>{if(!e||(J(),!b))return;const X=setInterval(()=>{J()},3e3);return()=>clearInterval(X)},[b,J,e,T]),{daemonLogs:r,daemonLogKind:a,daemonRawText:i,debugTrace:d,webEvents:u,lastUpdatedAt:x,autoRefresh:b,logLevel:k,traceCategory:h,daemonLoading:v,traceLoading:S,daemonFetchError:C,traceFetchError:O,setAutoRefresh:f,setLogLevel:L,setTraceCategory:U,refresh:K,clear:B}}function bj({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:i,traceCount:c,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":o>0||i>0?"ok":"empty",detail:r||(a==="text"?`${i} 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 sc(e){return e==="warn"||e==="error"}function gj(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 yj(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 rc(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function vj(e){const t=Hs(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function wj(e){const t=Hs(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function jj({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.forEach((o,i)=>{a.push({id:`daemon-log-${o.timestamp}-${i}`,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:wj(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:vj(o),category:o.category,stage:o.stage,interactionId:o.interactionId,payload:o.payload})}),t.forEach((o,i)=>{a.push({id:`raw-file-${i}`,source:"raw_file",ts:yj(o,i),severity:gj(o),message:o,raw:o})}),a.sort((o,i)=>o.ts!==i.ts?o.ts-i.ts:rc(o.source)-rc(i.source))}function kj(e){return`${e.source}:${e.severity}:${e.message}`}function Sj(e){const t=e.filter(n=>sc(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!sc(n.severity))continue;const a=kj(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 Nj(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function nc(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${Nj(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function Cj({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
84
+ `)),a.push(["[source status]",...r.map(i=>`${i.label}: ${i.status} - ${i.detail}`)].join(`
85
+ `)),t.latestIssue&&a.push(["[latest issue]",nc(t.latestIssue)].join(`
86
+ `)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(i=>`${i.count}x ${i.severity.toUpperCase()} ${i.source} ${i.message}`)].join(`
87
+ `));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(nc):["No diagnostic events captured."]].join(`
88
+ `)),a.join(`
89
+
90
+ `)}function Mj(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Ij(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Tj({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:i,searchQuery:c,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:p}){const x=aj(n,o),w=lj(e,c),b=uj(t,c),f=mj(x,c),k=hj(a,c),y=Mj(w,i),h=i==="all"?b:[],j=Ij(f,i),v=i==="issues"?[]:k,g=pj({daemonLogs:w,daemonRawLines:b,trace:f,webEvents:k}),S=jj({daemonLogs:y,daemonRawLines:h,trace:j,webEvents:v}),M=Sj(S),C=bj({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:p,daemonLogKind:r,daemonLogsCount:w.length,daemonRawLineCount:b.length,traceCount:f.length,webEventCount:k.length});return{filteredDaemonLogs:w,filteredDaemonRawLines:b,filteredTraceEntries:f,filteredWebEvents:k,visibleDaemonLogs:y,visibleDaemonRawLines:h,visibleTraceEntries:j,visibleWebEvents:v,quickFilterCounts:g,diagnosticEvents:S,diagnosticsSummary:M,sourceStates:C}}function Aj(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Hu(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Mo(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 Va(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 yi(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function _j({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Mo(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Hu(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:yi(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 Lj({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:i,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:i,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 Pj({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:rj.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 Rj({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:i,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=i||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 ${Va(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 ${Va(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:[yi(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:Hu(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 ${Va(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:i||c?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",Aj(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 Dj({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()," · ",yi(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function Ej({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:i,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(_j,{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 ${Mo(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:[i.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&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&i.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&i.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."}),i.map(u=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Mo(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:Hs(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:Hs(u.payload,360)||"No payload"})]},u.id))]})]})]})}function $j({machineId:e,sendDaemonCommand:t}){const r=xj({machineId:e,sendDaemonCommand:t}),[n,a]=l.useState("info"),[o,i]=l.useState(""),[c,d]=l.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=l.useRef(null),u=l.useRef(!1),p=l.useMemo(()=>Tj({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]);l.useEffect(()=>{if(r.autoRefresh&&p.diagnosticEvents.length>0){const b=u.current?"smooth":"instant";setTimeout(()=>{var f;(f=m.current)==null||f.scrollIntoView({behavior:b}),u.current=!0},50)}},[p.diagnosticEvents.length,r.autoRefresh]);const x=l.useCallback(async()=>{var f;const b=fj({daemonLogs:p.visibleDaemonLogs,daemonRawLines:p.visibleDaemonRawLines,trace:p.visibleTraceEntries,webEvents:p.visibleWebEvents});if(!b.trim()){Je.showToast("No visible logs to copy.","info");return}try{await((f=navigator.clipboard)==null?void 0:f.writeText(b)),Je.showToast("Copied visible logs to clipboard.","success")}catch(k){Je.showToast(k instanceof Error?k.message:"Could not copy visible logs","warning")}},[p.visibleDaemonLogs,p.visibleDaemonRawLines,p.visibleTraceEntries,p.visibleWebEvents]),w=l.useCallback(async()=>{var f;const b=Cj({events:p.diagnosticEvents,summary:p.diagnosticsSummary,sources:p.sourceStates});try{await((f=navigator.clipboard)==null?void 0:f.writeText(b)),Je.showToast("Copied diagnostic bundle to clipboard.","success")}catch(k){Je.showToast(k instanceof Error?k.message:"Could not copy diagnostic bundle","warning")}},[p.diagnosticEvents,p.diagnosticsSummary,p.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(Lj,{quickFilter:n,quickFilterCounts:p.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:()=>{w()},onCopyVisible:()=>{x()},onToggleAutoRefresh:()=>r.setAutoRefresh(b=>!b),onRefresh:r.refresh,onClear:r.clear}),s.jsx(Pj,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(Rj,{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(Dj,{patterns:p.diagnosticsSummary.repeatedPatterns}),s.jsx(Ej,{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 Bj(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 Wu(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 Oj(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=Wu((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(i)?t.push(o):(i==="stopped"||i==="failed")&&(d||c)?r.push(o):n.push(o)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function Fj(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function qa(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 Ya(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Xa(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function ac(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 Hj(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Wj(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 Kj(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 Uj({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=l.useState(""),[o,i]=l.useState(null),[c,d]=l.useState(!1),m=Zb(e,{enabled:!!e,includeSessions:!0,limit:rl,intervalMs:Df}),u=m.diagnostics,p=m.loading,x=m.applyDiagnostics,w=l.useMemo(()=>Bj({diagnostics:u,loading:p,refreshing:c,error:n}),[u,p,c,n]),b=l.useMemo(()=>new Map(t.map(_=>[_.sessionId||_.id,_])),[t]),f=l.useCallback(async()=>{if(e){d(!0);try{const _=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:rl}),T=Ya(_);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Could not load hosted runtime diagnostics");x(T.diagnostics||T.result||null),a("")}catch(_){const T=_ instanceof Error?_.message:"Could not load hosted runtime diagnostics";a(T)}finally{d(!1)}}},[x,e,r]);l.useEffect(()=>{!e||u||p||c||f()},[u,p,e,f,c]);const k=l.useCallback(async(_,T)=>{const H=`${_}:${T.sessionId}`;if(!(_==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
91
+ This will terminate the hosted runtime.`))){i(H);try{const R=await r(e,_,{sessionId:T.sessionId}),F=Ya(R);if(!(F!=null&&F.success))throw new Error((F==null?void 0:F.error)||"Session host action failed");const A=_==="session_host_resume_session"?"resumed":_==="session_host_restart_session"?"restarted":"stopped";Je.showToast(`Session host ${A}: ${T.displayName}`,"success"),await f()}catch(R){const F=R instanceof Error?R.message:"Session host action failed";Je.showToast(F,"warning"),a(F)}finally{i(R=>R===H?null:R)}}},[e,f,r]),y=l.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
92
+ The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const T=await r(e,"session_host_prune_duplicate_sessions",{}),H=Ya(T);if(!(H!=null&&H.success))throw new Error((H==null?void 0:H.error)||"Duplicate prune failed");const R=H.result||{},F=Array.isArray(R.prunedSessionIds)?R.prunedSessionIds.length:0,A=typeof R.duplicateGroupCount=="number"?R.duplicateGroupCount:0;Je.showToast(`Pruned ${F} duplicate runtime(s) across ${A} group(s)`,"success"),await f()}catch(T){const H=T instanceof Error?T.message:"Duplicate prune failed";Je.showToast(H,"warning"),a(H)}finally{i(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,f,r]),h=l.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((_,T)=>(T.lastActivityAt||0)-(_.lastActivityAt||0)),[u==null?void 0:u.sessions]),j=l.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)||[]}:Oj(h),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,h]),v=j.liveRuntimes,g=j.recoverySnapshots,S=j.inactiveRecords,M=l.useMemo(()=>Kj(v),[v]),C=l.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),N=l.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(_=>_.level==="warn"||_.level==="error")||null,[u==null?void 0:u.recentLogs]),O=(_,T)=>{var U;const H=o===`session_host_resume_session:${_.sessionId}`,R=o===`session_host_restart_session:${_.sessionId}`,F=o===`session_host_stop_session:${_.sessionId}`,A=Wu(_.meta),I=b.get(_.sessionId),$=_.attachedClients.length===1?"1 client":`${_.attachedClients.length} clients`,E=T==="recovery"?"Recover":"Resume",L=Fj(T);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:_.displayName||(I==null?void 0:I.cliName)||_.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Wj(_.lifecycle)}`,children:_.lifecycle}),A&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:A})]}),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:_.workspaceLabel||(I==null?void 0:I.runtimeWorkspaceLabel)||_.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:_.runtimeKey}),_.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",_.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((U=_.writeOwner)==null?void 0:U.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Hj(_.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(gc,{size:11})," ",$]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",ac(_.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",L]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[T==="recovery"&&(_.lifecycle==="interrupted"||_.lifecycle==="failed"||_.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{k("session_host_resume_session",_)},children:H?`${E}ing…`:E}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{k("session_host_restart_session",_)},children:R?"Restarting…":"Restart"}),T==="live"&&(_.lifecycle==="running"||_.lifecycle==="starting"||_.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:()=>{k("session_host_stop_session",_)},children:F?"Stopping…":"Stop"})]})]})},_.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(es,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Qx()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[M>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 (${M})`}),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:()=>{f()},disabled:p||c,children:[s.jsx(Zn,{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(jr,{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:g.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:ac(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Xa(u.hostStartedAt)})]})]}),N&&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(jr,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:N.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Xa(N.timestamp),N.sessionId?` · ${N.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(Eo,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:qa("live")}),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 live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:v.map(_=>O(_,"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(es,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:qa("recovery")}),g.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:g.map(_=>O(_,"recovery"))})]}),S.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:qa("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:S.map(_=>O(_,"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"}),C.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:C.map(_=>{var H;const T=h.find(R=>R.sessionId===_.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:(T==null?void 0:T.displayName)||((H=b.get(_.sessionId))==null?void 0:H.cliName)||_.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[_.action,_.lifecycle?` · ${_.lifecycle}`:"",_.detail?` · ${_.detail}`:"",_.error?` · ${_.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${_.success===!1?"text-red-300":"text-text-secondary"}`,children:Xa(_.timestamp)})]},`${_.sessionId}:${_.timestamp}:${_.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 zj({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 Gj(e,t){const r=Gd(e),n=Ts(e,t),a=Qo(e,n),o=br(e,n),i=r==="preview"?"Update to preview":"Update daemon";return a?{visible:!0,showButton:!0,title:o?"Daemon update required":"Version mismatch detected",description:o?"This machine is on an incompatible daemon version. Update it before starting more sessions.":r==="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.",buttonLabel:i,targetVersion:n,channel:r,required:o,tone:"warn"}:r==="preview"?{visible:!0,showButton:!1,title:n?"Preview daemon is up to date":"Preview update status unknown",description:n?"This machine is already on the current preview daemon target.":"The app is connected to preview, but the server did not report a preview target version yet.",buttonLabel:i,targetVersion:n,channel:r,required:!1,tone:n?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:i,targetVersion:n,channel:r,required:!1,tone:"info"}}function Ja({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 Qa({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 Vj({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:i}){const c=n.slice(0,6),d=r.slice(0,4),u=Gj(e,"0.9.81");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(Ja,{icon:s.jsx(ws,{size:13}),children:"Current Chats"}),s.jsx(Qa,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(p=>{const x=So(p);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:()=>i(p),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:nt(p)}),x>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:ea(x)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ys(p)})]},p.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ja,{icon:s.jsx(jc,{size:13}),children:"Recent Launches"}),s.jsx(Qa,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(p=>{const{metaText:x,updatedLabel:w}=ou(p);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(p),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:p.label}),w&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:w})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:x})]},p.id)})})})]}),u.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ja,{icon:s.jsx(jr,{size:13}),children:"Daemon Update"}),s.jsx(Qa,{className:u.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":u.tone==="info"?"border-sky-500/20 bg-sky-500/5":"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:u.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[u.description,u.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",u.targetVersion,u.channel?` (${u.channel})`:""]})]}),u.showButton?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(Zn,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:u.buttonLabel})]}):s.jsx("div",{className:u.tone==="good"?"text-xs font-medium text-emerald-300":"text-xs font-medium text-sky-300",children:"No preview update action is needed."})]})})]})]})}function qj({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:m,handleWorkspaceSetDefault:u}=o,[p,x]=l.useState(!1),[w,b]=l.useState(""),[f,k]=l.useState([]),[y,h]=l.useState(!1),[j,v]=l.useState(""),g=l.useCallback(async M=>{h(!0),v("");try{const C=await oi(i,e,M);b(C.path),k(C.directories)}catch(C){v(C instanceof Error?C.message:"Could not load folder")}finally{h(!1)}},[e,i]),S=l.useCallback(()=>{x(!0);const M=[...r.map(N=>N.workspace),...n.map(N=>N.workspace),...a.map(N=>N.workspace)],C=ai(t.platform,ni(M,t.defaultWorkspacePath,(t.workspaces||[]).map(N=>N.path)));g(C)},[a,n,r,g,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-4 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",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx($s,{size:14})," Workspaces"]}),s.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick:S,children:"+ Add workspace"})]}),(t.workspaces||[]).length===0?s.jsxs("div",{className:"text-[11px] text-text-muted py-4 text-center",children:["No saved workspaces yet. Click ",s.jsx("span",{className:"text-text-secondary",children:"+ Add workspace"})," to pick a folder."]}):s.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(M=>{const C=M.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${C?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:C?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void u(C?null:M.id),className:`text-base leading-none shrink-0 transition-colors ${C?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary truncate",children:Ec(M.path,M.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:M.path,children:M.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void m(M.id),children:"Remove"})]},M.id)})})]}),p&&s.jsx(li,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:w,directories:f,busy:y,error:j,confirmLabel:"Add workspace",onClose:()=>x(!1),onNavigate:M=>{g(M)},onConfirm:M=>{(async()=>{if(!M)return;await d(M)&&x(!1)})()}})]})}function Yj({machine:e,machineId:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i}){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:"Workspaces"}),s.jsx("div",{className:"text-sm text-text-secondary",children:'Save folders as workspaces on this machine. Use the dashboard "+" button to launch a session.'})]}),i&&s.jsx(qj,{machineId:t,machine:e,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function Xj({onNicknameSynced:e}={}){var Ce,Q,ge,ce,ye,me,fe,le,pe,oe;const{id:t}=Em(),r=Ir(),n=_o(),{sendCommand:a}=lt(),o=Lr(),i=Ld(),c=ld(),d=c.ides||[],m=c.initialLoaded??!0,u=d.find(P=>P.id===t&&P.type==="adhdev-daemon"),p=d.some(P=>P.type==="adhdev-daemon"),x=t?(Ce=c.connectionRetryStatuses)==null?void 0:Ce[t]:void 0,w=!!(x!=null&&x.blocked),[b,f]=l.useState("workspace"),[k,y]=l.useState(null);l.useCallback((P,ue)=>{y({daemonId:P,workspace:ue})},[]);const[,h]=l.useState("ide"),j=l.useRef(null),[v,g]=l.useState(null),S=l.useRef("__home__"),[M,C]=l.useState("__home__"),[N,O]=l.useState(!1),_=l.useRef(null);l.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||o(t,{minFreshMs:3e4}).catch(()=>{})},[o,u,t]),l.useEffect(()=>{if(!t||!u||b!=="overview")return;const P=u.machine;(typeof(P==null?void 0:P.cpus)!="number"||typeof(P==null?void 0:P.totalMem)!="number"||typeof(P==null?void 0:P.arch)!="string"||typeof(P==null?void 0:P.release)!="string")&&i(t,{minFreshMs:3e4}).catch(()=>{})},[b,i,u,t]),Qb(t&&b==="overview"?[t]:[],{enabled:b==="overview",intervalMs:_f});const T=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},H=Ww({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:_});l.useEffect(()=>Je.onToast(ue=>{c.setToasts(Ie=>{if(Ie.some(De=>De.message===ue.message&&ue.timestamp-De.timestamp<3e3))return Ie;const Ne={id:ue.id,message:ue.message,type:ue.type,timestamp:ue.timestamp,targetKey:ue.targetKey,actions:ue.actions};return[...Ie.slice(-4),Ne]});const Se=ue.duration||5e3;setTimeout(()=>c.setToasts(Ie=>Ie.filter(te=>te.id!==ue.id)),Se)}),[c]);const R=(u==null?void 0:u.availableProviders)||[],F={};for(const P of R)F[P.type]=P.icon;const A=u?{id:u.id,hostname:$c(u,{fallbackId:u.id}),platform:((Q=u.machine)==null?void 0:Q.platform)||"unknown",arch:((ge=u.machine)==null?void 0:ge.arch)||"",cpus:((ce=u.machine)==null?void 0:ce.cpus)||0,totalMem:((ye=u.machine)==null?void 0:ye.totalMem)||0,freeMem:(me=u.machine)==null?void 0:me.freeMem,availableMem:(fe=u.machine)==null?void 0:fe.availableMem,loadavg:(le=u.machine)==null?void 0:le.loadavg,uptime:(pe=u.machine)==null?void 0:pe.uptime,release:((oe=u.machine)==null?void 0:oe.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,I=d.filter(P=>P.daemonId===t&&P.type!=="adhdev-daemon").filter(P=>!kr(P)&&!Ls(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,version:P.version||"",instanceId:P.instanceId||"",status:P.status,workspace:P.workspace||null,terminals:P.terminals||0,aiAgents:kp(P.aiAgents||(P.agents||[]).map(ue=>({id:ue.name,name:ue.name,status:ue.status,version:ue.version}))),activeChat:P.activeChat||null,chats:P.chats||[],childSessions:P.childSessions||[],cdpConnected:P.cdpConnected||!1,daemonId:t,lastMessageAt:P.lastMessageAt})),$=d.filter(P=>P.daemonId===t&&kr(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,cliName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,mode:P.mode,runtimeKey:P.runtimeKey,runtimeDisplayName:P.runtimeDisplayName,runtimeWorkspaceLabel:P.runtimeWorkspaceLabel,runtimeWriteOwner:P.runtimeWriteOwner||null,runtimeAttachedClients:P.runtimeAttachedClients||[],daemonId:t,lastMessageAt:P.lastMessageAt})),E=d.filter(P=>P.daemonId===t&&Ls(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,acpName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,daemonId:t,lastMessageAt:P.lastMessageAt})),L=u?Ct(u,{fallbackId:t}):"",U="workspace",B=n.state,K=B==null?void 0:B.initialMachineTab,J=B==null?void 0:B.initialWorkspaceCategory;B==null||B.initialWorkspaceId,B==null||B.initialWorkspacePath;const X=K==="ides"||K==="clis"||K==="acps"?"workspace":K||U,ae=K==="ides"?"ide":K==="clis"?"cli":K==="acps"?"acp":J,de=[...I.map(P=>{var ue;return{id:`ide:${P.type}:${P.workspace||""}`,label:((ue=P.activeChat)==null?void 0:ue.title)||P.type,kind:"ide",providerType:P.type,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:P.lastMessageAt||0}}),...$.map(P=>{var ue;return{id:`cli:${P.type}:${P.workspace||""}`,label:((ue=P.activeChat)==null?void 0:ue.title)||P.cliName,kind:"cli",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:P.lastMessageAt||0}}),...E.map(P=>{var ue;return{id:`acp:${P.type}:${P.workspace||""}`,label:((ue=P.activeChat)==null?void 0:ue.title)||P.acpName,kind:"acp",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:gs(P.summaryMetadata)||P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:P.lastMessageAt||0}})].sort((P,ue)=>(ue.lastLaunchedAt||0)-(P.lastLaunchedAt||0)),ke=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(P=>({id:P.id,label:P.title||P.providerName||P.providerType,kind:P.kind,providerType:P.providerType,providerSessionId:P.providerSessionId,subtitle:gs(P.summaryMetadata)||P.workspace||void 0,workspace:P.workspace,summaryMetadata:P.summaryMetadata,lastLaunchedAt:P.lastLaunchedAt})):de,q=l.useMemo(()=>{var ue;const P=((ue=c.connectionStates)==null?void 0:ue[t||""])||void 0;return d.filter(Se=>Se.daemonId===t&&Se.type!=="adhdev-daemon").flatMap(Se=>Jo(Se,{connectionStates:t&&P?{[t]:P}:void 0,defaultConnectionState:P})).filter(Se=>!(Se.transport==="pty"&&Se.mode==="terminal")).sort((Se,Ie)=>So(Ie)-So(Se))},[d,c.connectionStates,t]),ve=l.useCallback(P=>{const ue=Jd(P);ue&&r(Nr(ue))},[r]),be=l.useCallback(()=>{j.current&&(O(!0),j.current().finally(()=>{j.current=null,O(!1),g(null)}))},[]),we=l.useCallback(P=>{if(!A)return;const{options:ue,selectedKey:Se}=au({machine:A,currentWorkspacePath:P.workspace}),Ie=async()=>{h(P.kind),f("workspace")};j.current=async()=>{const te=ue.find(Ee=>Ee.key===S.current),Ne=(te==null?void 0:te.workspacePath)??null,De=(te==null?void 0:te.workspaceId)??null;if(P.kind==="ide"&&P.providerType){await H.handleLaunchIde(P.providerType,Ne?{workspace:Ne}:void 0);return}if((P.kind==="cli"||P.kind==="acp")&&P.providerType){await H.runLaunchCliCore({cliType:P.providerType,dir:De?void 0:Ne||"",workspaceId:De||void 0,model:P.kind==="acp"&&Oc(P.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:P.providerSessionId});return}await Ie()},S.current=Se,C(Se),g({title:P.kind==="ide"?Fn("restart-ide",P.label):P.providerSessionId?bd(P.label):Fn("start-fresh",P.label),description:P.kind==="ide"?Hn("restart-ide"):P.providerSessionId?gd():Hn("start-fresh"),confirmLabel:P.kind==="ide"?Wn("restart-ide"):P.providerSessionId?On(!0):Wn("start-fresh"),busyLabel:P.kind==="ide"?Kn("restart-ide"):P.providerSessionId?Yo(!0):Kn("start-fresh"),workspaceOptions:ue,details:[{label:"Mode",value:P.kind.toUpperCase()},...P.providerType?[{label:"Provider",value:P.providerType}]:[]]})},[H,A]);if(l.useEffect(()=>{f(X)},[U,X,t]),l.useEffect(()=>{ae&&h(ae)},[ae,t]),!A)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:T,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 xe=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Bt,{size:14})," Workspace"]}),count:I.length+$.length+E.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(es,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Qn,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(hh,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(dh,{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:T,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:[H.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:H.nicknameInput,onChange:P=>H.setNicknameInput(P.target.value),onKeyDown:P=>{P.key==="Enter"&&H.handleSaveNickname(),P.key==="Escape"&&H.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:H.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:()=>H.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:()=>{H.setEditingNickname(!0),H.setNicknameInput(A.machineNickname||"")},title:"Click to set nickname",children:L}),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:[A.platform," · ",A.arch]}),s.jsxs("span",{children:[A.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),A.p2p.available&&s.jsxs("span",{children:["P2P ",A.p2p.state==="connected"?"connected":A.p2p.state]}),A.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:A.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:xe.map(P=>s.jsxs("button",{onClick:()=>f(P.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${b===P.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[P.label,P.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${b===P.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:P.count})]},P.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[b==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(Vj,{machineEntry:u,providers:R,recentLaunches:ke,currentConversations:q,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",Vd(u))}catch{}},onOpenRecent:we,onOpenConversation:ve}),s.jsx(Yj,{machine:A,machineId:t,ideSessions:I,cliSessions:$,acpSessions:E,actions:H,sendDaemonCommand:a})]}),b==="providers"&&s.jsx(sj,{machineId:t,providers:R,sendDaemonCommand:a}),b==="overview"&&s.jsx(Kw,{machine:A,ideSessions:I,cliSessions:$,acpSessions:E}),b==="session-host"&&s.jsx(Uj,{machineId:t,cliSessions:$,sendDaemonCommand:a}),b==="logs"&&s.jsx($j,{machineId:t,sendDaemonCommand:a})]})})}),H.launchPick&&A&&s.jsx(zj,{machine:A,launchPick:H.launchPick,actions:H}),v&&s.jsx(nu,{title:v.title,description:v.description,details:v.details,workspaceOptions:v.workspaceOptions,selectedWorkspaceKey:M,onWorkspaceChange:P=>{S.current=P,C(P)},confirmLabel:v.confirmLabel,busyLabel:v.busyLabel,busy:N,onConfirm:be,onCancel:()=>{j.current=null,g(null)}}),k&&s.jsx(Fu,{daemonId:k.daemonId,workspace:k.workspace,onClose:()=>y(null)}),s.jsx(vd,{toasts:c.toasts||[],onDismiss:P=>c.setToasts(ue=>ue.filter(Se=>Se.id!==P)),onClickToast:P=>{P.targetKey&&r(Nr(P.targetKey))}}),s.jsx("style",{children:`
93
+ @keyframes toast-in {
94
+ from { opacity: 0; transform: translateX(40px); }
95
+ to { opacity: 1; transform: translateX(0); }
96
+ }
97
+ `})]})}const pn=[{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."}],Jj={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function Mn(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 Qj(e){const t=Mn(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 Zj(e){return e.isLocalWorktree===!0}function ek(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function tk(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 sk(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{...Jj,...(e==null?void 0:e.policy)||{}}}function rk({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const o=a.id.toLowerCase(),i=a.name.toLowerCase();return o==="hermes-cli"||o.includes("hermes")||i.includes("hermes")}),n=Xd(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(it,{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(vu,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function nk({hideHostPairing:e=!1}={}){var se,W,V,ee,ne;const{sendCommand:t}=lt(),{ides:r}=ss(),n=r.find(D=>D.daemonMode||D.type==="adhdev-daemon"),a=(n==null?void 0:n.id)||"",o=[];let i=[];if(n){const D=n.availableProviders||[];i=db(D);for(const ie of D)ie.category==="cli"&&o.push({id:ie.type||ie.id,name:ie.displayName||ie.name||ie.type,meshCoordinator:ie.meshCoordinator})}const[c,d]=l.useState([]),[m,u]=l.useState(null),[p,x]=l.useState(!0),[w,b]=l.useState(null),[f,k]=l.useState(!1),[y,h]=l.useState(null),[j,v]=l.useState({}),[g,S]=l.useState({override:"",append:""}),[M,C]=l.useState(!1),[N,O]=l.useState({}),[_,T]=l.useState(null),[H,R]=l.useState([]),[F,A]=l.useState(null),[I,$]=l.useState(null),[E,L]=l.useState(!1),[U,B]=l.useState(null),[K,J]=l.useState(null),[X,ae]=l.useState(!1),[de,ke]=l.useState(!1),[q,ve]=l.useState(!1),[be,we]=l.useState(""),[xe,Ce]=l.useState(""),[Q,ge]=l.useState(!1),[ce,ye]=l.useState(""),[me,fe]=l.useState(""),[le,pe]=l.useState(""),[oe,P]=l.useState(!1),[ue,Se]=l.useState(""),[Ie,te]=l.useState([]),Ne=c.find(D=>D.id===m)||null;l.useEffect(()=>{v(Object.fromEntries(((Ne==null?void 0:Ne.nodes)||[]).map(D=>[D.id,Mn(D)])))},[Ne]),l.useEffect(()=>{const D=(Ne==null?void 0:Ne.coordinator)||{};S({override:typeof D.systemPromptOverride=="string"?D.systemPromptOverride:"",append:typeof D.systemPromptAppend=="string"?D.systemPromptAppend:typeof D.systemPromptSuffix=="string"?D.systemPromptSuffix:""}),O(Object.fromEntries(((Ne==null?void 0:Ne.nodes)||[]).map(ie=>[ie.id,typeof ie.systemPrompt=="string"?ie.systemPrompt:""])))},[Ne]),l.useEffect(()=>{const D=ub(i);oe&&Ie.length===0&&D.length>0&&te(D)},[oe,i,Ie.length]),l.useEffect(()=>{const D=new Set(((Ne==null?void 0:Ne.nodes)||[]).map(ie=>ie.id));F&&!D.has(F)&&A(null)},[Ne,F]);const De=l.useCallback(async()=>{if(a){x(!0);try{const D=await t(a,"list_meshes");D!=null&&D.success?(d(D.meshes||[]),b(null)):b((D==null?void 0:D.error)||"Failed to load meshes")}catch(D){b((D==null?void 0:D.message)||"Failed to load meshes")}finally{x(!1)}}},[a,t]),Ee=l.useCallback(async D=>{if(!a||!D){R([]);return}try{const ie=await t(a,"get_mesh_queue",{meshId:D});ie!=null&&ie.success?R(Array.isArray(ie.queue)?ie.queue:[]):R([])}catch{R([])}},[a,t]),ze=l.useCallback(async D=>{var ie;if(!a||!D){J(null),we(""),Ce("");return}ae(!0);try{const he=await t(a,"get_mesh_host_pairing",{meshId:D});he!=null&&he.success?(J(he),we(he.hostAddress||((ie=he.meshHost)==null?void 0:ie.hostAddress)||"")):J({success:!1,error:(he==null?void 0:he.error)||"Failed to load Mesh Host pairing"}),Ce("")}catch(he){J({success:!1,error:(he==null?void 0:he.message)||"Failed to load Mesh Host pairing"}),Ce("")}finally{ae(!1)}},[a,t]);l.useEffect(()=>{De()},[De]),l.useEffect(()=>{Ee(m)},[Ee,m]),l.useEffect(()=>{e||ze(m)},[ze,m,e]);async function Qe(){if(!(!a||!m))try{L(!0),B(null);const D=await t(a,"mesh_status",{meshId:m});if((D==null?void 0:D.success)===!1){$(null),B((D==null?void 0:D.error)||"mesh_status failed");return}const ie=Lu(D);ie?$(ie):($(null),B("mesh_status returned an unexpected payload."))}catch(D){$(null),B((D==null?void 0:D.message)||"Failed to load mesh graph")}finally{L(!1)}}l.useEffect(()=>{m&&($(null),B(null),Qe())},[m]);async function Ze(){var he;if(!a||!ce.trim())return;const D=le.trim(),ie=me.trim();if(!(!D&&!ie))try{const je=await t(a,"create_mesh",{name:ce.trim(),repoRemoteUrl:D||void 0,repoIdentity:ie||void 0});je!=null&&je.success?(ge(!1),ye(""),fe(""),pe(""),await De(),u(((he=je.mesh)==null?void 0:he.id)||null)):b((je==null?void 0:je.error)||"Create failed")}catch(je){b((je==null?void 0:je.message)||"Create failed")}}async function rt(D){if(!(!a||!confirm("Delete this mesh?")))try{await t(a,"delete_mesh",{meshId:D}),u(null),await De()}catch(ie){b((ie==null?void 0:ie.message)||"Delete failed")}}async function et(){if(!(!a||!m||!ue.trim()))try{const D=await t(a,"add_mesh_node",{meshId:m,workspace:ue.trim(),providerPriority:yo(Ie,i)});D!=null&&D.success?(P(!1),Se(""),te([]),await De(),await Ee(m)):b((D==null?void 0:D.error)||"Add node failed")}catch(D){b((D==null?void 0:D.message)||"Add node failed")}}async function ct(D){var je;if(!a||!m)return;const ie=Za(Ne),he=((je=pn.find(Me=>Me.value===ie.sessionCleanupOnNodeRemove))==null?void 0:je.label)||"Preserve history and runtimes";if(confirm(`Remove this node?
98
+
99
+ Node removal cleanup policy: ${he}`))try{await t(a,"remove_mesh_node",{meshId:m,nodeId:D}),F===D&&A(null),await De(),await Ee(m)}catch(Me){b((Me==null?void 0:Me.message)||"Remove node failed")}}async function Xe(D){if(!a||!m)return;const ie={...Za(Ne),...D};try{k(!0),b(null);const he=await t(a,"update_mesh",{meshId:m,policy:ie});if((he==null?void 0:he.success)===!1){b(he.error||"Policy update failed");return}await De()}catch(he){b((he==null?void 0:he.message)||"Policy update failed")}finally{k(!1)}}async function pt(){if(!a||!m)return;const ie={...(Ne==null?void 0:Ne.coordinator)||{}};g.override.trim()?ie.systemPromptOverride=g.override:delete ie.systemPromptOverride,g.append.trim()?ie.systemPromptAppend=g.append:delete ie.systemPromptAppend,delete ie.systemPromptSuffix;try{C(!0),b(null);const he=await t(a,"update_mesh",{meshId:m,coordinator:ie});if((he==null?void 0:he.success)===!1){b(he.error||"Coordinator prompt save failed");return}await De()}catch(he){b((he==null?void 0:he.message)||"Coordinator prompt save failed")}finally{C(!1)}}async function Ae(D){if(!a||!m)return;const ie=(N[D.id]||"").trim();try{T(D.id),b(null);const he=await t(a,"update_mesh_node",{meshId:m,nodeId:D.id,systemPrompt:ie});if((he==null?void 0:he.success)===!1){b(he.error||"Node instruction save failed");return}await De()}catch(he){b((he==null?void 0:he.message)||"Node instruction save failed")}finally{T(null)}}async function Fe(){var D;if(!(!a||!m||!be.trim()||!xe.trim())){ke(!0);try{const ie=await t(a,"configure_mesh_host_pairing",{meshId:m,hostAddress:be.trim(),token:xe.trim()});ie!=null&&ie.success?(J(ie),we(ie.hostAddress||((D=ie.meshHost)==null?void 0:D.hostAddress)||be.trim()),await De()):J({success:!1,error:(ie==null?void 0:ie.error)||"Failed to save Mesh Host pairing"})}catch(ie){J({success:!1,error:(ie==null?void 0:ie.message)||"Failed to save Mesh Host pairing"})}finally{ke(!1)}}}async function st(){if(!(!a||!m||!xe.trim())){ve(!0);try{const D=await t(a,"join_mesh_host_pairing",{meshId:m,token:xe.trim()});D!=null&&D.success?(J(D),Ce(""),await De(),await ze(m),await Qe()):J({success:!1,meshHost:D==null?void 0:D.meshHost,manualPairing:D==null?void 0:D.manualPairing,error:(D==null?void 0:D.error)||"Failed to apply Mesh Host join"})}catch(D){J({success:!1,error:(D==null?void 0:D.message)||"Failed to apply Mesh Host join"})}finally{ve(!1)}}}async function qe(D){if(!a||!m)return;const ie=j[D.id]||Mn(D),he=i.length>0?yo(ie,i):Dr(ie),je={...D.policy||{}};delete je.provider_priority,he.length?je.providerPriority=he:delete je.providerPriority;try{h(D.id),b(null);const Me=await t(a,"update_mesh_node",{meshId:m,nodeId:D.id,policy:je,providerPriority:he});if((Me==null?void 0:Me.success)===!1){b(Me.error||"Node policy update failed");return}await De()}catch(Me){b((Me==null?void 0:Me.message)||"Node policy update failed")}finally{h(null)}}if(!a)return s.jsx(xr,{icon:s.jsx(Qt,{}),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(!Ne)return s.jsxs(xr,{icon:s.jsx(Qt,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>ge(!0),children:"+ Create Mesh"}),children:[w&&s.jsx(_s,{variant:"error",className:"mb-4",children:w}),Q&&s.jsx(it,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(ht,{label:"Name",children:s.jsx(Ss,{value:ce,onChange:D=>ye(D.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(ht,{label:"Repo remote URL (optional)",hint:"Provide a remote URL OR a stable identity. Mesh nodes use this to match the same project across machines.",children:s.jsx(Ss,{value:le,onChange:D=>pe(D.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(ht,{label:"Repo identity (optional)",hint:"Provide a remote URL OR a stable identity. Mesh nodes use this to match the same project across machines.",children:s.jsx(Ss,{value:me,onChange:D=>fe(D.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:Ze,disabled:!ce.trim()||!le.trim()&&!me.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>{ge(!1),ye(""),fe(""),pe("")},children:"Cancel"})]})]})}),p?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):c.length===0?s.jsx(Un,{icon:s.jsx(Qt,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:c.map(D=>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:()=>u(D.id),children:[s.jsx("div",{className:"font-semibold text-sm",children:D.name}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:D.repoIdentity||"No repo identity"}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[D.nodes.length," node(s)"]})]},D.id))})]});const Ke=Za(Ne),z=(K==null?void 0:K.meshHost)||Ne.meshHost||{},G=((se=K==null?void 0:K.manualPairing)==null?void 0:se.status)||((W=z.pairing)==null?void 0:W.status)||"not_configured",Y=((V=K==null?void 0:K.manualPairing)==null?void 0:V.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(xr,{icon:s.jsx(Qt,{}),title:Ne.name,subtitle:Ne.repoIdentity||"Repo Mesh",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>u(null),children:"← Back"}),s.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>rt(Ne.id),children:"Delete"})]}),children:[w&&s.jsx(_s,{variant:"error",className:"mb-4",children:w}),!e&&s.jsx(it,{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:z.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:X?"loading":G})]}),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:z.hostAddress||"not configured"})]}),s.jsxs("div",{children:["Token id: ",s.jsx("code",{className:"text-text-primary",children:((ee=z.pairing)==null?void 0:ee.tokenId)||"not configured"})]}),s.jsxs("div",{children:["Can own coordinator: ",s.jsx("code",{className:"text-text-primary",children:String(z.canOwnCoordinator??z.role!=="member")})]}),s.jsxs("div",{children:["Can own queue: ",s.jsx("code",{className:"text-text-primary",children:String(z.canOwnQueue??z.role!=="member")})]})]}),s.jsx("p",{className:"mt-3 text-xs leading-relaxed text-text-secondary",children:Y}),(K==null?void 0:K.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:K.error})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-panel p-4",children:[s.jsx(ht,{label:"Mesh Host address",hint:"Example: http://127.0.0.1:3847 or a reachable HTTPS/WSS host endpoint.",children:s.jsx(Ss,{value:be,onChange:D=>we(D.target.value),placeholder:"http://127.0.0.1:3847",disabled:de||q})}),s.jsx(ht,{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(Ss,{value:xe,onChange:D=>Ce(D.target.value),placeholder:"paste Mesh Host pairing token",type:"password",disabled:de||q})}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:Fe,disabled:de||q||!be.trim()||!xe.trim(),children:de?"Saving...":"Save manual pairing"}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:st,disabled:q||de||!xe.trim(),children:q?"Applying...":"Apply join"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>ze(m),disabled:X||de||q,children:X?"Checking...":"Check saved config"})]})]})]})}),s.jsxs(it,{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(ht,{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:Ke.requirePreTaskCheckpoint?"yes":"no",onChange:D=>Xe({requirePreTaskCheckpoint:D.target.value==="yes"}),disabled:f,children:[s.jsx("option",{value:"no",children:"No"}),s.jsx("option",{value:"yes",children:"Yes"})]})}),s.jsx(ht,{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:Ke.requirePostTaskCheckpoint?"yes":"no",onChange:D=>Xe({requirePostTaskCheckpoint:D.target.value==="yes"}),disabled:f,children:[s.jsx("option",{value:"yes",children:"Yes"}),s.jsx("option",{value:"no",children:"No"})]})}),s.jsx(ht,{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:Ke.requireApprovalForPush?"required":"not_required",onChange:D=>Xe({requireApprovalForPush:D.target.value==="required"}),disabled:f,children:[s.jsx("option",{value:"required",children:"Require approval before push"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(ht,{label:"Submodule main auto-publish",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:Ke.allowAutoPublishSubmoduleMainCommits?"enabled":"disabled",onChange:D=>Xe({allowAutoPublishSubmoduleMainCommits:D.target.value==="enabled"}),disabled:f,children:[s.jsx("option",{value:"disabled",children:"Require explicit approval"}),s.jsx("option",{value:"enabled",children:"Allow Refinery non-force publish"})]})}),s.jsx(ht,{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:Ke.requireApprovalForDestructiveGit?"required":"not_required",onChange:D=>Xe({requireApprovalForDestructiveGit:D.target.value==="required"}),disabled:f,children:[s.jsx("option",{value:"required",children:"Require approval"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(ht,{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:Ke.dirtyWorkspaceBehavior||"warn",onChange:D=>Xe({dirtyWorkspaceBehavior:D.target.value}),disabled:f,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(ht,{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(Ke.maxParallelTasks??2),onChange:D=>Xe({maxParallelTasks:Number(D.target.value)}),disabled:f,children:[1,2,3,4,5,6,7,8].map(D=>s.jsx("option",{value:D,children:D},D))})})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(ht,{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:Ke.sessionCleanupOnNodeRemove||"preserve",onChange:D=>Xe({sessionCleanupOnNodeRemove:D.target.value}),disabled:f,children:pn.map(D=>s.jsx("option",{value:D.value,children:D.label},D.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((ne=pn.find(D=>D.value===Ke.sessionCleanupOnNodeRemove))==null?void 0:ne.description)||pn[0].description})]}),f&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),s.jsxs(it,{title:"Coordinator prompt",description:"Customize the system prompt for mesh coordinator sessions. Leave both fields empty to use the daemon's built-in prompt. Supports placeholders: {{meshName}}, {{repo}}, {{defaultBranch}}, {{cliType}}, {{nodes}}, {{policy}}, {{tools}}, {{workflow}}, {{rules}}, {{toolExposurePreflight}}.",children:[s.jsx(ht,{label:"Override (replaces default)",hint:"When set, REPLACES the daemon's default base prompt for this mesh. Use placeholders if you still want node/policy/tools to render. Leave empty to keep the default.",children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:g.override,onChange:D=>S(ie=>({...ie,override:D.target.value})),disabled:M,placeholder:"(empty — daemon default applies)"})}),s.jsx(ht,{label:"Append (added after the base)",hint:"Always added after whichever base prompt wins. Use this for mesh-specific rules that should layer on top of the default.",children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:4,value:g.append,onChange:D=>S(ie=>({...ie,append:D.target.value})),disabled:M,placeholder:"(empty — nothing appended at mesh layer)"})}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void pt(),disabled:M,children:M?"Saving…":"Save coordinator prompt"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>S({override:"",append:""}),disabled:M,title:"Clear both fields. Click Save to commit the reset.",children:"Clear"})]})]}),s.jsxs(it,{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:Qe,disabled:E,children:E?"Loading...":"Refresh Graph"})]}),U&&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:U}),I?s.jsx(Bu,{status:I,emptyMessage:"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon.",daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:E?"Loading graph...":"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon."})]}),s.jsxs(it,{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:()=>P(!0),children:"+ Add Node"})}),oe&&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:()=>P(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(gt,{size:16})})]}),s.jsx(ht,{label:"Workspace Path",children:s.jsx(Ss,{value:ue,onChange:D=>Se(D.target.value),placeholder:"/Users/dev/projects/myapp",autoFocus:!0})}),s.jsx(ht,{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(pl,{value:Ie,availableProviders:i,onChange:te})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:et,disabled:!ue.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>P(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),Ne.nodes.length===0?s.jsx(Un,{icon:s.jsx($s,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:Ne.nodes.map(D=>{const ie=Mn(D),he=Qj(D),je=ek(D,H),Me=sk(D,n),$e=F===D.id,Te=Zj(D);return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary cursor-pointer transition-colors ${$e?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`,role:"button",tabIndex:0,onClick:()=>A($e?null:D.id),onKeyDown:Le=>{(Le.key==="Enter"||Le.key===" ")&&(Le.preventDefault(),A($e?null:D.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:D.workspace.split("/").pop()}),je.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:[je.length," active task",je.length===1?"":"s"]}),Te&&s.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-cyan-500/15 text-cyan-300 border border-cyan-500/25",children:"worktree"})]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:D.workspace}),Te&&s.jsxs("div",{className:"mt-2 rounded-lg border border-cyan-500/20 bg-cyan-500/10 px-3 py-2 text-[11px] text-cyan-200",children:["Worktree node",D.worktreeBranch?` · ${D.worktreeBranch}`:"",". Provider priority saved here is node-local and disappears when this worktree node is removed."]}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:Le=>Le.stopPropagation(),children:[s.jsxs(ht,{label:"Provider priority",hint:Te?"Worktree-local launch defaults. Configure the source node for durable defaults.":"Used when launches omit an explicit provider. Empty keeps fail-closed behavior until a provider is selected manually.",children:[s.jsx(pl,{value:j[D.id]??ie,availableProviders:i,onChange:Le=>v(Ue=>({...Ue,[D.id]:Le})),disabled:y===D.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:Le=>{Le.stopPropagation(),qe(D)},disabled:y===D.id,children:y===D.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:he.configured?"text-text-primary font-mono":"text-amber-400",children:he.label}),he.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",he.launchBlockedMessage,")"]})]})]}),s.jsxs(ht,{label:"Node instruction (optional)",hint:"Surfaced in the coordinator system prompt as 📌 Node instruction. The coordinator quotes it verbatim when delegating tasks to this node.",children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:N[D.id]??"",onChange:Le=>{const Ue=Le.target.value;O(dt=>({...dt,[D.id]:Ue}))},onClick:Le=>Le.stopPropagation(),disabled:_===D.id,placeholder:"e.g. 'Run only smoke tests here', 'Use opus on this node'"}),s.jsx("div",{className:"mt-2 flex items-center gap-2",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:Le=>{Le.stopPropagation(),Ae(D)},disabled:_===D.id,children:_===D.id?"Saving…":"Save instruction"})})]})]})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:Le=>{Le.stopPropagation(),ct(D.id)},children:s.jsx(gt,{size:14})})]}),$e&&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:D.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:he.configured?"text-green-400":"text-amber-400",children:he.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:D.repoRoot||D.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",Me.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:"})," ",je.length>0||Me.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"}),je.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:je.map(Le=>s.jsx("li",{className:"font-mono",children:tk(Le)},Le.id))})]}),Me.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:Me.map(Le=>s.jsxs("li",{className:"font-mono",children:[Le.provider," / ",Le.status," / ",Le.id]},Le.id))})]})]})]},D.id)})})]}),s.jsx(rk,{meshId:Ne.id,availableCliAgents:o})]})}function vi(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function ak(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=vi();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 Ft(e,t){return await fetch(ak(e),{credentials:"same-origin",...t})}function Ku(){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 ok{constructor(){We(this,"adapters",new Map);We(this,"states",new Map);We(this,"runtimeListeners",new Map);We(this,"screenshotCallbacks",new Map);We(this,"statusCallbacks",new Set);We(this,"stateChangeCallbacks",new Set);We(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,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:o,rows:i})}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 Ft(`${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 i=await o.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.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 Ot=new ok;function ik(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=vi();return r?`${t}?token=${encodeURIComponent(r)}`:t}const fn=ik(),oc=3e3,lk=3e4;let Dt=null,ck=0;const Jn=new Map;let is=null,yr=null;function ic(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function or(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function dk(e){return e==="connected"?"connected":e}async function In(e,t,r){const n=Sd(e,r||{}),a=Dt;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++ck}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{Jn.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);Jn.set(o,{resolve:m=>{clearTimeout(d),i(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 Io(e,t){const r=Dt;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 Uu(e,t,r){const n=Dt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Sd(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}}Ot.registerPtyInputSender(Uu);class uk{constructor(t){We(this,"daemonId");We(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Dt==null?void 0:Dt.readyState)===WebSocket.OPEN}get connectionState(){return(Dt==null?void 0:Dt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return In(this.daemonId,t,r)}async sendInput(t,r){return In(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,is&&(clearInterval(is),is=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await In(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());Ot.emitScreenshot(this.daemonId,a)}}catch{}};r(),is=setInterval(r,2e3)}stopScreenshots(t){is&&(clearInterval(is),is=null)}}let It=null;function mk(e){return(!It||It.daemonId!==e)&&(It=new uk(e)),It}function hk({children:e}){const t=l.useRef(wr()),r=wr();t.current=r;const{setUserName:n}=ss(),a=l.useRef(n);a.current=n;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((f,k)=>{c(f),yr==null||yr(f,k)},[]),m=l.useRef(null),u=l.useRef(),p=l.useRef(oc),x=l.useRef(!0),w=l.useRef(!1),b=l.useRef("initial_connect");return l.useEffect(()=>{x.current=!0,w.current=!1;function f(){var h,j;if(!x.current||((h=m.current)==null?void 0:h.readyState)===WebSocket.OPEN||((j=m.current)==null?void 0:j.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${fn}...`),or("connect_attempt",{url:fn,reason:b.current,delayMs:p.current});let y;try{y=new WebSocket(fn)}catch(v){console.error("[Standalone WS] Failed to create WebSocket:",v),k();return}m.current=y,y.onopen=()=>{if(!x.current){y.close();return}d("connected"),p.current=oc,or("open",{url:fn,reason:b.current}),Gt.resubscribeAll({sendData:Io}),console.log("[Standalone WS] Connected")},Dt=y,y.onmessage=v=>{var g,S;try{const M=JSON.parse(v.data);if((M.type==="command_result"||M.type==="error")&&M.requestId){const C=Jn.get(M.requestId);C&&(Jn.delete(M.requestId),M.type==="error"?C.reject(new Error(((g=M.data)==null?void 0:g.message)||"Command failed")):C.resolve(M.data));return}if(M.type==="session_output"){const C=M.sessionId||M.cliId||M.cliType;C&&Ot.emitSessionOutput(C,typeof M.data=="string"?M.data:"",typeof M.seq=="number"?M.seq:void 0);return}if(M.type==="runtime_snapshot"){Ot.emitRuntimeSnapshot(M.sessionId,typeof M.text=="string"?M.text:"",typeof M.seq=="number"?M.seq:0,!!M.truncated,typeof M.cols=="number"?M.cols:void 0,typeof M.rows=="number"?M.rows:void 0);return}if(M.type==="topic_update"){const C=M.update;C&&Gt.publish(C);return}if(M.type==="status"||M.type==="initial_state"){const C=M.data;if(!C)return;const{injectEntries:N,markLoaded:O,getIdes:_}=t.current,T=C.instanceId||"standalone",H=_().find(A=>A.id===T),R=mk(T);Ot.register(T,R),Ot.setState(T,"connected"),d("connected",T),Ot.emitStatus(T,C);const F=En(C,{daemonId:T,existingDaemon:H,existingEntries:_()});ic("ws_status",{type:M.type,daemonId:T,sessions:(C.sessions||[]).map(A=>({id:A.id,parentId:A.parentId,providerType:A.providerType,kind:A.kind,transport:A.transport,unread:A.unread,inboxBucket:A.inboxBucket,lastSeenAt:A.lastSeenAt,lastUpdated:A.lastUpdated,title:A.title})),recentLaunches:(C.recentLaunches||[]).map(A=>({id:A.id,providerType:A.providerType,kind:A.kind,workspace:A.workspace,lastLaunchedAt:A.lastLaunchedAt}))}),ic("entries",{daemonId:T,entries:F.filter(A=>A.type!=="adhdev-daemon").map(A=>({id:A.id,type:A.type,unread:A.unread,inboxBucket:A.inboxBucket,lastSeenAt:A.lastSeenAt,lastUpdated:A.lastUpdated,sessionId:A.sessionId}))}),F.length>0&&N(F,{authoritativeDaemonIds:[T]}),O(),i.current!==T&&((S=o.current)==null||S.call(o),i.current=T,o.current=Gt.subscribe({sendData:Io},T,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${T}`,params:{includeSessions:!0}},A=>{if(A.topic!=="daemon.metadata")return;const I=t.current.getIdes(),$=I.find(L=>L.id===T),E=En(A.status,{daemonId:T,existingDaemon:$,existingEntries:I,timestamp:A.timestamp});E.length>0&&t.current.injectEntries(E,{authoritativeDaemonIds:[T]}),A.userName&&a.current&&a.current(A.userName)}))}}catch(M){console.error("[Standalone WS] Parse error:",M)}},y.onclose=v=>{x.current&&(It==null||It.stopScreenshots(),It&&Ot.setState(It.daemonId,"disconnected"),d("disconnected"),m.current=null,b.current=`close:${v.code}${v.wasClean?":clean":":unclean"}`,or("close",{code:v.code,reason:v.reason||"",wasClean:v.wasClean}),k())},y.onerror=v=>{w.current||!x.current||(b.current="error",or("error",{message:v instanceof Event?"event":String(v),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",v))}}function k(){if(!x.current)return;clearTimeout(u.current);const y=p.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),or("schedule_reconnect",{reason:b.current,delayMs:y}),u.current=setTimeout(()=>{p.current=Math.min(p.current*1.5,lk),f()},y)}return f(),()=>{var y;x.current=!1,w.current=!0,(y=o.current)==null||y.call(o),o.current=null,i.current=null,clearTimeout(u.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,Dt=null),It&&(It.stopScreenshots(),Ot.unregister(It.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function pk({children:e}){const[t,r]=l.useState("disconnected"),[n,a]=l.useState(null);l.useEffect(()=>(yr=(i,c)=>{r(i),c&&a(c)},()=>{yr=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=dk(t),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d}},[t,n]);return s.jsx(Zm,{connectionOverrides:o,children:s.jsx(hk,{children:e})})}const zu="adhdev_standalone_font_preferences",bs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},la=[{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"}],Mr=[{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"}],fk=new Set(la.map(e=>e.id)),xk=new Set(Mr.map(e=>e.id));function Wt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Tn("chat",t.chat),code:Tn("code",t.code),terminal:Tn("terminal",t.terminal)}}function Tn(e,t){const r=bs[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"?fk:xk).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function An(e,t){var a;const r=Tn(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?la:Mr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function bk(e){const t=Wt(e),r=An("chat",t.chat),n=An("code",t.code),a=An("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function cs(e,t=document.documentElement){const r=Wt(e),n=bk(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function To(e){const t=Wt(e);try{localStorage.setItem(zu,JSON.stringify(t))}catch{}return t}function gk(){try{const e=localStorage.getItem(zu);if(e)return Wt(JSON.parse(e))}catch{}return bs}function yk(){return cs(gk())}function ir(e,t){var n;const r=e==="chat"?la:Mr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const vk=[{id:"dashboard",path:"/dashboard",icon:s.jsx(bc,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(es,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(Bs,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(Qn,{}),label:"Settings"}];function wk({children:e}){const t=Ir(),r=_o(),n=l.useMemo(()=>vk.map(o=>({...o,active:r.pathname.startsWith(o.path),onSelect:()=>t(o.path)})),[r.pathname,t]),a=l.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(yc,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(vc,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(jb,{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:i})=>s.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":"mt-1"}`,onClick:i,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 jk=[{icon:s.jsx(es,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(ws,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(wc,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Bt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Bs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(yc,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],kk=[{icon:s.jsx(fh,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(bc,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Tr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(ch,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(gc,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(uh,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Sk=[{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 Nk(){return s.jsxs(xr,{icon:s.jsx(vc,{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(it,{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(it,{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:jk.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(it,{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:Nd.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Md.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Cd.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(it,{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:kk.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(it,{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:Sk.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(Un,{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(Nh,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function eo(e,t,r){return{...e,[t]:r}}function to({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:i=>{const c=i.target.value;o(c==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:c})},children:a.map(i=>s.jsx("option",{value:i.id,children:i.label},i.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:i=>o({preset:"custom",customFamily:i.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:An(e,n)})]})]})]})}function Ck({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:i,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(to,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:la,onChange:u=>o(eo(e,"chat",u))}),s.jsx(to,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Mr,onChange:u=>o(eo(e,"code",u))}),s.jsx(to,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Mr,onChange:u=>o(eo(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: ",ir("chat",e.chat.preset)," · Code: ",ir("code",e.code.preset)," · Terminal: ",ir("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",ir("chat",bs.chat.preset)," / ",ir("code",bs.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:i,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 Mk(){const{ides:e}=ss(),t=e.find(q=>q.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=lt(),{userName:a}=ss(),[o,i]=l.useState(a||""),[c,d]=l.useState(null),[m,u]=l.useState(null),[p,x]=l.useState(bs),[w,b]=l.useState(!1),[f,k]=l.useState(""),[y,h]=l.useState(""),[j,v]=l.useState("127.0.0.1"),[g,S]=l.useState(""),[M,C]=l.useState(""),[N,O]=l.useState(""),[_,T]=l.useState(""),[H,R]=l.useState(""),[F,A]=l.useState(!1),I=async()=>{const ve=await(await Ft("/auth/session")).json();d(ve)},$=async()=>{const ve=await(await Ft("/api/v1/standalone/preferences")).json();u(ve),v(ve.standaloneBindHost);const be=Wt(ve.standaloneFontPreferences);x(be),cs(be),To(be)};l.useEffect(()=>{a!==void 0&&i(a)},[a]),l.useEffect(()=>{Promise.all([I(),$()]).catch(q=>{T(q instanceof Error?q.message:String(q))})},[]),l.useEffect(()=>{cs(p)},[p]);const E=q=>{const ve=q.target.value.trim();t!=null&&t.id&&ve!==a&&n(t.id,"set_user_name",{userName:ve}).catch(console.error)},[L,U]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),B=q=>{U(q);try{localStorage.setItem("adhdev_sound",q?"1":"0")}catch{}},K=async()=>{k(""),h(""),b(!0);try{const q=Wt(p),ve=await Ft("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:q})}),be=await ve.json();if(!ve.ok)throw new Error((be==null?void 0:be.error)||"Failed to save standalone font preferences");const we=Wt(be.standaloneFontPreferences);u(be),x(we),cs(we),To(we),h("Standalone chat fonts saved for this self-hosted dashboard.")}catch(q){k(q instanceof Error?q.message:String(q))}finally{b(!1)}},J=()=>{const q=Wt(m==null?void 0:m.standaloneFontPreferences);k(""),h(""),x(q),cs(q)},X=()=>{k(""),h(""),x(bs),cs(bs)},ae=async()=>{T(""),R(""),A(!0);try{const q=await Ft("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:j})}),ve=await q.json();if(!q.ok)throw new Error((ve==null?void 0:ve.error)||"Failed to save standalone network preference");u(ve),v(ve.standaloneBindHost),R(ve.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){T(q instanceof Error?q.message:String(q))}finally{A(!1)}},de=async()=>{if(T(""),R(""),M.trim().length<4){T("Password must be at least 4 characters.");return}if(M!==N){T("New password and confirmation do not match.");return}A(!0);try{const q=await Ft("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,newPassword:M})}),ve=await q.json();if(!q.ok)throw new Error((ve==null?void 0:ve.error)||"Failed to save password");d(ve),await $(),S(""),C(""),O(""),R(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Ku()}catch(q){T(q instanceof Error?q.message:String(q))}finally{A(!1)}},ke=async()=>{T(""),R(""),A(!0);try{const q=await Ft("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,clear:!0})}),ve=await q.json();if(!q.ok)throw new Error((ve==null?void 0:ve.error)||"Failed to clear password");d(ve),await $(),S(""),C(""),O(""),R("Standalone password disabled.")}catch(q){T(q instanceof Error?q.message:String(q))}finally{A(!1)}};return s.jsxs(xr,{icon:s.jsx(Qn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(_s,{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(_s,{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(it,{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(it,{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:j==="127.0.0.1",onChange:()=>v("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:j==="0.0.0.0",onChange:()=>v("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:()=>{ae()},disabled:F,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:F?"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(it,{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."}),_&&s.jsx(_s,{variant:"error",children:_}),H&&s.jsx(_s,{variant:"success",children:H}),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:g,onChange:q=>S(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:M,onChange:q=>C(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:N,onChange:q=>O(q.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{de()},disabled:F,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:F?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ke()},disabled:F,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(it,{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(it,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(_b,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(it,{title:"Coordinator prompts",description:"User-level overrides for the mesh coordinator system prompt. Per-mesh overrides live in the Repo Mesh page.",children:s.jsx(Db,{daemonId:t==null?void 0:t.id})}),s.jsx(it,{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($b,{})]}),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(zb,{})]}),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(Ck,{value:p,savedValue:Wt(m==null?void 0:m.standaloneFontPreferences),saving:w,error:f,notice:y,onChange:x,onSave:()=>{K()},onResetToSaved:J,onResetToDefaults:X})]}),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(qb,{})]})]})}),s.jsx(it,{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(Ib,{}),s.jsx(ls,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Sh,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:L,onChange:B})]})}),s.jsx(it,{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(lh,{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=>i(q.target.value),onBlur:E,onKeyDown:q=>{q.key==="Enter"&&q.currentTarget.blur()}})]})})})]})}const Ik=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],ur="adhdev_onboarding_done",Tk=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],Ak={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function _k({onDone:e}){const[t,r]=l.useState([]),[n,a]=l.useState(new Set(Ik)),[o,i]=l.useState(!0),[c,d]=l.useState(null),[m,u]=l.useState(!1),[p,x]=l.useState(null),[w,b]=l.useState("all");l.useEffect(()=>{let g=!1;const S=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${S}/providers?sort=popular&limit=100`).then(M=>{if(!M.ok)throw new Error(`HTTP ${M.status}`);return M.json()}).then(M=>{g||r(M.providers??[])}).catch(M=>{g||d(M instanceof Error?M.message:String(M))}).finally(()=>{g||i(!1)}),()=>{g=!0}},[]);const f=t.filter(g=>w==="all"||g.category===w),k=["cli","ide","extension","acp"].map(g=>({category:g,items:f.filter(S=>S.category===g)})).filter(g=>g.items.length>0),y=l.useCallback(g=>{a(S=>{const M=new Set(S);return M.has(g)?M.delete(g):M.add(g),M})},[]),h=l.useCallback(async()=>{if(n.size===0){localStorage.setItem(ur,"1"),e();return}u(!0);const g=[];for(const S of n)try{const C=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:S})})).json().catch(()=>({}));g.push({type:S,ok:!!C.success,error:C.error})}catch(M){g.push({type:S,ok:!1,error:M instanceof Error?M.message:String(M)})}x(g),u(!1),g.every(S=>S.ok)&&localStorage.setItem(ur,"1")},[n,e]),j=l.useCallback(()=>{localStorage.setItem(ur,"1"),e()},[e]),v=l.useCallback(()=>{p&&p.every(g=>g.ok)?e():m||j()},[p,m,e,j]);return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60",onClick:v,children:s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-2xl max-w-2xl w-full p-6 flex flex-col gap-5 max-h-[85vh] overflow-y-auto",onClick:g=>g.stopPropagation(),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Welcome to ADHDev"}),s.jsxs("div",{className:"text-[12px] text-text-muted mt-1",children:["Pick the providers you want to use. Defaults to the four officially supported CLI providers; you can install IDE, ACP, or extension providers from the tabs below or later from ",s.jsx("span",{className:"text-text-secondary",children:"Burrow → Providers → Add provider"}),"."]})]}),!o&&!c&&t.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:Tk.map(g=>{const S=g.key==="all"?t.length:t.filter(M=>M.category===g.key).length;return S===0&&g.key!=="all"?null:s.jsxs("button",{onClick:()=>b(g.key),className:`machine-btn text-[10px] px-2 py-0.5 ${w===g.key?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:[g.label," ",s.jsxs("span",{className:"opacity-60",children:["(",S,")"]})]},g.key)})}),o&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"Loading registry…"}),!o&&c&&s.jsxs("div",{className:"rounded-xl border border-red-500/30 bg-red-500/5 px-3 py-2 text-[12px] text-red-400",children:["Failed to load registry: ",c]}),!o&&!c&&f.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"No providers in this category."}),!o&&!c&&f.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:k.map(g=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:Ak[g.category]??g.category}),s.jsx("div",{className:"grid gap-1.5",children:g.items.map(S=>{var _,T;const M=n.has(S.type),C=p==null?void 0:p.find(H=>H.type===S.type),N=((_=S.manifest)==null?void 0:_.icon)??"📦",O=((T=S.manifest)==null?void 0:T.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${M?"bg-violet-500/[0.06] border-violet-500/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:M,onChange:()=>y(S.type),disabled:m,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:N}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:S.displayName}),O&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:O})]}),C&&s.jsx("span",{className:`text-[10px] font-semibold ${C.ok?"text-green-400":"text-red-400"}`,children:C.ok?"✓ installed":`✗ ${C.error??"failed"}`})]},S.type)})})]},g.category))}),s.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-border-subtle",children:[s.jsxs("div",{className:"text-[11px] text-text-muted",children:[n.size," provider",n.size!==1?"s":""," selected"]}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx("button",{onClick:j,disabled:m,className:"machine-btn text-[11px] px-3 py-1",children:"Skip"}),s.jsx("button",{onClick:()=>{p?(localStorage.setItem(ur,"1"),e()):h()},disabled:m||!p&&n.size===0,className:"machine-btn text-[11px] px-3 py-1 bg-violet-500/15 border-violet-500/40 text-violet-400 hover:bg-violet-500/25",children:m?"Installing…":p?"Done":`Install ${n.size}`})]})]})]})})}function Lk(){try{return localStorage.getItem(ur)==="1"}catch{return!1}}vb();Kb();yk();const Pk=fc({baseUrl:"",getToken:vi});function Rk({children:e}){const[t,r]=l.useState(null),[n,a]=l.useState(!0),[o,i]=l.useState(""),[c,d]=l.useState(""),[m,u]=l.useState(!1),p=async()=>{a(!0),d("");try{const b=await(await Ft("/auth/session")).json();r(b)}catch(w){d(w instanceof Error?w.message:String(w))}finally{a(!1)}};l.useEffect(()=>{p()},[]),l.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let w=!1;return(async()=>{try{const b=await Ft("/api/v1/standalone/preferences");if(!b.ok)return;const f=await b.json();if(w)return;const k=Wt(f.standaloneFontPreferences);cs(k),To(k)}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 b=await Ft("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),f=await b.json();if(!b.ok)throw new Error((f==null?void 0:f.error)||"Login failed");r(f),i(""),Ku()}catch(b){d(b instanceof Error?b.message:String(b))}finally{u(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:x,children:[s.jsx("input",{type:"password",value:o,onChange:w=>i(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 lc(){const{ides:e,initialLoaded:t}=ss();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(no,{to:`/machines/${r.id}`,replace:!0}):s.jsx(no,{to:"/dashboard",replace:!0})}function Dk(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let r=!1;if(!Lk())return fetch("/api/v1/providers/installed").then(n=>n.ok?n.json():{providers:[]}).then(n=>{r||(n.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{r=!0}},[]),e?s.jsx(_k,{onDone:()=>t(!1)}):null}function Ek(){const e=l.useMemo(()=>({sendCommand:In,sendData:Io,sendPtyInput:Uu}),[]);return s.jsx($m,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(sh,{client:Pk,children:s.jsx(Rk,{children:s.jsx(pk,{children:s.jsx(nh,{value:e,children:s.jsxs(wk,{children:[s.jsx(Dk,{}),s.jsxs(Bm,{children:[s.jsx(Xt,{path:"/dashboard",element:s.jsx(Hw,{})}),s.jsx(Xt,{path:"/machine",element:s.jsx(lc,{})}),s.jsx(Xt,{path:"/machines/:id",element:s.jsx(Xj,{})}),s.jsx(Xt,{path:"/machines",element:s.jsx(lc,{})}),s.jsx(Xt,{path:"/about",element:s.jsx(Nk,{})}),s.jsx(Xt,{path:"/settings",element:s.jsx(Mk,{})}),s.jsx(Xt,{path:"/mesh",element:s.jsx(nk,{hideHostPairing:!0})}),s.jsx(Xt,{path:"*",element:s.jsx(no,{to:"/dashboard",replace:!0})})]})]})})})})})})}Ix({connectionManager:Ot});Om(document.getElementById("root")).render(s.jsx(Ek,{}));