@adhdev/daemon-standalone 0.9.82-rc.4 → 0.9.82-rc.6

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,98 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-DCVDkSIp.js","assets/vendor-piMzuE8Y.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
+ var bu=Object.defineProperty;var gu=(e,s,r)=>s in e?bu(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var Xe=(e,s,r)=>gu(e,typeof s!="symbol"?s+"":s,r);import{r as i,j as t,M as ro,a as yu,b as vu,c as wu,R as wt,d as xr,t as ju,e as ku,u as Hs,D as Su,f as La,g as Ra,i as Nu,h as Cu,C as Iu,B as Tu,k as Au,l as Mu,H as ti,P as si,m as no,n as Lu,o as Ru,p as _u,q as Pu,s as Yt,N as _a,v as Du}from"./vendor-piMzuE8Y.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.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 l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&n(l)}).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 Eu(e={}){const s=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>s&&r.splice(0,r.length-s),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 Ps=Eu();function ri(e){const s={};for(const r of e)r.transport&&(s[r.transport]=(s[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:s}}function $u(e,s){return typeof e=="string"&&e.trim().length>0&&e!==s}function ni(e){return Array.isArray(e)?[...e]:[]}function Ll(e,s){if(!e)return s??null;const r=Object.prototype.hasOwnProperty.call(e,"messages"),n=Object.prototype.hasOwnProperty.call(e,"activeModal");return s?{...s,...e,messages:r?ni(e.messages):s.messages,activeModal:n?e.activeModal??null:s.activeModal,inputContent:e.inputContent??s.inputContent}:{...e,...r?{messages:ni(e.messages)}:{},...n?{activeModal:e.activeModal??null}:{}}}function or(e,s){const r=$u(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(s==null?void 0:s.parentSessionId)??null,providerSessionId:e.providerSessionId??(s==null?void 0:s.providerSessionId),providerName:r??(s==null?void 0:s.providerName)??(s==null?void 0:s.cliName)??(s==null?void 0:s.type)??e.providerName??e.providerType,title:e.title??(s==null?void 0:s.title)??r??(s==null?void 0:s.providerName)??e.providerName??e.providerType,workspace:e.workspace??(s==null?void 0:s.workspace)??null,mode:e.mode??(s==null?void 0:s.mode),capabilities:e.capabilities??(s==null?void 0:s.sessionCapabilities)??(s==null?void 0:s.capabilities)??[],cdpConnected:e.cdpConnected??(s==null?void 0:s.cdpConnected),activeChat:Ll(e.activeChat,s==null?void 0:s.activeChat),controlValues:e.controlValues??(s==null?void 0:s.controlValues),providerControls:e.providerControls??(s==null?void 0:s.providerControls),summaryMetadata:e.summaryMetadata??(s==null?void 0:s.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(s==null?void 0:s.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(s==null?void 0:s.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(s==null?void 0:s.lastMessagePreview),lastMessageRole:e.lastMessageRole??(s==null?void 0:s.lastMessageRole),lastMessageAt:e.lastMessageAt??(s==null?void 0:s.lastMessageAt),lastMessageHash:e.lastMessageHash??(s==null?void 0:s.lastMessageHash),unread:e.unread??(s==null?void 0:s.unread),lastSeenAt:e.lastSeenAt??(s==null?void 0:s.lastSeenAt),inboxBucket:e.inboxBucket??(s==null?void 0:s.inboxBucket),completionMarker:e.completionMarker??(s==null?void 0:s.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(s==null?void 0:s.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(s==null?void 0:s.surfaceHidden),resume:e.resume??(s==null?void 0:s.resume),runtimeKey:e.runtimeKey??(s==null?void 0:s.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(s==null?void 0:s.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(s==null?void 0:s.runtimeWorkspaceLabel),settings:e.settings??(s==null?void 0:s.settings)}}function Rl(e,s,r){if(!(s!=null&&s.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(s)?s:e;if(!(e!=null&&e.length))return s;const n=s.map(a=>{const o=e.find(l=>l.id===a.id);return o?or(a,o):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(s.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 ao(e,s){const r=(s==null?void 0:s.joiner)??" ",n=(s==null?void 0:s.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 Ds(e){return ao(e,{normalizeWhitespace:!0})}const _l=i.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}),Pl=i.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function oi(e){var r,n;let s=0;return e.activeChat!==void 0&&(s+=4),(r=e.childSessions)!=null&&r.length&&(s+=2),e.workspace&&(s+=1),e.machine&&(s+=1),(n=e.agents)!=null&&n.length&&(s+=1),s}function Dl(e,s,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=s.version??r.version??e.version,o=s.serverVersion??e.serverVersion??r.serverVersion,l=s.versionMismatch===!0||e.versionMismatch===!0,c=s.versionUpdateRequired===!0||e.versionUpdateRequired===!0,d=s.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):((s.versionMismatch===!0||l&&a&&o&&a!==o)&&(n.versionMismatch=!0),c&&(n.versionUpdateRequired=!0),n)}function Bu(e){let s=2166136261;for(let r=0;r<e.length;r+=1)s^=e.charCodeAt(r),s=Math.imul(s,16777619)>>>0;return s.toString(16).padStart(8,"0")}function Fn(e){if(!e||typeof e!="object")return"";const s=e,r=Bu(Ds(s.content).slice(0,512));return[String(s.id||""),String(s._localId||""),String(s._turnKey||""),String(s.index??""),String(s.role||""),String(s.receivedAt??s.timestamp??""),r].join(":")}function Ou(e,s){if(!Array.isArray(e))return e;if(s!=null&&s.has(e))return{count:e.length,sharedRef:!0};let r=2166136261;for(const n of e){const a=Fn(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:Fn(e[0]),last:Fn(e[e.length-1])}}function Pa(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function Da(e,s,r){if(!e||!s||typeof e!="object"||typeof s!="object")return;if(Pa(e)&&Pa(s)){const l=e.messages;Array.isArray(l)&&l===s.messages&&r.add(l)}if(Array.isArray(e)&&Array.isArray(s)){const l=Math.min(e.length,s.length);for(let c=0;c<l;c+=1)Da(e[c],s[c],r);return}const n=e,a=s,o=new Set([...Object.keys(n),...Object.keys(a)]);for(const l of o)l!=="messages"&&Da(n[l],a[l],r)}function cr(e,s){return Array.isArray(e)?e.map(r=>cr(r,s)):!e||typeof e!="object"?e:Pa(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Ou(a,s):cr(a,s)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,cr(n,s)]))}function Ku(e,s){try{const r=new WeakSet;return Da(e,s,r),JSON.stringify(cr(e,r))===JSON.stringify(cr(s,r))}catch{return!1}}function Ea(e,s,r){return Ku(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function El(e){var s;return e.daemonId||((s=e.id)==null?void 0:s.split(":")[0])||e.id}function Fu(e,s,r){s[r]!==void 0&&(e[r]=s[r])}function ii(e,s,r,n){var c;const a=(c=s.chats)!=null&&c.length?s.chats:e.chats,o=Rl(e.childSessions,s.childSessions,{preserveMissing:n}),l=Ll(s.activeChat,e.activeChat);return Dl(e,s,{...e,...s,chats:a,childSessions:o,activeChat:l,_lastUpdate:r})}function Wu(e,s,r){var a,o;const n={};s.status&&s.status!==e.status&&(n.status=s.status),s.cdpConnected!==void 0&&(n.cdpConnected=s.cdpConnected),s.childSessions!==void 0&&(n.childSessions=Rl(e.childSessions,s.childSessions,{preserveMissing:r})),(a=s.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(n.chats=s.chats);for(const l 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"])Fu(n,s,l);return s.machineNickname!==void 0&&s.machineNickname!==e.machineNickname&&(n.machineNickname=s.machineNickname),s.versionMismatch===!0&&(n.versionMismatch=!0),n}function Hu(e,s,r,n){const a=Wu(e,s,n),o=Object.keys(a).length>0?Dl(e,s,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return Ea(e,o,r)}function Uu(e){const s=new Set(e.map(o=>o.id)),r=new Set,n=new Set,a=new Set;for(const o of e){const l=El(o);l&&r.add(l),l&&o.type!=="adhdev-daemon"&&n.add(l),l&&o.type==="adhdev-daemon"&&o._sessionListAuthoritative&&a.add(l)}return{incomingIds:s,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function zu(e,s,r,n,a,o){return!a.has(s)||!o.has(s)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function Vu(e,s,r,n,a){return e.transport?r.has(s)&&!n.has(s)?!0:a.has(s):!1}function Gu(e,s,r){var u,h;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return e.map(g=>({...g,_lastUpdate:n}));const o=new Map;for(const g of s)o.set(g.id,g);const{incomingIds:l,incomingDaemonIds:c,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:m}=Uu(e);for(const g of e){const v=o.get(g.id);if(!v){o.set(g.id,{...g,_lastUpdate:n});continue}const f=oi(g),p=oi(v),b=El(g),y=!a.has(b);if(f>p){const S=ii(v,g,n,y);o.set(g.id,Ea(v,S,n));continue}if(f<p){o.set(g.id,Hu(v,g,n,y));continue}const x=g.timestamp||n,N=v._lastUpdate||v.timestamp||0;if(x>=N){const S=ii(v,g,n,y);o.set(g.id,Ea(v,S,n));continue}(u=g.chats)!=null&&u.length&&!((h=v.chats)!=null&&h.length)&&o.set(g.id,{...v,chats:g.chats})}for(const[g,v]of o){const f=v.daemonId||g.split(":")[0];if(!c.has(f))continue;if(a.has(f)&&m.has(f)&&!l.has(g)){o.delete(g);continue}const p=n-(v._lastUpdate||v.timestamp||0);zu(v,f,p,l,a,d)&&o.delete(g)}for(const[g,v]of o){const f=v.daemonId||g.split(":")[0];if(Vu(v,f,c,d,o))continue;n-(v._lastUpdate||v.timestamp||0)>3e5&&v.status!=="online"&&o.delete(g)}return Array.from(o.values())}function qu(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==s[r])return!1;return!0}function Yu({children:e,connectionOverrides:s}){const[r,n]=i.useState([]),[a,o]=i.useState(!1),[l,c]=i.useState([]),[d,m]=i.useState(void 0),u=i.useRef(r);i.useEffect(()=>{u.current=r},[r]);const h=i.useCallback((y,x)=>{n(N=>{let S=!1;const w=N.map(A=>A.id!==y||A.chats===x?A:(S=!0,{...A,chats:x}));return S?w:N})},[]),g=i.useCallback((y,x)=>{n(N=>{const S=N.length===0?y:Gu(y,N,x),w=!qu(N,S);return w&&Ps.record({kind:"dashboard.entries_applied",payload:{incoming:ri(y),next:ri(S)}}),w?S:N})},[]),v=i.useCallback(()=>o(!0),[]),f=i.useMemo(()=>({injectEntries:g,markLoaded:v,getIdes:()=>u.current}),[g,v]),p=s,b=i.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:a,toasts:l,setToasts:c,wsStatus:(p==null?void 0:p.wsStatus)??"connected",isConnected:(p==null?void 0:p.isConnected)??!0,connectionStates:(p==null?void 0:p.connectionStates)??{},connectionTransports:(p==null?void 0:p.connectionTransports)??{},showReconnected:(p==null?void 0:p.showReconnected)??!1,retryConnection:p==null?void 0:p.retryConnection,retryServerConnection:p==null?void 0:p.retryServerConnection,connectionLoginUrl:p==null?void 0:p.connectionLoginUrl,isP2PActive:(p==null?void 0:p.isP2PActive)??!1,p2pStates:(p==null?void 0:p.p2pStates)??{},userRole:p==null?void 0:p.userRole,connectionRetryStatuses:p==null?void 0:p.connectionRetryStatuses,userName:d,setUserName:m}),[r,h,a,l,p==null?void 0:p.wsStatus,p==null?void 0:p.isConnected,p==null?void 0:p.connectionStates,p==null?void 0:p.connectionTransports,p==null?void 0:p.showReconnected,p==null?void 0:p.retryConnection,p==null?void 0:p.retryServerConnection,p==null?void 0:p.connectionLoginUrl,p==null?void 0:p.isP2PActive,p==null?void 0:p.p2pStates,p==null?void 0:p.userRole,p==null?void 0:p.connectionRetryStatuses,d]);return t.jsx(Pl.Provider,{value:f,children:t.jsx(_l.Provider,{value:b,children:e})})}function rs(){return i.useContext(_l)}function br(){return i.useContext(Pl)}function $l(e){const{baseUrl:s,getToken:r,onUnauthorized:n}=e;function a(c){return c.startsWith("http")?c:`${s}${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")&&!s?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function l(c,d={}){const m={"Content-Type":"application/json",...d.headers||{}},u=r==null?void 0:r();u&&(m.Authorization=`Bearer ${u}`);const h=a(c),g=new AbortController,v=setTimeout(()=>g.abort(),15e3);try{const f=await fetch(h,{...d,headers:m,signal:g.signal});if(f.status===401)throw n==null||n(),new Error("Unauthorized");if(!f.ok){const p=await f.json().catch(()=>({error:f.statusText}));throw new Error(p.error||`API Error: ${f.status}`)}return f.json()}finally{clearTimeout(v)}}return{getDaemons:()=>l("/api/v1/daemons"),getDaemonStatus:c=>l(`/api/v1/daemons/${c}/status`),sendCommand:(c,d,m={})=>l(`/api/v1/daemons/${c}/command`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),execTerminal:(c,d,m)=>l(`/api/v1/daemons/${c}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:m})}),sendAgentMessage:(c,d,m)=>l(`/api/v1/shortcuts/${c}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:m})}),getAgentStatus:c=>l(`/api/v1/shortcuts/${c}/status`),approveAgent:(c,d,m)=>l(`/api/v1/shortcuts/${c}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:m?"approve":"reject"})}),getMuxState:c=>l(`/api/v1/mux/${encodeURIComponent(c)}/state`),getMuxSocketInfo:c=>l(`/api/v1/mux/${encodeURIComponent(c)}/socket-info`),controlMux:(c,d,m={})=>l(`/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:l}}const Xu=$l({baseUrl:"http://localhost:3847"}),Ju=i.createContext(Xu);function Qu({client:e,children:s}){return t.jsx(Ju.Provider,{value:e,children:s})}const Zu={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Bl=i.createContext(Zu);function em({value:e,children:s}){return t.jsx(Bl.Provider,{value:e,children:s})}function yt(){return i.useContext(Bl)}function tm(e){let s=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)s^=n.charCodeAt(a),s=Math.imul(s,16777619)>>>0;s^=255,s=Math.imul(s,16777619)>>>0}return s.toString(16).padStart(8,"0")}function sm(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function rm(e){return e?tm([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),sm(e.content)]):""}const Ke={size:18};function Ol({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function oo({size:e=Ke.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polyline",{points:"15 18 9 12 15 6"})})}function es({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),t.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),t.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),t.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function Kl({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"9",cy:"7",r:"4"}),t.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),t.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function nm({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function am({size:e=Ke.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.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 Fl({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),t.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"}),t.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),t.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function om({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),t.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),t.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),t.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function Nn({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"3"}),t.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 Wl({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),t.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function im({size:e=Ke.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Vt({size:e=Ke.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.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 It({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function io({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),t.jsx("polyline",{points:"14 2 14 8 20 8"}),t.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),t.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function lm({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"11",cy:"11",r:"8"}),t.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function gs({size:e=Ke.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.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 wr({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"23 4 23 10 17 10"}),t.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function gr({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),t.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Es({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M12 22v-5"}),t.jsx("path",{d:"M9 8V2"}),t.jsx("path",{d:"M15 8V2"}),t.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function Qt({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"5",r:"2"}),t.jsx("circle",{cx:"5",cy:"19",r:"2"}),t.jsx("circle",{cx:"19",cy:"19",r:"2"}),t.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),t.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),t.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function cm({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polygon",{points:"12 2 2 7 12 12 22 7 12 2"}),t.jsx("polyline",{points:"2 12 12 17 22 12"}),t.jsx("polyline",{points:"2 17 12 22 22 17"})]})}function Hl({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),t.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function lo({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.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"}),t.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),t.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Ul({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function dm({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),t.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),t.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function co({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"4 17 10 11 4 5"}),t.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function um({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function uo({size:e=Ke.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function zl({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function gt({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function mm({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.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"}),t.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),t.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function pm({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),t.jsx("path",{d:"M12 2v6"}),t.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function fm({size:e=Ke.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.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 hm({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),t.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 Cn({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),t.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function xm({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"5"}),t.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),t.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),t.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),t.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),t.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),t.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),t.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),t.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function bm({size:e=Ke.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function gm({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function ym({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),t.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function vm({size:e=Ke.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function wm({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),t.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 jm({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.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"}),t.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 km({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),t.jsx("path",{d:"M13 2h9v9"}),t.jsx("path",{d:"M22 2L13 11"})]})}function Sm({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"9 14 4 9 9 4"}),t.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function Nm({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),t.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),t.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),t.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),t.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),t.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),t.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),t.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),t.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),t.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function Cm({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),t.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 Im({size:e=Ke.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),t.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),t.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const mo="adhdev_chat_activity_visible",li=new Set(["hidden","debug","internal"]),ci=new Set(["visible","user","chat"]),Tm=new Set(["debug","trace","internal"]),Am=new Set(["tool_call","terminal_command","runtime_activity"]),Mm=new Set(["runtime_status","provider_chrome","control"]),Lm=new Set(["thought","tool","terminal"]);function Vl(e){const s=e.meta;return s&&typeof s=="object"&&!Array.isArray(s)?s:null}function Ns(e){return typeof e=="string"?e.trim().toLowerCase():""}function Wn(e,s,r){return e[r]??(s==null?void 0:s[r])}function di(e,s,r){const n=e;return r.some(a=>n[a]===!0||(s==null?void 0:s[a])===!0)}function Rm(e,s){const r=Ns(e.kind);return r||(s==="tool"?"tool":"standard")}function Hn(e,s,r){const n=Vl(e),a=typeof(n==null?void 0:n.label)=="string"?n.label.trim():"";return a||(s==="terminal"||r==="terminal_command"?"Terminal":s==="tool"||r==="tool_call"?"Tool":s==="thought"?"Thought":r==="runtime_activity"?"Runtime":"Activity")}function _m(e){const s=e.content;return Array.isArray(s)&&s.some(r=>!!r&&typeof r=="object"&&r.type!=="text")}function po(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const s=Vl(e),r=Ns(e.role),n=Rm(e,r),a=Ns(Wn(e,s,"visibility")),o=Ns(e.transcriptVisibility??(s==null?void 0:s.transcriptVisibility)??a),l=Ns(Wn(e,s,"audience")),c=Ns(Wn(e,s,"source")),d=li.has(a)||li.has(o)||Tm.has(l)||di(e,s,["internal","isInternal","debug","statusOnly","controlOnly"]),m=ci.has(a)||ci.has(o)||l==="chat"||di(e,s,["userFacing"]),u=Lm.has(n)||Am.has(c);if(d)return{surface:u?"activity":"internal",isUserFacing:!1,isActivityFacing:u,isInternal:!u,role:r,kind:n,label:Hn(e,n,c)};if(m)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:Hn(e,n,c)};if((r==="system"||n==="system")&&_m(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:"Chat"};if(Mm.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:Hn(e,n,c)};const h=(r==="user"||r==="human"||r==="assistant")&&(n==="standard"||n==="");return{surface:h?"chat":"internal",isUserFacing:h,isActivityFacing:!1,isInternal:!h,role:r,kind:n,label:h?"Chat":"Internal"}}function Pm(e){return(Array.isArray(e)?e:[]).filter(s=>po(s).isUserFacing)}function Gl(e){return(Array.isArray(e)?e:[]).filter(s=>po(s).isActivityFacing)}function Dm(e,s,r){return!r||s.length===0?e:[...e,...s].sort((n,a)=>{const o=Number(n.receivedAt??n.timestamp??0)||0,l=Number(a.receivedAt??a.timestamp??0)||0;if(o!==l)return o-l;const c=Number(n.index??0)||0,d=Number(a.index??0)||0;return c-d})}function ui(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(mo))==="1"}catch{return!1}}function Em(e,s=typeof localStorage<"u"?localStorage:void 0){try{s==null||s.setItem(mo,e?"1":"0")}catch{}}const ql=[yu,{singleTilde:!1}],Yl=[ql,vu,wu],$m=[ql],fo=200,Bm=80,mi=650,Gs=new Map;function dn(e,s){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(s||""):!0}function Om(e,s){if(!Array.isArray(e)||e.length===0)return"0:empty";const r=String(s||"").trim();if(r)return`${e.length}:${r}`;const n=e[e.length-1];return`${e.length}:${rm(n)}`}function Km(e,s,r,n){return e||!s?!1:dn(r,n)}function Fm({scrollTop:e,scrollHeight:s,clientHeight:r,topThresholdPx:n=Bm,bottomThresholdPx:a=fo}){const o=Math.max(0,Number(e)||0),l=Math.max(0,Number(s)||0),c=Math.max(0,Number(r)||0);return Math.max(0,l-c)<=0?{showTop:!1,showBottom:!1}:{showTop:o>n,showBottom:Math.max(0,l-o-c)>a}}function Wm(e){return Fm({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function ir(e,s=fo){return!!e&&e.fromBottom>=s}function Hm(e,s){return dn(e,s)?!ir(e):!0}function Um({hasSelection:e,userScrolledUp:s,hasChatContentChanged:r=!0}){return!(e||s||!r)}function zm({hasSelection:e,userScrolledUp:s,contextAutoScrollActive:r}){return e?!1:r||!s}function Un(e,s){const r=Math.max(0,e.scrollHeight-e.clientHeight-s.fromBottom);e.scrollTop=Number.isFinite(r)?r:s.top}function Xl(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Vm(e,s,r){return Number(e.receivedAt||r[un(e,s)]||0)||0}function Jl(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Gm(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function qs(e,s){if(!e)return s;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||s}catch{return e.split(/[\\/]/).filter(Boolean).pop()||s}}function zn(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 Dr(e,s,r){return t.jsxs("div",{className:"rounded-md border border-border-subtle p-2 text-sm",role:"note",children:[t.jsx("span",{className:"font-medium",children:e}),s?t.jsx("span",{className:"ml-1 break-all",children:s}):null,r?t.jsx("div",{className:"mt-1 opacity-80",style:{whiteSpace:"pre-wrap"},children:r}):null]})}function pi(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):Jl(e)?t.jsx(ro,{remarkPlugins:Yl,children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function Ys({parts:e,renderAsPreformatted:s}){return t.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return t.jsx("div",{children:pi(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const a=zn(r),o=r.alt||r.description||qs(r.uri,"image");return a?t.jsx("img",{src:a,alt:o,className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):t.jsx("div",{children:Dr("Image",o,r.mimeType)},`image-fallback-${n}`)}if(r.type==="audio"){const a=zn(r);return a?t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("audio",{controls:!0,src:a,className:"max-w-full"}),r.transcript?t.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:r.transcript}):null]},`audio-${n}`):t.jsx("div",{children:Dr("Audio",qs(r.uri,"audio"),r.transcript||r.mimeType)},`audio-fallback-${n}`)}if(r.type==="video"){const a=zn(r),o=r.title||r.name||r.alt||qs(r.uri,"video"),l=[r.transcript,r.description,r.mimeType].filter(Boolean).join(`
3
+ `);return t.jsxs("div",{className:"flex flex-col gap-1",children:[a?t.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):Dr("Video",o,l),a&&l?t.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:l}):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 t.jsxs("div",{className:"flex flex-col gap-1",children:[r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",download:!0,className:"underline break-all",children:a}):Dr("Resource",a,o),r.uri&&o?t.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 t.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[t.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),pi(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return t.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${n}`)}return null})})}function un(e,s){const r=e,n=ao(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:${s}`].filter(Boolean).join("|")}const qm=i.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(ro,{remarkPlugins:$m,children:s.text}),t.jsx("span",{className:"action-time",children:Xl(s.timestamp)})]})},(e,s)=>e.log===s.log),Ym=i.memo(function({message:s,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:l,onToggleTextExpanded:c}){var k,j,O;const d=(s.role||"").toLowerCase(),m=d==="user"||d==="human",u=s.kind||(d==="tool"?"tool":"standard"),h=po(s),g=Gm(s.content)?s.content:null,v=!!(g!=null&&g.some(R=>R.type!=="text")),f=ao(s.content,{joiner:`
6
+ `});if(h.isActivityFacing&&u!=="thought"&&u!=="tool"&&u!=="terminal"){const R=h.label||"Activity";return t.jsxs("div",{className:"self-start chat-msg-activity","data-chat-activity-row":"true",children:[t.jsxs("div",{className:"chat-msg-activity-meta","aria-label":"Activity message",children:[t.jsx("span",{className:"activity-dot"}),t.jsx("span",{children:R})]}),v&&g?t.jsx("div",{className:"chat-msg-activity-body",children:t.jsx(Ys,{parts:g,renderAsPreformatted:!1})}):t.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:f})]})}if(u==="thought"){const R=typeof((k=s.meta)==null?void 0:k.label)=="string"?s.meta.label:"Thought";return t.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":h.isActivityFacing?"true":void 0,children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx(fm,{size:13}),t.jsx("span",{children:R})]}),t.jsx("div",{className:"chat-msg-body",children:f})]})}if(u==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":h.isActivityFacing?"true":void 0,children:[t.jsxs("div",{className:"chat-msg-tool-meta","aria-label":"Tool message",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),t.jsx("span",{className:"tool-label",children:"Tool"})]}),v&&g?t.jsx("div",{className:"tool-text w-full",children:t.jsx(Ys,{parts:g,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:f})]});if(u==="terminal"){const R=(j=s.meta)!=null&&j.isRunning?"⏳":"✅",T=typeof((O=s.meta)==null?void 0:O.label)=="string"?s.meta.label:"Ran command";return t.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":h.isActivityFacing?"true":void 0,children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx("span",{children:R}),t.jsx("span",{children:T})]}),v&&g?t.jsx("div",{className:"chat-msg-body",children:t.jsx(Ys,{parts:g,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:f})]})}if(u==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:v&&g?t.jsx(Ys,{parts:g,renderAsPreformatted:!1}):f.slice(0,100)});const p=s.meta,y=(typeof(p==null?void 0:p.renderMode)=="string"?p.renderMode.trim():"")==="preformatted",x=f,N=!1,S=x,w=y,A=!w&&Jl(S),L=["chat-message-row",m?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return t.jsx("div",{className:L,children:(x||v||m)&&t.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${x||v?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:m?a||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:Xl(r)})]}),(x||v)&&t.jsx("div",{className:"chat-markdown",children:v&&g?t.jsx(Ys,{parts:g,renderAsPreformatted:w}):w?t.jsx("pre",{className:"chat-preformatted",children:S}):A?t.jsx(ro,{remarkPlugins:Yl,children:S}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:S})}),N]})})},(e,s)=>e.message===s.message&&e.receivedAt===s.receivedAt&&e.agentName===s.agentName&&e.userName===s.userName&&e.isCliMode===s.isCliMode&&e.isTextExpanded===s.isTextExpanded),Xm=i.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:o=!1,isWorking:l=!1,contextKey:c="",receivedAtMap:d={},lastMessageHash:m,showActivityMessages:u=!1,emptyState:h,onLoadMore:g,isLoadingMore:v,hasMoreHistory:f,hiddenLiveCount:p=0,loadError:b,scrollToBottomRequestNonce:y,isVisible:x=!0},N){const S=i.useRef(null),w=i.useRef(null),A=i.useRef(null),L=i.useRef(0),k=i.useRef(""),j=i.useRef(""),O=i.useRef(!1),R=i.useRef(null),T=i.useRef(!1),F=i.useRef(null),W=i.useRef(!1),[D,C]=i.useState(new Set),[I,K]=i.useState({showTop:!1,showBottom:!1}),_=i.useRef(!1),E=i.useRef(!1),V=i.useRef(x),Y=i.useRef(x),ge=i.useRef(null);Y.current=x;const pe=()=>{const te=S.current;return te?te.scrollHeight-te.scrollTop-te.clientHeight<fo:!0},re=i.useCallback(()=>{const te=S.current,ie=te?Wm(te):{showTop:!1,showBottom:!1};K(se=>se.showTop===ie.showTop&&se.showBottom===ie.showBottom?se:ie)},[]),de=i.useCallback((te="auto")=>{var se;const ie=S.current;ie&&(ie.scrollTo({top:ie.scrollHeight,behavior:te}),(se=ie.ownerDocument.defaultView)==null||se.requestAnimationFrame(()=>re()))},[re]),ke=i.useCallback((te="auto")=>{var se;const ie=S.current;ie&&(ie.scrollTo({top:0,behavior:te}),(se=ie.ownerDocument.defaultView)==null||se.requestAnimationFrame(()=>re()))},[re]),ye=i.useCallback(()=>{var Ie;const te=S.current,ie=(Ie=window.getSelection)==null?void 0:Ie.call(window);if(!te||!ie||ie.rangeCount===0||ie.isCollapsed){W.current=!1;return}const se=ie.anchorNode,ve=ie.focusNode;W.current=!!(se&&ve&&te.contains(se)&&te.contains(ve))},[]),q=i.useMemo(()=>{const te=Pm(s),ie=Gl(s);return Dm(te,ie,u)},[s,u]),he=q.length===s.length?m:void 0,fe=Om(q,he),we=i.useCallback(()=>{const te=S.current;if(!te||!c||!Y.current)return;const ie={top:te.scrollTop,fromBottom:Math.max(0,te.scrollHeight-te.scrollTop-te.clientHeight),messageFingerprint:fe};ge.current={contextKey:c,snapshot:ie},Gs.set(c,ie)},[c,fe]),xe=i.useCallback((te="auto")=>{R.current!=null&&cancelAnimationFrame(R.current),R.current=requestAnimationFrame(()=>{R.current=null,de(te)})},[de]),Se=i.useCallback(()=>{_.current=!1,T.current=!0,E.current=!0,F.current!=null&&window.clearTimeout(F.current),F.current=window.setTimeout(()=>{T.current=!1,F.current=null},mi)},[]);i.useEffect(()=>{const te=!O.current,ie=j.current!==c;if(j.current=c,te||ie){O.current=!0;const ve=c?Gs.get(c):null,Ie=!!ve&&dn(ve,fe);_.current=Ie?ir(ve):!1,T.current=Hm(ve,fe),W.current||(Ie?requestAnimationFrame(()=>{const Me=S.current;Me&&(Un(Me,ve),_.current=ir(ve),re(),E.current=!0)}):xe("auto")),L.current=q.length,k.current=fe;return}q.length>L.current;const se=fe!==k.current;Um({hasSelection:W.current,userScrolledUp:_.current,hasChatContentChanged:se})&&xe("auto"),L.current=q.length,k.current=fe},[fe,c,q.length,xe,re]),i.useEffect(()=>{y&&(Se(),W.current||xe("auto"))},[Se,xe,y]),i.useEffect(()=>{const te=V.current;te&&!x&&we(),Y.current=x,V.current=x;const ie=c?Gs.get(c):null;if(Km(te,x,ie,fe)){if(!ie)return;_.current=ir(ie),T.current=!1,W.current||requestAnimationFrame(()=>{const se=S.current;se&&(Un(se,ie),re())});return}},[x,c,fe,Se,we,xe,re]),i.useEffect(()=>()=>{const te=ge.current;te&&Gs.set(te.contextKey,te.snapshot),R.current!=null&&cancelAnimationFrame(R.current),F.current!=null&&window.clearTimeout(F.current)},[]),i.useEffect(()=>{const te=w.current,ie=S.current;if(!te||!ie)return;const se=()=>{F.current!=null&&window.clearTimeout(F.current),F.current=window.setTimeout(()=>{T.current=!1,F.current=null},mi)},ve=new ResizeObserver(()=>{re();const Ie=T.current;zm({hasSelection:W.current,userScrolledUp:_.current,contextAutoScrollActive:Ie})&&(xe("auto"),Ie&&se())});return ve.observe(te),ie!==te&&ve.observe(ie),()=>{ve.disconnect(),F.current!=null&&(window.clearTimeout(F.current),F.current=null)}},[xe,c,re]),i.useImperativeHandle(N,()=>({scrollToBottom:(te="smooth")=>{de(te)}}),[de]),i.useEffect(()=>{const te=S.current;if(!te)return;let ie;const se=()=>{we(),clearTimeout(ie),ie=setTimeout(()=>{_.current=!pe(),re()},50)};return te.addEventListener("scroll",se,{passive:!0}),()=>{te.removeEventListener("scroll",se),clearTimeout(ie)}},[we,re]),i.useEffect(()=>(document.addEventListener("selectionchange",ye),()=>document.removeEventListener("selectionchange",ye)),[ye]);const Q=i.useRef(0),ue=i.useRef(!1);i.useEffect(()=>{const te=S.current;if(!te||!ue.current||Q.current===0)return;const ie=te.scrollHeight-Q.current;ie>0&&(te.scrollTop=ie),re(),we(),Q.current=0,ue.current=!1},[q.length,we,re]),i.useEffect(()=>{if(E.current||!c)return;const te=Gs.get(c),ie=S.current;if(!(!te||!ie)){if(!dn(te,fe)){de("auto"),E.current=!0;return}Un(ie,te),_.current=ir(te),re(),E.current=!0}},[c,fe,q.length,de,re]);const oe=()=>{const te=S.current;te&&(Q.current=te.scrollHeight),ue.current=!0,g==null||g()},me=()=>{_.current=!0,ke("smooth"),we()},le=()=>{Se(),de("smooth"),we()},P=i.useMemo(()=>{const te=q.map((Ie,Me)=>({type:"message",data:Ie,index:Me,ts:Vm(Ie,Me,d)}));if(!r||r.length===0)return te;const ie=[...r].sort((Ie,Me)=>Ie.timestamp-Me.timestamp).map((Ie,Me)=>({type:"action",data:Ie,index:Me,ts:Ie.timestamp})),se=[];let ve=0;for(const Ie of te){for(;ve<ie.length&&Ie.ts>0&&ie[ve].ts<Ie.ts;)se.push(ie[ve++]);se.push(Ie)}for(;ve<ie.length;)se.push(ie[ve++]);return se},[q,r,d]),U=p>0||!!f,ce=p>0?`↑ Show ${Math.min(p,80)} earlier messages${p>80?` (${p} hidden)`:""}`:b?`↻ ${b}`:"↑ Load older messages";return t.jsxs("div",{className:"chat-scroll-frame",children:[t.jsx("div",{ref:S,"data-chat-scroll":!0,className:"chat-container",children:t.jsxs("div",{ref:w,className:"chat-container-content",children:[v&&t.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),U&&!v&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{type:"button",onClick:oe,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${b&&p===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:ce})}),P.length===0&&!U&&(h||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),P.map(te=>{if(te.type==="action"){const Ne=te.data;return t.jsx(qm,{log:Ne},`action-${te.index}`)}const ie=te.data,se=te.index,ve=un(ie,se),Ie=ie.receivedAt||d[ve],Me=`${c}-${ve}`,B=D.has(Me);return t.jsx(Ym,{message:ie,receivedAt:Ie,agentName:n,userName:a,isCliMode:o,isTextExpanded:B,onToggleTextExpanded:()=>C(Ne=>{const Re=new Set(Ne);return B?Re.delete(Me):Re.add(Me),Re})},`msg-${ve}`)}),l&&t.jsx("div",{className:"self-start chat-typing-wrapper",children:t.jsxs("div",{className:"typing-indicator",children:[t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),t.jsx("div",{className:"min-h-10",ref:A})]})}),(I.showTop||I.showBottom)&&t.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[I.showTop&&t.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:me,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),I.showBottom&&t.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:le,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Jm=i.memo(Xm,(e,s)=>e.messages===s.messages&&e.actionLogs===s.actionLogs&&e.agentName===s.agentName&&e.userName===s.userName&&e.isCliMode===s.isCliMode&&e.isWorking===s.isWorking&&e.contextKey===s.contextKey&&e.receivedAtMap===s.receivedAtMap&&e.lastMessageHash===s.lastMessageHash&&e.showActivityMessages===s.showActivityMessages&&e.emptyState===s.emptyState&&e.onLoadMore===s.onLoadMore&&e.isLoadingMore===s.isLoadingMore&&e.hasMoreHistory===s.hasMoreHistory&&e.hiddenLiveCount===s.hiddenLiveCount&&e.loadError===s.loadError&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isVisible===s.isVisible),Qm="modulepreload",Zm=function(e){return"/"+e},fi={},ep=function(s,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));a=Promise.allSettled(r.map(d=>{if(d=Zm(d),d in fi)return;fi[d]=!0;const m=d.endsWith(".css"),u=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const h=document.createElement("link");if(h.rel=m?"stylesheet":Qm,m||(h.as="script"),h.crossOrigin="",h.href=d,c&&h.setAttribute("nonce",c),document.head.appendChild(h),m)return new Promise((g,v)=>{h.addEventListener("load",g),h.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return a.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return s().catch(o)})};let hi=!1;const Ql=i.forwardRef(({onInput:e,onViewportMetrics:s,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:o="measured"},l)=>{const c=i.useRef(null),[d,m]=i.useState(null),u=i.useRef([]),h=i.useRef(!1),g=i.useRef(!1),v=i.useRef(!1),f=i.useRef(!1),p=()=>{const b=c.current;if(b){h.current&&(b.clear(),h.current=!1);for(const y of u.current)b.write(y.data,y.onProcessed);u.current=[],g.current&&(b.fit(),g.current=!1),v.current&&(b.bumpResize(),v.current=!1),f.current&&(b.scrollToTop(),f.current=!1)}};return i.useImperativeHandle(l,()=>({write:(b,y)=>{c.current?c.current.write(b,y):u.current.push({data:b,onProcessed:y})},clear:()=>{c.current?c.current.clear():(u.current=[],h.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(u.current=[],h.current=!0)},resize:(b,y)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(b,y)},fit:()=>{c.current?c.current.fit():g.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():v.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():f.current=!0},getSelection:()=>{var b,y;return((y=(b=c.current)==null?void 0:b.getSelection)==null?void 0:y.call(b))||""},getVisibleText:()=>{var b,y;return((y=(b=c.current)==null?void 0:b.getVisibleText)==null?void 0:y.call(b))||""}}),[]),i.useEffect(()=>{d&&p()},[d]),i.useEffect(()=>{let b=!1;return ep(()=>import("./terminal-DCVDkSIp.js"),__vite__mapDeps([0,1,2])).then(y=>{hi||(hi=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),b||m(()=>y.GhosttyTerminalView)}).catch(y=>{console.error("[CliTerminal] failed to load terminal renderer",y)}),()=>{b=!0}},[]),d?t.jsx(d,{ref:c,onInput:e,onViewportMetrics:s,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:o,className:"w-full h-full rounded-lg overflow-hidden"}):t.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});Ql.displayName="CliTerminal";function Er({label:e,value:s,sub:r,icon:n}){return t.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[t.jsx("span",{className:"text-base flex items-center",children:n}),t.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),t.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:s}),r&&t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function xi({value:e,max:s,label:r,color:n="#8b5cf6",detail:a,compact:o=!1}){const l=s>0?Math.min(Math.round(e/s*100),100):0,c=l>85?"#ef4444":l>60?"var(--status-warning)":n;return o?t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex justify-between mb-0.5",children:[t.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),t.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[l,"%"]})]}),t.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:t.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${l}%`,background:c}})})]}):t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex justify-between mb-1.5",children:[t.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),t.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[l,"%"]})]}),t.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:t.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${l}%`,background:`linear-gradient(90deg, ${c}, ${c}cc)`}})}),a&&t.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function tp({cursorPos:e,viewportRef:s,imgRef:r}){var x;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(x=s.current)==null?void 0:x.getBoundingClientRect();if(!o)return null;const l=n.naturalWidth||a.width,c=n.naturalHeight||a.height,d=l/c,m=a.width/a.height;let u,h,g,v;d>m?(u=a.width,h=a.width/d,g=0,v=(a.height-h)/2):(h=a.height,u=a.height*d,g=(a.width-u)/2,v=0);const f=a.left-o.left+g+u*e.nx,p=a.top-o.top+v+h*e.ny,b=Math.max(8,Math.min(o.width-8,f)),y=Math.max(8,Math.min(o.height-8,p));return t.jsxs("div",{style:{position:"absolute",left:b-8,top:y-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[t.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),t.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),t.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 sp({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:l,setImeText:c,handleImeSubmit:d,isConnActive:m,zoom:u,isMobile:h,mobileFillZoom:g,onZoomOut:v,onZoomReset:f,onZoomIn:p,transportType:b,screenshotUsage:y,lastActionStatus:x}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:N=>N.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:[t.jsxs("div",{onClick:s,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:[t.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),t.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),t.jsxs("div",{className:"relative",children:[t.jsx("div",{onClick:()=>{n(N=>!N),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:t.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&t.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:t.jsx("input",{type:"text",placeholder:"Type & Enter...",value:l,autoFocus:!0,onTouchStart:N=>N.stopPropagation(),onChange:N=>c(N.target.value),onKeyDown:N=>{d(N)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),t.jsx("div",{className:"relative",children:t.jsx("div",{onClick:()=>{o(N=>!N),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:t.jsx("span",{className:"text-sm",children:"⚙️"})})}),t.jsx("div",{className:"w-px h-[18px] bg-white/10"}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.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:[t.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:m?"#22c55e":"#eab308",boxShadow:m?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:m?"#22c55e":"#eab308"},children:m?"Connected":"WS"})]}),u>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),b==="direct"&&t.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"}),b==="relay"&&t.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&&t.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`}),x&&t.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:x})]})]}),a&&t.jsxs("div",{onTouchStart:N=>N.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:[t.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",u<=(h?g:1)+.01?h?"FILL":"FIT":`${Math.round(u*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:N=>{N.stopPropagation(),v()},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:"−"}),t.jsx("button",{onClick:N=>{N.stopPropagation(),f()},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:h?"FILL":"FIT"}),t.jsx("button",{onClick:N=>{N.stopPropagation(),p()},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 rp({waitingLabel:e,waitingHint:s,transportType:r}){return t.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[t.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:t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),t.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),t.jsx("div",{className:"text-[11px] text-white/40",children:s}),r==="relay"&&t.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function np(){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 bi(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 jr(e,s){const r=i.useRef(null),n=i.useRef(0);i.useEffect(()=>{if(!np())return;n.current+=1;const a=r.current;if(!a){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(s).map(([l,c])=>[l,bi(c)]))}),r.current=s;return}const o=Object.keys({...a,...s}).filter(l=>!Object.is(a[l],s[l]));o.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:o,snapshot:Object.fromEntries(o.map(l=>[l,bi(s[l])]))}),r.current=s})}function ap({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:l,panXRef:c,panYRef:d,setPanX:m,setPanY:u,setZoom:h,lastWheelTimeRef:g,onAction:v,setLastActionStatus:f,spawnRippleFromNormalized:p,clampPan:b,isMobile:y,mobileFillZoom:x}){const[N,S]=i.useState(null),w=i.useRef(null),A=i.useRef(null),L=i.useRef(null),k=i.useRef(!1),j=i.useRef(null),O=i.useRef(0),R=i.useRef(null),T=i.useRef(1),F=i.useRef({x:0,y:0}),W=i.useRef(!1),D=i.useRef(n),C=i.useRef(v),I=30,K=550,_=18,E=60,V=400,Y=12,ge=()=>{if(w.current)return;const de={nx:.5,ny:.5};w.current=de,S(de)};return i.useEffect(()=>{D.current=n,n==="mouse"&&ge()},[n]),i.useEffect(()=>{C.current=v},[v]),i.useEffect(()=>{const de=e.current;if(!de)return;const ke=xe=>{if(!r.current)return null;const Se=r.current.getBoundingClientRect();return!Se.width||!Se.height?null:{nx:Math.max(0,Math.min(1,(xe.clientX-Se.left)/Se.width)),ny:Math.max(0,Math.min(1,(xe.clientY-Se.top)/Se.height))}},ye=(xe,Se)=>{if(!r.current)return{dnx:0,dny:0};const Q=r.current,ue=Q.getBoundingClientRect(),oe=Q.naturalWidth||ue.width,me=Q.naturalHeight||ue.height,le=oe/me,P=ue.width/ue.height;let U,ce;return le>P?(U=ue.width,ce=ue.width/le):(ce=ue.height,U=ue.height*le),{dnx:xe/U,dny:Se/ce}},q=(xe,Se,Q)=>{if(Q<=1.05)return;const ue=-(xe-.5)*100,oe=-(Se-.5)*100,me=b(ue,oe,Q);(Math.abs(me.x-c.current)>.1||Math.abs(me.y-d.current)>.1)&&(m(me.x),u(me.y),c.current=me.x,d.current=me.y)},he=xe=>{const Se=s.current;if(Se&&xe.target instanceof Node&&Se.contains(xe.target))xe.preventDefault();else return;if(xe.touches.length===1){const Q=xe.touches[0];A.current={x:Q.clientX,y:Q.clientY,time:Date.now()},L.current={x:Q.clientX,y:Q.clientY},W.current||(k.current=!1),j.current=setTimeout(()=>{if(!k.current&&!W.current)if(k.current=!0,D.current==="mouse"){const ue=w.current||{nx:.5,ny:.5};f("Right Click"),p(ue.nx,ue.ny,"right"),C.current("input_click",{...ue,button:"right"}).catch(()=>{})}else{const ue=ke(Q);ue&&(f("Right Click"),p(ue.nx,ue.ny,"right"),C.current("input_click",{...ue,button:"right"}).catch(()=>{}))}},500);return}if(xe.touches.length===2){j.current&&clearTimeout(j.current),k.current=!0,W.current=!0;const Q=xe.touches[1].clientX-xe.touches[0].clientX,ue=xe.touches[1].clientY-xe.touches[0].clientY;R.current=Math.sqrt(Q*Q+ue*ue),T.current=l.current,F.current={x:(xe.touches[0].clientX+xe.touches[1].clientX)/2,y:(xe.touches[0].clientY+xe.touches[1].clientY)/2}}},fe=xe=>{const Se=s.current;if(Se&&xe.target instanceof Node&&Se.contains(xe.target)&&xe.preventDefault(),xe.touches.length===1&&L.current){const Q=xe.touches[0],ue=Q.clientX-L.current.x,oe=Q.clientY-L.current.y;if(!k.current&&A.current){const me=Q.clientX-A.current.x,le=Q.clientY-A.current.y;Math.sqrt(me*me+le*le)>8&&(k.current=!0,j.current&&clearTimeout(j.current))}if(k.current)if(D.current==="mouse"){const me=ye(ue,oe),le=w.current||{nx:.5,ny:.5},P=Math.max(0,Math.min(1,le.nx+me.dnx)),U=Math.max(0,Math.min(1,le.ny+me.dny));w.current={nx:P,ny:U},S({nx:P,ny:U}),f(`Cursor: ${Math.round(P*100)}%, ${Math.round(U*100)}%`),q(P,U,l.current);const ce=Date.now();ce-g.current>=30&&(g.current=ce,C.current("input_mouseMoved",{nx:P,ny:U}).catch(()=>{}))}else if(l.current>1){const me=s.current;if(me){const le=me.clientWidth,P=me.clientHeight,U=c.current+ue/le*100,ce=d.current+oe/P*100,te=b(U,ce,l.current);m(te.x),u(te.y),c.current=te.x,d.current=te.y}}else{const me=ke(Q);if(me){const le=Date.now();le-g.current>=40&&(g.current=le,f("Scroll"),C.current("input_wheel",{nx:me.nx,ny:me.ny,deltaX:Math.round(-ue*2.5),deltaY:Math.round(-oe*2.5)}).catch(()=>{}))}}L.current={x:Q.clientX,y:Q.clientY};return}if(xe.touches.length===2&&R.current!==null){const Q=xe.touches[1].clientX-xe.touches[0].clientX,ue=xe.touches[1].clientY-xe.touches[0].clientY,me=Math.sqrt(Q*Q+ue*ue)/R.current,le=(xe.touches[0].clientX+xe.touches[1].clientX)/2,P=(xe.touches[0].clientY+xe.touches[1].clientY)/2,U=le-F.current.x,ce=P-F.current.y,te=Math.abs(me-1)>.03;if(D.current==="mouse"){if(te){const ie=Math.max(o,Math.min(5,T.current*me));h(ie),l.current=ie}else if(Math.abs(U)>2||Math.abs(ce)>2){const ie=w.current||{nx:.5,ny:.5},se=Date.now();se-g.current>=30&&(g.current=se,f("Scroll"),C.current("input_wheel",{nx:ie.nx,ny:ie.ny,deltaX:Math.round(-U*3),deltaY:Math.round(-ce*3)}).catch(()=>{}))}}else{const ie=Math.max(o,Math.min(5,T.current*me));h(ie),l.current=ie;const se=s.current;if(se&&ie>1){const ve=se.clientWidth,Ie=se.clientHeight,Me=c.current+U/ve*100,B=d.current+ce/Ie*100,Ne=b(Me,B,ie);m(Ne.x),u(Ne.y),c.current=Ne.x,d.current=Ne.y}}F.current={x:le,y:P}}},we=xe=>{var Se;if(j.current&&clearTimeout(j.current),R.current=null,xe.touches.length===1&&W.current){const Q=xe.touches[0];A.current={x:Q.clientX,y:Q.clientY,time:Date.now()},L.current={x:Q.clientX,y:Q.clientY},k.current=!0;return}if(xe.touches.length===0){if(W.current){W.current=!1,k.current=!1;return}if(xe.changedTouches.length===1){const Q=xe.changedTouches[0],ue=Date.now(),oe=ue-(((Se=A.current)==null?void 0:Se.time)||0),me=A.current?Q.clientX-A.current.x:0,le=A.current?Q.clientY-A.current.y:0,P=Math.sqrt(me*me+le*le);if(D.current==="mouse"){if(oe<I||oe>K||P>_){k.current=!1;return}const U=w.current||ke(Q);U&&(f(`Click: ${Math.round(U.nx*100)}%, ${Math.round(U.ny*100)}%`),p(U.nx,U.ny,"left"),C.current("input_click",{...U}).catch(()=>{}))}else{if(k.current){k.current=!1;return}if(oe<E||oe>V||P>Y){k.current=!1;return}const U=ke(Q);if(!U)return;ue-O.current<300?(f("Double tap"),p(U.nx,U.ny,"double"),C.current("input_click",{...U,clickCount:2}).catch(()=>{}),O.current=0):(f(`Tap: ${Math.round(U.nx*100)}%, ${Math.round(U.ny*100)}%`),p(U.nx,U.ny,"left"),C.current("input_click",{...U}).catch(()=>{}),O.current=ue)}}k.current=!1}};return de.addEventListener("touchstart",he,{passive:!1}),de.addEventListener("touchmove",fe,{passive:!1}),de.addEventListener("touchend",we,{passive:!1}),()=>{de.removeEventListener("touchstart",he),de.removeEventListener("touchmove",fe),de.removeEventListener("touchend",we),j.current&&clearTimeout(j.current)}},[e,s,r,o,l,c,d,m,u,h,g,f,p,b]),{cursorPos:N,cursorPosRef:w,handleToggleInputMode:()=>{a(de=>{const ke=de==="touch"?"mouse":"touch";return ke==="mouse"&&ge(),ke})},handleZoomReset:()=>{const de=y?x:1;h(de),l.current=de,m(0),u(0),c.current=0,d.current=0}}}function Zl({onAction:e,addLog:s,connState:r,connScreenshot:n,screenshotUsage:a,transportType:o}){const l=i.useRef(null),c=i.useRef(null),d=i.useRef(null),[m,u]=i.useState(null),[h,g]=i.useState(""),[,v]=i.useState(!1),[f,p]=i.useState([]),b=i.useRef(0),[y,x]=i.useState(!1),[N,S]=i.useState(!1),w=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[A,L]=i.useState(w?"mouse":"touch"),[k,j]=i.useState(1),O=i.useRef(!1),[R,T]=i.useState(1),[F,W]=i.useState(0),[D,C]=i.useState(0);jr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:A,zoom:R,panX:F,panY:D,isMenuOpen:y,isImeOpen:N});const I=i.useRef(0),K=i.useRef(R),_=i.useRef(F),E=i.useRef(D);i.useEffect(()=>{K.current=R},[R]),i.useEffect(()=>{_.current=F},[F]),i.useEffect(()=>{E.current=D},[D]),i.useEffect(()=>{var oe;(oe=l.current)==null||oe.focus()},[]);const V=r==="connected",Y=n,ge=V?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",pe=V?"The remote stream is warming up":"Waiting for the remote stream to catch up";i.useEffect(()=>{if(!w||O.current||!Y)return;const oe=d.current,me=c.current;if(!oe||!me)return;const le=()=>{const P=me.clientWidth,U=me.clientHeight,ce=oe.naturalWidth,te=oe.naturalHeight;if(!ce||!te||!P||!U)return;const ie=Math.min(P/ce,U/te),ve=Math.max(P/ce,U/te)/ie;ve>1.01&&(j(ve),T(ve),K.current=ve),O.current=!0};oe.complete&&oe.naturalWidth?le():oe.addEventListener("load",le,{once:!0})},[Y,w]);const re=.5;i.useEffect(()=>{R<=re&&(W(0),C(0))},[R,re]);const de=(oe,me,le)=>{if(le<=re)return{x:0,y:0};const P=(le-1)/(2*le)*100,U=(le-1)/(2*le)*100;return{x:Math.max(-P,Math.min(P,oe)),y:Math.max(-U,Math.min(U,me))}},ke=(oe,me)=>{if(!d.current)return null;const le=d.current.getBoundingClientRect();return!le.width||!le.height?null:{nx:Math.max(0,Math.min(1,(oe-le.left)/le.width)),ny:Math.max(0,Math.min(1,(me-le.top)/le.height))}},ye=(oe,me,le)=>{const P=c.current;if(!P)return;const U=P.getBoundingClientRect(),ce=++b.current;p(te=>[...te,{id:ce,x:oe-U.left,y:me-U.top,type:le}]),setTimeout(()=>p(te=>te.filter(ie=>ie.id!==ce)),600)},q=(oe,me,le)=>{const P=d.current,U=c.current;if(!P||!U)return;const ce=P.getBoundingClientRect(),te=U.getBoundingClientRect(),ie=P.naturalWidth||ce.width,se=P.naturalHeight||ce.height,ve=ie/se,Ie=ce.width/ce.height;let Me,B,Ne,Re;ve>Ie?(Me=ce.width,B=ce.width/ve,Ne=0,Re=(ce.height-B)/2):(B=ce.height,Me=ce.height*ve,Ne=(ce.width-Me)/2,Re=0);const Fe=ce.left-te.left+Ne+Me*oe,He=ce.top-te.top+Re+B*me,Ge=++b.current;p(qe=>[...qe,{id:Ge,x:Fe,y:He,type:le}]),setTimeout(()=>p(qe=>qe.filter(et=>et.id!==Ge)),600)},he=async oe=>{var le;const me=ke(oe.clientX,oe.clientY);if(me){u(`Click: ${Math.round(me.nx*100)}%, ${Math.round(me.ny*100)}%`),ye(oe.clientX,oe.clientY,"left"),(le=l.current)==null||le.focus();try{const P=await e("input_click",{nx:me.nx,ny:me.ny});P!=null&&P.success||s(`❌ Click failed: ${P==null?void 0:P.error}`)}catch(P){s(`❌ Click error: ${P.message||P}`)}}},fe=async(oe,me,le,P=0)=>{try{await e("input_key",{type:le?"char":"keyDown",key:oe,code:me,text:le?oe:void 0,unmodifiedText:le?oe:void 0,modifiers:P})}catch(U){s(`❌ Key error: ${U.message||U}`)}},we=async oe=>{if(oe.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(oe.key)&&oe.preventDefault();let le=0;oe.altKey&&(le|=1),oe.ctrlKey&&(le|=2),oe.metaKey&&(le|=4),oe.shiftKey&&(le|=8),u(`Key: ${oe.key}`),await fe(oe.key,oe.code,oe.key.length===1,le)},xe=async oe=>{if(oe.key==="Enter"){if(oe.nativeEvent.isComposing)return;if(h){const me=h;g(""),u(`IME Sent: ${me}`);try{const le=await e("input_type",{text:me});le!=null&&le.success||s(`❌ IME error: ${le==null?void 0:le.error}`)}catch(le){s(`❌ IME error: ${le.message}`)}}else u("Key: Enter"),await fe("Enter","Enter",!1)}};i.useEffect(()=>{const oe=l.current;if(!oe)return;const me=le=>{var P;if((P=d.current)!=null&&P.contains(le.target)){le.preventDefault();const U=Date.now();if(U-I.current<40)return;I.current=U;const ce=ke(le.clientX,le.clientY);if(!ce)return;u(`Scroll: ${Math.round(le.deltaY)}`),e("input_wheel",{nx:ce.nx,ny:ce.ny,deltaX:Math.round(le.deltaX),deltaY:Math.round(le.deltaY)}).catch(()=>{})}};return oe.addEventListener("wheel",me,{passive:!1}),()=>oe.removeEventListener("wheel",me)},[e]);const{cursorPos:Se,handleToggleInputMode:Q,handleZoomReset:ue}=ap({containerRef:l,viewportRef:c,imgRef:d,inputMode:A,setInputMode:L,minZoom:re,zoomRef:K,panXRef:_,panYRef:E,setPanX:W,setPanY:C,setZoom:T,lastWheelTimeRef:I,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:q,clampPan:de,isMobile:w,mobileFillZoom:k});return t.jsxs("div",{ref:l,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:we,onContextMenu:oe=>oe.preventDefault(),onFocus:()=>v(!0),onBlur:()=>v(!1),tabIndex:0,children:[t.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[Y?t.jsx("img",{ref:d,src:Y,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${R}) translate(${F}%, ${D}%)`,transformOrigin:"center center",cursor:A==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:he,onContextMenu:oe=>oe.preventDefault(),onDragStart:oe=>oe.preventDefault()}):t.jsx(rp,{waitingLabel:ge,waitingHint:pe,transportType:o}),A==="mouse"&&Y&&t.jsx(tp,{cursorPos:Se,viewportRef:c,imgRef:d}),f.map(oe=>{const le={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[oe.type];return t.jsxs("div",{style:{position:"absolute",left:oe.x,top:oe.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${le}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),t.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${le}, 0.9)`,boxShadow:`0 0 12px rgba(${le}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},oe.id)})]}),t.jsx(sp,{inputMode:A,onToggleInputMode:Q,isImeOpen:N,setIsImeOpen:S,isMenuOpen:y,setIsMenuOpen:x,imeText:h,setImeText:g,handleImeSubmit:xe,isConnActive:V,zoom:R,isMobile:w,mobileFillZoom:k,onZoomOut:()=>T(oe=>Math.max(.5,oe-.25)),onZoomReset:ue,onZoomIn:()=>T(oe=>Math.min(5,oe+.25)),transportType:o,screenshotUsage:a,lastActionStatus:m}),t.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 In(e,s={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=s,o=Date.now()-e,l=Math.floor(o/1e3);if(l<a)return n;const c=Math.floor(l/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 ec=e=>In(e);function op(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 Us(e){const s=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",a=e.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:a}}function ip(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...op(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 s}function mn(e,s){if(e.sessionId){const r=s.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 Tn(e,s,r){const n=mn(e,s),a=Us(e),o=a.isReconnecting,l=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,g=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:g,requiresAction:m,isWorking:u,isReconnecting:o,isConnecting:l,isGenerating:c,isWaiting:d,inboxBucket:m?"needs_attention":u?"working":g?"task_complete":"idle"}}function lp(e,s,r){return Tn(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function tc({activeConv:e,onModalButton:s}){const[r,n]=i.useState(null);if(i.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Us(e).isWaiting||!e.modalButtons)return null;const o=c=>{r||(n(c),s(c))},l=c=>c.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return t.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&&t.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)}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[t.jsx(gr,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((c,d)=>{const m=l(c).toLowerCase(),u=/^(run|approve|accept|yes|allow|always)/.test(m),h=/^(reject|deny|delete|remove|abort)/.test(m),g=r===c,v=r!==null;return t.jsx("button",{onClick:()=>o(c),disabled:v,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${u?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${v&&!g?"opacity-40":"opacity-100"} ${v?"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)"}:h?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:g?"⏳ ...":l(c)},d)})})]})]})}const ho="adhdev_controls_bar_visible",$a="adhdev:controlsbarvisibilitychange";function Vn(e){if(!e)return!1;try{return e.getItem(ho)==="1"}catch{return!1}}function cp(e,s){if(s)try{s.setItem(ho,e?"1":"0")}catch{}}function dp(e){typeof window>"u"||window.dispatchEvent(new CustomEvent($a,{detail:{visible:e}}))}function xo(){const[e,s]=i.useState(()=>typeof window>"u"?!1:Vn(window.localStorage)),r=i.useRef(e),n=i.useCallback((l,c=!0)=>{r.current=l,s(l),typeof window<"u"&&cp(l,window.localStorage),c&&dp(l)},[]);i.useEffect(()=>{const l=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:Vn(window.localStorage);r.current=u,s(u)},c=d=>{if(d.key!==ho)return;const m=Vn(window.localStorage);r.current=m,s(m)};return window.addEventListener($a,l),window.addEventListener("storage",c),()=>{window.removeEventListener($a,l),window.removeEventListener("storage",c)}},[]);const a=i.useCallback(l=>{n(l)},[n]),o=i.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:o}}var up=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function mp(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function xt(e,s){if(mp(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":up.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 pn(e){return xt(e)==="generating"}function gi(e,s){return xt(e,s)==="waiting_approval"}function ot(e){return e?e.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" "):"IDE"}function pp(e){if(e<60)return`${Math.round(e)}s`;const s=Math.floor(e/60);if(s<60)return`${s}m`;const r=Math.floor(s/60),n=s%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 Gn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function An(e,s){const r=typeof s=="string"?s.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 fp(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const s=e.split("_"),r=s[s.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function hp(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function xp(e){return fp(e.trim().replace(/\.local$/i,""))}function bp(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function sc(e,s={}){var a,o;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(o=e.system)==null?void 0:o.hostname].find(l=>typeof l=="string"&&l.trim().length>0&&!hp(l));if(r&&r!=="Unknown")return xp(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function Ct(e,s={}){return bp(e)||sc(e,s)}function rc(e){return!e||!Array.isArray(e.items)?[]:e.items.map(s=>String((s==null?void 0:s.value)||(s==null?void 0:s.shortValue)||"").trim()).filter(Boolean)}function nc(e,s,r={}){const n=String(s).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 ys(e,s){return rc(e).join(" · ")}function yr(e){return e.transport==="pty"}function Ls(e){return e.transport==="acp"}function gp(e,s){var r,n;return(r=s==null?void 0:s.providerLabels)!=null&&r[e]?s.providerLabels[e]:(n=s==null?void 0:s.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?s.providerLabels[e.toLowerCase()]:s!=null&&s.agentName&&s.agentName!==e?s.agentName:ot(e)}function yi(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(s||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),l=ot(r||"").trim().toLowerCase();return n===a||n===o||n===l}function yp(e,s=[],r=[]){var d,m,u,h;const n=xt(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=s.find(g=>gi(g.status,{activeModal:g.activeModal})||pn(g.status));if(a)return xt(a.status,{activeModal:a.activeModal});const o=r.find(g=>gi(g.status,{activeModal:g.activeModal})||pn(g.status));if(o)return xt(o.status,{activeModal:o.activeModal});if(n&&n!=="idle")return n;const l=xt((d=s[0])==null?void 0:d.status,{activeModal:(m=s[0])==null?void 0:m.activeModal});if(l!=="idle")return l;const c=xt((u=r[0])==null?void 0:u.status,{activeModal:(h=r[0])==null?void 0:h.activeModal});return c!=="idle"?c:"idle"}function vp(e){return xt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function wp(e){if(!Array.isArray(e)||e.length<=1)return e;const s=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=s.get(a),l=xt(n.status);if(!o){s.set(a,{...n,status:l});continue}const c=r.indexOf(o.status||"idle"),d=r.indexOf(l||"idle");d>=0&&(c<0||d<c)&&s.set(a,{...n,status:l})}return Array.from(s.values())}function jp(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function kp(e){var r,n;const s=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return s&&jp(s.receivedAt)||0}function Sp(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Ba(e){return Math.max(Sp(e),kp(e.activeChat))}function Np(e,s,r,n,a,o){const l=s-e;if(l!==0)return l;const c=r.localeCompare(n);return c!==0?c:a.localeCompare(o)}function bo(e,s){return Np(Ba(e),Ba(s),Ct(e,{fallbackId:e.id}),Ct(s,{fallbackId:s.id}),e.id,s.id)}const ac="adhdev_notification_prefs",vi={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Cp(){try{const e=localStorage.getItem(ac);if(e){const s=JSON.parse(e);return{...vi,...s}}}catch{}return{...vi}}function Ip(e){try{localStorage.setItem(ac,JSON.stringify(e))}catch{}}let Ht=Cp(),Jr=[];function Tp(){Jr.forEach(e=>e())}function Ap(e){Ht={...Ht,...e},Ip(Ht),Tp()}function Mp(){const[,e]=i.useState(0);i.useEffect(()=>{const r=()=>e(n=>n+1);return Jr.push(r),()=>{Jr=Jr.filter(n=>n!==r)}},[]);const s=i.useCallback(r=>{Ap(r)},[]);return[{...Ht},s]}function dr(e){if(!Ht.globalEnabled)return!1;switch(e){case"disconnect":return Ht.disconnectAlert;case"completion":return Ht.completionAlert;case"approval":return Ht.approvalAlert;case"browser":return Ht.browserNotifications;default:return!0}}const Lp={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function oc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function ic(){return"Notification"in window&&Notification.permission==="granted"}let ns=null;function Rp(e){return e!==!1}async function _p(){if(ns!==null)return ns;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return ns=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(ns=!!await e.pushManager.getSubscription(),ns):(ns=!1,!1)}catch{return ns=!1,!1}}function Oa(e,s,r){if(ic())try{const n=new Notification(e,{body:s,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function Pp(e,s={}){const r={...Lp,...s},n=i.useRef(new Map),a=i.useRef(0),[o,l]=i.useState(null);i.useEffect(()=>{let d=!1;return _p().then(m=>{d||l(m)}),()=>{d=!0}},[]);const c=i.useCallback((d,m,u)=>{const h=Date.now();h-a.current<r.throttleMs||(a.current=h,Oa(d,m,u))},[r.throttleMs]);i.useEffect(()=>{var d;if(!(!r.enabled||!ic())&&dr("browser")&&!Rp(o)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,xt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const u=n.current.get(m.id),h=xt(m.status,{activeModal:m.activeModal}),g=m.name||m.id;if(r.onApproval&&dr("approval")&&h==="waiting_approval"&&u!=="waiting_approval"){const v=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${g} — Approval needed`,v.slice(0,120),`approval-${m.id}`)}r.onComplete&&dr("completion")&&pn(u)&&h==="idle"&&c(`✅ ${g} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&h==="error"&&u!=="error"&&c(`⚠️ ${g} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,h)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,c])}const Dp=/^(run|approve|accept|yes|allow|always)/,Ep=/^(run|approve|accept|yes|allow|always|proceed|save)/,$p=/^(reject|deny|delete|remove|abort|cancel|no)/;function go(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Bp(e){const s=go(e).toLowerCase();return Dp.test(s)?"primary":$p.test(s)?"danger":"default"}function Op(e){return Ep.test(go(e).toLowerCase())?"approve":"reject"}function Kp(e){return e.map((s,r)=>({label:go(s),variant:Bp(s),action:Op(s),button:s,buttonIndex:r}))}function Fp(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Wp(e,s,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,s,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,s,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class Hp{constructor(){Xe(this,"dedupMap",new Map);Xe(this,"DEDUP_WINDOW_MS",5e3);Xe(this,"DEDUP_MAX_SIZE",50);Xe(this,"DEDUP_CLEANUP_AGE_MS",1e4);Xe(this,"toastCallbacks",[]);Xe(this,"statusEventCallbacks",[]);Xe(this,"resolveActionFn",null);Xe(this,"viewRequestRespondFn",null);Xe(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==s)}}onStatusEvent(s){return this.statusEventCallbacks.push(s),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(r=>r!==s)}}setResolveAction(s){this.resolveActionFn=s}setIdes(s){this.ides=s}setViewRequestRespond(s){this.viewRequestRespondFn=s}emitToast(s){for(const r of this.toastCallbacks)r(s)}showToast(s,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:s,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(s){const r=Date.now(),n=this.dedupMap.get(s)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(s,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(s){if(s.daemonId){const a=this.ides.find(o=>o.id===s.daemonId&&o.type==="adhdev-daemon");if(a)return a}const r=s.targetSessionId&&this.findOwningSession(s.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const o=this.ides.find(l=>l.id===a&&l.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(s){for(const r of this.ides)if(r.id===s||r.sessionId===s||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===s))return r;return null}resolveActionRouteTarget(s){if(s.targetSessionId){const r=this.findOwningSession(s.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return s.daemonId||null}resolveConversationKey(s){return s.targetSessionId?s.targetSessionId:s.daemonId?s.daemonId:null}handleRawEvent(s,r){var f;const n=this.resolveConversationKey(s),a=Number.isFinite(s.timestamp)?Number(s.timestamp):Date.now(),o=n||s.daemonId||"",l=s.requestId||s.targetName||s.requesterName||s.modalMessage||String(a),c=`${o}:${s.event}:${l}`;if(this.isDuplicate(c))return;for(const p of this.statusEventCallbacks)p(s);const d=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,m=(d==null?void 0:d.type)||"";let u=ot(m);const h=this.resolveOwningDaemon(s);if(h){const p=Ct(h,{fallbackId:h.id});p&&(u=!m||m==="adhdev-daemon"?p:`${p}/${u}`)}let g="",v="info";if(s.event==="agent:generating_completed"){const p=s.duration?` (${s.duration}s)`:"";g=`✅ ${u} agent task completed${p}`,v="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(s.event!=="agent:generating_started")if(s.event==="agent:waiting_approval"){if(g=`⚡ ${u} approval needed`,v="warning",(f=s.modalButtons)!=null&&f.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(s);if(!p)return;const b=this.resolveActionFn,y=Kp(s.modalButtons).map(S=>({label:S.label,variant:S.variant,onClick:()=>{b(p,"resolve_action",{action:S.action,button:S.button,buttonIndex:S.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),x=Fp(u,s.modalMessage,g),N=Date.now();this.emitToast({id:N,message:x,type:v,timestamp:N,targetKey:n||p,actions:y,duration:15e3}),g=""}}else if(s.event==="monitor:long_generating"){const p=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";g=`⚠️ ${u} agent is taking a long time${p}`,v="warning",dr("browser")&&!document.hasFocus()&&Oa(`⚠️ ${u} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const p=s.requesterName||"A team member",b=s.requestId,y=s.orgId;if(g=`👁️ ${p} wants to view your session`,v="warning",b&&y&&this.viewRequestRespondFn){const x=Date.now(),N=Wp(y,b,this.viewRequestRespondFn,(S,w)=>console.error(`[EventManager] ${S} view request failed:`,w));this.emitToast({id:x,message:g,type:v,timestamp:x,actions:N,duration:3e4}),g=""}dr("browser")&&!document.hasFocus()&&Oa("👁️ View Request",`${p} wants to view your session`,`view-request-${b}`)}else s.event==="team:view_request_approved"?(g="✅ View request approved",v="success"):s.event==="team:view_request_rejected"&&(g=`❌ ${s.targetName||"Team member"} declined your view request`,v="warning");if(g){const p=Date.now();this.emitToast({id:p,message:g,type:v,timestamp:p,targetKey:n||s.daemonId,duration:5e3})}}}const nt=new Hp,wi=new Map;function fn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Rs(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Mn(e){return fn(e)?fn(e.result)?e.result:e:null}function Up(e){const s=Mn(e);return!s||!fn(s.controlResult)||!Array.isArray(s.controlResult.options)?null:s.controlResult}function $r(e){const s=Mn(e);return!s||!fn(s.controlResult)||typeof s.controlResult.ok!="boolean"?null:s.controlResult}function Xs(e){const s=Mn(e);if(!(!s||typeof s.error!="string"||!s.error.trim()))return s.error}function Br(e){const s=Mn(e);return!!s&&s.success===!1}function zp(e){var s,r;for(const n of e||[]){if(n.type==="toast"&&((s=n.toast)!=null&&s.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";nt.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";nt.showToast(n.notification.body,a)}}}function Vp(e,s){return e&&Rs(e.currentValue)?e.currentValue:s}function Gp(e,s){return Rs(s)?Rs(e)?typeof e=="string"&&e.trim()==="":!0:!1}function qp(e,s){var o,l;if((s.now??Date.now())<s.localOverrideUntil){const c=s.localValues[e];if(Rs(c))return c}const n=(o=s.controlValues)==null?void 0:o[e];if(Rs(n))return n;const a=(l=s.defaultValues)==null?void 0:l[e];return Rs(a)?a:void 0}function Qr(e,s){return e.options||s[e.id]||[]}const Yp={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 Xp(e,s,r){var n;return((n=Yp[s])==null?void 0:n.has(r.id))===!0}function yo(e,s){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Xp(s.hostIdeType,s.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function qn(e,s){return{value:s}}function Jp(e,s,r){var a;return r?((a=Qr(e,s).find(o=>o.value===r))==null?void 0:a.label)||r:""}const Qp={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Zp({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:l}){const{sendCommand:c}=yt(),d=`${e}:${s||n}`,m=Qp[n]||"#94a3b8",[u,h]=i.useState({}),g=i.useRef({}),v=i.useRef(l);g.current=u,v.current=l;const f=i.useRef(0),p={};for(const I of o||[])I.defaultValue!==void 0&&(p[I.id]=I.defaultValue);const b={...p,...l||{},...Date.now()<f.current?u:{}};i.useEffect(()=>{l&&Date.now()>f.current&&h({})},[l]);const[y,x]=i.useState(wi.get(d)||{}),[N,S]=i.useState(null),[w,A]=i.useState(null),L=i.useCallback(async(I,K={})=>{const _={...K,...s&&{targetSessionId:s}};return await c(e,I,_)},[e,s,c]),k=i.useCallback(async(I,K={})=>{const _=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await L("invoke_provider_script",{..._,scriptName:I,...K})},[L,n,r,s]),j=i.useCallback((I,K,_)=>{const E=Vp(_,K);h(V=>({...V,[I.id]:E})),zp(_==null?void 0:_.effects)},[]),O=i.useCallback((I,K)=>{h(_=>{const E={..._};return K===void 0?delete E[I.id]:E[I.id]=K,E}),f.current=0},[]);if(!o||o.length===0)return null;const R=yo(o,{hostIdeType:r,providerType:n});if(R.length===0)return null;const T=async I=>{if(N===I.id){S(null);return}if(Qr(I,y).length>0){S(I.id);return}if(I.dynamic&&I.listScript){A(I.id);try{const _=await k(I.listScript,{}),E=Up(_);if(!E){const ge=Xs(_);ge&&nt.showToast(ge,"warning");return}const V=E.options;x(ge=>{const pe={...ge,[I.id]:V};return wi.set(d,pe),pe});const Y=qp(I.id,{localOverrideUntil:f.current,localValues:g.current,controlValues:v.current,defaultValues:p});if(Gp(Y,E.currentValue)){const ge=E.currentValue;h(pe=>({...pe,[I.id]:ge}))}S(I.id)}catch(_){const E=_ instanceof Error?_.message:`Could not load ${I.label}`;nt.showToast(E,"warning")}finally{A(null)}}},F=async(I,K)=>{S(null);const _=(l==null?void 0:l[I.id])??p[I.id];h(E=>({...E,[I.id]:K})),f.current=Date.now()+5e3;try{if(!I.setScript)return;const E=await k(I.setScript,qn(I,K)),V=$r(E);if(V&&!V.ok||Br(E))throw new Error((V==null?void 0:V.error)||Xs(E)||`Could not update ${I.label}`);j(I,K,V)}catch(E){O(I,_);const V=E instanceof Error?E.message:`Could not update ${I.label}`;nt.showToast(V,"warning")}},W=async I=>{const K=Qr(I,y).map(pe=>pe.value);if(K.length===0)return;const _=String(b[I.id]||""),V=(K.indexOf(_)+1)%K.length,Y=K[V];if(typeof Y!="string")return;const ge=(l==null?void 0:l[I.id])??p[I.id];h(pe=>({...pe,[I.id]:Y})),f.current=Date.now()+5e3;try{if(!I.setScript)return;const pe=await k(I.setScript,qn(I,Y)),re=$r(pe);if(re&&!re.ok||Br(pe))throw new Error((re==null?void 0:re.error)||Xs(pe)||`Could not update ${I.label}`);j(I,Y,re)}catch(pe){O(I,ge);const re=pe instanceof Error?pe.message:`Could not update ${I.label}`;nt.showToast(re,"warning")}},D=async I=>{const _=!b[I.id],E=(l==null?void 0:l[I.id])??p[I.id];h(V=>({...V,[I.id]:_})),f.current=Date.now()+5e3;try{if(!I.setScript)return;const V=await k(I.setScript,qn(I,_)),Y=$r(V);if(Y&&!Y.ok||Br(V))throw new Error((Y==null?void 0:Y.error)||Xs(V)||`Could not update ${I.label}`);j(I,_,Y)}catch(V){O(I,E);const Y=V instanceof Error?V.message:`Could not update ${I.label}`;nt.showToast(Y,"warning")}},C=async I=>{if(!I.invokeScript)return;if(I.confirmMessage){const _=[I.confirmTitle,I.confirmMessage,I.confirmLabel].filter(V=>typeof V=="string"&&V.trim().length>0);if(!window.confirm(_.join(`
30
+
31
+ `)))return}const K=(l==null?void 0:l[I.id])??p[I.id];try{const _=await k(I.invokeScript),E=$r(_);if(E&&!E.ok||Br(_))throw new Error((E==null?void 0:E.error)||Xs(_)||`Could not run ${I.label}`);E&&j(I,K??!0,E)}catch(_){O(I,K);const E=_ instanceof Error?_.message:`Could not run ${I.label}`;nt.showToast(E,"warning")}};return t.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.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}),R.map(I=>{const K=String(b[I.id]||""),_=Jp(I,y,K),E=N===I.id,V=w===I.id,Y=Qr(I,y),ge="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 t.jsxs("div",{className:"relative max-w-full",children:[t.jsxs("button",{type:"button",className:`${ge} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:E?`${m}55`:"var(--border-default)",background:E?`${m}10`:"var(--surface-tertiary)",color:K?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void T(I),title:I.label,children:[I.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:V?"Loading…":_||I.label}),t.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),E&&Y.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>S(null)}),t.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:[t.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}),Y.map(pe=>t.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:pe.value===K?`${m}14`:"transparent",color:pe.value===K?"var(--text-primary)":"var(--text-secondary)",borderLeft:pe.value===K?`2px solid ${m}`:"2px solid transparent"},title:pe.description||pe.label,onMouseEnter:re=>{re.currentTarget.style.background=`${m}10`},onMouseLeave:re=>{re.currentTarget.style.background=pe.value===K?`${m}14`:"transparent"},onClick:()=>void F(I,pe.value),children:[t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:pe.label}),pe.value===K&&t.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},pe.value))]})]})]},I.id);case"cycle":return t.jsxs("button",{type:"button",className:`${ge} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:K?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void W(I),title:`Click to cycle: ${Y.map(pe=>pe.label).join(" → ")}`,children:[I.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:_||I.label}),t.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},I.id);case"toggle":return t.jsxs("button",{type:"button",className:`${ge} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:K?`${m}44`:"var(--border-default)",background:K?`${m}14`:"var(--surface-tertiary)",color:K?m:"var(--text-muted)"},onClick:()=>void D(I),"aria-pressed":!!K,children:[I.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),I.label]},I.id);case"action":return t.jsxs("button",{type:"button",className:`${ge} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void C(I),children:[I.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:I.resultDisplay==="inline"&&K?`${I.label}: ${K}`:I.label})]},I.id);case"display":return t.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:K?"var(--text-primary)":"var(--text-muted)"},children:[I.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:K?`${I.label}: ${K}`:I.label})]},I.id);default:return null}})]})})}function ef({isActive:e=!0,isCliTerminal:s=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:l,controls:c,controlValues:d}){const{isVisible:m}=xo(),u=yo(c,{hostIdeType:a,providerType:o});return!e||s||u.length===0||!m?null:t.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:t.jsx(Zp,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:l,controls:u,controlValues:d})})}const Js=5,lc=10*1024*1024;function tf({hasDraft:e,isBusy:s=!1}){return!e||s}function sf(e){return new Promise((s,r)=>{const n=new FileReader;n.onload=()=>s(n.result),n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(e)})}async function rf(e){if(e.size>lc)return null;const s=await sf(e),r=s.indexOf(",");if(r<0)return null;const n=s.slice(r+1);return{mimeType:e.type||"image/png",data:n,name:e.name,previewUrl:s}}function nf(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const cc=i.memo(function({contextKey:s,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,onSend:l,isActive:c=!0,showControlsToggle:d=!1,animateVisibility:m=!0,onControlsToggle:u,messageInput:h}){const g=i.useRef(null),v=i.useRef(null),[f,p]=i.useState(""),[b,y]=i.useState([]),[x,N]=i.useState(null),[S,w]=i.useState(!1),A=i.useRef(!1),{isVisible:L,toggleVisibility:k}=xo(),j=nf(h),O=!!f.trim()||b.length>0;i.useEffect(()=>{p(""),y([]),N(null)},[s]),i.useEffect(()=>{var I;c&&((I=g.current)==null||I.focus({preventScroll:!0}))},[s,c]);const R=i.useCallback(async I=>{N(null);const K=Array.from(I).filter(pe=>pe.type.startsWith("image/"));if(K.length===0)return;const _=Js-b.length;if(_<=0){N(`Max ${Js} images`);return}const E=K.slice(0,_);if(E.filter(pe=>pe.size>lc).length>0){N("Image too large (max 10 MB)");return}const ge=(await Promise.all(E.map(rf))).filter(pe=>pe!==null);y(pe=>[...pe,...ge])},[b.length]),T=i.useCallback(I=>{y(K=>K.filter((_,E)=>E!==I))},[]),F=i.useCallback(async()=>{const I=f.trim();if(!I&&b.length===0||a||A.current)return;A.current=!0;const K=b.length>0?[...b]:void 0;try{await l(I,K)!==!1&&(p(""),y([]),N(null))}finally{A.current=!1}},[f,b,a,l]),W=i.useCallback(I=>{j&&(I.preventDefault(),w(!0))},[j]),D=i.useCallback(()=>w(!1),[]),C=i.useCallback(I=>{j&&(I.preventDefault(),w(!1),I.dataTransfer.files.length>0&&R(I.dataTransfer.files))},[j,R]);return t.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"transition-all duration-200 ease-out":"",S?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:c?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:c?200:0,opacity:c?1:0,transform:c?"translateY(0)":"translateY(10px)",padding:c?"10px 12px":"0 12px",pointerEvents:c?"auto":"none"},"aria-hidden":!c,onDragOver:W,onDragLeave:D,onDrop:C,children:[b.length>0&&t.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:b.map((I,K)=>t.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:[t.jsx("img",{src:I.previewUrl,alt:I.name,className:"w-full h-full object-cover"}),t.jsx("button",{type:"button",onClick:()=>T(K),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 ${I.name}`,children:"✕"})]},K))}),t.jsxs("div",{className:"flex gap-2 items-center",title:c?`Send message to ${r}`:void 0,children:[d&&t.jsx("button",{type:"button",onClick:()=>{k(),u==null||u()},"aria-label":L?"Hide controls":"Show controls","aria-pressed":L,title:L?"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:t.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[t.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),t.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),t.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),j&&t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:v,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:I=>{I.target.files&&R(I.target.files),I.target.value=""}}),t.jsx("button",{type:"button",onClick:()=>{var I;return(I=v.current)==null?void 0:I.click()},disabled:b.length>=Js,title:b.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:t.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:t.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"})})})]}),t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:g,type:"text",placeholder:o||(j&&b.length>0?"Add a message (optional)...":`Send message to ${r}...`),value:f,onChange:I=>p(I.target.value),onPaste:I=>{if(j&&I.clipboardData.files.length>0&&Array.from(I.clipboardData.files).some(E=>E.type.startsWith("image/"))){I.preventDefault(),R(I.clipboardData.files);return}const K=I.clipboardData.getData("text");K&&p(_=>_+K),I.preventDefault()},onKeyDown:I=>{if(I.key==="Enter"){if(I.nativeEvent.isComposing){I.preventDefault();return}I.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))"}})}),t.jsx("button",{onClick:()=>{F()},disabled:tf({hasDraft:O,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${O&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:O&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":"Send message",children:t.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:O?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),(x||j&&S)&&t.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${x?"text-red-400":"text-[var(--accent-primary)]"}`,children:x||"Drop image here"}),o&&!x&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:o})]})}),st=e=>e.transport==="pty",zs=(e,s)=>st(e)?e.mode||"terminal":"chat",dc=(e,s)=>st(e)&&zs(e)==="terminal",Ze=e=>e.transport==="acp",af=180;function ts(e){return e.streamSource!=="agent-stream"}function ks(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function uc(e){return e.machineName||""}function kr(e){return ks(e)}function Ft(e){return e.agentType||""}function hn(e){return e.hostIdeType||""}function vo(e){return e.displayPrimary||e.agentName||"Agent"}function mc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function of(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function pc(e){const s=of(e),r=Ds(s==null?void 0:s.content),n=Ds(e.lastMessagePreview);return r||n||""}function lf(e,s=af){const r=Ds(e);if(!r||s<=0)return"";const n=Array.from(r);return n.length<=s?r:`${n.slice(0,Math.max(0,s-1)).join("").trimEnd()}…`}function cf(e){return lf(pc(e)||e.displaySecondary||"")}function fc(e){return[e.displaySecondary,uc(e)].filter(Boolean)}function $s(e){return e.agentName||ot(Ft(e))}function df(e){var s,r;if(!ts(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return ot(hn(e)||Ft(e))}function hc(e){return ts(e)?e.sessionId:e.nativeSessionId}function ji(e){return ts(e)?"native":e.tabKey}function uf(e){return e.sessionId}function mf(e,s){if(s)return ts(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function pf(e,s){const r=Ft(e),n=ts(e),a=st(e)||Ze(e),o=n?a?$s(e)||(s==null?void 0:s.cliName)||ot(hn(e)||r):s!=null&&s.type?ot(s.type):ot(hn(e)||r):$s(e);return{isNativeConversation:n,isCli:st(e),isAcp:Ze(e),isCliTerminal:dc(e),providerType:r,displayLabel:o,targetEntry:mf(e,s)}}function cs(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:st(e)||Ze(e)?{agentType:Ft(e)}:e.streamSource==="agent-stream"?{agentType:Ft(e)}:s}function Bs(e){return e?kr(e):""}function Qs(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function wo(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function ff(e){const s=e instanceof Error?e.message:String(e||""),r=s.toLowerCase();return r.includes("still processing the previous prompt")?"Wait for the current reply to finish before sending another message.":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.":s||"Unable to send message right now."}function xc(){return"select_session"}function hf(){return"open_panel"}function xf({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function bf(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function ki(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function xn(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function jo(e){return e instanceof Error?e.message:String(e||"")}function Si(e){const s=jo(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Ni(e,s){const r=jo(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function gf(e,s,r){const n=cs(r);if(!s||s.length===0)return{message:e,...n};const a=s.map(o=>({type:"image",mimeType:o.mimeType,data:o.data,alt:o.name}));return e&&a.push({type:"text",text:e}),{message:e,input:{parts:a,textFallback:e},...n}}function Ln({sendDaemonCommand:e,activeConv:s,setActionLogs:r,isStandalone:n}){const[a,o]=i.useState(!1),[l,c]=i.useState(!1),[d,m]=i.useState(null),u=i.useRef(!1),h=i.useRef(null);i.useEffect(()=>{m(null)},[s==null?void 0:s.tabKey]);const g=i.useCallback(async(b,y)=>{if(!s||u.current)return!1;const x=b.trim(),N=wo(s);if(xf({hasMessage:!!x,blockedMessage:N,sendInFlight:u.current}))return N&&m(N),!1;const S=Date.now(),w={tabKey:s.tabKey,message:x,timestamp:S};if(bf(h.current,w))return m(null),!0;u.current=!0,c(!0),m(null),h.current=w;try{const A=Bs(s);if(!A)return h.current=ki(h.current,w),m("Unable to send message right now."),!1;const L=await e(A,"send_chat",gf(x,y,s)),k=xn(L);if(k!=null&&k.deduplicated)return m(null),!0;if((k==null?void 0:k.sent)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");if((k==null?void 0:k.success)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");return m(null),!0}catch(A){const L=jo(A);return L.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",L):console.warn("Send blocked/failed",A),h.current=ki(h.current,w),m(ff(A)),!1}finally{u.current=!1,c(!1)}},[s,e]),v=i.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(b){console.error("Relaunch failed",b)}},[s,e]),f=i.useCallback(async b=>{if(s)try{const x=(s.modalButtons||[]).indexOf(b),N=b.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N),w=Bs(s);if(!w)return;const A=await e(w,"resolve_action",{button:b,action:S?"approve":"reject",...x>=0&&{buttonIndex:x},...cs(s)}),L=xn(A);L.success||r(k=>[...k,{routeId:s.tabKey,text:Ni(b,L==null?void 0:L.error),timestamp:Date.now()}])}catch(y){Si(y)||console.error("[ModalButton] Error:",y),r(x=>[...x,{routeId:s.tabKey,text:Si(y)?Ni(b,y):`❌ **${b}** error`,timestamp:Date.now()}])}},[s,e,r]),p=i.useCallback(async()=>{if(!(!s||a)){o(!0);try{await e(s.routeId,hf(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(b){console.error("Focus agent failed",b)}finally{o(!1)}}},[s,a,e]);return{isSendingChat:l,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:g,handleRelaunch:v,handleModalButton:f,handleFocusAgent:p}}const yf=10,vf=8e3,wf=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function jf(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 Ka(e,s="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(wf.test(s)&&e.trim())return"[REDACTED:secret-field]";const n=jf(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=>Ka(a,s,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,Ka(a,n,r+1)]))}function Zs(e,s){return Array.isArray(e)?e.slice(-s):[]}function kf(e,s=Date.now()){const r=e&&s-e.firstAt<=vf,n=r?e.count+1:1;return n>=yf?{state:{count:0,firstAt:s},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:s},shouldCollect:!1}}function bc(e){var n,a;const{activeConv:s}=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:s.routeId,tabKey:s.tabKey,sessionId:s.sessionId,providerSessionId:s.providerSessionId,transport:s.transport,agentName:s.agentName,agentType:s.agentType,hostIdeType:s.hostIdeType,status:s.status,connectionState:s.connectionState,title:s.title,workspaceName:s.workspaceName,displayPrimary:s.displayPrimary,displaySecondary:s.displaySecondary,streamSource:s.streamSource,lastMessageHash:s.lastMessageHash},messageCounts:{live:((n=e.chatTailState.liveMessages)==null?void 0:n.length)??s.messages.length,activeConversation:s.messages.length,visible:e.visibleMessages.length,history:((a=e.chatTailState.historyMessages)==null?void 0:a.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:Zs(e.chatTailState.liveMessages??s.messages,10),activeConversationMessagesTail:Zs(s.messages,10),visibleMessagesTail:Zs(e.visibleMessages,5),historyMessagesTail:Zs(e.chatTailState.historyMessages,5),actionLogsTail:Zs(e.actionLogs.filter(o=>o.routeId===s.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 Ka(r)}function gc(e,s={}){const r=e&&typeof e=="object"?e:{},n=s.locatorCopyStatus??(s.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 yc(e){var s;if(typeof navigator<"u"&&((s=navigator.clipboard)!=null&&s.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 vc(e){const s=e&&typeof e=="object"?e:{};if(s.delivery==="daemon_file"){const r=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(s.bundleId||"")}`,`savedPath: ${String(s.savedPath||"")}`,`sizeBytes: ${String(s.sizeBytes||"")}`,`createdAt: ${String(s.createdAt||"")}`];return s.summary&&typeof s.summary=="object"&&r.push("","summary:",JSON.stringify(s.summary,null,2)),Array.isArray(s.warnings)&&s.warnings.length>0&&r.push("","warnings:",...s.warnings.map(n=>`- ${String(n)}`)),r.join(`
32
+ `)}return typeof s.text=="string"?s.text:s.bundle&&typeof s.bundle=="object"?`# ADHDev Chat Debug Bundle
33
+
34
+ \`\`\`json
35
+ ${JSON.stringify(s.bundle,null,2)}
36
+ \`\`\``:`# ADHDev Chat Debug Bundle
37
+
38
+ \`\`\`json
39
+ ${JSON.stringify(s,null,2)}
40
+ \`\`\``}function Yn(e,s){return`${e}:${s}`}function Sf(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function er(e,s){Sf()&&console.debug(`[subscription-manager] ${e}`,s)}class Nf{constructor(){Xe(this,"active",new Map);Xe(this,"retryTimers",new Map)}subscribe(s,r,n,a,o){var u;const l=Yn(n.topic,n.key),c=this.active.get(l);let d=!0;if(c)c.handlers.add(a),c.lastUpdate&&a(c.lastUpdate);else{const h={daemonId:r,request:n,handlers:new Set([a])};this.active.set(l,h),er("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((u=s.sendData)==null?void 0:u.call(s,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(l,s,o.retryIntervalMs)}const m=()=>{var v;this.clearRetry(l);const h=this.active.get(l);if(!h||(h.handlers.delete(a),h.handlers.size>0))return;this.active.delete(l);const g={type:"unsubscribe",topic:n.topic,key:n.key};er("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(v=s.sendData)==null||v.call(s,r,g)};return m.initialSendAccepted=d,m}publish(s){const r=Yn(s.topic,s.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=s,Ps.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.publish",topic:s.topic,payload:{key:s.key}}),n.handlers.forEach(a=>{a(s),Ps.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.handler_invoked",topic:s.topic,payload:{key:s.key}})}))}updateParams(s,r,n){const a=Yn(s,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(s){var r;er("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=s.sendData)==null||r.call(s,n.daemonId,n.request)}resubscribeForDaemon(s,r){var a;const n=Array.from(this.active.values()).filter(o=>o.daemonId===s);er("resubscribe_daemon",{daemonId:s,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(s,r,n){if(this.retryTimers.has(s))return;const a=setTimeout(()=>{var c;this.retryTimers.delete(s);const o=this.active.get(s);if(!o)return;const l=((c=r.sendData)==null?void 0:c.call(r,o.daemonId,o.request))??!1;er("subscribe_retry",{id:s,accepted:l,topic:o.request.topic,key:o.request.key}),l||this.scheduleRetry(s,r,n)},n);this.retryTimers.set(s,a)}clearRetry(s){const r=this.retryTimers.get(s);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(s))}}const zt=new Nf;function Cf(e,s){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===s&&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 l=r.get(o.id)||{};r.set(o.id,{...l,...o})}}return r}function If(e){const s=[],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 s.push(n);return{topLevel:s,childrenByParent:r}}function Xn(e,s){return s&&(s.startsWith(`${e}:`)?s:`${e}:${s}`)}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(s=>({id:s.id,daemonId:s.daemonId,sessionId:s.sessionId,instanceId:s.instanceId,providerSessionId:s.providerSessionId,transport:s.transport,type:s.type})))}function bn(e,s){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:l}=s,c=l||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:m,childrenByParent:u}=If(d),h=Cf(o,n),g=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,v=m.filter(b=>b.kind==="workspace"&&b.transport==="cdp-page"),f=m.filter(b=>b.kind==="agent"&&b.transport==="pty"),p=m.filter(b=>b.kind==="agent"&&b.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:c,...e.version&&{version:e.version},...g&&{machine:g,platform:g.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:v.some(b=>!!b.cdpConnected)});for(const b of v){const y=h.get(b.id),x=or(b,y),N=(u.get(b.id)||[]).map(S=>or(S,h.get(S.id)));r.push({id:`${n}:ide:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,status:x.cdpConnected?"online":"detected",daemonId:n,instanceId:Xn(n,b.id),workspace:x.workspace,terminals:0,childSessions:N,agents:N.map(S=>({id:S.id,name:S.providerName||S.providerType,type:S.providerType,status:S.status})),activeChat:x.activeChat,chats:[],cdpConnected:x.cdpConnected,...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},...x.settings!==void 0&&{settings:x.settings},...x.messageInput!==void 0&&{messageInput:x.messageInput},timestamp:c})}for(const b of f){const y=h.get(b.id),x=or(b,y);r.push({id:`${n}:cli:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,agentType:x.providerType,status:x.status||"running",daemonId:n,instanceId:Xn(n,b.id),cliName:x.providerName||x.providerType,mode:x.mode||(y==null?void 0:y.mode)||"terminal",workspace:x.workspace||"",activeChat:x.activeChat,...x.resume!==void 0&&{resume:x.resume},...x.runtimeKey!==void 0&&{runtimeKey:x.runtimeKey},...x.runtimeDisplayName!==void 0&&{runtimeDisplayName:x.runtimeDisplayName},...x.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:x.runtimeWorkspaceLabel},...x.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:x.runtimeWriteOwner},...x.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:x.runtimeAttachedClients},...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},...x.settings!==void 0&&{settings:x.settings},...x.messageInput!==void 0&&{messageInput:x.messageInput},timestamp:c,_isCli:!0})}for(const b of p){const y=h.get(b.id),x=or(b,y);r.push({id:`${n}:acp:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,agentType:x.providerType,status:x.status||"running",daemonId:n,instanceId:Xn(n,b.id),cliName:x.providerName||x.providerType,mode:"chat",workspace:x.workspace||"",activeChat:x.activeChat,...x.runtimeKey!==void 0&&{runtimeKey:x.runtimeKey},...x.runtimeDisplayName!==void 0&&{runtimeDisplayName:x.runtimeDisplayName},...x.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:x.runtimeWorkspaceLabel},...x.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:x.runtimeWriteOwner},...x.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:x.runtimeAttachedClients},...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},...x.settings!==void 0&&{settings:x.settings},...x.messageInput!==void 0&&{messageInput:x.messageInput},timestamp:c,_isAcp:!0})}return Af(r),r}const Mf=15e3,Lf=15e3,Rf=6e4,_f=1200,Ci=12,Pf=8e3,Df=4e3,Jn=new Map,Qn=new Map,Or=new Set,ur=new Map;function Ef(e){if(!e||typeof e!="object")return null;const s=e,r=s.status;if(r&&typeof r=="object")return r;const n=s.result;if(n&&typeof n=="object"&&"status"in n){const a=n.status;if(a&&typeof a=="object")return a}return s}function Ii(e,s){const r=ur.get(e);!r||r.size===0||(ur.delete(e),r.forEach(n=>n(s)))}function $f(e,s){return new Promise(r=>{const n=ur.get(e)||new Set;ur.set(e,n);const a=l=>{clearTimeout(o),n.delete(a),n.size===0&&ur.delete(e),r(l)},o=setTimeout(()=>a(!1),s);n.add(a)})}function Sr(){const{sendCommand:e,sendData:s}=yt(),{injectEntries:r,getIdes:n}=br();return i.useCallback(async(a,o)=>{if(!a)return;const l=(o==null?void 0:o.minFreshMs)??Rf,c=Qn.get(a)||0;if(!(o!=null&&o.force)&&Or.has(a)&&c>0||!(o!=null&&o.force)&&c>0&&Date.now()-c<l)return;const d=Jn.get(a);if(d)return d;const m=(async()=>{if(s&&!Or.has(a)){const p=zt.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},b=>{const y=n(),x=y.find(S=>S.id===a),N=bn(b.status,{daemonId:a,existingDaemon:x,existingEntries:y,timestamp:b.timestamp});N.length>0&&r(N),Qn.set(a,Date.now()),Ii(a,!0)});if(p.initialSendAccepted?Or.add(a):Or.delete(a),!(o!=null&&o.force)&&p.initialSendAccepted&&await $f(a,_f))return}const u=await e(a,"get_status_metadata"),h=Ef(u);if(!h)return;const g=n(),v=g.find(p=>p.id===a),f=bn(h,{daemonId:a,existingDaemon:v,existingEntries:g,timestamp:h.timestamp||Date.now()});f.length>0&&r(f,{authoritativeDaemonIds:[a]}),Qn.set(a,Date.now()),Ii(a,!0)})().finally(()=>{Jn.delete(a)});return Jn.set(a,m),m},[n,r,e,s])}function Bf(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}const Of=60,Kf=50;function wc(e={}){return e.isCliLike?Kf:Of}function Ff(e={}){return wc(e)}function St(e){return(typeof e=="string"?e.trim():"")||void 0}function Ut(e,s){const r=St(s);return r?`${e}:${r}`:void 0}function Zt(e,s,r){const n=Ut(s,r),a=St(r);n&&e.push(n),a&&e.push(a)}function As(e){const s=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),s.push(n));return s}function jc(e){return St(e.providerSessionId)||St(e.sessionId)||St(e.tabKey)||St(e.routeId)}function ko(e){return As([St(e.providerSessionId),St(e.sessionId)])}function _s(e){const s=[];return Zt(s,"provider",e.providerSessionId),Zt(s,"session",e.sessionId),Zt(s,"tab",e.tabKey),Zt(s,"route",e.routeId),As(s)}function Wf(e){const s=[];return St(e.providerSessionId)?(Zt(s,"provider",e.providerSessionId),As(s)):St(e.sessionId)?(Zt(s,"session",e.sessionId),As(s)):St(e.tabKey)?(Zt(s,"tab",e.tabKey),As(s)):St(e.routeId)?(Zt(s,"route",e.routeId),As(s)):[]}function So(e){return Ut("provider",e.providerSessionId)||Ut("session",e.sessionId)||Ut("tab",e.tabKey)||Ut("route",e.routeId)||"unknown:"}function Nr(e){return ko(e)[0]}function Hf(e){const s=St(e.providerSessionId),r=St(e.sessionId),n=St(e.tabKey),a=St(e.routeId),o=[Ut("provider",s),Ut("session",r),Ut("tab",n),Ut("route",a)].filter(d=>typeof d=="string"),l=_s({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),c=So({providerSessionId:s,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:s,sessionId:r,tabKey:n,routeId:a,canonicalKey:c,targetKey:c,targetValue:jc({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),historySessionId:Nr({providerSessionId:s,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:l}}function Fa(e,s){const r=Hf(e);return Wf(s).some(n=>r.lookupKeys.includes(n))}const Cr=60,Uf=1e3,No=12e4,zf=new Set(["generating","waiting_approval","starting","streaming","working"]),Ti=new Map;function kc(e,s){return`${e}::${s}`}function Wa(e=Cr){return{liveMessages:[],hasLiveSnapshot:!1,cursor:Vf([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Vf(e,s=Cr){return{tailLimit:s}}function Ai(e,s){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("|")}class Gf{constructor(s){Xe(this,"manager");Xe(this,"sendData");Xe(this,"daemonId");Xe(this,"sessionId");Xe(this,"historySessionId");Xe(this,"subscriptionKey");Xe(this,"fallbackRecentCount");Xe(this,"snapshot");Xe(this,"transportSubscription",null);Xe(this,"listeners",new Set);Xe(this,"retainCount",0);Xe(this,"loadHistoryPromise",null);Xe(this,"pendingDisconnectTimer",null);this.manager=s.manager||zt,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.fallbackRecentCount=Math.max(0,s.fallbackRecentCount??0),this.snapshot=Wa(Math.max(0,s.tailLimit??Cr))}updateOptions(s){if(s.manager&&(this.manager=s.manager),s.sendData&&(this.sendData=s.sendData),s.historySessionId&&(this.historySessionId=s.historySessionId),s.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,s.fallbackRecentCount)),s.tailLimit!==void 0){const r=Math.max(0,s.tailLimit);r!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect()))}}getSnapshot(){return this.snapshot}subscribe(s){return this.listeners.add(s),s(this.snapshot),()=>{this.listeners.delete(s)}}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(s){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 s({offset:this.snapshot.historyOffset,excludeRecentCount:a}),l=Array.isArray(o.messages)?o.messages:[],c=!n&&l.length===0&&o.hasMore!==!0&&this.fallbackRecentCount>0;this.snapshot={...this.snapshot,historyMessages:[...l,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+l.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(),s=>{this.handleUpdate(s)},{retryIntervalMs:Uf}))}disconnect(){var s;(s=this.transportSubscription)==null||s.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(s=>s(this.snapshot))}handleUpdate(s){if(s.error)return;const r=Array.isArray(s.messages)?s.messages:[],n={tailLimit:this.snapshot.cursor.tailLimit};Ai(this.snapshot.liveMessages)===Ai(r)&&this.snapshot.cursor.tailLimit===n.tailLimit||(this.snapshot={...this.snapshot,liveMessages:r,hasLiveSnapshot:!0,cursor:n},this.emit())}}function Sc(e){const s=kc(e.daemonId,e.sessionId),r=Ti.get(s);if(r)return r.updateOptions(e),r;const n=new Gf(e);return Ti.set(s,n),n}function qf(e,s){return{...e,loadHistoryPage:s}}function Yf(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function Xf(e,s={}){const r=String(e.status||"").trim().toLowerCase();if(zf.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=s.now??Date.now(),a=Math.max(0,Number(s.recentActivityMs??No)),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 Jf(e=No){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Qf(e,s={}){const r=new Set,n=[];for(const a of e){if(!Xf(a,s))continue;const o=kr(a),l=a.sessionId||"";if(!o||!l)continue;const c=kc(o,l);if(r.has(c))continue;r.add(c);const d=Nr(a);n.push({daemonId:o,sessionId:l,historySessionId:d||l,subscriptionKey:`daemon:${o}:session:${l}`})}return n.sort(Yf),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Zf(e,s){const{sendData:r,sendCommand:n}=yt(),a=(s==null?void 0:s.enabled)!==!1,o=kr(e),l=e.sessionId||"",c=Nr(e)||l,d=`daemon:${o}:session:${l}`,m=Math.max(0,(s==null?void 0:s.tailLimit)??Cr),u=i.useMemo(()=>!a||!o||!l?null:Sc({daemonId:o,sessionId:l,historySessionId:c,subscriptionKey:d,sendData:r,tailLimit:m,fallbackRecentCount:e.messages.length}),[e.messages.length,o,a,c,r,l,d,m]),[h,g]=i.useState(()=>(u==null?void 0:u.getSnapshot())||Wa(m));i.useEffect(()=>{if(!u){g(Wa(m));return}u.retain(),g(u.getSnapshot());const f=u.subscribe(p=>{g(p)});return()=>{f(),u.release()}},[u,m]);const v=i.useCallback(async()=>{!u||!o||!l||await u.loadHistoryPage(async({offset:f,excludeRecentCount:p})=>{const b=e.agentType,y=await n(o,"chat_history",{agentType:b,offset:f,limit:30,targetSessionId:l,historySessionId:c,excludeRecentCount:p}),x=y&&typeof y=="object"&&"result"in y?y.result||{}:y||{};return{messages:Array.isArray(x.messages)?x.messages:[],hasMore:x.hasMore===!0}})},[e.agentType,u,o,c,n,l]);return i.useMemo(()=>qf(h,v),[v,h])}function eh(e,s){const{sendData:r}=yt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,(s==null?void 0:s.tailLimit)??Cr),o=Math.max(0,Number((s==null?void 0:s.recentActivityMs)??No)),l=Jf(o),[c,d]=i.useState(0);i.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(h=>h+1)},l);return()=>{clearInterval(u)}},[e.length,n,l]);const m=i.useMemo(()=>Qf(e,{recentActivityMs:o}),[e,o,c]);i.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const u=m.descriptors.map(h=>Sc({...h,sendData:r,tailLimit:a}));return u.forEach(h=>{h.retain()}),()=>{u.forEach(h=>h.release())}},[m.signature,n,r,a])}function th(e,s){return s!=null&&s.hasLiveSnapshot?s.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function Mi(e){const s=String(e.role||"").toLowerCase();if(s!=="user"&&s!=="assistant")return!1;const r=String(e.kind||"standard").toLowerCase();return r===""||r==="standard"}function sh(e,s){if(e.length===0)return[];if(s.some(Mi))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||!Mi(o))continue;const l=String(o.role||"").toLowerCase();n.has(l)||(n.add(l),r.unshift(o))}return r}function rh(e){const{historyMessages:s,liveMessages:r,visibleLiveCount:n}=e,a=Math.max(0,r.length-n),o=a>0?r.slice(0,a):[],l=a>0?r.slice(-n):r,c=sh(o,l),d=c.length>0?[...c,...l]:l;return s.length===0?d:[...s,...d]}function nh(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function ah(e){return nh(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function oh(e,s,r=`${s}s`){return`${e} ${e===1?s:r}`}function ih(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function lh(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Nc(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function Cc(e){const s=typeof e.completionMarker=="string"?e.completionMarker.trim():"";return s||(e.lastMessageHash?e.lastMessageHash:e.lastMessageAt?String(e.lastMessageAt):e.lastUpdated?String(e.lastUpdated):"")}function ch(e){return Nc(e)?!1:e.inboxBucket==="task_complete"&&Cc(e).length>0}function Li(e){return e.branch||"detached HEAD"}function dh(e){if(e.error)return`${Li(e)} · Git error: ${e.error}`;const s=[Li(e)];return e.changedFiles>0?s.push(oh(e.changedFiles,"file")+" changed"):e.dirty||s.push("clean"),e.ahead>0&&s.push(`ahead ${e.ahead}`),e.behind>0&&s.push(`behind ${e.behind}`),e.hasConflicts&&s.push("conflicts"),s.join(" · ")}function uh(e,s){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${dh(s)}`}function mh(e,s){return e.lastUpdated||e.lastMessageAt||s.lastCheckedAt||0}function ph(e,s={}){if(s.enabled===!1)return[];if(!lh(e))return[];const r=Nc(e)?"working":ch(e)?"complete":null;if(!r)return[];const n=r==="complete"?Cc(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${ih(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:uh(r,e.git),timestamp:mh(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 fh=60;function Ha({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:o,isFocusingAgent:l,actionLogs:c,userName:d,scrollToBottomRequestNonce:m,isInputActive:u=!0,isVisible:h=!0}){var Se,Q,ue,oe,me,le,P;const g=i.useRef(new Map),v=i.useRef(void 0),f=Sr(),{sendCommand:p}=yt(),{isVisible:b}=xo();jr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:c.length,isSendingChat:n});const y=wt.useMemo(()=>Us(e),[e.status,e.connectionState]),x=i.useMemo(()=>pf(e,s),[e,s]),N=i.useMemo(()=>{var U;return yo((U=x.targetEntry)==null?void 0:U.providerControls,{hostIdeType:e.hostIdeType,providerType:x.providerType})},[e.hostIdeType,x.providerType,(Se=x.targetEntry)==null?void 0:Se.providerControls]),S=wc({isCliLike:x.isCli||x.isAcp}),w=Ff({isCliLike:x.isCli||x.isAcp}),A=Zf(e,{enabled:h&&!!e.sessionId,tailLimit:w}),[L,k]=i.useState(S),[j,O]=i.useState(()=>ui()),R=e.tabKey,T=A.historyMessages,F=A.hasMoreHistory,W=A.historyError,D=th(e,A),C=Gl(D).length;i.useEffect(()=>{k(S)},[S,R]);const I=Math.max(0,D.length-L),K=vo(e),_=kr(e),E=ah(e),V=wo(e),Y=a||V,ge=!!V,[pe,re]=i.useState(!1);i.useEffect(()=>{const U=x.targetEntry;_&&(!U||U.providerControls===void 0||U.controlValues===void 0)&&f(_,{minFreshMs:3e4}).catch(()=>{})},[_,x.isAcp,(Q=x.targetEntry)==null?void 0:Q.providerControls,(ue=x.targetEntry)==null?void 0:ue.controlValues,f]);const de=i.useCallback(async()=>{if(!pe){if(D.length>L){k(U=>Math.min(D.length,U+fh));return}re(!0);try{await A.loadHistoryPage()}finally{re(!1)}}},[A,pe,D.length,L]),{allMessages:ke,receivedAtMap:ye}=i.useMemo(()=>{const U=rh({historyMessages:T,liveMessages:D,visibleLiveCount:L}),ce=ph(e),te=ce.length>0?[...U,...ce]:U,ie={};return te.forEach((se,ve)=>{const Ie=`${e.tabKey}:${un(se,ve)}`;let Me=Bf(se)||g.current.get(Ie)||0;Me||(Me=Date.now(),g.current.set(Ie,Me)),ie[un(se,ve)]=Me}),{allMessages:te,receivedAtMap:ie}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,I,T,D,L]),q=i.useMemo(()=>c.filter(U=>U.routeId===e.tabKey).sort((U,ce)=>U.timestamp-ce.timestamp),[c,e.tabKey]),he=i.useCallback(async()=>{var ve,Ie;if(!_)return;const U=bc({activeConv:e,visibleMessages:ke,actionLogs:c,controls:(ve=x.targetEntry)==null?void 0:ve.providerControls,controlValues:(Ie=x.targetEntry)==null?void 0:Ie.controlValues,visibleBarControlCount:N.length,chatTailState:{liveMessages:A.liveMessages,hasLiveSnapshot:A.hasLiveSnapshot,hasMoreHistory:F,historyError:W,historyMessages:T},ui:{controlsVisible:b,visibleLiveCount:L,activityVisible:j,activityCount:C,hiddenLiveCount:I,isInputActive:u,isVisible:h}}),ce=await p(_,"get_chat_debug_bundle",{agentType:x.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:U}),te=xn(ce),ie=vc(te),se=await yc(ie);se==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),nt.showToast(gc(te,{locatorCopyStatus:se}),se==="failed"?"warning":"success")},[e,c,C,ke,b,A.hasLiveSnapshot,A.liveMessages,x.providerType,(oe=x.targetEntry)==null?void 0:oe.controlValues,(me=x.targetEntry)==null?void 0:me.providerControls,_,F,I,T,u,h,W,p,j,N.length,L]),fe=i.useCallback(()=>{O(U=>{const ce=!U;return Em(ce),ce})},[]);i.useEffect(()=>{const U=ce=>{ce.key===mo&&O(ui())};return window.addEventListener("storage",U),()=>window.removeEventListener("storage",U)},[]);const we=i.useCallback(()=>{const U=kf(v.current);v.current=U.state,U.shouldCollect&&he().catch(ce=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",ce),nt.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[he]),xe=i.useMemo(()=>{if(D.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[t.jsx("div",{className:"connecting-logo-float",children:t.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:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),t.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[t.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",t.jsx("span",{className:"connecting-dots"})]}),t.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((y.isGenerating||e.status==="streaming")&&re(!1),e.status==="not_monitored"&&E)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(Es,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:o,disabled:l,className:"btn btn-primary",children:l?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(gs,{size:14})," Open ",K," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&E)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(Hl,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:o,disabled:l,className:"btn btn-primary",children:l?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(gs,{size:14})," Open ",K," Panel"]})}),t.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"&&!pe)return!F&&T.length===0?t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-2xl opacity-40",children:"💬"}),t.jsx("div",{className:"text-[13px] opacity-40",children:"No messages yet"})]}):t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),t.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,E,o,F,T.length,l,pe,D.length,K,y.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[t.jsx("div",{className:"chat-activity-toggle-bar",children:t.jsxs("button",{type:"button",className:`chat-activity-toggle ${j?"chat-activity-toggle-active":""}`,onClick:fe,"aria-pressed":j,title:"Show tool, terminal, and runtime activity rows",children:[t.jsx("span",{className:"chat-activity-toggle-dot"}),"Activity",C>0&&t.jsx("span",{className:"chat-activity-toggle-count",children:C})]})}),t.jsx(Jm,{messages:ke,actionLogs:q,agentName:$s(e)||K||"Agent",userName:d,isCliMode:x.isCli||x.isAcp,isWorking:y.isGenerating,contextKey:e.tabKey,receivedAtMap:ye,lastMessageHash:e.lastMessageHash,showActivityMessages:j,onLoadMore:de,isLoadingMore:pe,hasMoreHistory:F,hiddenLiveCount:I,loadError:W??void 0,emptyState:xe,scrollToBottomRequestNonce:m,isVisible:h}),t.jsx(ef,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:x.providerType,displayLabel:x.displayLabel,controls:(le=x.targetEntry)==null?void 0:le.providerControls,controlValues:(P=x.targetEntry)==null?void 0:P.controlValues,isActive:u,isCliTerminal:x.isCliTerminal}),!x.isCliTerminal&&t.jsx(cc,{contextKey:e.tabKey,panelLabel:K,isSending:n,isBusy:ge,statusMessage:Y,onSend:r,isActive:u,showControlsToggle:N.length>0,onControlsToggle:we,messageInput:e.messageInput})]})}let Ic=rs;function Tc(){return Ic()}class hh{constructor(){Xe(this,"listeners",new Map)}send(s){}isConnected(){return!1}on(s,r){return this.listeners.has(s)||this.listeners.set(s,new Set),this.listeners.get(s).add(r),()=>{var n;(n=this.listeners.get(s))==null||n.delete(r)}}emit(s,...r){var n;(n=this.listeners.get(s))==null||n.forEach(a=>a(...r))}}let Ac=new hh;class xh{sendPtyInput(s,r,n){return!1}retryConnection(s){}getState(s){return"disconnected"}sendData(s,r){return!1}get(s){}onScreenshot(s,r){return()=>{}}onRuntimeEvent(s,r,n){return()=>{}}requestRuntimeSnapshot(s,r,n){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let ct=new xh;function bh(e){e.dashboardWS&&(Ac=e.dashboardWS),e.connectionManager&&(ct=e.connectionManager),e.useDaemonsHook&&(Ic=e.useDaemonsHook)}const gh=.5,yh=1.25;function lt(e){return vo(e)}function vs(e){return fc(e).join(" · ")}function Mc(e){const s=pc(e);return s||(e.title?e.title:vs(e)||"No messages yet")}function Lc(e,s){const{isReconnecting:r,isConnecting:n}=Us(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function vh(e,s){const r=["Chat",...fc(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function ds(e){return Lc(e)||vs(e)}function wh(e){return`${lt(e)} · ${Mc(e)}`}function jh(e){const s=hn(e),r=s?ot(s):$s(e);return`${lt(e)} — ${r||"Agent"}`}function kh(e){return $s(e)||"CLI"}function Rc(e){return mc(e)}function _c(e){return e?`Remote · ${lt(e)||e.workspaceName||"Session"}`:"Remote"}function Sh({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:l=!0,isInputActive:c=!0}){var ne;rs();const{sendPtyInput:d}=yt(),[m,u]=i.useState(!1),h=i.useRef(!1);h.current=m;const[g,v]=i.useState("Runtime terminal unavailable"),[f,p]=i.useState(!1),[b,y]=i.useState(null),[x,N]=i.useState(!1),[S,w]=i.useState(!1),[A,L]=i.useState(1),[k,j]=i.useState(!1),[O,R]=i.useState({width:0,height:0}),[T,F]=i.useState({width:0,height:0}),[W,D]=i.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[C,I]=i.useState(null),K=i.useRef(null),_=i.useRef(null),E=i.useRef(!1),V=i.useRef(!1),Y=i.useRef(l),ge=i.useRef(0),pe=i.useRef(!1),re=i.useRef(""),de=i.useRef(null),ke=i.useRef(!1),ye=i.useRef(!1),q=i.useRef(null),he=i.useRef(null),fe=i.useRef(null),we=32*1024,xe=()=>{var $,G,ee,ae;return((G=($=K.current)==null?void 0:$.ownerDocument)==null?void 0:G.defaultView)||((ae=(ee=_.current)==null?void 0:ee.ownerDocument)==null?void 0:ae.defaultView)||window},Se=$=>{const G=xe();return{ownerWindow:G,frameId:G.requestAnimationFrame($)}},Q=()=>{const $=q.current;if($){try{$.ownerWindow.cancelAnimationFrame($.frameId)}catch{}q.current=null}},ue=()=>{const $=he.current;if($){try{$.ownerWindow.clearTimeout($.timeoutId)}catch{}he.current=null}},oe=()=>{const $=fe.current;if($){try{$.ownerWindow.clearTimeout($.timeoutId)}catch{}fe.current=null}},me=()=>{l&&q.current===null&&(q.current=Se(()=>{et()}))},le=e.tabKey,P=e.sessionId||"",U=e.daemonId||((ne=e.routeId)==null?void 0:ne.split(":")[0])||e.routeId||"",ce=wo(e),te=m?o||ce:g,ie=gh,se=yh,ve=.05,Ie=()=>{const $=T.width,G=T.height;if(!Number.isFinite(O.width)||O.width<=0||!Number.isFinite(O.height)||O.height<=0||!Number.isFinite($)||$<=0||!Number.isFinite(G)||G<=0)return 1;const ee=O.width/$,ae=O.height/G;return Number(Math.min(se,Math.max(ie,Math.min(ee,ae))).toFixed(2))},Me=Ie(),B=E.current&&A>Me,Ne=Number.isFinite(T.width)&&T.width>0?Math.max(O.width,Math.round(T.width*A)):O.width,Re=Number.isFinite(T.height)&&T.height>0?Math.max(O.height,Math.round(T.height*A)):O.height,Fe=()=>{Se(()=>{const $=_.current;$&&($.scrollLeft=0,$.scrollTop=$.scrollHeight-$.clientHeight)})},He=()=>{var $,G;ge.current=0,pe.current=!1,re.current="",de.current=null,ke.current=!1,ye.current=!1,E.current||(V.current=!1,L(1)),q.current!==null&&Q(),u(!1),v("Runtime terminal unavailable"),oe(),ue(),y(null),I(null),j(!1),p(!1),N(!1),w(!1),(G=($=r.current)==null?void 0:$.reset)==null||G.call($)},Ge=()=>{var $,G;ge.current=0,pe.current=!1,re.current="",de.current=null,ke.current=!1,ye.current=!1,q.current!==null&&Q(),u(!0),v(""),oe(),ue(),y(null),I(null),j(!1),p(!1),N(!1),w(!1),(G=($=r.current)==null?void 0:$.reset)==null||G.call($)},qe=()=>{ye.current&&(ye.current=!1,Se(()=>{var $,G;(G=($=r.current)==null?void 0:$.scrollToTop)==null||G.call($)}))},et=()=>{if(q.current=null,!l)return;const $=re.current;if(!$)return;const G=$.slice(0,we);re.current=$.slice(G.length);const ee=r.current;if(!ee){re.current=G+re.current,me();return}ee.write(G,()=>{if(re.current.length>0){me();return}qe()})},dt=$=>{$&&(re.current+=$,me())},pt=($,G=0,ee,ae,je={})=>{var De,Ae,Ee,Oe;const _e=!!je.force;!_e&&G>0&&ge.current>=G||!_e&&G===0&&pe.current||(ge.current=G,G>0&&N(!0),u(!0),v(""),typeof ee=="number"&&typeof ae=="number"&&ee>0&&ae>0&&((Ae=(De=r.current)==null?void 0:De.resize)==null||Ae.call(De,ee,ae)),re.current="",(Oe=(Ee=r.current)==null?void 0:Ee.reset)==null||Oe.call(Ee),$?dt($):qe())};i.useEffect(()=>{He()},[P]),i.useEffect(()=>{var G;if(!P)return;const $=((G=ct.onRuntimeEvent)==null?void 0:G.call(ct,P,ee=>{if(!(!ee||ee.sessionId!==P)){if(ee.type==="runtime_snapshot"){if(!l){de.current={text:ee.text||"",seq:ee.seq||0,cols:ee.cols,rows:ee.rows,force:!!ee.force};return}pt(ee.text||"",ee.seq||0,ee.cols,ee.rows,{force:!!ee.force});return}if(ee.type==="session_output"){pe.current=!0,typeof ee.seq=="number"&&(ge.current=Math.max(ge.current,ee.seq),ee.seq>0&&N(!0)),h.current||u(!0),h.current||v(""),typeof ee.data=="string"&&dt(ee.data);return}if(ee.type==="session_cleared"){if(!l){ke.current=!0,re.current="",de.current=null;return}Ge();return}if(ee.type==="session_io_error"){const ae=typeof ee.error=="string"&&ee.error?ee.error:typeof ee.reason=="string"&&ee.reason?ee.reason:"unknown error";u(!1),v(`Runtime input failed: ${ae}`);return}}},U))||(()=>{});return()=>{$()}},[U,P,r,l]);const bt=async($={})=>{var G;if(!U||!P)return{success:!1,error:"daemonId and sessionId are required"};$.preserveStatus||v($.loadingMessage||"Loading runtime terminal...");try{const ee=await((G=ct.requestRuntimeSnapshot)==null?void 0:G.call(ct,U,P,{sinceSeq:$.sinceSeq,force:$.force}));return ee&&ee.success===!1?($.preserveStatus||(u(!1),v(`Runtime terminal unavailable: ${ee.error}`)),ee):ee||{success:!0}}catch(ee){const ae=(ee==null?void 0:ee.message)||String(ee);return $.preserveStatus||(u(!1),v(`Runtime terminal unavailable: ${ae}`)),{success:!1,error:ae}}},Ce=async $=>{var _e,De;const G=((_e=K.current)==null?void 0:_e.ownerDocument)||document,ee=G.defaultView||window,ae=(De=ee.navigator)==null?void 0:De.clipboard;if(ae!=null&&ae.writeText&&ee.isSecureContext)try{return await ae.writeText($),!0}catch{}let je=null;try{return je=G.createElement("textarea"),je.value=$,je.setAttribute("readonly","true"),je.style.position="fixed",je.style.left="-9999px",je.style.top="0",G.body.appendChild(je),je.focus(),je.select(),G.execCommand("copy")}catch{return!1}finally{je==null||je.remove()}},Ue=$=>{ue(),I($);const G=xe();he.current={ownerWindow:G,timeoutId:G.setTimeout(()=>{he.current=null,I(ee=>ee===$?null:ee)},2200)}},Qe=$=>{oe(),y($);const G=xe();fe.current={ownerWindow:G,timeoutId:G.setTimeout(()=>{fe.current=null,y(ee=>ee===$?null:ee)},2200)}},ze=async()=>{var je,_e,De,Ae;const $=((_e=(je=r.current)==null?void 0:je.getSelection)==null?void 0:_e.call(je))||"",G=((Ae=(De=r.current)==null?void 0:De.getVisibleText)==null?void 0:Ae.call(De))||"",ee=$.trimEnd()||G.trimEnd();if(!ee){Ue("Nothing to copy");return}if(!await Ce(ee)){Ue("Copy failed");return}Ue($.trimEnd()?"Copied selection":"Copied visible terminal")},rt=$=>{if(!m||!l)return;((d==null?void 0:d(U,P,$))??!1)||Ue("Terminal input failed")},H=async()=>{if(f)return;p(!0),y("Loading older terminal output..."),ye.current=!0;const $=await bt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(p(!1),($==null?void 0:$.success)===!1){ye.current=!1,y(`Older terminal output unavailable: ${$.error}`);return}w(!0),Qe("Older terminal output loaded"),Se(()=>{var G;(G=r.current)==null||G.bumpResize()})};i.useEffect(()=>{var G,ee;if(!P)return;U&&((G=ct.getState)==null?void 0:G.call(ct,U))==="connected"&&bt();const $=(ee=ct.onStateChange)==null?void 0:ee.call(ct,(ae,je)=>{ae!==U||je!=="connected"||bt()});return()=>{$==null||$()}},[U,P,r]),i.useEffect(()=>{s&&He()},[s,le,r]),i.useEffect(()=>{var ae,je;const $=K.current,G=(je=(ae=$==null?void 0:$.ownerDocument)==null?void 0:ae.defaultView)==null?void 0:je.ResizeObserver;if(!$||!G)return;const ee=new G(_e=>{const De=_e[0];if(!De)return;const{width:Ae,height:Ee}=De.contentRect;R(Oe=>{const Te=Math.round(Ae),Ye=Math.round(Ee);return Oe.width===Te&&Oe.height===Ye?Oe:{width:Te,height:Ye}})});return ee.observe($),()=>ee.disconnect()},[]),i.useEffect(()=>{if(E.current)return;const $=Ie();!Number.isFinite($)||$<=0||L(G=>V.current?$<G-ve?$:G:(V.current=!0,$))},[T.height,T.width,O.height,O.width]),i.useEffect(()=>{B&&Fe()},[B,Re,Ne]),i.useEffect(()=>{var ee;const $=Y.current;if(Y.current=l,!l)return;$||w(!1),ke.current&&(ke.current=!1,Ge());const G=de.current;G&&(de.current=null,pt(G.text,G.seq,G.cols,G.rows,{force:!!G.force})),U&&P&&((ee=ct.getState)==null?void 0:ee.call(ct,U))==="connected"&&bt(),re.current&&q.current===null&&me(),Se(()=>{var ae;(ae=r.current)==null||ae.bumpResize()})},[U,l,P]),i.useEffect(()=>()=>{q.current!==null&&Q(),ue(),oe()},[]),i.useEffect(()=>{const $=ae=>{var _e;const je=ae.detail;je!=null&&je.sessionId&&je.sessionId!==P||m&&((_e=r.current)==null||_e.bumpResize())},G=xe(),ee=G===window?[window]:[window,G];for(const ae of ee)ae.addEventListener("adhdev:fit-cli-terminal",$);return()=>{for(const ae of ee)ae.removeEventListener("adhdev:fit-cli-terminal",$)}},[m,P,r]);const J=m&&x&&!S&&(W.atTop||!W.canScroll)||f||!!b;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{ref:K,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[J&&t.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[t.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:()=>{H()},disabled:!P||f,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:f?"Loading older...":"Load older terminal output"}),b&&t.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:b})]}),t.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[C&&t.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:C}),t.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:()=>{ze()},disabled:!m,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),t.jsxs("div",{className:"relative",children:[t.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:()=>j($=>!$),disabled:!m,"aria-label":"Open terminal control keys","aria-expanded":k,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),k&&t.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:[t.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),t.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:()=>j(!1),"aria-label":"Close terminal control keys",children:"×"})]}),t.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[t.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:()=>rt("\x1B"),children:"Esc"}),t.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:()=>rt(" "),children:"Tab"}),t.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:()=>rt("\r"),children:"Enter"}),t.jsx("span",{"aria-hidden":"true"}),t.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:()=>rt("\x1B[A"),"aria-label":"Arrow up",children:"↑"}),t.jsx("span",{"aria-hidden":"true"}),t.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:()=>rt("\x1B[D"),"aria-label":"Arrow left",children:"←"}),t.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:()=>rt("\x1B[B"),"aria-label":"Arrow down",children:"↓"}),t.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:()=>rt("\x1B[C"),"aria-label":"Arrow right",children:"→"}),t.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:()=>rt(""),children:"Ctrl-C"}),t.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:()=>rt(""),children:"Ctrl-D"}),t.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:()=>rt(""),children:"Bksp"})]})]})]}),t.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:()=>{E.current=!0,L($=>{const G=Math.max(Me,Number(($-.1).toFixed(2)));return G>Me&&Fe(),G})},title:"Shrink terminal viewport",children:"-"}),t.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:()=>{E.current=!0,L($=>{const G=Math.min(se,Number(($+.1).toFixed(2)));return G>Me&&Fe(),G})},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{ref:_,className:B?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:t.jsx("div",{style:{width:Ne>0?`${Ne}px`:"100%",height:Re>0?`${Re}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:t.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:A},children:t.jsx(Ql,{ref:r,readOnly:!m||!l,sizingMode:"measured",onViewportMetrics:F,onScrollMetrics:D,onInput:$=>{!m||(d==null||d(U,P,$))}})})})}),!m&&t.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:g})]}),t.jsx(cc,{contextKey:e.tabKey,panelLabel:lt(e),isSending:a,isBusy:!!ce,statusMessage:te,onSend:async $=>ce?!1:n($),isActive:c&&l,showControlsToggle:!1,animateVisibility:!1})]})}const Nh=5e3,Ch=12e3;function Ih(e){return e==="disconnected"||e==="reconnecting"}function Th({wsStatus:e,showReconnected:s,loginUrl:r,onReconnect:n,reconnectDelayMs:a=Nh,reconnectActionDelayMs:o=Ch}){const l=Ih(e),[c,d]=i.useState(()=>!l||a<=0),[m,u]=i.useState(()=>!l||o<=0),h=i.useRef(!1);i.useEffect(()=>{if(!l){d(!1);return}if(h.current=!1,a<=0){h.current=!0,d(!0);return}d(!1);const w=setTimeout(()=>{h.current=!0,d(!0)},a);return()=>clearTimeout(w)},[a,l]),i.useEffect(()=>{if(!l){u(!1);return}if(o<=0){u(!0);return}u(!1);const w=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(w)},[o,l]);const g=l?c:e==="offline"||e==="auth_failed",v=!!(n&&e!=="auth_failed"&&(!l||m)),f=i.useMemo(()=>!s||e!=="connected"?!1:a<=0||h.current,[a,s,e]),p=e==="auth_failed"?"red":e==="offline"?"orange":"accent",b={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)"},x={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},N="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",S={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return t.jsxs(t.Fragment,{children:[g&&t.jsx("div",{className:N,style:S,children:t.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:b[p],border:y[p],color:x[p]},children:[t.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}}),t.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?t.jsxs(t.Fragment,{children:["Session expired."," ",t.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),v&&t.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"})]})}),f&&t.jsx("div",{className:N,style:S,children:t.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:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function Ah({terminalBackend:e,isStandalone:s=!1,machineLabel:r,machineKey:n}){const a=i.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[o,l]=i.useState(!1);if(i.useEffect(()=>{if(!a){l(!1);return}try{l(localStorage.getItem(a)==="1")}catch{l(!1)}},[a]),!s||!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{}l(!0)};return t.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:[t.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[t.jsxs("span",{children:[c," is using `xterm` fallback."]}),t.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),t.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 Co({mode:e,onChange:s,compact:r=!1}){const n=r?14:15;return t.jsx("button",{type:"button",onClick:()=>s(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?t.jsx(co,{size:n}):t.jsx(Vt,{size:n})})}const Ot="New session",Pc="A connected machine is ready. Start a new session to begin chatting, or open a workspace to launch an IDE, CLI, or ACP session.";function Mh(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 s=[e.branch||"Git"];return e.changedFiles>0&&s.push(`±${e.changedFiles}`),e.ahead>0&&s.push(`↑${e.ahead}`),e.behind>0&&s.push(`↓${e.behind}`),s.length===1&&e.dirty&&s.push("dirty"),s.join(" ")}function Lh(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 Rh(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 Os({git:e,className:s="",compact:r=!1}){const n=Mh(e),a=Lh(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 t.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 ${Rh(a)} ${s}`.trim(),title:o.join(" · ")||n,"data-git-tone":a,children:[t.jsx("span",{"aria-hidden":"true",children:"⑂"}),t.jsx("span",{className:"truncate",children:n})]})}function _h({wsStatus:e,isConnected:s,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,l=a.filter(c=>c==="connecting"||c==="new"||c==="checking").length;return r>0&&l>0&&o===0?{tone:"limited",title:"Connected to dashboard",subtitle:"Connecting to machine..."}:s?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function Ri({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function _i({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const l=In(e.updatedAt),c=!e.readAt;return t.jsxs("div",{className:`dashboard-header-inbox-item ${c?"is-attention":""}`.trim(),children:[t.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[s?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",s]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",l].filter(Boolean).join(" · ")]}),e.preview?t.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),t.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[c?t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),n()},children:"Mark read"}):t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),a()},children:"Mark unread"}),t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),o()},children:"Delete"})]})]})}function Ph({activeConv:e,wsStatus:s,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:l,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:h,onShowAllHidden:g,onResetPanelsToMain:v,inboxOpen:f,onInboxOpenChange:p,hiddenOpen:b,onHiddenOpenChange:y,onOpenNewSession:x,onOpenDashboardGuide:N,guideNudgeVisible:S=!1,actionShortcuts:w,notifications:A,notificationUnreadCount:L,onOpenNotification:k,onMarkNotificationRead:j,onMarkNotificationUnread:O,onDeleteNotification:R,onOpenGitDialog:T,onOpenMeshGraph:F}){var Se;const{ides:W,p2pStates:D={}}=rs(),C=!!e&&st(e)&&!Ze(e),I=!!e&&Ze(e),K=!!(e!=null&&e.daemonId)&&typeof((Se=e==null?void 0:e.settings)==null?void 0:Se.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.length>0,_=c||(e?dc(e)?"terminal":"chat":null),[E,V]=i.useState(!1),Y=i.useRef(null),ge=i.useRef(null),pe=W.filter(Q=>Q.type==="adhdev-daemon"),re=_h({wsStatus:s,isConnected:r,daemonCount:pe.length,p2pStates:D}),de=re.subtitle,ke=re.tone==="connected"?"#22c55e":re.tone==="limited"?"#eab308":"#ef4444",ye=re.tone==="connected"?"0 0 4px #22c55e80":re.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",q=i.useMemo(()=>A.filter(Q=>!Q.readAt),[A]),he=i.useMemo(()=>A.filter(Q=>!!Q.readAt),[A]),fe=i.useMemo(()=>q.slice(0,9),[q]),we=L;i.useEffect(()=>{if(!f)return;const Q=ue=>{var oe;(oe=Y.current)!=null&&oe.contains(ue.target)||p(!1)};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[f,p]),i.useEffect(()=>{if(!b)return;const Q=ue=>{var oe;(oe=ge.current)!=null&&oe.contains(ue.target)||y(!1)};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[b,y]),i.useEffect(()=>{if(!b&&!f)return;const Q=ue=>{if(!ue.altKey)return;const oe=ue.code.match(/^Digit([1-9])$/);if(!oe)return;const me=Number(oe[1])-1,le=b?u[me]:void 0,P=f?fe[me]:void 0;if(!(!le&&!P)){if(ue.preventDefault(),ue.stopPropagation(),le){h==null||h(le),y(!1);return}P&&(k(P),p(!1))}};return window.addEventListener("keydown",Q,!0),()=>window.removeEventListener("keydown",Q,!0)},[u,b,f,fe,y,p,k,h]);const xe=Q=>{if(!Q)return;const ue=n.find(oe=>oe.tabKey===Q);ue&&(m==null||m(ue))};return t.jsxs("div",{className:"dashboard-header",children:[t.jsx("div",{className:"flex items-center gap-3",children:t.jsx("div",{className:"header-title-block",children:t.jsxs("div",{className:"header-title-row",children:[t.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[t.jsx(Vt,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?lt(e):"Dashboard"}),t.jsx("span",{title:re.title,"aria-label":re.title,className:"header-title-status-dot",style:{background:ke,boxShadow:ye}}),t.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:t.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:ke,boxShadow:ye}})})]}),t.jsxs("div",{className:"header-subtitle flex items-center",children:[de&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",de]}),x&&t.jsx("button",{type:"button",onClick:x,className:"btn btn-secondary btn-sm ml-2",title:`${Ot}${w!=null&&w.openNewSession?` (${w.openNewSession})`:""}`,"aria-label":Ot,children:t.jsx(zl,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[N&&t.jsxs("button",{type:"button",onClick:N,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:[t.jsx("span",{className:"font-semibold leading-none",children:"?"}),S&&t.jsx("span",{children:"Guide"})]}),e&&(C||I||!Ze(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:vs(e)||lt(e),children:lt(e)}),T&&e.git&&e.daemonId&&e.workspacePath?t.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:t.jsx(Os,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):t.jsx(Os,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),K&&F&&t.jsxs("button",{type:"button",onClick:()=>F(e),className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",title:"Open live repo mesh graph",children:[t.jsx(Qt,{size:14}),t.jsx("span",{className:"hidden lg:inline",children:"Mesh graph"})]}),(C||I)&&l&&t.jsxs(t.Fragment,{children:[C&&d&&_&&t.jsx(Co,{mode:_,onChange:d,compact:!0}),t.jsx("button",{onClick:()=>l(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:t.jsx(gt,{size:14})})]}),!Ze(e)&&t.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(io,{size:14})}),!C&&!Ze(e)&&t.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(It,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:Y,children:[t.jsxs("div",{className:`dashboard-header-hidden${E?" is-drop-target":""}`,ref:ge,onDragEnter:Q=>{Q.dataTransfer.types.includes("text/tab-key")&&(Q.preventDefault(),V(!0))},onDragOver:Q=>{Q.dataTransfer.types.includes("text/tab-key")&&(Q.preventDefault(),Q.dataTransfer.dropEffect="move",V(!0))},onDragLeave:Q=>{Q.currentTarget.contains(Q.relatedTarget)||V(!1)},onDrop:Q=>{const ue=Q.dataTransfer.getData("text/tab-key");Q.preventDefault(),V(!1),xe(ue)},children:[t.jsxs("button",{type:"button",onClick:()=>y(!b),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${w!=null&&w.toggleHiddenTabs?` (${w.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(lo,{size:16}),u.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),b&&t.jsxs("div",{className:"dashboard-header-hidden-popover",children:[t.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),t.jsx(Ri,{value:w==null?void 0:w.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[v&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:v,children:"Reset panels"}),u.length>0&&g&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{g(),y(!1)},children:"Restore all"})]})]}),e&&m&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[t.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[t.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),t.jsx(Ri,{value:w==null?void 0:w.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:lt(e)})]}),u.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(Q=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(Q),y(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:lt(Q)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(Q)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(Q)+1]}):null,vs(Q)]})]},Q.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>p(!f),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(Cn,{size:16}),we>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:we})]}),f&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[q.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),q.map(Q=>t.jsx(_i,{notification:Q,shortcutIndex:fe.indexOf(Q)>=0?fe.indexOf(Q)+1:void 0,onOpen:()=>k(Q),onMarkRead:()=>j(Q.id),onMarkUnread:()=>O(Q.id),onDelete:()=>R(Q.id)},Q.id))]}),he.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),he.map(Q=>t.jsx(_i,{notification:Q,onOpen:()=>k(Q),onMarkRead:()=>j(Q.id),onMarkUnread:()=>O(Q.id),onDelete:()=>R(Q.id)},Q.id))]}),A.length===0&&t.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 Dh(e,s){return String(e||"")!==String(s||"")}function Eh(e,s={}){const r=String(s.textQuery||"").trim().toLowerCase(),n=String(s.workspaceQuery||"").trim().toLowerCase(),a=String(s.modelQuery||"").trim().toLowerCase(),o=!!s.resumableOnly;return!r&&!n&&!a&&!o?e:e.filter(l=>!(o&&!l.canResume||r&&![l.title,l.preview].map(d=>String(d||"").toLowerCase()).join(`
41
+ `).includes(r)||n&&!String(l.workspace||"").toLowerCase().includes(n)||a&&!rc(l.summaryMetadata).map(d=>d.toLowerCase()).join(`
42
+ `).includes(a)))}function $h(e,s="recent"){const r=e.slice();return r.sort((n,a)=>{if(s==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(s==="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 Dc(e,s={}){return $h(Eh(e,s),s.sortMode||"recent")}function gn(e){return e?"Resume saved history":"Start fresh"}function Io(e){return e?"Resuming saved history…":"Starting fresh…"}function Bh(){return"Start fresh"}function Ec(e,s=!1){return e==="cli"?gn(s):e==="ide"?"Start IDE":"Start ACP session"}function $c(e,s=!1){return e==="cli"?Io(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Oh(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Kh(){return"Open saved history"}function Fh(){return"Saved History"}function To(){return"Use saved history when you want continuity in the same provider conversation."}function Wh(){return"No saved history found yet."}function Hh(){return"Refresh saved history"}function Uh(){return"Refreshing saved history…"}function us(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function ms(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 Ks(e){return e==="start-fresh"?"Start fresh":"Restart"}function Fs(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Ao(e){return`Resume saved history with ${e}?`}function Mo(){return"Review or change the target workspace before resuming saved history."}function zh(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 Lo({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:l=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:m,onClose:u,onNewChat:h,onSwitchSession:g,onRefreshHistory:v,onResumeSavedSession:f}){var R;const p=s.find(T=>T.id===e.routeId),b=(p==null?void 0:p.chats)||[],y=(R=p==null?void 0:p.activeChat)==null?void 0:R.id,x=st(e)&&!Ze(e),[N,S]=i.useState(()=>jt()),w=c||N,A=String(d||"").trim(),L=T=>{if(m){m(T);return}S(T)},k=i.useMemo(()=>a.map(T=>{const F=String(T.workspace||"").trim();return T.canResume||F||!A?T:{...T,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,a]),j=i.useMemo(()=>Dc(k,{textQuery:w.textQuery,workspaceQuery:w.workspaceQuery,modelQuery:w.modelQuery,resumableOnly:w.resumableOnly,sortMode:w.sortMode}),[k,w.modelQuery,w.resumableOnly,w.sortMode,w.textQuery,w.workspaceQuery]),O=t.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:[t.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.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:[t.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:[t.jsxs("div",{children:[t.jsx("h3",{className:"m-0 text-lg font-extrabold",children:x?Fh():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:jh(e)}),x&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:To()})]}),t.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:t.jsx(gt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!x&&t.jsx("button",{onClick:h,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"}),x?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[t.jsx("input",{type:"text",value:w.textQuery,onChange:T=>L({...w,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"}),t.jsx("input",{type:"text",value:w.workspaceQuery,onChange:T=>L({...w,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"}),t.jsx("input",{type:"text",value:w.modelQuery,onChange:T=>L({...w,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"}),t.jsxs("select",{value:w.sortMode,onChange:T=>L({...w,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:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:w.resumableOnly,onChange:T=>L({...w,resumableOnly:T.target.checked})}),"Resume-ready only"]})]}),j.map(T=>{const F=e.providerSessionId===T.providerSessionId,W=F||!T.canResume||!!l,D=T.workspaceFallbackSource==="selected-workspace";return t.jsxs("button",{type:"button",onClick:()=>{W||!f||f(T)},disabled:W,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${F?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${W?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:`font-bold text-sm mb-1 truncate ${F?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:T.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:zh(T.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:T.preview||"No saved preview yet"}),t.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[t.jsxs("div",{className:"truncate",children:[T.workspace||"Workspace unknown",D?" · selected workspace":"",ys(T.summaryMetadata)?` · ${ys(T.summaryMetadata)}`:"",T.messageCount>0?` · ${T.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:F?"ACTIVE":T.canResume?D?"RESUME IN SELECTED WORKSPACE":l===T.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},T.id)})]}):b.map(T=>t.jsxs("div",{onClick:()=>{g(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:[t.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"}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[T.id.substring(0,12),"..."]}),y===T.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},T.id)),(x&&!o&&j.length===0||!x&&b.length===0)&&t.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[t.jsx("div",{className:"text-3xl mb-3 opacity-60",children:t.jsx(hm,{size:32})}),t.jsx("div",{className:"text-[13px]",children:x?a.length>0?"No saved history matches these filters.":Wh():"No recent chat sessions found."})]}),x&&o&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:Uh()})})]}),t.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:t.jsx("button",{onClick:v,disabled:n||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||o?"⌛ Refreshing...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(wr,{size:13})," ",x?Hh():"Refresh History"]})})})]})]});return typeof document>"u"?O:xr.createPortal(O,document.body)}const Pi={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 Bc({toasts:e,onDismiss:s,onClickToast:r}){return t.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=Pi[n.type]||Pi.info;return t.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:[t.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))`}}),t.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(),s(n.id)},"aria-label":"Dismiss",children:t.jsx(gt,{size:14})}),t.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[t.jsx("div",{className:"flex items-center gap-2 pr-8",children:t.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})}),t.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&t.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((o,l)=>t.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(),s(n.id)},children:o.label},l))})]})]},n.id)})})}const Vh=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Gh(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function qh(e){return e.sessionId||e.instanceId||e.agentType}function Zn(e,s){return s||e||"unknown"}function Oc(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=Ct(r,{fallbackId:r.id}));return s}function Kc(e,s={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=s.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:s.connectionStates?s.connectionStates[r]||s.defaultConnectionState||"new":s.defaultConnectionState}}function Ro(e,s={}){return Yh(e,Kc(e,s))}function Yh(e,s={}){var h,g,v,f,p;const r=[],n=s.machineName,a=s.connectionState,o=Gh(e),l=e.workspace||"",c=gp(e.type,{agentName:e.cliName}),d=st(e)||Ze(e)?c:ot(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(b=>{var y,x;return{sessionId:b.id,instanceId:b.id,providerSessionId:b.providerSessionId,transport:b.transport,sessionCapabilities:b.capabilities,agentType:b.providerType,agentName:b.providerName||ot(b.providerType),status:b.status,title:b.title,lastMessagePreview:b.lastMessagePreview,lastMessageRole:b.lastMessageRole,lastMessageAt:b.lastMessageAt,lastMessageHash:b.lastMessageHash,messages:((y=b.activeChat)==null?void 0:y.messages)||[],activeModal:((x=b.activeChat)==null?void 0:x.activeModal)||void 0,unread:b.unread,lastSeenAt:b.lastSeenAt,lastUpdated:b.lastUpdated,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,surfaceHidden:b.surfaceHidden,git:b.git,settings:b.settings,messageInput:b.messageInput}}):[],u=Vh(e);if(u){const b=e.sessionId||e.instanceId,y=(h=e.settings)==null?void 0:h.meshCoordinatorFor,x=(g=e.settings)==null?void 0:g.meshNodeFor,N=y?" (Coordinator)":x?" (Mesh Node)":"",S=c+N,w=(v=e.activeChat)==null?void 0:v.activeModal,A=w&&Array.isArray(w.buttons)&&w.buttons.length>0,L=yp(e.activeChat,[{status:e.status,activeModal:(f=e.activeChat)==null?void 0:f.activeModal}],e.agents||[]),k=e.activeChat||{title:"",messages:[]};let j=k.title&&String(k.title).trim()?String(k.title).trim():"";const O=(p=e.activeChat)==null?void 0:p.id,R=e.chats;if(O&&Array.isArray(R)&&R.length>0){const D=R.find(C=>C.id===O||C.id&&String(C.id)===String(O));D!=null&&D.title&&String(D.title).trim()&&(j=String(D.title).trim())}const T=(st(e)||Ze(e),e.type),F=(st(e)||Ze(e))&&yi(j,S,T)?"":j,W=k.messages||[];r.push({routeId:e.id,sessionId:b,providerSessionId:e.providerSessionId,nativeSessionId:b,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:st(e)?e.mode||"terminal":"chat",agentName:S,agentType:T,status:L,title:F,messages:W,resume:e.resume,hostIdeType:!st(e)&&!Ze(e)?e.type:void 0,workspaceName:o,workspacePath:l,git:e.git,displayPrimary:F||o||(st(e)?e.mode==="chat"?S:`Terminal${N}`:S),displaySecondary:st(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:A?w.buttons:void 0,modalMessage:A?w.message:void 0,streamSource:"native",tabKey:Zn(b,e.id),machineName:n,connectionState:a,settings:e.settings,messageInput:e.messageInput})}if(u&&(st(e)||Ze(e)))return r;for(const b of m){const y=b.activeModal&&Array.isArray(b.activeModal.buttons)&&b.activeModal.buttons.length>0,x=vp(b),N=qh(b),S=`${e.id}:${N}`,w=b.title&&String(b.title).trim()||"",A=yi(w,b.agentName,b.agentType)?"":w,L=b.messages||[];(b.transport==="cdp-webview"||b.sessionId||b.providerSessionId||L.length>0||y||A||!["idle","panel_hidden","disconnected","not_monitored"].includes(x))&&r.push({routeId:e.id,sessionId:b.sessionId||b.instanceId,providerSessionId:b.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:b.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:b.sessionCapabilities,mode:"chat",agentName:b.agentName,agentType:b.agentType,status:x,title:A,messages:L,hostIdeType:e.type,workspaceName:o,workspacePath:l,git:b.git||e.git,displayPrimary:A||o||b.agentName||d,displaySecondary:`${d} · ${b.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:b.lastMessagePreview,lastMessageRole:b.lastMessageRole,lastMessageAt:b.lastMessageAt,lastMessageHash:b.lastMessageHash,lastUpdated:b.lastUpdated||e.lastUpdated,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,modalButtons:y?b.activeModal.buttons:void 0,modalMessage:y?b.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Zn(b.sessionId||b.instanceId,S),machineName:n,connectionState:a,settings:b.settings,messageInput:b.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:l,git:e.git,displayPrimary:o||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Zn(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function Fc(e){return String(e.type||e.id||"").trim()}function Xh(e){var s;return e.category!=="cli"||!Fc(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((s=e.lastDetection)==null?void 0:s.ok)===!0||e.installed===!0||!!e.detectedPath}function Jh(e){var n;const s=new Set,r=[];for(const a of e||[]){if(!Xh(a))continue;const o=Fc(a);if(!o||s.has(o))continue;s.add(o);const l=String(a.displayName||a.name||o),c=a.detectedPath||((n=a.lastDetection)==null?void 0:n.path)||null;r.push({type:o,label:l,icon:a.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c})}return r}function Rn(e){const s=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],r=new Set,n=[];for(const a of s){const o=typeof a=="string"?a.trim():"";!o||r.has(o)||(r.add(o),n.push(o))}return n}function Ua(e,s){const r=new Set(s.map(n=>n.type));return Rn(e).filter(n=>r.has(n))}function Qh(e){return e.map(s=>s.type)}function Zh(e,s){const r=Rn(e),n=s.trim();return!n||r.includes(n)?r:[...r,n]}function ex(e,s){return Rn(e).filter(r=>r!==s)}function Di(e,s,r){const n=Rn(e),a=n.indexOf(s);if(a<0)return n;const o=n.filter(c=>c!==s);if(r==="top")return[s,...o];if(r==="bottom")return[...o,s];const l=r==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(l,0,s),o}function Ei({direction:e}){return t.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"?t.jsx("polyline",{points:"18 15 12 9 6 15"}):t.jsx("polyline",{points:"6 9 12 15 18 9"})})}function $i({value:e,availableProviders:s,onChange:r,disabled:n=!1,saveButton:a}){const[o,l]=i.useState(""),c=i.useMemo(()=>new Map(s.map(g=>[g.type,g])),[s]),d=i.useMemo(()=>Ua(e,s),[e,s]),m=e.length-d.length,u=s.filter(g=>!d.includes(g.type)),h=()=>{o&&(r(Zh(d,o)),l(""))};return t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[t.jsx("div",{className:"flex flex-col gap-2",children:d.length===0?t.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((g,v)=>{const f=c.get(g);return t.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:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",v+1]}),(f==null?void 0:f.icon)&&t.jsx("span",{"aria-hidden":"true",children:f.icon}),t.jsx("span",{className:"font-mono text-[12px] text-text-primary",children:g}),t.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"})]}),t.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:f?`${f.label} · ${f.statusLabel}`:g})]}),t.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[t.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||v===0,title:"Move up",onClick:()=>r(Di(d,g,"up")),children:t.jsx(Ei,{direction:"up"})}),t.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||v===d.length-1,title:"Move down",onClick:()=>r(Di(d,g,"down")),children:t.jsx(Ei,{direction:"down"})}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(ex(d,g)),children:"Remove"})]})]},g)})}),t.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[t.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:"Add available CLI provider"}),t.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:g=>l(g.target.value),disabled:n||u.length===0,children:[t.jsx("option",{value:"",children:u.length?"Select provider…":"No additional detected CLI providers"}),u.map(g=>t.jsxs("option",{value:g.type,children:[g.label," (",g.type,")"]},g.type))]})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!o,onClick:h,children:"Add provider"}),a]}),t.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 tx(e){const s=e.split(":");return s.length>=3&&(s[1]==="ide"||s[1]==="cli"||s[1]==="acp")?{daemonId:s[0],targetSessionId:s.slice(2).join(":")||void 0}:{daemonId:e}}function Wc(e,s){const r=tx(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Hc=[{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:"🏄"}],Uc=[{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:"🧩"}],zc=[{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:"🟠"}],sx=Hc,rx=Uc,nx=zc;function Gt(...e){return ju(ku(e))}function ax({icon:e,title:s,subtitle:r,badge:n,actions:a,className:o}){return t.jsxs("div",{className:Gt("dashboard-header",o),children:[t.jsxs("div",{children:[t.jsxs("h1",{className:"header-title flex items-center gap-2",children:[t.jsx("span",{className:"flex items-center text-lg",children:e})," ",s,n&&t.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&&t.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&t.jsx("div",{className:"flex gap-2",children:a})]})}function mr({icon:e,title:s,subtitle:r,badge:n,actions:a,widthClassName:o="max-w-6xl",contentClassName:l,children:c}){return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsx(ax,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:Gt("mx-auto flex w-full flex-col gap-4",o,l),children:c})})]})}const za="adhdev:themechange";function ox(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Cs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Is(e){return e==="system"?ox():e}function Vc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Zr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(za,{detail:{preference:e,theme:s}}))}function ix(){const e=Cs(),s=Is(e);Vc(s),Zr(e,s)}function _o(){const[e,s]=i.useState(Cs),[r,n]=i.useState(()=>Is(Cs()));i.useEffect(()=>{Vc(r)},[r]),i.useEffect(()=>{const l=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const m=d.matches?"light":"dark";n(m),Zr("system",m)}};return l.addEventListener("change",c),()=>l.removeEventListener("change",c)},[e]),i.useEffect(()=>{const l=d=>{const m=d.detail||{},u=m.preference,h=m.theme;s(u==="dark"||u==="light"||u==="system"?u:Cs()),n(h==="dark"||h==="light"?h:Is(Cs()))},c=d=>{if(d.key!=="theme")return;const m=Cs(),u=Is(m);s(m),n(u)};return window.addEventListener(za,l),window.addEventListener("storage",c),()=>{window.removeEventListener(za,l),window.removeEventListener("storage",c)}},[]);const a=i.useCallback(l=>{const c=Is(l);s(l),n(c);try{localStorage.setItem("theme",l)}catch{}Zr(l,c)},[]),o=i.useCallback(()=>{s(l=>{const c=l==="dark"?"light":l==="light"?"system":"dark",d=Is(c);n(d);try{localStorage.setItem("theme",c)}catch{}return Zr(c,d),c})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const Bi={dark:"Dark",light:"Light",system:"System"};function lx({collapsed:e}){const{preference:s,cycleTheme:r}=_o(),n=s==="dark"?t.jsx(bm,{size:16}):s==="light"?t.jsx(xm,{size:16}):t.jsx(gm,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Bi[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:Bi[s]})]})}function ea(e,s){return e?typeof e=="function"?e(s):e:null}function cx({children:e,brand:s,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:l,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const[m,u]=i.useState(!1),[h,g]=i.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),v=()=>u(!0),f=()=>u(!1),p=()=>{g(N=>{const S=!N;try{localStorage.setItem(d,S?"1":"0")}catch{}return S})},b=i.useMemo(()=>({collapsed:h,mobileMenuOpen:m,openMobileMenu:v,closeMobileMenu:f,toggleCollapsed:p}),[h,m]),y=N=>`nav-item${N.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${N.className?` ${N.className}`:""}`,x=N=>t.jsxs("div",{className:y(N),id:`nav-${N.id}`,onClick:()=>{N.onSelect(),f()},title:h?N.title??(typeof N.label=="string"?N.label:void 0):N.title,children:[t.jsx("span",{className:"nav-icon",children:N.icon}),!h&&N.label]},N.id);return t.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[t.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:v,children:[t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"})]}),m&&t.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:f,onKeyDown:N=>N.key==="Escape"&&f()}),t.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[t.jsxs("div",{className:"sidebar-header",children:[t.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:ea(s,b)}),t.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:f,children:t.jsx(gt,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:r.map(x)}),n.map(N=>t.jsxs("div",{className:N.className??"border-t border-border-subtle pt-2 mt-2",children:[!h&&N.title?t.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:N.title}):null,N.items.map(x)]},N.key)),t.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(x),ea(o,b),t.jsx(lx,{collapsed:h}),ea(l,b)]})]}),t.jsx("main",{className:"main-content relative",children:t.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function vt({title:e,icon:s,description:r,accentColor:n,className:a,children:o}){return t.jsxs("div",{className:Gt("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)&&t.jsxs("div",{className:"mb-4",children:[e&&t.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[s&&t.jsx("span",{className:"mr-1.5",children:s}),e]}),r&&t.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),o]})}function yn({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:Gt("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[t.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),t.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:s}),t.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const dx={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"},ux={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ms({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:Gt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",dx[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:ux[e]}),t.jsx("span",{children:s})]}),r&&t.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function Tt({label:e,hint:s,children:r,className:n}){return t.jsxs("div",{className:Gt("mb-5",n),children:[t.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),r,s&&t.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:s})]})}function ta(e){const{className:s,...r}=e;return t.jsx("input",{...r,className:Gt("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",s)})}const mx={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"},px={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function fx({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:Gt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",mx[e],r),children:[t.jsx("span",{className:Gt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",px[e])}),n]})}function is({label:e,description:s,checked:r,disabled:n,onChange:a,extra:o}){return t.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[t.jsxs("div",{className:"pr-4",children:[t.jsx("div",{className:"font-medium text-sm",children:e}),t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:s})]}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o,t.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:[t.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))"}}),t.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 hx({onPrefChange:e}){const[s,r]=Mp(),[n,a]=i.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);i.useEffect(()=>{const l=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return l(),window.addEventListener("focus",l),document.addEventListener("visibilitychange",l),()=>{window.removeEventListener("focus",l),document.removeEventListener("visibilitychange",l)}},[]);const o=(l,c)=>{r({[l]:c}),e==null||e(l,c)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(is,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Cn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:l=>o("globalEnabled",l)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(is,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(It,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:l=>o("browserNotifications",l)}),s.globalEnabled&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.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"&&t.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[t.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),t.jsx("button",{onClick:()=>{oc().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"&&t.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"&&t.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."})]}),s.globalEnabled&&s.browserNotifications&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx(is,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(ym,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:l=>o("completionAlert",l)}),t.jsx(is,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(vm,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:l=>o("approvalAlert",l)}),t.jsx(is,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Es,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:l=>o("disconnectAlert",l)})]}),!s.globalEnabled&&t.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function vn(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function xx(e,s){const r=vn(e),n=vn(s);if(!r||!n)return e.localeCompare(s);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 Gc(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function pr(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||xx(r,s)>=0)return!1;const n=vn(r),a=vn(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function bx(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function sa(e,s){return e instanceof Error?e.message:s}function gx({ides:e,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const o=e.filter(l=>l.type==="adhdev-daemon");return o.length===0?t.jsx(yn,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:s||"Install ADHDev on a machine and sign in to connect it here."}):t.jsx("div",{className:"flex flex-col gap-2",children:o.map(l=>t.jsx(vx,{ide:l,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},l.id))})}function Oi({title:e,message:s,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:o}){const l=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return xr.createPortal(t.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:o,children:t.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:[t.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),t.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:s}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.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"}),t.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${l}`,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 yx(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...sx,...rx,...nx].find(a=>a.id===s||s.includes(a.id)||a.id.includes(s));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function vx({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var W,D;const[o,l]=i.useState("idle"),[c,d]=i.useState(""),[m,u]=i.useState(null),[h,g]=i.useState("idle"),[v,f]=i.useState(""),p=e.version||null,b=((W=e.machine)==null?void 0:W.platform)||((D=e.system)==null?void 0:D.platform)||"",y=Ct(e,{fallbackId:e.id}),x=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",N=s.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),S=s.filter(C=>C.daemonId===e.id&&C.transport==="pty"),w=s.filter(C=>C.daemonId===e.id&&C.transport==="acp"),A=e.p2p,L=async()=>{if(r){l("upgrading"),d("Starting upgrade...");try{const C=bx(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(l("done"),d(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(l("done"),d(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(l("error"),d(C.error||"Upgrade failed"))}catch(C){l("error"),d(sa(C,"Connection lost during upgrade"))}}},k=async()=>{if(u(null),!!n){g("loading");try{await n(e.id),g("done"),f("Machine disconnected.")}catch(C){g("error"),f(sa(C,"Failed to disconnect"))}}},j=async()=>{if(u(null),!!a){g("loading");try{await a(e.id),g("done"),f("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){g("error"),f(sa(C,"Failed to revoke token"))}}},O="0.9.81",R=Gc(e,O),T=pr(e,O),F=N.length+S.length+w.length;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("span",{className:"text-xl",children:x}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:y}),t.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[t.jsxs("span",{children:[e.id.substring(0,12),"…"]}),p&&t.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${R?"":"bg-bg-secondary"}`,style:R?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!R&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&R&&t.jsx("button",{onClick:L,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"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${T?"↑ Update now":`↑ Update${` to v${O}`}`}`}),n&&t.jsx("button",{onClick:()=>u("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&t.jsx("button",{onClick:()=>u("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(fx,{status:e.status==="online"?"online":"error"})]})]}),t.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[A&&t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${A.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${A.state==="connecting"||A.state==="new"?"animate-pulse":""}`,style:A.state==="connecting"||A.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",A.state==="connected"?"connected":A.state==="connecting"||A.state==="new"?"connecting...":A.state||"off"]}),A.peers!==void 0&&A.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",A.peers," peer",A.peers!==1?"s":"",")"]})]}),A&&F>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),F>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(C=>{const I=yx(C.type),K=C.cdpConnected;return t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:I.icon}),t.jsx("span",{children:I.name}),K!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${K?"bg-green-400":"animate-pulse"}`,style:K?void 0:{background:"var(--status-warning)"},title:K?"CDP connected":"CDP connecting..."})]},C.id)}),S.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"⌨️"}),t.jsx("span",{children:C.cliName||"CLI"})]},C.id)),w.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"🔗"}),t.jsx("span",{children:C.cliName||"ACP"})]},C.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(c||v)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||h==="error"?"text-red-400":o==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:v||c})]}),m==="disconnect"&&t.jsx(Oi,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
43
+
44
+ This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
45
+
46
+ Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:k,onCancel:()=>u(null)}),m==="revoke"&&t.jsx(Oi,{title:"⚠️ Remove Machine",message:`Remove "${y}" from your dashboard?
47
+
48
+ This will:
49
+ • Immediately disconnect the machine
50
+ • Delete the machine registration
51
+ • Require restarting ADHDev on that machine
52
+
53
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:j,onCancel:()=>u(null)})]})}const wx=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function jx(){const{preference:e,setPreference:s}=_o();return t.jsx("div",{className:"flex gap-2",children:wx.map(r=>t.jsxs("button",{onClick:()=>s(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:[t.jsx("span",{children:r.icon}),r.label]},r.id))})}function kx(e){const s=e.trim();return/^#[0-9a-fA-F]{6}$/.test(s)?s:/^#[0-9a-fA-F]{3}$/.test(s)?`#${s[1]}${s[1]}${s[2]}${s[2]}${s[3]}${s[3]}`:null}function Sx(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function ra(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function Ki(e){const{r:s,g:r,b:n}=Sx(e);return .2126*ra(s)+.7152*ra(r)+.0722*ra(n)}function Fi(e,s){const r=Ki(e),n=Ki(s),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function qc(e){const s=kx(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return Fi(s,r)>=Fi(s,n)?r:n}const Va={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},Ga={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},Nx=[{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"}}}],Yc="adhdev-chat-theme",Xc="adhdev-chat-theme-custom";function en(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Yc)||"ember"}catch{return"ember"}}function Dt(e){try{const s=localStorage.getItem(Xc);if(s){const r=JSON.parse(s);return{...e==="dark"?Va:Ga,...r[e]}}}catch{}return e==="dark"?Va:Ga}function Kr(e,s){try{localStorage.setItem(Xc,JSON.stringify({dark:e,light:s}))}catch{}}function At(e,s){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}, ${s})`}function wn(e,s){const r=Math.min(255,parseInt(e.slice(1,3),16)+s),n=Math.min(255,parseInt(e.slice(3,5),16)+s),a=Math.min(255,parseInt(e.slice(5,7),16)+s);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const Cx={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function fr(e,s){var a;const r=(a=Cx[e])==null?void 0:a[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",wn(r,24)),n.style.setProperty("--accent-on-primary",qc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${wn(r,18)})`),n.style.setProperty("--border-accent",At(r,.35)),n.style.setProperty("--nav-active-bg",At(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${At(r,.06)}`)}function ps(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",At(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",At(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",At(e.borderSubtle,.25)),s.style.setProperty("--text-primary",e.textPrimary),s.style.setProperty("--text-secondary",e.textSecondary),s.style.setProperty("--text-muted",e.textMuted),s.style.setProperty("--border-subtle",At(e.borderSubtle,.5)),s.style.setProperty("--border-default",At(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",wn(e.accentColor,30)),s.style.setProperty("--accent-on-primary",qc(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${wn(e.accentColor,40)})`),s.style.setProperty("--border-accent",At(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",At(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${At(e.accentColor,.06)}`),s.style.setProperty("--chat-user-bg",e.userBubble),s.style.setProperty("--chat-user-color",e.userText),s.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),s.style.setProperty("--chat-assistant-bg",e.assistantBubble),s.style.setProperty("--chat-assistant-color",e.assistantText),s.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),s.style.setProperty("--chat-assistant-border",`1px solid ${At(e.accentColor,.12)}`),s.style.setProperty("--chat-container-bg",e.containerBg),s.style.setProperty("--dashboard-pane-bg",e.containerBg),s.style.setProperty("--chat-thought-accent",e.accentColor),s.style.setProperty("--chat-tool-accent",e.accentColor),s.style.setProperty("--chat-action-color",e.accentColor),s.style.setProperty("--chat-send-bg",e.sendButton),s.style.setProperty("--chat-input-border",e.inputBorder)}function Po(){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 Ix(e){try{localStorage.setItem(Yc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=fs()?"dark":"light";ps(Dt(s))}else Po(),fr(e,fs()?"dark":"light")}function Tx(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=en();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=fs()?"dark":"light";ps(Dt(s))}else Po(),fr(e,fs()?"dark":"light")}function fs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function kt({label:e,value:s,onChange:r}){return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[t.jsx("input",{type:"color",value:s,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),t.jsx("input",{type:"text",value:s,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 tr({title:e,children:s}){return t.jsxs("div",{style:{marginBottom:14},children:[t.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}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function Ax({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=i.useState(()=>Dt(r));i.useEffect(()=>{a(Dt(r))},[r]);const o=i.useCallback((l,c)=>{a(d=>{const m={...d,[l]:c},h=Dt(r==="dark"?"light":"dark");return r==="dark"?Kr(m,h):Kr(h,m),ps(m),s(m),m})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.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",t.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"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(tr,{title:"App Background",children:[t.jsx(kt,{label:"Background",value:n.bgPrimary,onChange:l=>o("bgPrimary",l)}),t.jsx(kt,{label:"Surface",value:n.bgSecondary,onChange:l=>o("bgSecondary",l)}),t.jsx(kt,{label:"Card",value:n.surfacePrimary,onChange:l=>o("surfacePrimary",l)})]}),t.jsxs(tr,{title:"App Text",children:[t.jsx(kt,{label:"Primary",value:n.textPrimary,onChange:l=>o("textPrimary",l)}),t.jsx(kt,{label:"Secondary",value:n.textSecondary,onChange:l=>o("textSecondary",l)}),t.jsx(kt,{label:"Muted",value:n.textMuted,onChange:l=>o("textMuted",l)})]}),t.jsxs(tr,{title:"Borders & Accent",children:[t.jsx(kt,{label:"Border subtle",value:n.borderSubtle,onChange:l=>o("borderSubtle",l)}),t.jsx(kt,{label:"Border default",value:n.borderDefault,onChange:l=>o("borderDefault",l)}),t.jsx(kt,{label:"Accent",value:n.accentColor,onChange:l=>o("accentColor",l)})]})]}),t.jsxs("div",{children:[t.jsxs(tr,{title:"Chat Bubbles",children:[t.jsx(kt,{label:"User bubble",value:n.userBubble,onChange:l=>o("userBubble",l)}),t.jsx(kt,{label:"User text",value:n.userText,onChange:l=>o("userText",l)}),t.jsx(kt,{label:"Agent bubble",value:n.assistantBubble,onChange:l=>o("assistantBubble",l)}),t.jsx(kt,{label:"Agent text",value:n.assistantText,onChange:l=>o("assistantText",l)})]}),t.jsxs(tr,{title:"Chat Layout",children:[t.jsx(kt,{label:"Chat BG",value:n.containerBg,onChange:l=>o("containerBg",l)}),t.jsx(kt,{label:"Send button",value:n.sendButton,onChange:l=>o("sendButton",l)}),t.jsx(kt,{label:"Input border",value:n.inputBorder,onChange:l=>o("inputBorder",l)}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[t.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:l=>o("bubbleRadius",Number(l.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),t.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),t.jsx("button",{onClick:()=>{const l=e?Va:Ga,d=Dt(e?"light":"dark");e?Kr(l,d):Kr(d,l),a(l),ps(l),s(l)},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 Mx(){const[e,s]=i.useState(en),[r,n]=i.useState(!0),[a,o]=i.useState(()=>Dt("dark"));i.useEffect(()=>{n(fs());const d=new MutationObserver(()=>{const h=fs();n(h);const g=en();g==="custom"?ps(Dt(h?"dark":"light")):fr(g,h?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const h=fs();n(h);const g=en();g==="custom"?ps(Dt(h?"dark":"light")):fr(g,h?"dark":"light")};return m.addEventListener("change",u),()=>{d.disconnect(),m.removeEventListener("change",u)}},[]),i.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ps(Dt(r?"dark":"light")):(Po(),fr(e,r?"dark":"light"))},[e,r]),i.useEffect(()=>{o(Dt(r?"dark":"light"))},[r]);const l=d=>{s(d),Ix(d)},c=[...Nx,{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 t.jsxs("div",{children:[t.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,h=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return t.jsxs("button",{onClick:()=>l(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:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:u.containerBg},children:[t.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?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:h},children:"Fix the bug please"}),t.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! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[m&&t.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:d.id==="custom"?"🎨 Custom":d.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:d.description})]})]})]},d.id)})}),e==="custom"&&t.jsx(Ax,{dark:r,onColorsChange:d=>o(d)})]})}const Do="adhdev_mobileDashboardMode_v1",qa="adhdev:mobile-dashboard-mode-change";function Eo(){try{return localStorage.getItem(Do)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Lx(e){if(typeof window>"u")return()=>{};const s=a=>{e(a??Eo())},r=a=>{const o=a.detail;s(o)},n=a=>{a.key&&a.key!==Do||s()};return window.addEventListener(qa,r),window.addEventListener("storage",n),()=>{window.removeEventListener(qa,r),window.removeEventListener("storage",n)}}function Rx(e){try{localStorage.setItem(Do,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(qa,{detail:e}))}function _x(){const[e,s]=i.useState(!0);return i.useEffect(()=>{s(Eo()==="chat")},[]),t.jsx(is,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Vt,{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=>{s(r),Rx(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const na=new Map,Wi=new Map;function Px(e){if(!e||typeof e!="object")return null;const s=e,r=s.result&&typeof s.result=="object"?s.result:s,n=r.machine;return!n||typeof n!="object"?null:{machine:n,timestamp:typeof r.timestamp=="number"?r.timestamp:void 0}}function Dx(e,s,r,n){return{...e||{},id:s,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 Jc(){const{sendCommand:e}=yt(),{injectEntries:s,getIdes:r}=br();return i.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??Lf,l=Wi.get(n)||0;if(!(a!=null&&a.force)&&l>0&&Date.now()-l<o)return;const c=na.get(n);if(c)return c;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=Px(m);if(!u)return;const h=r().find(v=>v.id===n),g=Dx(h,n,u.machine,u.timestamp||Date.now());s([g]),Wi.set(n,Date.now())})().finally(()=>{na.delete(n)});return na.set(n,d),d},[r,s,e])}function Ex(e,s,r){return{...e||{},id:s,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 $x(e,s){const{sendData:r}=yt(),{injectEntries:n,getIdes:a}=br(),o=Array.from(new Set(e.filter(Boolean))).join("|");i.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const l=o?o.split("|"):[];if(l.length===0)return;const c=l.map(d=>zt.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:s==null?void 0:s.intervalMs}},u=>{const h=a().find(v=>v.id===d),g=Ex(h,d,u);n([g])}));return()=>{c.forEach(d=>d())}},[o,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}function Bx(e,s){const{sendData:r}=yt(),[n,a]=i.useState(null),[o,l]=i.useState(!1);return i.useEffect(()=>{if(!e){a(null),l(!1);return}if(!(s!=null&&s.enabled)||!r){l(!1);return}a(null),l(!0);let c=null;const d=zt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},m=>{c&&(clearTimeout(c),c=null),a(m.diagnostics),l(!1)});return d.initialSendAccepted?c=setTimeout(()=>{l(!1)},Df):l(!1),()=>{c&&clearTimeout(c),d()}},[e,s==null?void 0:s.enabled,s==null?void 0:s.includeSessions,s==null?void 0:s.intervalMs,s==null?void 0:s.limit,r]),{diagnostics:n,loading:o,applyDiagnostics:a}}function Ox(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Qc(e){const{sendData:s}=yt(),[r,n]=i.useState({});return i.useEffect(()=>{const a=Ox(e);if(!a||!e.sessionId||!s){n({});return}const o=zt.subscribe({sendData:s},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},l=>{n({status:l.status,modalMessage:l.modalMessage,modalButtons:l.modalButtons}),Ps.record({interactionId:l.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:l.status,modalButtonCount:Array.isArray(l.modalButtons)?l.modalButtons.length:0}})});return o.initialSendAccepted||n({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,s]),r}const Zc="adhdev_hiddenTabs",ed="adhdev_autoHiddenMeshTabs";function Kx(){try{const e=localStorage.getItem(Zc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function as(e){try{localStorage.setItem(Zc,JSON.stringify([...e]))}catch{}}function Fx(){try{const e=localStorage.getItem(ed);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function Hi(e){try{localStorage.setItem(ed,JSON.stringify([...e]))}catch{}}function lr(e){return So(e)}function _n(e,s){return _s(s).some(r=>e.has(r))}function Wx(e){var s,r,n;return((s=e.settings)==null?void 0:s.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 Hx(e,s,r=new Set){return e.filter(n=>{if(!Wx(n))return!1;const a=lr(n);return r.has(a)?!1:!_n(s,n)})}function Ux(){const[e,s]=i.useState(Kx),[r,n]=i.useState(Fx),a=i.useCallback(g=>{const v=lr(g);s(f=>{const p=new Set(f);return p.has(v)?p.delete(v):p.add(v),as(p),p})},[]),o=i.useCallback(g=>{const v=lr(g);s(f=>{if(f.has(v))return f;const p=new Set(f);return p.add(v),as(p),p})},[]),l=i.useCallback(g=>{const v=lr(g);s(f=>{if(f.has(v))return f;const p=new Set(f);return p.add(v),as(p),p}),n(f=>{if(f.has(v))return f;const p=new Set(f);return p.add(v),Hi(p),p})},[]),c=i.useCallback(g=>{const v=lr(g);s(f=>{if(!f.has(v))return f;const p=new Set(f);return p.delete(v),as(p),p}),n(f=>{if(f.has(v))return f;const p=new Set(f);return p.add(v),Hi(p),p})},[]),d=i.useCallback(()=>{s(g=>{if(g.size===0)return g;const v=new Set;return as(v),v})},[]),m=i.useCallback((g,v)=>{s(f=>{const p=new Set(f);for(const b of v)p.add(b);return as(p),p})},[]),u=i.useCallback((g,v)=>{s(f=>{const p=new Set(f);for(const b of v)p.delete(b);return as(p),p})},[]),h=i.useCallback(g=>_n(e,g),[e]);return{hiddenTabs:e,autoHiddenTabs:r,toggleTarget:a,hideTarget:o,autoHideTarget:l,showTarget:c,showAllTabs:d,hideAllForDaemon:m,showAllForDaemon:u,isHidden:h}}function td(e){return e instanceof Error?e.message:String(e||"")}function sd(e){const s=td(e);return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("P2P channel not open")||s.includes("P2P not available")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function rd(e){const s=td(e);return s.includes("P2P command timeout")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}async function nd({conversation:e,mode:s,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!st(e)||Ze(e))return;const o=zs(e);if(o===s)return;const l=e.sessionId;l&&a(c=>({...c,[l]:s}));try{await n(ks(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Ft(e),mode:s})}catch(c){const d=rd(c);l&&!d&&a(m=>{const u={...m};return o===ad(r,l)?delete u[l]:u[l]=o,u}),sd(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 Ui(e,s){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=s[r];return!n||e.mode===n?e:{...e,mode:n}}function zx(e,s){if(!Array.isArray(e)||e.length===0||!s||Object.keys(s).length===0)return e;let r=!1;const n=e.map(a=>{const o=Ui(a,s),l=Array.isArray(a.childSessions)?a.childSessions.map(d=>Ui(d,s)):a.childSessions,c=l!==a.childSessions;return o!==a||c?(r=!0,{...o,...c?{childSessions:l}:{}}):a});return r?n:e}function ad(e,s){if(!s)return null;for(const r of e){if(r.sessionId===s&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===s&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function Vx(e,s){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,o]of Object.entries(e))ad(s,a)===o&&(delete n[a],r=!0);return r?n:e}function Gx({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){i.useEffect(()=>{oc()},[]);const a=i.useMemo(()=>e.map(o=>({id:o.tabKey,name:Rc(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return Pp(a),i.useEffect(()=>{if(Object.keys(s).length===0)return;const l=setTimeout(()=>{r(c=>{const d=Date.now(),m={};for(const[u,h]of Object.entries(c))d-h<5e3&&(m[u]=h);return Object.keys(m).length===Object.keys(c).length?c:m})},5500);return()=>clearTimeout(l)},[s,r]),i.useEffect(()=>{const o=setInterval(()=>{const l=Date.now()-3e5;n(c=>{const d=c.filter(m=>m.timestamp>l).slice(-100);return d.length===c.length?c:d})},6e4);return()=>clearInterval(o)},[n]),null}function zi(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function hs(e){const s=[...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=zi(s==null?void 0:s.receivedAt)||zi(s==null?void 0:s.timestamp)||0;return Math.max(r,n)}function Ya(e,s=0){return hs(e)||e.lastUpdated||s||0}function od(e){return hs(e)||e.lastUpdated||0}function id(e,s,r=od){const n=r(s)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(s.machineName||"");if(a!==0)return a;const o=e.displayPrimary.localeCompare(s.displayPrimary);if(o!==0)return o;const l=e.displaySecondary.localeCompare(s.displaySecondary);return l!==0?l:e.tabKey.localeCompare(s.tabKey)}function Xa(e){var r;const s=xt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function qx(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!Xa(e)&&!e.title.trim()}function Yx(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(Xa(r))-Number(Xa(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:id(s,r)})[0]||null}function Et(e,s){const r=e.filter(l=>l.routeId===s);if(r.length===0)return null;const n=r.find(l=>l.streamSource==="native")||null,a=r.filter(l=>l.streamSource==="agent-stream"),o=Yx(a);return n?o&&qx(n)?o:n:o||r[0]||null}function Xx(e){const s=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return!s||r.startsWith(`${s}:`)?r:`${s}:${r}`}function Jx(e){const s=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of s){const a=Xx(n),o=r.get(a);if(!o){r.set(a,n);continue}const l=(o.workspace?1:0)+(o.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>l||(n.timestamp||0)>(o.timestamp||0))&&r.set(a,n)}return Array.from(r.values())}function aa(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==s[r])return!1;return!0}function Qx(e){let s=2166136261;for(let r=0;r<e.length;r+=1)s^=e.charCodeAt(r),s=Math.imul(s,16777619)>>>0;return s.toString(16).padStart(8,"0")}function Vi(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?Qx(Ds(r.content)):"";return[e.id||"",e.title||"",e.status||"",s.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 Zx(e){const s=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||""),Vi(e.activeChat),...s.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||""),Vi(r.activeChat)].join(":"))].join("|")}function eb(e,s){const r=Date.now();return e.map(n=>{const a=s[n.tabKey];return a&&r-a<5e3?{...n,messages:[],title:""}:n})}function tb(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const o of _s({routeId:n.routeId}))r.set(o,a);for(const o of _s({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of _s({tabKey:n.tabKey}))r.set(o,n)}return r}function sb(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function rb(e){const s=sb(e);if(!s)return`empty:${e.messages.length}`;if(s.id)return`id:${String(s.id)}`;if(s._localId)return`local:${String(s._localId)}`;const r=String(s.role||""),n=Ds(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function nb({ides:e,connectionStates:s,clearedTabs:r,hiddenTabs:n}){const a=i.useMemo(()=>Jx(e),[e]),o=i.useMemo(()=>Oc(e),[e]),l=i.useRef([]),c=i.useRef([]),d=i.useRef([]),m=i.useRef(new Map),u=i.useRef(new Map),h=i.useMemo(()=>{const S=new Map,w=[];for(const j of a){const{connectionState:O="new",machineName:R}=Kc(j,{machineNames:o,connectionStates:s,defaultConnectionState:"new"}),T=Zx(j),F=m.current.get(j.id);if(F&&F.ide===j&&F.sourceSignature===T&&F.connectionState===O&&F.machineName===R){S.set(j.id,F),w.push(...F.conversations);continue}const W=Ro(j,{machineNames:o,connectionStates:s,defaultConnectionState:"new"}),D={ide:j,sourceSignature:T,connectionState:O,machineName:R,conversations:W};S.set(j.id,D),w.push(...W)}m.current=S;const A=new Map,L=j=>{const O=rb(j),R=u.current.get(j.tabKey);if(R&&R.signature===O)return A.set(j.tabKey,R),R.timestamp;const T={signature:O,timestamp:od(j)||(R==null?void 0:R.timestamp)||0};return A.set(j.tabKey,T),T.timestamp},k=[...w].sort((j,O)=>id(j,O,L));return u.current=A,k},[a,s,o]),g=i.useMemo(()=>{const S=eb(h,r);return aa(l.current,S)?l.current:(l.current=S,S)},[h,r]),v=i.useMemo(()=>{const S=new Map,w=Array.from(new Set(g.map(A=>A.routeId)));for(const A of w){const L=Et(g,A);L&&S.set(A,L)}return S},[g]),f=i.useMemo(()=>{const S=new Map;for(const w of g){const A=v.get(w.routeId),L=w.streamSource==="native"&&A?A:w;for(const k of _s({providerSessionId:w.providerSessionId,sessionId:w.sessionId,tabKey:w.tabKey}))S.set(k,L)}return S},[g,v]),p=i.useMemo(()=>tb(g,v),[g,v]),b=i.useCallback(S=>{if(S)return f.get(S)},[f]),y=i.useCallback(S=>{if(S)return p.get(S)},[p]),x=i.useMemo(()=>{const S=g.filter(w=>!_n(n,w));return aa(c.current,S)?c.current:(c.current=S,S)},[g,n]),N=i.useMemo(()=>{const S=x.map(w=>w.tabKey);return aa(d.current,S)?d.current:(d.current=S,S)},[x]);return{chatIdes:a,conversations:g,visibleConversations:x,visibleTabKeys:N,resolveConversationBySessionId:b,resolveConversationByTarget:y}}function ab({isMobile:e,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const a=i.useMemo(()=>{var c;return e||!s?null:((c=r(s))==null?void 0:c.tabKey)??null},[e,r,s]),o=i.useMemo(()=>{var c;return!e||!s?null:((c=r(s))==null?void 0:c.tabKey)??null},[e,r,s]),l=i.useCallback(()=>{s&&n(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[n,s]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:l}}function ob({ides:e,sendDaemonCommand:s,setToasts:r,resolveConversationByTarget:n}){i.useEffect(()=>{nt.setIdes(e)},[e]),i.useEffect(()=>{nt.setResolveAction((a,o,l)=>{s(a,o,l).catch(()=>{})})},[s]),i.useEffect(()=>{const a=nt.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 l=o.duration||5e3;setTimeout(()=>r(c=>c.filter(d=>d.id!==o.id)),l)});return()=>{a()}},[r]),i.useEffect(()=>{const a=Ac.on("status_event",o=>{nt.handleRawEvent(o,"ws")});return()=>{a()}},[]),i.useEffect(()=>{var o;const a=l=>{var p;const c=l.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 h=Number(c.buttonIndex),g=c.button||((p=m==null?void 0:m.modalButtons)==null?void 0:p[h])||"Approve",v=String(g).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),f=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(v);s(u,"resolve_action",{action:f?"approve":"reject",button:g,...Number.isFinite(h)&&{buttonIndex:h},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(b=>console.error("[SW Action] approval failed:",b))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var l;return(l=navigator.serviceWorker)==null?void 0:l.removeEventListener("message",a)}},[n,s])}const ib="adhdev_dashboardLayout_v1",lb="adhdev_dashboardDockview_v1",cb="adhdev_dashboardDockviewHiddenRestore_v1",sr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function $o(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function db(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function ld(e){return`${ib}:${e}`}function ub(e){const s=ld(e);return $o(s,null)}function mb(e,s){try{const r=s.groupAssignments.length===0&&s.focusedGroup===0&&Object.keys(s.groupActiveTabIds).length===0&&Object.keys(s.groupTabOrders).length===0&&s.groupSizes.length===0,n=ld(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function cd(e){return`${lb}:${e}`}function pb(e){const s=cd(e);return $o(s,null)}function fb(e,s){try{const r=cd(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function dd(e){return`${cb}:${e}`}function hb(e){const s=dd(e);return $o(s,{})}function xb(e,s){try{const r=dd(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function bb(){return{groupAssignments:[...sr.groupAssignments],focusedGroup:sr.focusedGroup,groupActiveTabIds:{...sr.groupActiveTabIds},groupTabOrders:{...sr.groupTabOrders},groupSizes:[...sr.groupSizes]}}function gb(e,s){return e?e.length===s.length&&e.every((r,n)=>r===s[n]):s.length===0}function yb(){const[e]=i.useState(()=>db(typeof window<"u"?window.innerWidth:1280)),[s,r]=i.useState(()=>new Map),[n,a]=i.useState(0),[o,l]=i.useState({}),[c,d]=i.useState({}),[m,u]=i.useState([]),[h,g]=i.useState(()=>typeof window<"u"&&window.innerWidth<768),[v,f]=i.useState(!1),p=i.useCallback(()=>{if(v)return;const j=ub(e)??bb();r(new Map(j.groupAssignments)),a(j.focusedGroup),l(j.groupActiveTabIds),d(j.groupTabOrders),u(j.groupSizes),f(!0)},[v,e]);i.useEffect(()=>{v&&mb(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:c,groupSizes:m})},[v,e,s,n,o,c,m]),i.useEffect(()=>{const j=window.matchMedia("(max-width: 767px)"),O=R=>g(R.matches);return j.addEventListener("change",O),()=>j.removeEventListener("change",O)},[]);const b=i.useCallback(j=>{r(j)},[]),y=i.useCallback(j=>{a(j)},[]),x=i.useCallback(j=>{l(j)},[]),N=i.useCallback(j=>{d(j)},[]),S=i.useCallback(j=>{u(j)},[]),w=i.useCallback(j=>{y(j)},[y]),A=i.useCallback((j,O)=>{l(R=>(R[j]??null)===(O??null)?R:{...R,[j]:O})},[]),L=i.useCallback((j,O)=>{d(R=>{const T=R[j];return gb(T,O)?R:{...R,[j]:O}})},[]),k=i.useCallback((j,O)=>{const R=O.get(j)??0;return A(R,j),w(R),R},[w,A]);return{layoutProfile:e,groupAssignments:s,updateGroupAssignments:b,focusedGroup:n,updateFocusedGroup:y,focusGroup:w,groupActiveTabIds:o,updateGroupActiveTabIds:x,setGroupActiveTab:A,groupTabOrders:c,updateGroupTabOrders:N,setGroupTabOrder:L,groupSizes:m,updateGroupSizes:S,isMobile:h,hasHydratedStoredLayout:v,hydrateStoredLayout:p,focusConversationTab:k}}function vb(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=ko(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function wb({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:l,setSearchParams:c,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,ides:h,handleRefreshHistory:g}){const v=i.useRef(!1),f=i.useRef(!1),p=i.useRef(null),b=i.useRef(!1);i.useEffect(()=>{if(!e||v.current||s.length===0)return;if(!a){o();return}const y=r(e);y&&(l(y.tabKey,n),v.current=!0,f.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),c(x=>{const N=new URLSearchParams(x);return N.delete("activeTab"),N},{replace:!0}))},[e,s,r,n,a,o,l,c]),i.useEffect(()=>{if(!(f.current||a)&&s.length!==0){if(!e){o(),f.current=!0;return}if(v.current){f.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(f.current||a)&&(o(),f.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,s.length,a,o]),i.useEffect(()=>{if(!d){b.current=!1;return}if(!m||b.current||u)return;const y=h.find(x=>x.id===m.routeId);y&&(!y.chats||y.chats.length===0||vb(y.chats,m))&&(b.current=!0,g())},[d,m,u,h,g])}function oa(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=ko(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function ud({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[l,c]=i.useState(!1),[d,m]=i.useState(!1),u=i.useCallback(async f=>{try{await e("standalone","launch_ide",{ideType:f,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),h=i.useCallback(async(f,p)=>{try{const b=f||(s==null?void 0:s.daemonId)||"",y=await e(b,"switch_chat",{id:p,sessionId:p,...cs(s)}),x=y==null?void 0:y.result;if((y==null?void 0:y.success)===!0||x==="switched"||x==="switched-by-title")return;x===!1||x==="not_found"?Qs(a,"⚠️ Session tab not found — try refreshing history"):typeof x=="string"&&x.startsWith("error:")?Qs(a,`⚠️ Switch error: ${x}`):Qs(a,"⚠️ Session switch failed")}catch(b){console.error("Switch failed",b),Qs(a,`❌ Switch failed: ${b.message||"connection error"}`)}},[s,e,a]),g=i.useCallback(async()=>{if(!(!s||l)){c(!0);try{const f=Bs(s);await e(f,"new_chat",{...cs(s)}),o(p=>({...p,[s.tabKey]:Date.now()}))}catch(f){console.error("New chat failed",f)}finally{c(!1)}}},[s,l,e,o]),v=i.useCallback(async()=>{var f,p;if(!(!s||d)){m(!0);try{const b=Bs(s),y=async()=>e(b,"list_chats",{forceExpand:!0,...cs(s)});let x=await y(),N=(x==null?void 0:x.chats)||((f=x==null?void 0:x.result)==null?void 0:f.chats);oa(N,s)&&(await new Promise(S=>setTimeout(S,450)),x=await y(),N=(x==null?void 0:x.chats)||((p=x==null?void 0:x.result)==null?void 0:p.chats)),x!=null&&x.success&&Array.isArray(N)&&(n(s.routeId,N),oa(N,s)&&!oa(r,s)&&Qs(a,"⚠️ History dialog did not fully open — try once more"))}catch(b){console.error("Refresh history failed",b)}finally{m(!1)}}},[s,r,d,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:h,handleNewChat:g,handleRefreshHistory:v}}function jb(e,s){if(e.size!==s.size)return!1;for(const[r,n]of e)if(s.get(r)!==n)return!1;return!0}function kb(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function Gi(e,s){const r=Object.keys(e),n=Object.keys(s);return r.length!==n.length?!1:r.every(a=>s[Number(a)]===e[Number(a)])}function Fr(e,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[l,c]of e)!r.has(l)||c<=0||n.includes(c)||n.push(c);n.sort((l,c)=>l-c);const a={};n.forEach((l,c)=>{a[l]=c}),n.length===0&&(a[0]=0);const o=new Map;for(const[l,c]of e){if(!r.has(l)||c<=0)continue;const d=a[c];typeof d=="number"&&d>0&&o.set(l,d)}return{assignments:o,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function qi(e,s){const r={};for(const[n,a]of Object.entries(e)){const o=s[Number(n)];typeof o=="number"&&(r[o]=a)}return r}function Sb(e,s,r){if(s.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...s].reverse().find(a=>a<e)??s[0];return r[n]??0}function Nb(e,s,r){if(s.length<=1)return[];const n=s.map(l=>e[l]).filter(l=>Number.isFinite(l)),a=n.length===s.length?n:Array(r).fill(100/r),o=a.reduce((l,c)=>l+c,0);return o>0?a.map(l=>l/o*100):Array(r).fill(100/r)}function Yi(e,s){const r={};for(const[n,a]of Object.entries(e)){const o=Number(n);r[o>=s?o+1:o]=a}return r}function Xi(e){return Array(e).fill(100/e)}function Cb({groupAssignments:e,updateGroupAssignments:s,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:l,isMobile:c,visibleConversations:d,visibleTabKeys:m}){const u=i.useRef(null),h=i.useMemo(()=>Fr(e,m),[e,m]),g=h.assignments,v=i.useMemo(()=>c?1:h.groupCount,[h.groupCount,c]),f=v>1,p=i.useCallback((w,A)=>{s(L=>{const k=new Map(Fr(L,m).assignments);return A===0?k.delete(w):k.set(w,A),k}),n(L=>({...L,[A]:w})),r(A)},[s,m,n,r]),b=i.useCallback(w=>{s(A=>{const L=Fr(A,m).assignments,k=new Map;for(const[j,O]of L)O!==w&&(O>w?k.set(j,O-1):k.set(j,O));return k}),l(A=>{if(A.length<=1)return[];const L=[...A];L.splice(w,1);const k=L.reduce((j,O)=>j+O,0);return k>0?L.map(j=>j/k*100):[]}),r(0)},[s,m,l,r]),y=i.useCallback((w,A)=>{A.preventDefault();const L=u.current;if(!L)return;const k=A.clientX,j=L.offsetWidth,O=o.length===v?[...o]:Xi(v),R=F=>{const D=(F.clientX-k)/j*100,C=[...O];C[w]=Math.max(15,O[w]+D),C[w+1]=Math.max(15,O[w+1]-D),l(C)},T=()=>{document.removeEventListener("mousemove",R),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",R),document.addEventListener("mouseup",T)},[o,v,l]),x=i.useCallback((w,A,L)=>{if(v>=4)return;const k=L==="left"?A:A+1;s(j=>{const O=Fr(j,m).assignments,R=new Map;for(const T of d){const F=O.get(T.tabKey)??0,W=F>=k?F+1:F;W>0&&R.set(T.tabKey,W)}return k>0&&R.set(w,k),R}),l(j=>{const O=j.length===v?[...j]:Xi(v),R=O[A]??100/v,T=Math.max(15,R/2),F=Math.max(15,R/2),W=[...O];W[A]=T,W.splice(k,0,F);const D=W.reduce((C,I)=>C+I,0);return W.map(C=>C/D*100)}),n(j=>{const O=Yi(j,k);return O[k]=w,O}),a(j=>{const O=Yi(j,k);return O[k]=[w],O}),r(k)},[v,s,m,d,l,n,a,r]);i.useEffect(()=>{jb(e,g)||s(g)},[e,g,s]),i.useEffect(()=>{const{mapping:w,usedGroups:A}=h;n(L=>{const k=qi(L,w);return Gi(L,k)?L:k}),a(L=>{const k=qi(L,w);return Gi(L,k)?L:k}),r(L=>{const k=c?0:Sb(L,A,w);return L===k?L:k}),l(L=>{const k=c?[]:Nb(L,A,h.groupCount);return kb(L,k)?L:k})},[h,c,n,a,r,l]);const N=i.useMemo(()=>{const w=Array.from({length:v},()=>[]);for(const A of d){const L=g.get(A.tabKey)??0,k=Math.min(L,v-1);w[k].push(A)}return w},[d,g,v]),S=i.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:u,normalizedGroupAssignments:g,numGroups:v,isSplitMode:f,groupedConvs:N,moveTabToGroup:p,closeGroup:b,handleResizeStart:y,splitTabRelative:x,clearAllSplits:S}}function ia(e){if(typeof e!="string")return null;const s=e.trim().toLowerCase();return s==="stable"||s==="latest"?"stable":s==="preview"||s==="next"?"preview":null}function Ib(e){if(typeof e!="string")return null;const s=e.trim().toLowerCase();return s==="latest"||s==="stable"?"latest":s==="next"||s==="preview"?"next":null}function Wr(e){if(typeof e!="string")return null;const s=e.trim();return s.length>0?s:null}function Bo(e){const s=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=ia(s.channel)||ia(e.updateChannel)||ia(e.releaseChannel)||void 0,n=Ib(s.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=Wr(s.targetVersion)||Wr(e.serverVersion)||void 0,o=Wr(s.minVersion)||void 0,l=Wr(s.updateCommand)||(r?`adhdev update --channel ${r}`:void 0);return{...r?{channel:r}:{},...n?{npmTag:n}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...l?{updateCommand:l}:{}}}function Ts(e,s=null){return Bo(e).targetVersion||s}function md(e){return Bo(e).channel||null}function pd(e){const s=Bo(e);return{...s.channel?{channel:s.channel}:{},...s.npmTag?{npmTag:s.npmTag}:{},...s.targetVersion?{targetVersion:s.targetVersion}:{},...Object.keys(s).length>0?{updatePolicy:s}:{}}}function Tb({ides:e,sendDaemonCommand:s}){const r="0.9.81",n=i.useMemo(()=>e.filter(h=>h.type!=="adhdev-daemon"?!1:Gc(h,Ts(h,r))).sort((h,g)=>Number(pr(g,Ts(g,r)))-Number(pr(h,Ts(h,r)))),[r,e]),a=i.useMemo(()=>n.some(h=>pr(h,Ts(h,r))),[r,n]),o=i.useMemo(()=>n.map(h=>Ts(h,r)).find(h=>typeof h=="string"&&h.trim().length>0)||r,[r,n]),[l,c]=i.useState(!1),[d,m]=i.useState({}),u=i.useCallback(async h=>{var v,f;const g=e.find(p=>p.id===h);if(g){m(p=>({...p,[h]:"upgrading"}));try{const p=await s(h,"daemon_upgrade",pd(g));(v=p==null?void 0:p.result)!=null&&v.upgraded||(f=p==null?void 0:p.result)!=null&&f.success?m(b=>({...b,[h]:"done"})):m(b=>({...b,[h]:"error"}))}catch{m(p=>({...p,[h]:"error"}))}}},[e,s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:l,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const fd=80;function tn(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function Ab(e){return{...e,createdAt:tn(e.createdAt),updatedAt:tn(e.updatedAt,e.createdAt),lastEventAt:tn(e.lastEventAt,e.updatedAt||e.createdAt)}}function Mb(e){const s=So(e);return s==="unknown:"?e.id:s}function Lb(e){return[e.type,jc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Rb(e,s=fd){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Mb(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,s))}function _b(e,s){const r=Date.now(),n=[];for(const a of e){const o=a.sessionId?s.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden)continue;const l=Tn(a,s),c=l.inboxBucket==="needs_attention"?"needs_attention":l.inboxBucket==="task_complete"&&l.unread?"task_complete":null;if(!c)continue;const d=tn(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),m=Lb({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(Ab({id:m,dedupKey:m,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:mc(a),preview:cf(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return Rb(n)}function Pb(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function Db(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=fd}=e,a=i.useMemo(()=>_b(s,r).slice(0,Math.max(0,n)),[s,r,n]),o=i.useMemo(()=>Pb(a),[a]);return{notifications:a,unreadCount:o}}function Eb({notifications:e,sendDaemonCommand:s}){const r=i.useCallback(o=>{const l=e.find(d=>d.id===o),c=Math.max(Date.now(),(l==null?void 0:l.updatedAt)||0);l!=null&&l.sessionId&&s(l.machineId||l.routeId,"mark_session_seen",{sessionId:l.sessionId,seenAt:c}).catch(()=>{})},[e,s]),n=i.useCallback(o=>{const l=e.find(c=>c.id===o);l!=null&&l.sessionId&&s(l.machineId||l.routeId,"mark_notification_unread",{sessionId:l.sessionId,notificationId:l.id}).catch(()=>{})},[e,s]),a=i.useCallback(o=>{const l=e.find(c=>c.id===o);l!=null&&l.sessionId&&s(l.machineId||l.routeId,"delete_notification",{sessionId:l.sessionId,notificationId:l.id}).catch(()=>{})},[e,s]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}const $b=i.createContext(null);function Bb(){return i.useContext($b)}function Pn(...e){const s=new Set,r=[],n=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const l=o.toLowerCase();s.has(l)||(s.add(l),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 Ob(e){const s=e.trim();if(!s)return null;if(s.startsWith("~"))return s;if(/^[A-Za-z]:$/.test(s))return`${s[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(s))return`${s[0].toUpperCase()}:${s.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(s))return`${s[0].toUpperCase()}:\\${s.slice(2).replace(/[\\/]+/g,"\\")}`;const r=s.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function Dn(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=Ob(r);if(n)return n}return"C:\\"}for(const r of s){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function Kb(e){const s=e.replace(/[\\/]+$/,"");if(!s||s==="/"||/^[A-Za-z]:$/.test(s))return null;const r=s.includes("\\")?"\\":"/",n=s.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 Fb(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function En(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=Fb(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,l=o.includes("\\")?"\\":"/",c=(m,u)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${u}`:m==="/"||m==="\\"?`${l}${u}`:`${m.replace(/[\\/]+$/,"")}${l}${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 Wb(e,s){const r={meshId:s.meshId||"",workspace:s.workspace||"",serverName:s.serverName||"adhdev-mesh",adhdevMcpCommand:s.adhdevMcpCommand||"adhdev-mcp"};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand)\s*\}\}/g,(n,a)=>r[a]||"")}function hd(e,s={}){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:Wb(r.template||"",{...s,serverName:r.serverName||"adhdev-mesh"})}}function Hb(e){if(!e||typeof e!="object")return null;const s=e,r=typeof s.instructions=="string"?s.instructions:"",n=typeof s.template=="string"?s.template:"";return!r&&!n?null:{serverName:typeof s.serverName=="string"?s.serverName:void 0,configFormat:typeof s.configFormat=="string"?s.configFormat:void 0,configPathCommand:typeof s.configPathCommand=="string"?s.configPathCommand:void 0,requiresRestart:s.requiresRestart===!0,instructions:r||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:n}}function ss(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function xd(e){return Nr(e)||e.tabKey||e.routeId||null}function bd(e){const s=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 l=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(s&&l.includes(s)||r&&l.includes(r)||n&&o.routeId===n)});if(a!=null&&a.tabKey)return a.tabKey;if(n){const o=Et(e.conversations,n)||e.conversations.find(l=>l.routeId===n);if(o!=null&&o.tabKey)return o.tabKey}return s||r||n||null}function Jt(e){return String(e||"").trim()}function gd(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function jn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ub(e,s){return!e||!s?!1:e===s||e.endsWith(`/${s}`)||s.endsWith(`/${e}`)}function zb(e,s){const r=Jt(e.providerSessionId),n=Jt(e.targetSessionId),a=s.find(o=>{const l=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Jt).filter(Boolean);return!!(r&&l.includes(r)||n&&l.includes(n))});return a?a.tabKey:n||r||null}function Vb(e,s,r){if(s.event!=="agent:generating_completed")return null;const n=gd(s.daemonId);if(n&&n!==e.machineId)return null;const a=Jt(s.providerType);if(e.providerType&&a!==e.providerType)return null;const o=Jt(e.resumeSessionId),l=Jt(e.launchedSessionId),c=Jt(s.providerSessionId),d=Jt(s.targetSessionId);if(o&&o!==c&&o!==d||l&&l!==c&&l!==d)return null;const m=jn(e.workspacePath);if(m){const u=jn(s.workspaceName);if(u&&!Ub(u,m))return null}return zb(s,r)}function Ji(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Gb({ides:e,conversations:s,onOpenSession:r}){const[n,a]=i.useState(null),o=i.useRef(null),l=i.useCallback(()=>{o.current=null,a(null)},[]),c=i.useCallback(d=>{o.current=d,a(d)},[]);return i.useEffect(()=>{if(!n)return;const d=jn(n.workspacePath),m=e.find(h=>{var b,y,x,N;if(!h||h.type==="adhdev-daemon"||gd(h.daemonId||h.id)!==n.machineId||(yr(h)?"cli":Ls(h)?"acp":"ide")!==n.kind)return!1;const f=String(h.agentType||h.type||"");if(n.providerType&&f!==n.providerType)return!1;if(n.resumeSessionId)return String(h.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const S=String(n.launchedSessionId||"");return[h.providerSessionId,h.sessionId,h.instanceId,h.id].map(A=>String(A||"")).filter(Boolean).includes(S)}if(d){const S=jn(h.workspace||h.runtimeWorkspaceLabel);return S?S===d:!1}return Number(h.lastUpdated||h._lastUpdate||h.timestamp||((N=(x=(y=(b=h.activeChat)==null?void 0:b.messages)==null?void 0:y.at)==null?void 0:x.call(y,-1))==null?void 0:N.timestamp)||0)>=n.startedAt-5e3});if(!m)return;const u=bd({entrySessionId:m.sessionId,entryInstanceId:m.instanceId,entryRouteId:m.id,conversations:s});u&&(l(),r(u))},[l,s,e,r,n]),i.useEffect(()=>nt.onStatusEvent(d=>{const m=o.current;if(!m)return;const u=Vb(m,d,s);u&&(l(),r(u))}),[l,s,r]),i.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 qb({sendDaemonCommand:e,trackPendingLaunch:s,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const l=Bb(),c=i.useCallback(async(p,b)=>En(e,p,b),[e]),d=i.useCallback(async(p,b)=>{if(!b.trim())return{ok:!1,error:"Choose a workspace path first."};try{const y=await e(p,"workspace_add",{path:b.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=i.useCallback(async(p,b,y)=>{var x;try{const N={ideType:b,enableCdp:!0};(x=y==null?void 0:y.workspacePath)!=null&&x.trim()&&(N.workspace=y.workspacePath.trim());const S=await e(p,"launch_ide",N);return!(S!=null&&S.success)&&(S==null?void 0:S.success)!==void 0?{ok:!1,error:(S==null?void 0:S.error)||"Could not launch IDE"}:(s({machineId:p,kind:"ide",providerType:b,workspacePath:(y==null?void 0:y.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(N){return{ok:!1,error:N instanceof Error?N.message:"Could not launch IDE"}}},[e,s]),u=i.useCallback(async(p,b,y,x)=>{var S,w,A;const N=Date.now();try{const L={cliType:y};(S=x==null?void 0:x.workspacePath)!=null&&S.trim()?L.dir=x.workspacePath.trim():x!=null&&x.workspaceId&&(L.workspaceId=x.workspaceId),(w=x==null?void 0:x.resumeSessionId)!=null&&w.trim()&&(L.resumeSessionId=x.resumeSessionId.trim()),Array.isArray(x==null?void 0:x.cliArgs)&&x.cliArgs.length>0&&(L.cliArgs=x.cliArgs),(A=x==null?void 0:x.initialModel)!=null&&A.trim()&&(L.initialModel=x.initialModel.trim());const k=await e(p,"launch_cli",L),j=(k==null?void 0:k.result)||k,O=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return k!=null&&k.success&&O?(s({machineId:p,kind:b,providerType:y,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,launchedSessionId:O,startedAt:N}),{ok:!0}):k!=null&&k.success?(s({machineId:p,kind:b,providerType:y,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,startedAt:N}),{ok:!0}):{ok:!1,error:(k==null?void 0:k.error)||(j==null?void 0:j.error)||`Could not launch ${b.toUpperCase()} session`}}catch(L){return Ji(L)?(s({machineId:p,kind:b,providerType:y,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,startedAt:N}),{ok:!0}):{ok:!1,error:L instanceof Error?L.message:`Could not launch ${b.toUpperCase()} session`}}},[r,e,s]),h=i.useCallback(async p=>{var b;if(l!=null&&l.listMeshes)return l.listMeshes(p);if(!p)return[];try{const y=await e(p,"list_meshes",{}),x=(y==null?void 0:y.result)??y;if((x==null?void 0:x.success)===!1)throw new Error((x==null?void 0:x.error)||"Could not load meshes");return(Array.isArray(x==null?void 0:x.meshes)?x.meshes:Array.isArray((b=x==null?void 0:x.result)==null?void 0:b.meshes)?x.result.meshes:[]).map(S=>{var w;return{id:String((S==null?void 0:S.id)||""),name:String((S==null?void 0:S.name)||(S==null?void 0:S.id)||"Untitled mesh"),repoIdentity:(S==null?void 0:S.repoIdentity)||(S==null?void 0:S.repo_identity)||null,workspace:Array.isArray(S==null?void 0:S.nodes)&&S.nodes.length>0?String(((w=S.nodes[0])==null?void 0:w.workspace)||""):null,nodesCount:Array.isArray(S==null?void 0:S.nodes)?S.nodes.length:void 0,status:(S==null?void 0:S.status)||null}}).filter(S=>S.id)}catch(y){throw console.error("List meshes failed",y),y}},[l,e]),g=i.useCallback(async(p,b,y)=>{if(!b.trim())return{ok:!1,error:"Choose a mesh first."};if(l!=null&&l.launchMeshCoordinator)return l.launchMeshCoordinator(p,b,y);const x=Date.now();try{const N={meshId:b.trim()};y.trim()&&(N.cliType=y.trim());const S=await e(p,"launch_mesh_coordinator",N),w=(S==null?void 0:S.result)??S;if((w==null?void 0:w.success)===!1||(S==null?void 0:S.success)===!1){const L=String((w==null?void 0:w.code)||(S==null?void 0:S.code)||""),k=Hb((w==null?void 0:w.meshCoordinatorSetup)||(w==null?void 0:w.manualSetup)||(S==null?void 0:S.meshCoordinatorSetup)||(S==null?void 0:S.manualSetup));return{ok:!1,error:(w==null?void 0:w.error)||(S==null?void 0:S.error)||"Could not launch mesh coordinator",code:L||void 0,manualSetup:k}}const A=(w==null?void 0:w.sessionId)||(w==null?void 0:w.id);return A?r(A):s({machineId:p,kind:"cli",providerType:(w==null?void 0:w.cliType)||y.trim()||void 0,workspacePath:(w==null?void 0:w.workspace)||null,startedAt:x}),{ok:!0}}catch(N){return Ji(N)?(s({machineId:p,kind:"cli",providerType:y.trim()||void 0,startedAt:x}),{ok:!0}):{ok:!1,error:N instanceof Error?N.message:"Could not launch mesh coordinator"}}},[l,r,e,s]),v=i.useCallback(async(p,b)=>{if(!p||!b)return[];try{const y=await e(p,"list_saved_sessions",{providerType:b,kind:"cli",limit:30}),x=(y==null?void 0:y.result)??y;return Array.isArray(x==null?void 0:x.sessions)?x.sessions:[]}catch(y){return console.error("List saved sessions failed",y),[]}},[e]),f=i.useCallback(async p=>{await nd({conversation:n,mode:p,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:d,handleLaunchMachineIde:m,handleLaunchMachineProvider:u,handleListMachineMeshes:h,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:v,setActiveCliViewMode:f}}function Yb(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 Xb(e,s,r=Date.now()){return!e||!Yb(s)?null:{tabKey:e,nonce:r}}function Jb({isMobile:e,conversations:s,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:l}){const[c,d]=i.useState(null),[m,u]=i.useState(null),h=i.useMemo(()=>{var b,y;if(!e){if(c){const x=s.find(N=>N.tabKey===c);if(x)return x}return r[0]}const p=n[a];if(p){const x=s.find(N=>N.tabKey===p);if(x)return x}return((b=o[a])==null?void 0:b[0])||((y=o[0])==null?void 0:y[0])},[s,c,a,n,o,e,r]),g=i.useCallback(p=>{d(p)},[]),v=i.useCallback(p=>{d(p.tabKey),l(b=>{const y=new URLSearchParams(b),x=uf(p);return x?y.set("activeTab",x):y.delete("activeTab"),y},{replace:!0})},[l]),f=i.useCallback((p,b)=>{const y=Xb(p,b);y&&u(y)},[]);return{activeConv:h,openDesktopConversation:v,requestScrollToBottom:f,scrollToBottomRequest:m,setDesktopActiveTab:g}}function Qb(e){const s=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?s===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 Zb(e){const s=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",s,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&s&&s!==r),autoReadKey:o,completionMarker:s,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function eg({activeConv:e,isMobile:s,liveSessionInboxState:r,sendDaemonCommand:n}){const a=i.useRef(null),o=i.useRef(null),l=i.useRef(null),c=i.useRef(null),d=i.useRef(null);i.useEffect(()=>{const m=()=>{l.current&&(clearTimeout(l.current),l.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(s){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const u=mn(e,r),h=Zb({tabKey:e.tabKey,historySessionId:Nr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:hs(e),liveState:u}),g=h.autoReadKey,v=Qb({autoReadKey:g,shouldMarkSeen:h.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!h.shouldMarkSeen){v.shouldCancelPending&&m(),a.current=g;return}if(!v.shouldSchedule)return;v.shouldCancelPending&&m();const f=()=>{if(document.visibilityState!=="visible"||a.current===g)return;a.current=g,o.current=null,l.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const b=h.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:b,completionMarker:h.completionMarker}).catch(()=>{})};if(o.current=v.nextPendingKey,document.visibilityState==="visible"){l.current=setTimeout(f,1500);const b=()=>{document.visibilityState!=="visible"&&l.current&&(clearTimeout(l.current),l.current=null)};d.current=b,document.addEventListener("visibilitychange",b);return}const p=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(f,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=p,document.addEventListener("visibilitychange",p)},[e,s,r,n]),i.useEffect(()=>()=>{l.current&&clearTimeout(l.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function la(e){if(!e)return"";const s=String(e.workspacePath||"").trim();if(s)return s;const r=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(r)?r:""}function tg({activeConv:e,remoteDialogConv:s,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:l,setClearedTabs:c,setSearchParams:d}){var I;const[m,u]=i.useState(!1),[h,g]=i.useState([]),[v,f]=i.useState(()=>jt()),[p,b]=i.useState(!1),[y,x]=i.useState(null),N=i.useRef(null),S=i.useMemo(()=>r||s||e,[e,r,s]),w=!!S&&st(S)&&!Ze(S),A=i.useMemo(()=>{if(!S||!w)return null;const K=S.daemonId||S.routeId||"",_=Ft(S),E=la(S);return`${K}:${_}:${S.providerSessionId||""}:${E}`},[S,w]),L=i.useMemo(()=>!S||!w?"":la(S),[S,w]),{isCreatingChat:k,isRefreshingHistory:j,handleSwitchSession:O,handleNewChat:R,handleRefreshHistory:T}=ud({sendDaemonCommand:a,activeConv:S,chats:(I=n.find(K=>K.id===(S==null?void 0:S.routeId)))==null?void 0:I.chats,updateRouteChats:o,setToasts:l,setClearedTabs:c}),F=i.useCallback(()=>{u(!0)},[]),W=i.useCallback(()=>{u(!1)},[]),D=i.useCallback(async()=>{if(!(!S||!w||p)){b(!0);try{const K=S.daemonId||S.routeId,_=Ft(S),E=la(S),V=await a(K,"list_saved_sessions",{agentType:_,providerType:_,kind:"cli",limit:50,...S.providerSessionId?{providerSessionId:S.providerSessionId}:{},...E?{workspace:E}:{}}),Y=(V==null?void 0:V.result)??V;g(Array.isArray(Y==null?void 0:Y.sessions)?Y.sessions:[])}catch(K){console.error("Refresh saved sessions failed",K),g([])}finally{b(!1)}}},[S,p,w,a]);i.useEffect(()=>{if(!m){N.current=null;return}if(!w){N.current=null,g([]),b(!1);return}!A||p||N.current!==A&&(N.current=A,D())},[D,m,p,w,A]);const C=i.useCallback(async K=>{if(!S||!w||!K.providerSessionId||!K.workspace)return;const _=S.daemonId||S.routeId,E=Ft(S);try{x(K.providerSessionId);const V=await a(_,"launch_cli",{cliType:E,dir:K.workspace,resumeSessionId:K.providerSessionId,initialModel:nc(K.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Y=(V==null?void 0:V.result)??V,ge=typeof(Y==null?void 0:Y.sessionId)=="string"?Y.sessionId:typeof(Y==null?void 0:Y.id)=="string"?Y.id:"";ge&&d(pe=>{const re=new URLSearchParams(pe);return re.set("activeTab",ge),re},{replace:!0}),W()}catch(V){console.error("Resume saved session failed",V)}finally{x(null)}},[W,S,w,a,d]);return{historyModalOpen:m,openHistoryModal:F,closeHistoryModal:W,historyTargetConv:S,isSavedSessionHistoryTarget:w,isHistoryCreatingChat:k,isHistoryRefreshingHistory:j,handleHistorySwitchSession:O,handleHistoryNewChat:R,handleHistoryRefresh:T,savedHistorySessions:h,savedHistoryFilters:v,setSavedHistoryFilters:f,missingWorkspaceResumePath:L,isSavedHistoryLoading:p,resumingSavedHistorySessionId:y,handleRefreshSavedHistory:D,handleResumeSavedHistorySession:C}}function sg({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c}){const[d,m]=i.useState(null),[u,h]=i.useState(null),g=i.useMemo(()=>{if(e||!n)return null;const y=c(n);return y&&!st(y)&&!Ze(y)?y:null},[e,n,c]),v=i.useMemo(()=>{const y=d==null?void 0:d.routeId;if(!y)return null;const x=d!=null&&d.tabKey?o.find(N=>N.tabKey===d.tabKey):a?o.find(N=>N.tabKey===a):null;return(x==null?void 0:x.routeId)===y?x:Et(o,y)},[o,d,a]),f=i.useMemo(()=>{if(v)return l.find(y=>y.id===v.routeId)},[l,v]);i.useEffect(()=>{g&&(m({routeId:g.routeId,tabKey:ji(g)}),h(g),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,g]);const p=i.useCallback(y=>{y&&(m({routeId:y.routeId,tabKey:ji(y)}),h(y))},[]),b=i.useCallback(()=>{m(null),h(null)},[]);return{remoteDialogConv:v,remoteDialogIdeEntry:f,remoteDialogActiveConv:u,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:b}}function rg({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:g,setRemoteDialogActiveConv:v,openRemoteDialog:f,closeRemoteDialog:p}=sg({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c}),[b,y]=i.useState(!1),[x,N]=i.useState(null),S=i.useCallback(async L=>{const k=L||d;!k||!st(k)&&!Ze(k)||(N(k),y(!0))},[d]),w=i.useCallback(()=>{y(!1),N(null)},[]),A=i.useCallback(async L=>{const k=x||d;if(!k||!st(k)&&!Ze(k)){w();return}y(!1);try{const j=Ft(k),O=k.routeId||k.daemonId||"";await m(O,"stop_cli",{cliType:j,targetSessionId:k.sessionId,mode:L})}catch(j){console.error("Stop CLI failed:",j)}finally{N(null)}},[d,w,x,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:g,setRemoteDialogActiveConv:v,openRemoteDialog:f,closeRemoteDialog:p,cliStopDialogOpen:b,cliStopTargetConv:x,requestCliStop:S,cancelCliStop:w,confirmCliStop:A}}function yd({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var N,S;const l=Hs(),c=ks(e),d=o?null:uc(e),m=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!o&&e.streamSource==="agent-stream"&&!!e.agentName,h=!o&&!u&&(e.transport==="pty"||e.transport==="acp"),g=$s(e),v=df(e),f=(N=e.settings)==null?void 0:N.meshNodeFor,p=e.meshQueueStats,b=(S=e.settings)==null?void 0:S.meshCoordinatorFor;if(!m&&!u&&!h&&!d&&!f&&!p)return null;const y=i.useCallback(()=>{if(n){n();return}c&&l("/dashboard",{state:{openMachineId:c}})},[c,l,n]),x=i.useCallback(()=>{if(r){r();return}const w=xd(e);w&&l(ss(w))},[e,l,r]);return t.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[m&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:x,title:v,children:[t.jsx(It,{size:12}),t.jsx("span",{children:v})]}):t.jsxs("span",{className:"conversation-meta-chip",title:v,children:[t.jsx(It,{size:12}),t.jsx("span",{children:v})]})),u&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[t.jsx(Es,{size:12}),t.jsx("span",{children:g})]}),h&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[t.jsx(Es,{size:12}),t.jsx("span",{children:g})]}),d&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:y,title:d,children:[t.jsx(es,{size:12}),t.jsx("span",{children:d})]}):t.jsxs("span",{className:"conversation-meta-chip",title:d,children:[t.jsx(es,{size:12}),t.jsx("span",{children:d})]})),f&&t.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[t.jsx(es,{size:12}),t.jsx("span",{children:"Mesh Node"})]}),b&&p&&t.jsxs("span",{className:`conversation-meta-chip ${p.pending>0?"is-active":""}`,style:p.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${p.pending} pending, ${p.assigned} assigned, ${p.completed} completed, ${p.failed} failed`,children:[t.jsx(cm,{size:12}),t.jsxs("span",{children:[p.pending," Pending"]})]})]})}function ca(e,s=!0){return(e??!0)&&s}const Oo=i.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:l,handleRelaunch:c,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u=null,handleFocusAgent:h,isFocusingAgent:g,actionLogs:v,userName:f,scrollToBottomRequestNonce:p,isInputActive:b=!0,isVisible:y=!0}){const x=n,N=!n,S=ca(y,x),w=ca(y,N),A=ca(y),L=Qc(s),k=L.status||L.modalMessage||L.modalButtons?{...s,...L.status?{status:L.status}:{},...L.modalMessage!==void 0?{modalMessage:L.modalMessage}:{},...L.modalButtons!==void 0?{modalButtons:L.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(tc,{activeConv:k,onModalButton:l}),t.jsx(yd,{conversation:k,className:"chat-pane-meta-row mx-3 mt-1",meshOnly:!0}),k.transport!=="pty"&&k.transport!=="acp"&&k.cdpConnected===!1?t.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:t.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:[t.jsx("span",{className:"text-sm",children:t.jsx(gr,{size:14})}),t.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),t.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,k.transport==="pty"?t.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[t.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:x?"visible":"hidden",pointerEvents:x?"auto":"none"},children:t.jsx(Sh,{activeConv:k,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,isVisible:S,isInputActive:b&&S})}),t.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:N?"visible":"hidden",pointerEvents:N?"auto":"none"},children:t.jsx(Ha,{activeConv:k,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:h,isFocusingAgent:g,actionLogs:v,userName:f,scrollToBottomRequestNonce:p,isInputActive:b&&w,isVisible:w})})]}):t.jsx(Ha,{activeConv:k,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:h,isFocusingAgent:g,actionLogs:v,userName:f,scrollToBottomRequestNonce:p,isInputActive:b&&A,isVisible:A})]})},(e,s)=>e.activeConv===s.activeConv&&e.isCliTerminal===s.isCliTerminal&&e.ideEntry===s.ideEntry&&e.terminalRef===s.terminalRef&&e.handleModalButton===s.handleModalButton&&e.handleRelaunch===s.handleRelaunch&&e.handleSendChat===s.handleSendChat&&e.isSendingChat===s.isSendingChat&&e.sendFeedbackMessage===s.sendFeedbackMessage&&e.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive&&e.isVisible===s.isVisible);function ng({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:l,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:m,onOpenNativeConversation:u,onOpenMachine:h,onOpenHistory:g,onOpenRemote:v,onOpenMeshGraph:f,onStopCli:p,cliViewMode:b,onSetCliViewMode:y,handleSendChat:x,handleFocusAgent:N,handleModalButton:S,handleRelaunch:w}){var R;const A=i.useRef(null),L=st(e)&&!s,k=L&&b==="terminal",j=!!e.daemonId&&typeof((R=e.settings)==null?void 0:R.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.length>0,O=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`flex items-center justify-between gap-3 ${O} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.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:t.jsx(oo,{size:18})}),t.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:lt(e)}),t.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:t.jsx(yd,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>h(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[L&&b&&t.jsx(Co,{mode:b,onChange:y,compact:!0}),L&&p&&t.jsx("button",{onClick:()=>{p(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:t.jsx(gt,{size:14})}),j&&f&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:t.jsx(Qt,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:t.jsx(io,{size:14})}),!s&&!L&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e),type:"button",children:t.jsx(It,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(Oo,{activeConv:e,clearToken:0,isCliTerminal:k,ideEntry:n,terminalRef:A,handleModalButton:S,handleRelaunch:w,handleSendChat:x,isSendingChat:l,sendFeedbackMessage:c,handleFocusAgent:N,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const da={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 ag(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function vd(){const[e,s]=i.useState("unix"),[r,n]=i.useState("powershell"),[a,o]=i.useState(!1),l=e==="unix"?"unix":r;i.useEffect(()=>{s(ag())},[]);const c=i.useCallback(()=>{navigator.clipboard.writeText(da[l].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[l]);return t.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:[t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.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:()=>s("unix"),children:"🍎🐧 macOS / Linux"}),t.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:()=>s("windows"),children:"🪟 Windows"})]}),e==="windows"&&t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.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"}),t.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"})]}),t.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:c,title:"Click to copy",children:[t.jsx("span",{className:"text-text-muted select-none",children:da[l].prompt}),t.jsx("span",{className:"flex-1 break-all",children:da[l].cmd}),t.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),t.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",t.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function wd({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:It},{key:"chats",label:"Chats",icon:Vt}];return t.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:t.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 l=e===n;return t.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 ${l?"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:l?{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:()=>s(n),type:"button","aria-pressed":l,children:[t.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${l?"text-accent-primary":"bg-transparent text-current"}`,style:l?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:t.jsx(o,{size:15})}),t.jsx("span",{children:a})]},n)})})})}function Hr({title:e,className:s=""}){return t.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:t.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function Ss({children:e,className:s=""}){return t.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)] ${s}`,children:e})}function rr({icon:e,title:s,subtitle:r,children:n}){return t.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:[t.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}),t.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function og({conversation:e,onCancel:s,onConfirm:r}){const n=lt(e),a=vs(e);return t.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:[t.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:s}),t.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:[t.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border-subtle bg-[var(--surface-primary)] px-4 py-4",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base font-extrabold text-text-primary",children:"Hide this chat from the inbox?"}),t.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."})]}),t.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:s,"aria-label":"Cancel hide chat",children:t.jsx(gt,{size:16})})]}),t.jsx("div",{className:"px-4 py-4",children:t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary/60 px-3.5 py-3",children:[t.jsx("div",{className:"truncate text-sm font-bold text-text-primary",children:n}),t.jsx("div",{className:"mt-1 truncate text-xs text-text-muted",children:a})]})}),t.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:[t.jsx("button",{type:"button",className:"btn btn-secondary min-h-[40px] px-4 text-sm",onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary min-h-[40px] px-4 text-sm",onClick:r,children:"Hide tab"})]})]})]})}function Ur({item:e,type:s,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onOpenMeshGraph:o,onCollectChatDebugBundle:l}){var O;const c=s==="needs_attention"||s==="task_complete",d=s==="working",m=s==="earlier",u=s==="task_complete",{isReconnecting:h,isConnecting:g}=Us(e.conversation),v=lt(e.conversation),f=vs(e.conversation),p=Lc(e.conversation,{requiresAction:s==="needs_attention"}),b=c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":d?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",y=c?"bg-accent-primary shadow-glow":d?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":m?"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",x=m?"text-text-secondary":"text-text-primary",N=m?"text-text-muted":"text-text-secondary",S=m?"text-text-secondary opacity-80":"text-text-muted",w=m?"text-text-muted opacity-80":"text-text-muted",A=!d&&!u,L=!!e.conversation.daemonId&&typeof((O=e.conversation.settings)==null?void 0:O.meshCoordinatorFor)=="string"&&e.conversation.settings.meshCoordinatorFor.length>0,k="text-[color:var(--status-warning)]",j=R=>{if(!l)return;R.preventDefault(),R.stopPropagation();const T=l==null?void 0:l(e.conversation);Promise.resolve(T).catch(F=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",F)})};return t.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${b}`,children:t.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[c||d?t.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,t.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[t.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${y}`,style:c?{color:"var(--accent-on-primary)"}:void 0,children:r(v)}),a&&t.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 ${v}`,title:"Hide conversation",children:[t.jsx(lo,{size:11}),t.jsx("span",{children:"Hide"})]}),L&&o&&t.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 ${v}`,title:"Open live repo mesh graph",children:[t.jsx(Qt,{size:11}),t.jsx("span",{children:"Graph"})]})]}),t.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:j,type:"button",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${x}`,children:v}),A&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${w}`,children:ec(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${N}`,children:[t.jsx("span",{className:"truncate",children:f}),t.jsx(Os,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),h?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${k} animate-pulse`,children:"Reconnecting…"})]}):g?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):p==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:k,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${S}`,children:e.preview})]}),c&&!u&&t.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),u&&t.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"}),d&&t.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 Qi({size:e=32}){return t.jsx("div",{className:"flex flex-col items-center gap-2.5",children:t.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 ig({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:l,getAvatarText:c,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:h,onHideConversation:g,onOpenMeshGraph:v,onOpenNewSession:f,onOpenMachine:p,onOpenSettings:b,onSectionChange:y,wsStatus:x="connected",isStandalone:N=!1,onCollectChatDebugBundle:S}){const[w,A]=i.useState(null),L=x==="disconnected"||x==="reconnecting"||x==="offline"||x==="auth_failed",k=l.length>0,j=s.length>0||r.length>0||n.length>0||a.length>0,O=e==="machines"?"Machines":"Chats",R=N?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",T=N?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",F=i.useCallback(async C=>{const I=Bs(C);if(!I)return;const K=Array.isArray(C.messages)?C.messages:[],_=bc({activeConv:C,visibleMessages:K,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:K.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),E=await m(I,"get_chat_debug_bundle",{...cs(C),delivery:"daemon_file",frontendSnapshot:_}),V=xn(E),Y=vc(V),ge=await yc(Y);ge==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),nt.showToast(gc(V,{locatorCopyStatus:ge}),ge==="failed"?"warning":"success")},[d,m]),W=S||F,D=i.useCallback(()=>{w&&(g==null||g(w),A(null))},[w,g]);return t.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[t.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${R}`,children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:O}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(s.length>0||r.length>0)&&t.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:[t.jsx(Cn,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:b,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:t.jsx(Nn,{size:18})})]})]})}),t.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] ${T}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:L?t.jsx(rr,{icon:t.jsx(Qi,{}),title:x==="offline"?"Network offline":x==="auth_failed"?"Session expired":"Reconnecting",subtitle:x==="offline"?"Waiting for network…":x==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):l.length===0?t.jsx(rr,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:N?"Waiting for your daemon":"Connect your machines",subtitle:N?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!N&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(vd,{})})}):t.jsx(Ss,{children:l.map((C,I)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${I>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(C.id),type:"button",children:[t.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(C.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:C.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:C.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[C.unread," new"]}):C.total>0?`${C.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:C.subtitle}),C.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[C.total," chat",C.total!==1?"s":"",C.unread>0?` · ${C.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},C.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Hr,{title:"Needs attention",className:"mb-0"}),t.jsx(Ss,{children:s.map((C,I)=>t.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:t.jsx(Ur,{item:C,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:g?()=>A(C.conversation):void 0,onOpenMeshGraph:v,onCollectChatDebugBundle:W})},C.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Hr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(Ss,{children:r.map((C,I)=>t.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:t.jsx(Ur,{item:C,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:g?()=>A(C.conversation):void 0,onOpenMeshGraph:v,onCollectChatDebugBundle:W})},C.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Hr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(Ss,{children:n.map((C,I)=>t.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:t.jsx(Ur,{item:C,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:g?()=>A(C.conversation):void 0,onOpenMeshGraph:v,onCollectChatDebugBundle:W})},C.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&t.jsx(Hr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(Ss,{children:a.map((C,I)=>t.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:t.jsx(Ur,{item:C,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:g?()=>A(C.conversation):void 0,onOpenMeshGraph:v,onCollectChatDebugBundle:W})},C.conversation.tabKey))}):j?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):L?t.jsx(rr,{icon:t.jsx(Qi,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):k?t.jsx(rr,{icon:t.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:t.jsx(Vt,{size:20})}),title:"No conversations yet",subtitle:Pc,children:f&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:f,"aria-label":Ot,title:Ot,children:[t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),t.jsx("span",{children:Ot})]})}):t.jsx(rr,{icon:t.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&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:t.jsx(Ss,{className:"mt-4 border-dashed bg-bg-secondary/20",children:t.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),t.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[o.length," collapsed ",o.length===1?"conversation":"conversations"]})]}),t.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:h,children:"Restore all"})]})})})]}),e==="chats"&&f&&j&&t.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:f,"aria-label":Ot,title:Ot,children:t.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),w&&t.jsx(og,{conversation:w,onCancel:()=>A(null),onConfirm:D}),t.jsx(wd,{section:e,onSectionChange:y})]})}function lg(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 jd(e){const s=[e.workspace||"Workspace unknown"],r=ys(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=lg(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function $n({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:l="Use this folder",onClose:c,onNavigate:d,onConfirm:m}){const[u,h]=i.useState(r);i.useEffect(()=>{h(r)},[r]);const g=Kb(r),v=u.trim();return t.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:t.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:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.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:t.jsx(gt,{size:16})})]}),t.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[t.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:()=>{!g||a||d(g)},disabled:!g||a,children:[t.jsx(oo,{size:15}),"Parent"]}),t.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"text",value:u,onChange:f=>h(f.target.value),onKeyDown:f=>{f.key!=="Enter"||!v||a||(f.preventDefault(),d(v))},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"}),t.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:()=>{!v||a||d(v)},disabled:!v||a,children:"Go"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?t.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):n.length===0?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):t.jsx("div",{className:"p-3",children:n.map(f=>t.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(f.path),children:[t.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:t.jsx(gs,{size:17})}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:f.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:f.path})]})]},f.path))})}),t.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:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(v||r),disabled:!v&&!r||a,children:l})]})]})})}function Ko({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:l="Launch",busyLabel:c="Launching…",busy:d=!1,showArgsInput:m,argsValue:u,onArgsChange:h,showModelInput:g,modelValue:v,onModelChange:f,historyProviderNode:p,onConfirm:b,onCancel:y}){const x=n==null?void 0:n.find(N=>N.key===a);return t.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:t.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:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.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:t.jsx(gt,{size:16})})]}),t.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&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),t.jsx("select",{value:a||"",onChange:N=>o(N.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(N=>t.jsx("option",{value:N.key,children:N.label},N.key))}),(x==null?void 0:x.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:x.description})]}),p,r.map(N=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:N.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:N.value})]},`${N.label}:${N.value}`)),g&&f&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),t.jsx("input",{type:"text",value:v||"",onChange:N=>f(N.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&&h&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),t.jsx("input",{type:"text",value:u||"",onChange:N=>h(N.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})]})]}),t.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:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:y,disabled:d,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:b,disabled:d,children:[t.jsx(uo,{size:14}),d?c:l]})]})]})})}function Zi(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function xs(e){const{machine:s,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 s.workspaces||[])o.push({key:`saved:${d.id}`,label:`${d.id===s.defaultWorkspaceId?"⭐ ":""}${Zi(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const l=(r==null?void 0:r.trim())||"",c=l?(s.workspaces||[]).find(d=>d.path===l):null;if(l&&!c&&o.push({key:`custom:${l}`,label:Zi(l),description:l,workspaceId:null,workspacePath:l}),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}`}:l?{options:o,selectedKey:`custom:${l}`}:{options:o,selectedKey:"__home__"}}function cg(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function dg(e){return[cg(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function ug(e){return e.lastLaunchedAt?In(e.lastLaunchedAt):""}function kd(e){return{metaText:dg(e),updatedLabel:ug(e)}}function ua(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function mg({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var et,dt,pt,bt;const l=Sr(),[c,d]=i.useState(!1),m=(((et=e.detectedIdes)==null?void 0:et.length)||0)>0,u=i.useMemo(()=>(e.workspaces||[]).map(Ce=>({id:Ce.id,path:Ce.path,label:Ce.label})),[e]),h=e.defaultWorkspaceId||null,[g,v]=i.useState(h||((dt=u[0])==null?void 0:dt.id)||""),[f,p]=i.useState(""),[b,y]=i.useState(""),[x,N]=i.useState([]),[S,w]=i.useState(!1),[A,L]=i.useState(""),[k,j]=i.useState(!1),[O,R]=i.useState(ua(m,s.length,r.length)),T=i.useRef(null),[F,W]=i.useState(null),D=i.useRef("__home__"),[C,I]=i.useState("__home__"),[K,_]=i.useState(""),[E,V]=i.useState(""),[Y,ge]=i.useState(""),[pe,re]=i.useState([]),[de,ke]=i.useState(()=>jt().textQuery),[ye,q]=i.useState(()=>jt().workspaceQuery),[he,fe]=i.useState(()=>jt().modelQuery),[we,xe]=i.useState(()=>jt().resumableOnly),[Se,Q]=i.useState(()=>jt().sortMode),[ue,oe]=i.useState(!1),[me,le]=i.useState(!1),P=i.useRef(null),U=i.useRef(null);i.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&l(e.id,{minFreshMs:3e4}).catch(()=>{})},[l,e]);const ce=g==="__custom__"?f.trim():((pt=u.find(Ce=>Ce.id===g))==null?void 0:pt.path)||"",te=g==="__custom__"&&!!ce&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),ie=g!=="__custom__"&&((bt=u.find(Ce=>Ce.id===g))==null?void 0:bt.path)||"",se=i.useMemo(()=>(e.recentLaunches||[]).map(Ce=>Ce.workspace),[e]),ve=i.useCallback(async Ce=>{w(!0),L("");try{const Ue=await a(Ce);y(Ue.path),p(Ue.path),N(Ue.directories)}catch(Ue){L(Ue instanceof Error?Ue.message:"Could not load folder")}finally{w(!1)}},[a]),Ie=i.useCallback(()=>{var Ue;v("__custom__"),j(!0);const Ce=Dn(e.platform,Pn(f.trim(),ie,se,e.defaultWorkspacePath,(Ue=u.find(Qe=>Qe.id===h))==null?void 0:Ue.path,u.map(Qe=>Qe.path)));ve(Ce)},[f,h,ve,se,ie,e.platform,u]),Me=i.useCallback(Ce=>{if(Ce!=null&&Ce.workspaceId){v(Ce.workspaceId),p("");return}if(Ce!=null&&Ce.workspacePath){v("__custom__"),p(Ce.workspacePath);return}v(""),p("")},[]),B=i.useCallback(Ce=>{if(v(Ce),Ce==="__custom__"){Ie();return}p("")},[Ie]),Ne=i.useCallback(Ce=>{v("__custom__"),p(Ce)},[]),Re=i.useCallback((Ce,Ue)=>{T.current=Ue,D.current=Ce.selectedWorkspaceKey||"__home__",I(Ce.selectedWorkspaceKey||"__home__"),_(Ce.initialArgs||""),V(Ce.initialModel||""),ge(""),re([]);const Qe=Ce.providerType?`${e.id}:${Ce.providerType}`:null;if(Dh(U.current,Qe)){const ze=jt();ke(ze.textQuery),q(ze.workspaceQuery),fe(ze.modelQuery),xe(ze.resumableOnly),Q(ze.sortMode)}U.current=Qe,W(Ce),Ce.providerType&&o&&(oe(!0),o(Ce.providerType).then(ze=>re(ze||[])).catch(ze=>console.warn("Failed to load saved sessions",ze)).finally(()=>oe(!1)))},[o,e.id]),Fe=i.useMemo(()=>Dc(pe,{textQuery:de,workspaceQuery:ye,modelQuery:he,resumableOnly:we,sortMode:Se}),[he,we,pe,Se,de,ye]);i.useEffect(()=>{Y&&(Fe.some(Ce=>Ce.providerSessionId===Y)||ge(""))},[Fe,Y]);const He=i.useCallback(()=>{T.current&&(le(!0),T.current().finally(()=>{T.current=null,le(!1),W(null)}))},[]),Ge=i.useCallback(()=>{T.current=null,W(null)},[]),qe=i.useCallback(Ce=>{D.current=Ce,I(Ce)},[]);return i.useEffect(()=>{var Ce;P.current!==e.id&&(P.current=e.id,v(h||((Ce=u[0])==null?void 0:Ce.id)||"__custom__"),p(""),y(""),N([]),L(""),j(!1),ke(jt().textQuery),q(jt().workspaceQuery),fe(jt().modelQuery),xe(jt().resumableOnly),Q(jt().sortMode),U.current=null,R(ua(m,s.length,r.length)))},[r.length,s.length,h,m,e.id,u]),i.useEffect(()=>{var Ce;g!=="__custom__"&&(g&&u.some(Ue=>Ue.id===g)||v(h||((Ce=u[0])==null?void 0:Ce.id)||"__custom__"))},[h,g,u]),i.useEffect(()=>{O==="ide"&&m||O==="cli"&&s.length>0||O==="acp"&&r.length>0||R(ua(m,s.length,r.length))},[O,r.length,s.length,m]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:m,workspaceRows:u,defaultWorkspaceId:h,workspaceChoice:g,customWorkspacePath:f,browseCurrentPath:b,browseDirectories:x,browseBusy:S,browseError:A,browseDialogOpen:k,activeLauncherKind:O,launchConfirm:F,launchConfirmWorkspaceKeyRef:D,launchConfirmWorkspaceKey:C,launchConfirmArgs:K,launchConfirmModel:E,launchConfirmResumeId:Y,launchConfirmSavedSessions:pe,launchConfirmTextFilter:de,launchConfirmWorkspaceFilter:ye,launchConfirmModelFilter:he,launchConfirmResumableOnly:we,launchConfirmSortMode:Se,filteredLaunchConfirmSavedSessions:Fe,launchConfirmSessionsLoading:ue,launchConfirmBusy:me,resolvedWorkspacePath:ce,canCreateMissingWorkspace:te,openBrowseDialog:Ie,loadBrowsePath:ve,handleWorkspaceChoiceChange:B,chooseCustomWorkspacePath:Ne,setCustomWorkspacePath:p,setBrowseDialogOpen:j,setActiveLauncherKind:R,openLaunchConfirm:Re,handleConfirmLaunch:He,closeLaunchConfirm:Ge,setWorkspaceSelectionFromOption:Me,setLaunchConfirmWorkspaceKeyAndSync:qe,setLaunchConfirmArgs:_,setLaunchConfirmModel:V,setLaunchConfirmResumeId:ge,setLaunchConfirmTextFilter:ke,setLaunchConfirmWorkspaceFilter:q,setLaunchConfirmModelFilter:fe,setLaunchConfirmResumableOnly:xe,setLaunchConfirmSortMode:Q}}function pg({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:l,machineAction:c,isStandalone:d,section:m,showBottomNav:u,onBack:h,onSectionChange:g,onOpenConversation:v,onOpenRecent:f,onOpenMachineDetails:p,onMachineUpgrade:b,onLaunchDetectedIde:y,onAddWorkspace:x,onBrowseDirectory:N,onLaunchWorkspaceProvider:S,onListSavedSessions:w}){const A=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",L=r.slice(0,4),k=s.slice(0,3),j=mg({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:c,onBrowseDirectory:N,onListSavedSessions:w}),O=i.useMemo(()=>L.map(C=>{const{metaText:I,updatedLabel:K}=kd(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:I,updatedLabel:K,onClick:()=>{const{options:_,selectedKey:E}=xs({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspacePath:C.workspace});j.openLaunchConfirm({title:C.kind==="ide"?us("restart-ide",C.label):C.providerSessionId?Ao(C.label):us("start-fresh",C.label),description:C.kind==="ide"?ms("restart-ide"):C.providerSessionId?Mo():ms("start-fresh"),confirmLabel:C.kind==="ide"?Ks("restart-ide"):C.providerSessionId?gn(!0):Ks("start-fresh"),busyLabel:C.kind==="ide"?Fs("restart-ide"):C.providerSessionId?Io(!0):Fs("start-fresh"),workspaceOptions:_,selectedWorkspaceKey:E,details:[{label:"Mode",value:A(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const V=_.find(Y=>Y.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(V),await f({...C,workspace:(V==null?void 0:V.workspacePath)??null})})}}}),[j,f,L]),R=i.useMemo(()=>k.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:lt(C.conversation),secondary:vh(C.conversation,{timestampLabel:C.timestamp?ec(C.timestamp):null}),unread:C.unread,onClick:()=>v(C.conversation)})),[v,k]),T=j.showAllRecent?O:O.slice(0,4),F=O.length>0,W=R.length>0,D=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:`flex items-center justify-between gap-3 ${D} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.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:h,type:"button","aria-label":"Back",children:t.jsx(oo,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Ct(e,{fallbackId:e.id})}),t.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}`:""]})]})]})}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[W&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:R.map(C=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),F&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:T.map(C=>t.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:C.onClick,children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:C.primary}),C.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:C.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),O.length>4&&t.jsx("div",{className:"flex justify-center px-4 pt-2",children:t.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:()=>j.setShowAllRecent(C=>!C),children:j.showAllRecent?"Show fewer":`Show ${O.length-4} more`})})]}),(j.hasIdeOptions||n.length>0||a.length>0)&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:t.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),t.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),t.jsx("select",{value:j.workspaceChoice,onChange:C=>j.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:j.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[j.workspaceRows.map(C=>t.jsxs("option",{value:C.id,children:[C.id===j.defaultWorkspaceId?"⭐ ":"",An(C.path,C.label)||C.path]},C.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),j.workspaceChoice==="__custom__"&&t.jsxs("div",{className:"flex flex-col gap-2.5",children:[t.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start gap-3",children:[t.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:t.jsx(gs,{size:17})}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),t.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:j.resolvedWorkspacePath||j.browseCurrentPath||"No folder selected yet."})]})]})}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:j.openBrowseDialog,children:"Select workspace…"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{j.resolvedWorkspacePath&&x(j.resolvedWorkspacePath)},disabled:!j.resolvedWorkspacePath||j.browseBusy,children:"Save as workspace"})]})]}),j.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[j.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.activeLauncherKind==="ide"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>j.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.activeLauncherKind==="cli"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>j.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.activeLauncherKind==="acp"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>j.setActiveLauncherKind("acp"),children:"ACP"})]}),j.activeLauncherKind&&t.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[t.jsx("div",{className:"text-xs font-bold text-text-secondary",children:j.activeLauncherKind==="ide"?"Choose an IDE":j.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:j.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(C=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:I,selectedKey:K}=xs({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:I,selectedWorkspaceKey:K,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const _=I.find(E=>E.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(_),y(C.type,{workspacePath:(_==null?void 0:_.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(j.activeLauncherKind==="cli"?n:a).map(C=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const I=j.activeLauncherKind==="cli"?"cli":"acp",{options:K,selectedKey:_}=xs({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${I.toUpperCase()}`,workspaceOptions:K,selectedWorkspaceKey:_,details:[{label:"Mode",value:I.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:I==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const E=K.find(V=>V.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(E),S(I,C.type,{workspaceId:(E==null?void 0:E.workspaceId)??null,workspacePath:(E==null?void 0:E.workspacePath)??null,args:j.launchConfirmArgs,model:j.launchConfirmModel,resumeSessionId:j.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[C.icon?`${C.icon} `:"",C.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},C.type))})]}),c.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${c.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[c.message,j.canCreateMissingWorkspace&&t.jsx("div",{className:"mt-2",children:t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>x(j.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&t.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:b,children:[t.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",l]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),t.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:p,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),j.browseDialogOpen&&t.jsx($n,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:j.browseCurrentPath,directories:j.browseDirectories,busy:j.browseBusy,error:j.browseError,confirmLabel:"Use this folder",onClose:()=>j.setBrowseDialogOpen(!1),onNavigate:C=>{j.loadBrowsePath(C)},onConfirm:C=>{j.chooseCustomWorkspacePath(C),j.setBrowseDialogOpen(!1)}}),j.launchConfirm&&t.jsx(Ko,{title:j.launchConfirm.title,description:j.launchConfirm.description,details:j.launchConfirm.details,workspaceOptions:j.launchConfirm.workspaceOptions,selectedWorkspaceKey:j.launchConfirmWorkspaceKey,onWorkspaceChange:j.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:j.launchConfirm.providerType?gn(!!j.launchConfirmResumeId):j.launchConfirm.confirmLabel,busyLabel:j.launchConfirm.providerType?void 0:j.launchConfirm.busyLabel,busy:j.launchConfirmBusy,showArgsInput:j.launchConfirm.showArgsInput,argsValue:j.launchConfirmArgs,onArgsChange:j.setLaunchConfirmArgs,showModelInput:j.launchConfirm.showModelInput,modelValue:j.launchConfirmModel,onModelChange:j.setLaunchConfirmModel,historyProviderNode:j.launchConfirm.providerType&&(j.launchConfirmSessionsLoading||j.launchConfirmSavedSessions.length>0)&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),j.launchConfirmSessionsLoading&&t.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:To()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:j.launchConfirmTextFilter,onChange:C=>j.setLaunchConfirmTextFilter(C.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:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:j.launchConfirmWorkspaceFilter,onChange:C=>j.setLaunchConfirmWorkspaceFilter(C.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:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:j.launchConfirmModelFilter,onChange:C=>j.setLaunchConfirmModelFilter(C.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:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),t.jsxs("select",{value:j.launchConfirmSortMode,onChange:C=>j.setLaunchConfirmSortMode(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:j.launchConfirmBusy||j.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:j.launchConfirmResumableOnly,onChange:C=>j.setLaunchConfirmResumableOnly(C.target.checked),disabled:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:j.launchConfirmResumeId,onChange:C=>j.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:j.launchConfirmBusy||j.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:Bh()}),j.filteredLaunchConfirmSavedSessions.map(C=>t.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.providerSessionId))]}),!j.launchConfirmSessionsLoading&&j.launchConfirmSavedSessions.length>0&&j.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),j.launchConfirmResumeId&&(()=>{const C=j.filteredLaunchConfirmSavedSessions.find(K=>K.providerSessionId===j.launchConfirmResumeId);if(!C)return null;const I=jd(C);return t.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:[t.jsx("div",{className:"font-semibold text-text-primary truncate",children:I.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:I.providerSessionId}),t.jsx("div",{className:"mt-1",children:I.metaLine}),I.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:I.updatedLabel}),I.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:I.preview})]})})()]}),onConfirm:j.handleConfirmLaunch,onCancel:j.closeLaunchConfirm}),u&&t.jsx(wd,{section:m,onSectionChange:g})]})}function sn(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function fg(e,s=[]){const r=new Map(e.map(a=>[a.conversation.tabKey,a])),n=s.map(a=>r.get(a)).filter(a=>!!a);return n.length===e.length?n:sn(e)}function hg(e){var r;const s=((r=e.p2p)==null?void 0:r.state)||"";return s==="connected"?"Connected":s==="connecting"||s==="new"||s==="checking"?"Connecting":"Offline"}function xg(e,s){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:ys(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):s.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var l;const a=yr(n)?"cli":Ls(n)?"acp":"ide",o=ys(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((l=n.activeChat)==null?void 0:l.title)||(yr(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 bg(e,s){const r=new Map;for(const n of s){const a=ks(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((h,g)=>g.timestamp-h.timestamp)[0]||null,l=(o==null?void 0:o.conversation)||null,c=Ba(n),d=a.filter(h=>h.unread||h.requiresAction).length,m=hg(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:l,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:c,preview:l?wh(l):"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,l=a.latestTimestamp||a.fallbackActivityAt||0;return l!==o?l-o:n.label.localeCompare(a.label)})}function gg(e){return e==="chat"}function zr(e,s){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}`,s)}catch{}}function yg({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:l,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:g,onRequestedMobileSectionConsumed:v,setSelectedTabKey:f,setScreen:p,setSelectedMachineId:b,setSection:y,setMachineBackTarget:x,resetMachineAction:N}){const S=i.useRef(null),w=i.useCallback(A=>{if(!(A!=null&&A.sessionId))return;const L=mn(A,l),k=Math.max(Date.now(),hs(A),L.lastUpdated||0);zr("mark_read:start",{tabKey:A.tabKey,sessionId:A.sessionId,displayPrimary:lt(A),inboxBucket:L.inboxBucket,unread:L.unread,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,activityAt:hs(A),readAt:k}),c(ks(A)||A.routeId,"mark_session_seen",{sessionId:A.sessionId,providerSessionId:A.providerSessionId,seenAt:k,completionMarker:L.completionMarker}).then(j=>{zr("mark_read:result",{tabKey:A.tabKey,sessionId:A.sessionId,result:j})}).catch(j=>{zr("mark_read:error",{tabKey:A.tabKey,sessionId:A.sessionId,error:j instanceof Error?j.message:String(j)})})},[l,c]);return i.useEffect(()=>{var L;if(!n){gg(o)&&p("inbox"),f(((L=e[0])==null?void 0:L.tabKey)||null),S.current=null;return}if(o!=="chat"){S.current=null;return}const A=`${n.tabKey}:${n.sessionId||""}`;S.current!==A&&(S.current=A,w(n))},[e,w,o,n,p,f]),i.useEffect(()=>{if(!d)return;const A=e.find(L=>L.tabKey===d);A&&(f(A.tabKey),p("chat"),m==null||m())},[e,m,d,p,f]),i.useEffect(()=>{if(!u)return;const A=s.find(L=>L.id===u);A&&(b(A.id),N(),y("machines"),x("inbox"),p("machine"),h==null||h())},[s,h,u,N,x,p,y,b]),i.useEffect(()=>{g&&(y(g),p("inbox"),v==null||v())},[v,g,p,y]),i.useEffect(()=>{const A=r.filter(L=>L.inboxBucket==="task_complete"||L.unread);A.length!==0&&zr("inbox_state",{screen:o,selectedTabKey:a,items:A.map(L=>{const k=mn(L.conversation,l);return{liveState:k,tabKey:L.conversation.tabKey,sessionId:L.conversation.sessionId,displayPrimary:lt(L.conversation),serverBucket:k.inboxBucket,computedBucket:L.inboxBucket,serverUnread:k.unread,computedUnread:L.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,activityAt:hs(L.conversation)}})})},[r,l,o,a]),{markConversationRead:w}}function vg(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function el(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function wg(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function jg({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,o]=i.useState("idle"),[l,c]=i.useState(""),[d,m]=i.useState(null),u=i.useCallback(()=>{o("idle"),c(""),m(null)},[]),h=i.useCallback(async(x,N,S)=>{var w;try{o("loading"),c(`Launching ${N}…`);const A={ideType:N,enableCdp:!0};(w=S==null?void 0:S.workspacePath)!=null&&w.trim()&&(A.workspace=S.workspacePath.trim()),await e(x,"launch_ide",A),o("done"),c(`${N} launch requested`)}catch(A){o("error"),c(A instanceof Error?A.message:"Launch IDE failed"),console.error("Launch IDE failed",A)}},[e]),g=i.useCallback(async(x,N,S)=>{if(N.trim())try{o("loading"),c(S!=null&&S.createIfMissing?"Creating folder…":"Saving workspace…");const w=await e(x,"workspace_add",{path:N.trim(),createIfMissing:(S==null?void 0:S.createIfMissing)===!0});if(w!=null&&w.success){o("done"),c(S!=null&&S.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}o("error"),c((w==null?void 0:w.error)||"Could not save workspace")}catch(w){o("error"),c(w instanceof Error?w.message:"Could not save workspace")}},[e]),v=i.useCallback(async x=>{var N,S,w,A,L,k;try{o("loading"),c("Starting daemon upgrade…");const j=await e(x,"daemon_upgrade",{});if((N=j==null?void 0:j.result)!=null&&N.alreadyLatest){o("done"),c(`Already on v${((S=j==null?void 0:j.result)==null?void 0:S.version)||"latest"}.`);return}if((w=j==null?void 0:j.result)!=null&&w.upgraded||(A=j==null?void 0:j.result)!=null&&A.success){o("done"),c(`Upgrade to v${((L=j==null?void 0:j.result)==null?void 0:L.version)||"latest"} started. Daemon is restarting…`);return}o("error"),c(((k=j==null?void 0:j.result)==null?void 0:k.error)||"Upgrade failed")}catch(j){o("error"),c(j instanceof Error?j.message:"Upgrade failed")}},[e]),f=i.useCallback(async(x,N,S,w)=>{var k,j,O;const A=Date.now(),L={machineId:x,kind:N,providerType:S,workspaceId:(w==null?void 0:w.workspaceId)||null,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:A};try{o("loading"),c(`Launching ${S}…`),m(L);const R={cliType:S};(k=w==null?void 0:w.workspacePath)!=null&&k.trim()?R.dir=w.workspacePath.trim():w!=null&&w.workspaceId&&(R.workspaceId=w.workspaceId),w!=null&&w.resumeSessionId&&(R.resumeSessionId=w.resumeSessionId),(j=w==null?void 0:w.args)!=null&&j.trim()&&(R.cliArgs=w.args.trim().split(/\s+/).filter(Boolean)),(O=w==null?void 0:w.model)!=null&&O.trim()&&(R.initialModel=w.model.trim());const T=await e(x,"launch_cli",R),F=(T==null?void 0:T.result)||T,W=(F==null?void 0:F.sessionId)||(F==null?void 0:F.id);if(T!=null&&T.success&&W){m(null),o("done"),c(`${S} launched`),s(ss(W));return}if(T!=null&&T.success){o("loading"),c(`${S} launch requested — waiting for session…`);return}m(null),o("error"),c((T==null?void 0:T.error)||(F==null?void 0:F.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(R){if(wg(R)){o("loading"),c(`${S} launch requested — waiting for session…`);return}m(null),o("error"),c(R instanceof Error?R.message:`Could not launch ${N.toUpperCase()} workspace`)}},[s,e]),p=i.useCallback(async(x,N)=>{try{const S=await e(x,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),w=(S==null?void 0:S.result)??S;return Array.isArray(w==null?void 0:w.sessions)?w.sessions:[]}catch(S){return console.error("Failed to list saved sessions on mobile:",S),[]}},[e]),b=i.useCallback(async(x,N)=>En(e,x,N),[e]);i.useEffect(()=>{if(!d)return;const x=el(d.workspacePath),N=r.find(w=>{var R,T,F,W;if(!w||w.type==="adhdev-daemon"||vg(w.daemonId||w.id)!==d.machineId||(w.transport==="acp"?"acp":w.transport==="pty"?"cli":null)!==d.kind||String(w.agentType||w.type||"")!==d.providerType)return!1;const j=String(w.providerSessionId||"");if(d.resumeSessionId&&j)return j===d.resumeSessionId;if(x){const D=el(w.workspace||w.runtimeWorkspaceLabel);return D?D===x:!1}return Number(w.lastUpdated||w._lastUpdate||w.timestamp||((W=(F=(T=(R=w.activeChat)==null?void 0:R.messages)==null?void 0:T.at)==null?void 0:F.call(T,-1))==null?void 0:W.timestamp)||0)>=d.startedAt-5e3});if(!N)return;const S=bd({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});S&&(m(null),o("done"),c(`${d.providerType} launched`),s(ss(S)))},[n,r,s,d]),i.useEffect(()=>{if(!d)return;const x=window.setTimeout(()=>{m(N=>!N||N.startedAt!==d.startedAt?N:(o("error"),c("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(x)},[d]);const y=i.useCallback(async(x,N)=>{if(N.kind==="ide"&&N.providerType){await h(x,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await f(x,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[h,f]);return{machineAction:{state:a,message:l},resetMachineAction:u,handleLaunchDetectedIde:h,handleAddWorkspace:g,handleMachineUpgrade:v,handleLaunchWorkspaceProvider:f,handleListSavedSessions:p,handleBrowseDirectory:b,handleOpenRecent:y}}function kg({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:l,setSelectedMachineId:c,setSection:d,setMachineBackTarget:m}){const u=i.useCallback(y=>{o(y.tabKey),l("chat"),n(y)},[n,l,o]),h=i.useCallback(y=>{const x=e.find(N=>N.routeId===y.routeId&&N.streamSource==="native");x&&(o(x.tabKey),l("chat"),n(x))},[e,n,l,o]),g=i.useCallback(()=>{n(s),l("inbox")},[n,s,l]),v=i.useCallback((y,x="inbox")=>{c(y),a(),d("machines"),m(x),l("machine")},[a,m,l,d,c]),f=i.useCallback(y=>{const x=ks(y);x&&v(x,"chat")},[v]),p=i.useCallback(()=>{a(),l(r)},[r,a,l]),b=i.useCallback(y=>{d(y),l("inbox")},[l,d]);return{openConversation:u,openNativeConversation:h,backFromConversation:g,openMachine:v,openConversationMachine:f,backFromMachine:p,changeMachineSection:b}}function ws(e,s){return e.category!==s?!1:s==="ide"?!0:e.enabled===!0}function Sg(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Ng({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:g,onRequestedMobileSectionConsumed:v,onOpenHistory:f,onOpenRemote:p,onStopCli:b,wsStatus:y,isConnected:x,onShowAllHiddenConversations:N,onHideConversation:S,onOpenMeshGraph:w,onOpenNewSession:A,liveSessionInboxState:L,setCliViewModeOverrides:k}){const[j,O]=i.useState(()=>{var se;return((se=e[0])==null?void 0:se.tabKey)||null}),[R,T]=i.useState(()=>e[0]?"chat":"inbox"),[F,W]=i.useState("chats"),[D,C]=i.useState(null),[I,K]=i.useState("inbox"),_=i.useRef([]),E=Hs(),V="0.9.81",Y=i.useMemo(()=>e.find(se=>se.tabKey===j)||e[0]||null,[e,j]),ge=i.useMemo(()=>Y?r.find(se=>se.id===Y.routeId):void 0,[r,Y]),pe=i.useMemo(()=>!Y||Ze(Y)||!st(Y)?null:zs(Y),[Y]),re=i.useMemo(()=>r.filter(se=>se.type==="adhdev-daemon").sort(bo),[r]),de=i.useMemo(()=>re.find(se=>se.id===D)||null,[re,D]),ke=Ln({sendDaemonCommand:a,activeConv:Y||void 0,setActionLogs:o,isStandalone:l}),ye=jg({sendDaemonCommand:a,navigate:E,ides:r,conversations:e}),q=i.useMemo(()=>e.map(se=>{const ve=R==="chat"&&(Y==null?void 0:Y.tabKey)===se.tabKey,Ie=Tn(se,L,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ve}),Me=hs(se),B=Mc(se);return{conversation:se,timestamp:Me,preview:B,unread:Ie.unread,requiresAction:Ie.requiresAction,isWorking:Ie.isWorking,inboxBucket:Ie.inboxBucket}}),[e,L,R,Y]),{markConversationRead:he}=yg({conversations:e,machineEntries:re,items:q,selectedConversation:Y,selectedTabKey:j,screen:R,liveSessionInboxState:L,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:g,onRequestedMobileSectionConsumed:v,setSelectedTabKey:O,setScreen:T,setSelectedMachineId:C,setSection:W,setMachineBackTarget:K,resetMachineAction:ye.resetMachineAction}),fe=kg({conversations:e,selectedConversation:Y,machineBackTarget:I,markConversationRead:he,resetMachineAction:ye.resetMachineAction,setSelectedTabKey:O,setScreen:T,setSelectedMachineId:C,setSection:W,setMachineBackTarget:K}),we=i.useMemo(()=>sn(q.filter(se=>se.requiresAction)),[q]),xe=i.useMemo(()=>sn(q.filter(se=>se.unread&&!se.requiresAction)),[q]),Se=i.useMemo(()=>fg(q.filter(se=>!se.unread&&!se.requiresAction&&se.isWorking),_.current),[q]);i.useEffect(()=>{_.current=Se.map(se=>se.conversation.tabKey)},[Se]);const Q=i.useMemo(()=>sn(q.filter(se=>!se.unread&&!se.requiresAction&&!se.isWorking)),[q]),ue=i.useMemo(()=>de?q.filter(se=>ks(se.conversation)===de.id):[],[q,de]),oe=i.useMemo(()=>xg(de,r),[r,de]),me=(de==null?void 0:de.version)||null,le=!!de&&!!me&&!0&&me!==V,P=i.useMemo(()=>(de==null?void 0:de.availableProviders)||[],[de]),U=i.useMemo(()=>P.filter(se=>ws(se,"cli")).map(se=>({type:se.type,displayName:se.displayName||se.type,icon:se.icon})),[P]),ce=i.useMemo(()=>P.filter(se=>ws(se,"acp")).map(se=>({type:se.type,displayName:se.displayName||se.type,icon:se.icon})),[P]),te=i.useMemo(()=>bg(re,q),[q,re]),ie=i.useCallback(async se=>{de&&await ye.handleOpenRecent(de.id,se)},[ye,de]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:R==="chat"&&Y?t.jsx(ng,{selectedConversation:Y,isAcp:Ze(Y),isStandalone:l,selectedIdeEntry:ge,actionLogs:n,userName:c,isSendingChat:ke.isSendingChat,sendFeedbackMessage:ke.sendFeedbackMessage,isFocusingAgent:ke.isFocusingAgent,handleModalButton:ke.handleModalButton,handleRelaunch:ke.handleRelaunch,onBack:fe.backFromConversation,onOpenNativeConversation:fe.openNativeConversation,onOpenMachine:fe.openConversationMachine,onOpenHistory:f,onOpenRemote:p,onOpenMeshGraph:w,onStopCli:b,cliViewMode:pe,onSetCliViewMode:async se=>{await nd({conversation:Y,mode:se,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:k})},handleSendChat:ke.handleSendChat,handleFocusAgent:ke.handleFocusAgent}):R==="machine"&&de?t.jsx(pg,{selectedMachineEntry:de,selectedMachineConversations:ue,selectedMachineRecentLaunches:oe,cliProviders:U,acpProviders:ce,selectedMachineNeedsUpgrade:le,appVersion:V,machineAction:ye.machineAction,isStandalone:l,section:F,showBottomNav:I==="inbox",onBack:fe.backFromMachine,onSectionChange:fe.changeMachineSection,onOpenConversation:fe.openConversation,onOpenRecent:ie,onOpenMachineDetails:()=>E(`/machines/${de.id}`),onMachineUpgrade:()=>ye.handleMachineUpgrade(de.id),onLaunchDetectedIde:(se,ve)=>ye.handleLaunchDetectedIde(de.id,se,ve),onAddWorkspace:(se,ve)=>ye.handleAddWorkspace(de.id,se,ve),onBrowseDirectory:se=>ye.handleBrowseDirectory(de.id,se),onLaunchWorkspaceProvider:(se,ve,Ie)=>ye.handleLaunchWorkspaceProvider(de.id,se,ve,Ie),onListSavedSessions:se=>ye.handleListSavedSessions(de.id,se)}):t.jsx(ig,{section:F,attentionItems:we,unreadItems:xe,workingItems:Se,completedItems:Q,hiddenConversations:s,machineCards:te,getAvatarText:Sg,actionLogs:n,sendDaemonCommand:a,onOpenConversation:fe.openConversation,onShowAllHidden:N,onHideConversation:S,onOpenMeshGraph:w,onOpenNewSession:A,onOpenMachine:fe.openMachine,onOpenSettings:()=>E("/settings"),onSectionChange:W,wsStatus:y,isConnected:x,isStandalone:l})})}function ma(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function Cg({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const l=i.useRef(0),[c,d]=i.useState(!1),[m,u]=i.useState(null),h=i.useCallback(()=>{l.current=0,d(!1),u(null)},[]);i.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const g=i.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(l.current+=1,d(!0))},[]),v=i.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!ma(s,r)){u("merge");return}const y=b.currentTarget.getBoundingClientRect(),x=b.clientX-y.left,N=y.width/3;x<N?u("split-left"):x>N*2?u("split-right"):u("merge")},[s,r]),f=i.useCallback(()=>{l.current-=1,!(l.current>0)&&(l.current=0,d(!1),u(null))},[]),p=i.useCallback(b=>{l.current=0,d(!1);const y=b.dataTransfer.getData("text/tab-key"),x=y?e.some(S=>S.tabKey===y):!1,N=m;if(u(null),o(),!!y){if(b.preventDefault(),N==="split-left"&&ma(s,r)){r==null||r(y,"split-left");return}if(N==="split-right"&&ma(s,r)){r==null||r(y,"split-right");return}if(x){a(y);return}n==null||n(y)}},[e,m,s,r,n,a,o]);return{dragOver:c,dropAction:m,resetDragState:h,handleDragEnter:g,handleDragOver:v,handleDragLeave:f,handleDrop:p}}function Ig(e,s){const r=new Set(s.map(o=>o.tabKey)),n=e.filter(o=>r.has(o)),a=s.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...n,...a]}function Tg({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,l]=i.useState(s??null),[c,d]=i.useState(r??[]),[m,u]=i.useState(null),h=i.useRef(null),g=i.useRef(null),v=i.useRef(n),f=i.useRef(a);i.useEffect(()=>{v.current=n},[n]),i.useEffect(()=>{f.current=a},[a]),i.useEffect(()=>{s&&s!==o&&l(s)},[s,o]),i.useEffect(()=>{d(L=>{const k=Ig(L,e);return k.length===L.length&&k.every((j,O)=>j===L[O])?L:k})},[e]);const p=i.useMemo(()=>{const L=m??c;if(L.length===0)return e;const k=new Map(L.map((j,O)=>[j,O]));return[...e].sort((j,O)=>{const R=k.get(j.tabKey)??999,T=k.get(O.tabKey)??999;return R-T})},[e,m,c]);i.useEffect(()=>{var k,j;if(p.length===0){o!==null&&(l(null),(k=v.current)==null||k.call(v,null));return}if(o&&p.some(O=>O.tabKey===o))return;const L=p[0].tabKey;L!==o&&(l(L),(j=v.current)==null||j.call(v,L))},[p,o]);const b=i.useMemo(()=>p.find(L=>L.tabKey===o),[p,o]),y=i.useCallback(L=>{var k;l(L),(k=v.current)==null||k.call(v,L)},[]),x=i.useCallback((L,k,j)=>{d(O=>{var W;const R=O.filter(D=>D!==L),T=R.indexOf(k);if(T<0)return O;const F=j==="left"?T:T+1;return R.splice(F,0,L),(W=f.current)==null||W.call(f,R),R}),u(null)},[]),N=i.useCallback((L,k,j)=>{const R=(c.length>0?c:e.map(W=>W.tabKey)).filter(W=>W!==L),T=R.indexOf(k);if(T<0)return;const F=j==="left"?T:T+1;R.splice(F,0,L),h.current=R,u(R)},[c,e]),S=i.useCallback(()=>{var k;const L=h.current;L&&(d(L),(k=f.current)==null||k.call(f,L))},[]),w=i.useCallback(()=>{h.current=null,u(null)},[]),A=i.useCallback(L=>{d(k=>{var O;const j=k.filter(R=>R!==L);return j.push(L),(O=f.current)==null||O.call(f,j),j})},[]);return{activeTabId:o,activeConv:b,sortedConversations:p,previewOrderRef:h,draggingTabRef:g,selectTab:y,handleTabReorder:x,updatePreviewOrder:N,commitPreviewOrder:S,clearPreviewOrder:w,moveTabToEnd:A,setDraggingTabKey:L=>{g.current=L}}}function Ag({dropAction:e,canSplit:s}){return t.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[t.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:s?1:.45},children:t.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"})}),t.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:t.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"})}),t.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:s?1:.45},children:t.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 Fo({conversationsCount:e,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:o}){if(a)return t.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const l=!r&&!n,c=n&&!!o,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?Pc:r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!s?t.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[t.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),t.jsxs("div",{className:"text-center max-w-lg",children:[t.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),t.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),c&&t.jsx("div",{className:"flex items-center justify-center mb-4",children:t.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Ot,"aria-label":Ot,children:[t.jsx(zl,{size:14}),t.jsx("span",{children:Ot})]})}),l&&t.jsx(vd,{}),l&&t.jsx("div",{className:"mt-8",children:t.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 →"})})]})]}):t.jsx("div",{className:"text-sm text-text-muted opacity-50",children:s?"Move a tab here to view":"No active agent"})}const Sd="adhdev-tab-shortcuts";function Nd(){try{return JSON.parse(localStorage.getItem(Sd)||"{}")}catch{return{}}}function Cd({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,l]=i.useState(()=>Nd()),[c,d]=i.useState(null),m=i.useCallback(h=>{const g=[];return h.metaKey&&g.push(a?"⌘":"Meta"),h.ctrlKey&&g.push("Ctrl"),h.altKey&&g.push(a?"⌥":"Alt"),h.shiftKey&&g.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(g.push(h.key.length===1?h.key.toUpperCase():h.key),g.join("+"))},[a]),u=i.useCallback(h=>{l(h);try{localStorage.setItem(Sd,JSON.stringify(h))}catch{}},[]);return i.useEffect(()=>{if(!e||!c)return;const h=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){d(null);return}const v=m(g);if(!v)return;const f={...o};for(const[p,b]of Object.entries(f))b===v&&delete f[p];f[c]=v,u(f),d(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,c,o,u,m]),i.useEffect(()=>{if(!e)return;const h=g=>{if(!(!g.ctrlKey&&!g.metaKey&&!g.altKey)){for(const[v,f]of Object.entries(o))if(s.includes(v)&&m(g)===f){g.preventDefault(),r(),n(v);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,o,s,r,n,m]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const pa=e=>{e.preventDefault()},Mg=i.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:l,draggingTabRef:c,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:h,onReorderTab:g,onCommitPreviewOrder:v,onClearPreviewOrder:f,onDragStateReset:p,onDragTabKeyChange:b,onReceiveTab:y,onOpenContextMenu:x,longPressTimer:N,isGroupActive:S}){const w=Us(s),A=w.isGenerating?"agent-tab-generating":w.isWaiting?"agent-tab-waiting":"",L=w.isReconnecting,k=i.useCallback(I=>{c.current=s.tabKey,b(s.tabKey),I.dataTransfer.setData("text/tab-key",s.tabKey),I.dataTransfer.effectAllowed="move"},[s.tabKey,c,b]),j=i.useCallback(()=>{c.current=null,b(null),v(),f(),p()},[c,b,v,f,p]),O=i.useCallback(I=>{const K=c.current;if(!(!K||K===s.tabKey)&&I.dataTransfer.types.includes("text/tab-key")){I.preventDefault(),I.stopPropagation();const _=I.currentTarget.getBoundingClientRect(),E=I.clientX<_.left+_.width/2?"left":"right";h(K,s.tabKey,E)}},[s.tabKey,c,h]),R=i.useCallback(I=>{I.preventDefault(),I.stopPropagation();const K=I.dataTransfer.getData("text/tab-key");if(K&&K!==s.tabKey){const _=I.currentTarget.getBoundingClientRect(),E=I.clientX<_.left+_.width/2?"left":"right";l.includes(K)?g(K,s.tabKey,E):y&&y(K)}f()},[s.tabKey,l,g,y,f]),T=i.useCallback(I=>{I.stopPropagation(),d(),m(s.tabKey),u(s)},[s,u,d,m]),F=i.useCallback(I=>{I.preventDefault(),x(I.clientX,I.clientY,s.tabKey)},[s.tabKey,x]),W=i.useCallback(I=>{const K=I.touches[0];N.current=setTimeout(()=>{x(K.clientX,K.clientY,s.tabKey)},600)},[s.tabKey,N,x]),D=i.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),C=["adhdev-dockview-tab",A,r&&"is-active",S&&"is-group-active",L&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:C,draggable:!0,onDragStart:k,onDragEnd:j,onDragOver:O,onDrop:R,onClick:T,onContextMenu:F,onTouchStart:W,onTouchEnd:D,onTouchMove:D,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status",children:w.isGenerating?t.jsx("div",{className:"tab-spinner"}):w.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):L?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):w.isConnecting?t.jsx("div",{className:"tab-connecting-spinner"}):s.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("span",{className:"adhdev-dockview-tab-primary",title:lt(s),children:lt(s)}),t.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[L?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:ds(s)}):w.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[ds(s),t.jsx("span",{className:"connecting-dots"})]}):t.jsx("span",{className:"truncate",children:ds(s)}),t.jsx(Os,{git:s.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),o&&t.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,s)=>e.conv===s.conv&&e.isActive===s.isActive&&e.isDraggedTab===s.isDraggedTab&&e.isTaskCompleteUnread===s.isTaskCompleteUnread&&e.shortcut===s.shortcut&&e.conversationKeys===s.conversationKeys&&e.isGroupActive===s.isGroupActive);function Lg({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:l,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:g,onDragTabKeyChange:v,onReceiveTab:f,onHideTab:p,isGroupActive:b,allowTabShortcuts:y=!0}){const[x,N]=i.useState(null),S=i.useRef(null),w=i.useRef(null),A=i.useMemo(()=>e.map(F=>F.tabKey),[e]);jr("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(x==null?void 0:x.tabKey)||null});const{isMac:L,tabShortcuts:k,shortcutListening:j,setShortcutListening:O,saveShortcuts:R}=Cd({enabled:y,sortedTabKeys:e.map(F=>F.tabKey),onFocus:o,onSelectTab:l});i.useEffect(()=>{if(!x)return;const F=W=>{const D=document.querySelector("[data-pane-context-menu]");D&&D.contains(W.target)||N(null)};return window.addEventListener("mousedown",F,!0),()=>window.removeEventListener("mousedown",F,!0)},[x]),i.useEffect(()=>{const F=w.current;if(!F)return;const W=D=>{Math.abs(D.deltaY)<=Math.abs(D.deltaX)||(D.preventDefault(),F.scrollLeft+=D.deltaY)};return F.addEventListener("wheel",W,{passive:!1}),()=>F.removeEventListener("wheel",W)},[]);const T=i.useCallback((F,W,D)=>{N({x:F,y:W,tabKey:D})},[]);return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:t.jsxs("div",{ref:w,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(F=>t.jsx(Mg,{conv:F,isActive:s===F.tabKey,isDraggedTab:a.current===F.tabKey,isTaskCompleteUnread:n.has(F.tabKey),shortcut:y?k[F.tabKey]:void 0,conversationKeys:A,draggingTabRef:a,onFocus:o,onSelectTab:l,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:g,onDragTabKeyChange:v,onReceiveTab:f,onOpenContextMenu:T,longPressTimer:S,isGroupActive:b},F.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),x&&t.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:x.x,top:x.y},children:[y&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:pa,onClick:F=>{F.stopPropagation(),O(x.tabKey),N(null)},children:["⌨ ",k[x.tabKey]?`Change shortcut (${k[x.tabKey]})`:"Set shortcut"]}),k[x.tabKey]&&t.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:pa,onClick:()=>{const F={...k};delete F[x.tabKey],R(F),N(null)},children:"✕ Remove shortcut"})]}),p&&t.jsxs(t.Fragment,{children:[y&&t.jsx("div",{className:"border-t border-border-subtle my-1"}),t.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:pa,onClick:()=>{p(x.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&j&&t.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:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:F=>F.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",L?"⌘+1":"Ctrl+1",", ",L?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Rg({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,hasRegisteredMachines:c,userName:d,groupIndex:m,onFocus:u,isSplitMode:h,numGroups:g,onMoveTab:v,onReceiveTab:f,style:p,onActiveTabChange:b,initialActiveTabId:y,initialTabOrder:x,onTabOrderChange:N,onHideTab:S,isFocused:w,allowTabShortcuts:A=!0,onOpenNewSession:L,liveSessionInboxState:k}){const{sendCommand:j}=yt(),O=i.useRef(null),{activeTabId:R,activeConv:T,sortedConversations:F,draggingTabRef:W,selectTab:D,handleTabReorder:C,updatePreviewOrder:I,commitPreviewOrder:K,clearPreviewOrder:_,moveTabToEnd:E,setDraggingTabKey:V}=Tg({conversations:e,initialActiveTabId:y,initialTabOrder:x,onActiveTabChange:b,onTabOrderChange:N}),Y=Ln({sendDaemonCommand:a,activeConv:T,setActionLogs:o,isStandalone:l}),{dragOver:ge,dropAction:pe,resetDragState:re,handleDragEnter:de,handleDragOver:ke,handleDragLeave:ye,handleDrop:q}=Cg({conversations:e,numGroups:g,onMoveTab:v,onReceiveTab:f,onOwnTabDrop:E,onClearPreviewOrder:_}),he=T&&!Ze(T)&&zs(T)==="terminal",fe=i.useMemo(()=>T?s.find(Q=>Q.id===T.routeId):void 0,[s,T]),we=i.useMemo(()=>T?n.filter(Q=>Q.routeId===T.tabKey):[],[n,T]),xe=i.useMemo(()=>new Set(F.filter(Q=>lp(Q,k,{isOpenConversation:Q.tabKey===R})).map(Q=>Q.tabKey)),[R,k,F]);jr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:R,dragOver:ge});const Se=i.useCallback(Q=>{Q.streamSource==="agent-stream"&&Q.agentType&&j(Q.routeId,xc(),{agentType:Q.agentType,...Q.sessionId&&{targetSessionId:Q.sessionId}}).catch(()=>{})},[j]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...p,outline:ge?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(Lg,{conversations:F,activeTabId:R,groupIndex:m,numGroups:g,unreadTabKeys:xe,draggingTabRef:W,onFocus:u,onSelectTab:D,onConversationActivated:Se,onPreviewReorder:I,onReorderTab:C,onCommitPreviewOrder:K,onClearPreviewOrder:_,onDragStateReset:re,onDragTabKeyChange:V,onMoveTab:v,onReceiveTab:f,onHideTab:S,isGroupActive:w??!1,allowTabShortcuts:A}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:de,onDragOver:ke,onDragLeave:ye,onDrop:q,children:[ge&&t.jsx(Ag,{dropAction:pe,canSplit:!!(g<4&&v)}),T?t.jsx(Oo,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!he,ideEntry:fe,terminalRef:O,handleModalButton:Y.handleModalButton,handleRelaunch:Y.handleRelaunch,handleSendChat:Y.handleSendChat,isSendingChat:Y.isSendingChat,sendFeedbackMessage:Y.sendFeedbackMessage,handleFocusAgent:Y.handleFocusAgent,isFocusingAgent:Y.isFocusingAgent,actionLogs:we,userName:d,isInputActive:!h||!!w}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(Fo,{conversationsCount:e.length,isSplitMode:h,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:L})})]})]})}function _g({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:l,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,userName:g,focusedGroup:v,focusGroup:f,moveTabToGroup:p,splitTabRelative:b,closeGroup:y,handleResizeStart:x,groupActiveTabIds:N,setGroupActiveTab:S,groupTabOrders:w,setGroupTabOrder:A,toggleHiddenTab:L,onOpenNewSession:k,allowTabShortcuts:j=!0,liveSessionInboxState:O}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map((R,T)=>{const F=s&&n.length===r?`${n[T]}%`:void 0;return t.jsxs(wt.Fragment,{children:[s&&T>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:W=>x(T-1,W),onDoubleClick:()=>y(T),title:"Drag to resize · Double-click to merge",children:t.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),t.jsx(Rg,{style:s?{flexBasis:F??`${100/r}%`,flexGrow:F?0:1,flexShrink:F?0:1}:void 0,conversations:R,clearedTabs:o,ides:l,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,userName:g,groupIndex:T,isFocused:s&&v===T,onFocus:()=>f(T),isSplitMode:s,numGroups:r,onMoveTab:(W,D)=>{D==="left"&&T>0?p(W,T-1):D==="right"&&T<r-1?p(W,T+1):D==="split-left"&&r<4?b(W,T,"left"):D==="split-right"&&r<4&&b(W,T,"right")},onReceiveTab:W=>p(W,T),onActiveTabChange:W=>S(T,W),initialActiveTabId:N[T],initialTabOrder:w[T],onTabOrderChange:W=>A(T,W),onHideTab:L,onOpenNewSession:k,allowTabShortcuts:j,liveSessionInboxState:O})]},T)})})}function Id({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,o]=i.useState(null),[l,c]=i.useState(null);i.useEffect(()=>e?ct.onScreenshot("ide-page",(u,h)=>{if(u!==e)return;const g=new FileReader;g.onload=()=>o(g.result),g.readAsDataURL(h)}):void 0,[e]),i.useEffect(()=>{r!=="connected"&&o(null)},[r]),i.useEffect(()=>{var u;return e?((u=ct.onStatus)==null?void 0:u.call(ct,(h,g)=>{h===e&&g!=null&&g.screenshotUsage&&c(g.screenshotUsage)}))||(()=>{}):void 0},[e]),i.useEffect(()=>{o(null)},[e,s]),i.useEffect(()=>{const m=e?ct.get(e):null;if(!(!m||r!=="connected"))return n!=="chat"&&s?m.startScreenshots(s):m.stopScreenshots(s),()=>{m.stopScreenshots(s)}},[n,r,s,e]);const d=i.useCallback(async(m,u)=>{const h=e?ct.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(m,u,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:l,handleRemoteAction:d}}const Td="adhdev-dashboard-action-shortcuts",Pg=1200,Dg=[["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 Eg(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function at(e,s){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return s?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return s?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return s?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return s?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return s?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return s?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return s?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return s?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return s?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return s?"⌘+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 s?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return s?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return s?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return s?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return s?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return s?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return s?"⌥+T":"Ctrl+Alt+T"}}function Ad(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:at("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:at("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:at("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:at("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:at("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:at("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:at("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:at("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:at("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:at("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:at("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:at("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:at("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:at("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:at("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:at("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:at("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:at("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:at("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:at("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:at("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:at("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:at("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:at("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:at("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:at("toggleCliView",e)}]}function Ja(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function kn(e){const s=Object.fromEntries(Ad(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Td)||"{}"),n={...s,...r};for(const[a,o]of Dg)n[a]===o&&(n[a]=s[a]);return n}catch{return s}}function Md(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function $g({enabled:e=!0,onTrigger:s}){const r=Eg(),[n,a]=i.useState(()=>kn(r)),[o,l]=i.useState(null),[c,d]=i.useState([]),m=i.useRef({parts:[],timer:null}),u=i.useCallback(p=>{const b=[];return p.metaKey&&b.push(r?"⌘":"Meta"),p.ctrlKey&&b.push("Ctrl"),p.altKey&&b.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&b.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(b.push(Md(p.key)),b.join("+"))},[r]),h=i.useCallback(p=>{a(p);try{localStorage.setItem(Td,JSON.stringify(p))}catch{}},[]);i.useEffect(()=>{const p=kn(r),b=Object.entries(n),y=Object.entries(p);b.length===y.length&&b.every(([x,N])=>p[x]===N)||h(p)},[n,r,h]);const g=i.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),v=i.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},Pg))},[]);i.useEffect(()=>{if(!o)return;const p=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){l(null),d([]);return}const y=u(b);if(!y)return;const N=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(y);if(c.length===0&&N){d([y]);return}const w=[...c,y].slice(0,2).join(" "),A={...n};for(const[L,k]of Object.entries(A))k===w&&delete A[L];A[o]=w,h(A),l(null),d([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,u,h,o,c]),i.useEffect(()=>{if(!e||o)return;const p=b=>{if(b.defaultPrevented)return;const y=u(b);if(!y)return;const x=b.metaKey||b.ctrlKey||b.altKey;if(Ja(b.target))return;const N=m.current.parts,S=x?[y]:[...N.slice(-1),y].slice(-2),w=S.join(" "),A=S[S.length-1],L=Object.entries(n).filter(([,T])=>!!T),k=L.find(([,T])=>T===w);if(k){b.preventDefault(),g(),s(k[0]);return}if(L.some(([,T])=>T.startsWith(`${w} `))){b.preventDefault(),m.current.parts=S,v();return}const O=L.find(([,T])=>T===A);if(O){b.preventDefault(),g(),s(O[0]);return}if(L.some(([,T])=>T.startsWith(`${A} `))){b.preventDefault(),m.current.parts=[A],v();return}g()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,v,e,u,s,g,o]),i.useEffect(()=>()=>g(),[g]);const f=i.useMemo(()=>Ad(r),[r]);return{isMac:r,actionDefinitions:f,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:l,setShortcutListeningDraft:d,saveShortcuts:h}}function Bg({isTabInPopout:e,isTabFloating:s,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(s&&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})):s?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 Ld(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function tl({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!Ld(n):!0}function Og({previousVisibleConversationCount:e,visibleConversationCount:s,ides:r}){return s>0||e<=0?!1:Ld(r)}const Rd=1e3,Kg=4;function sl(e,s){return s?e.clientX>=s.left&&e.clientX<=s.right&&e.clientY>=s.top&&e.clientY<=s.bottom:!1}function rl(e,s,r){return Math.abs(s.clientX-e.clientX)>r||Math.abs(s.clientY-e.clientY)>r}function Fg({detachDelayMs:e=Rd,stillnessThresholdPx:s=Kg,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,l=null,c=null,d=null,m=null,u=!1;const h=()=>{m!=null&&(a(m),m=null)},g=()=>{h(),c=null},v=()=>{h(),o=null,l=null,c=null,d=null,u=!1},f=()=>{!o||!c||!d||u||m!=null||(m=n(()=>{m=null,!(!o||!c||!d||u)&&sl(d,l)&&(rl(c,d,s)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},p=y=>{if(!(!o||u)){if(!sl(y,l)){d={clientX:y.clientX,clientY:y.clientY},g();return}(!c||rl(c,y,s))&&(h(),c={clientX:y.clientX,clientY:y.clientY}),d={clientX:y.clientX,clientY:y.clientY},f()}},b=y=>{!o||u||(y&&(d={clientX:y.clientX,clientY:y.clientY}),g())};return{startDrag:y=>{h(),o=y.panelId,l=y.selfPanelBounds??null,c=null,d={clientX:y.clientX,clientY:y.clientY},u=!1},markSelfPanel:p,markNonSelfPanel:b,markNoDropTarget:b,markDockTarget:b,endDrag:v,isDragging:()=>o!=null,hasDetached:()=>u,dispose:v}}function Wg(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Vr(e){return e.isActive}function nl(e){return e.isVisible}const _d=i.createContext(null);function Bn(){const e=i.useContext(_d);if(!e)throw new Error("DashboardDockviewContext missing");return e}function rn(e){return lt(e)||e.tabKey}function Hg(e){return`remote:${e}`}function _t(e){return e.startsWith("remote:")}function al(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Ug(e){e.preventDefault()}function fa(e){var n;const s=e==null?void 0:e.defaultView;if(!s)return;const r=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{s.focus(),r(e==null?void 0:e.body),r(e==null?void 0:e.documentElement),(n=s.requestAnimationFrame)==null||n.call(s,()=>{try{s.focus(),r(e==null?void 0:e.body)}catch{}})}catch{}}function ha(e,s){e.classList.remove(La.className,Ra.className),e.classList.add(s==="light"?La.className:Ra.className)}function ol(e){return e?Array.from(new Set(e.groups.map(s=>{var r,n;return(n=(r=s.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(s=>!!s&&s!==window))):[]}function zg(e){const[,s]=i.useState(0);i.useEffect(()=>{const r=()=>s(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 Vg(e,s,r){var l;const n=[s];let a;for(const c of n){let d;for(const m of c){const u=e.addPanel({id:m.tabKey,component:"conversation",title:rn(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??((l=s[0])==null?void 0:l.tabKey)??null}function il(e,s){const r=new Set(s.map(a=>a.tabKey)),n=new Map;for(const a of s)n.set(a.tabKey,(n.get(a.tabKey)||0)+1);for(const a of[...e.panels])_t(a.id)||r.has(a.id)||e.removePanel(a);for(const a of s){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!==rn(a)&&o.api.setTitle(rn(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:rn(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 ll(e,s,r){var d,m;const n=r?Hg(r):null;for(const u of[...e.panels])_t(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Et(s,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),l=_c(a);if(o){o.title!==l&&o.api.setTitle(l);return}const c=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((m=e.panels.find(u=>!_t(u.id)))==null?void 0:m.id);e.addPanel({id:n,component:"remote",title:l,params:{kind:"remote",routeId:r},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function Gg({params:e,api:s}){var v;const r=Bn(),n=i.useRef(null),[a,o]=i.useState(()=>Vr(s)),[l,c]=i.useState(()=>nl(s)),d=r.conversationsByTabKey.get(e.tabKey),m=Ln({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});i.useEffect(()=>{o(Vr(s)),c(nl(s));const f=[s.onDidActiveChange(p=>o(p.isActive)),s.onDidActiveGroupChange(p=>{if(!Vr(s)&&!p.isActive){o(!1);return}o(Vr(s))}),s.onDidVisibilityChange(p=>c(p.isVisible))];return()=>{for(const p of f)p.dispose()}},[s]);const u=i.useMemo(()=>d?r.ides.find(f=>f.id===d.routeId):void 0,[r.ides,d]),h=i.useMemo(()=>d?r.actionLogs.filter(f=>f.routeId===d.tabKey):[],[r.actionLogs,d]);if(!d)return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:t.jsx(Fo,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const g=!Ze(d)&&zs(d)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(Oo,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:g,ideEntry:u,terminalRef:n,handleModalButton:m.handleModalButton,handleRelaunch:m.handleRelaunch,handleSendChat:m.handleSendChat,isSendingChat:m.isSendingChat,handleFocusAgent:m.handleFocusAgent,isFocusingAgent:m.isFocusingAgent,actionLogs:h,userName:r.userName,scrollToBottomRequestNonce:((v=r.scrollToBottomRequest)==null?void 0:v.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:l})})}function qg({params:e}){var d;const s=Bn(),r=i.useMemo(()=>Et([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=i.useMemo(()=>s.ides.find(m=>m.id===e.routeId),[s.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:l,handleRemoteAction:c}=Id({doId:a,targetSessionId:r?hc(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?t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:t.jsx(Zl,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:o,screenshotUsage:l,transportType:r.transport,onAction:c})}):t.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 Yg(){const e=Bn();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(Fo,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Xg(e){var v,f;zg(e);const s=Bn(),r=i.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=Et([...s.conversationsByTabKey.values()],e.params.routeId),b=((v=e.api.group.activePanel)==null?void 0:v.id)===e.api.id,y=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${y?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:p!=null&&p.machineName?t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Live remote view"}),t.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),t.jsx("span",{className:"adhdev-dockview-tab-machine",children:p.machineName})]}):t.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(e.params.tabKey);if(!n)return t.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:t.jsx("div",{className:"adhdev-dockview-tab-copy",children:t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((f=e.api.group.activePanel)==null?void 0:f.id)===e.api.id,o=e.api.isGroupActive,l=Tn(n,s.liveSessionInboxState,{isOpenConversation:a}),c=l.isReconnecting,d=l.isConnecting,m=l.isGenerating,u=l.isWaiting,h=l.unread,g=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${o?" is-group-active":""}${c?" is-reconnecting":""}`,title:lt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var b;p.preventDefault(),r(p),s.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((b=p.target)==null?void 0:b.ownerDocument)??document})},children:[h&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:m?t.jsx("div",{className:"tab-spinner"}):u?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):c?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):d?t.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:lt(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:c?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ds(n)}):d?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ds(n)}):t.jsx("span",{children:ds(n)})})]}),g&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:g,children:g})]})}function Jg({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,hasRegisteredMachines:c,initialDataLoaded:d,userName:m,toggleHiddenTab:u,actionShortcuts:h,registerActionHandlers:g,onActiveTabChange:v,onOpenNewSession:f,onRequestScrollToBottom:p,requestedActiveTabKey:b,requestedRemoteIdeId:y,onRequestedActiveTabConsumed:x,scrollToBottomRequest:N,liveSessionInboxState:S,layoutProfile:w}){var Qe,ze,rt;const{theme:A}=_o(),{sendCommand:L}=yt(),k=i.useRef(null),j=i.useRef(null),O=i.useRef(null),R=i.useRef(!1),T=i.useRef(!1),F=i.useRef(!1),W=i.useRef(null),D=i.useRef([]),[C,I]=i.useState(null),[K,_]=i.useState(0),E=i.useRef(typeof window>"u"?{}:hb(w)),V=i.useMemo(()=>new Map(e.map(H=>[H.tabKey,H])),[e]),Y=i.useMemo(()=>{const H=k.current;return H?H.groups.some(z=>{try{const J=z.model.location.type;return J!=="floating"&&J!=="popout"?!1:z.panels.some(ne=>V.has(ne.id))}catch{return!1}}):!1},[V,K,e]),ge=i.useCallback(()=>{var H;(H=k.current)==null||H.focus()},[]),pe=i.useCallback((H,z)=>{p==null||p(H,z)},[p]),re=i.useCallback(H=>{const z=document,J=H.document;for(const ae of z.querySelectorAll('link[rel="stylesheet"]')){const je=J.createElement("link");je.rel="stylesheet",je.href=ae.href,ae.crossOrigin&&(je.crossOrigin=ae.crossOrigin),J.head.appendChild(je)}for(const ae of z.querySelectorAll("style")){const je=J.createElement("style");je.textContent=ae.textContent,J.head.appendChild(je)}const ne=[];for(const ae of z.styleSheets)try{for(const je of ae.cssRules)je instanceof CSSStyleRule&&(je.selectorText===":root"||je.selectorText==="html")&&ne.push(je.cssText)}catch{}if(ne.length>0){const ae=J.createElement("style");ae.textContent=ne.join(`
54
+ `),J.head.appendChild(ae)}const $=z.documentElement.getAttribute("data-theme");$&&J.documentElement.setAttribute("data-theme",$),J.documentElement.style.colorScheme=$==="light"?"light":"dark",J.body.className=z.body.className;const G=z.documentElement.getAttribute("style");G&&J.documentElement.setAttribute("style",G);const ee=J.getElementById("dv-popout-window");ee instanceof HTMLElement&&(ee.classList.add("adhdev-dockview"),ha(ee,A))},[A]),de=i.useCallback(()=>{var z;const H=k.current;if(H)for(const J of H.groups)try{const ne=(z=J.element)==null?void 0:z.ownerDocument;if(!ne||ne===document)continue;const $=ne.getElementById("dv-popout-window");$ instanceof HTMLElement&&($.classList.add("adhdev-dockview"),ha($,A));const G=document.documentElement.getAttribute("data-theme");G&&ne.documentElement.setAttribute("data-theme",G),ne.documentElement.style.colorScheme=G==="light"?"light":"dark",ne.body.className=document.body.className;const ee=document.documentElement.getAttribute("style");ee?ne.documentElement.setAttribute("style",ee):ne.documentElement.removeAttribute("style")}catch{}},[A]),ke=i.useCallback(H=>{const z=k.current;if(!z)return;const J=z.getPanel(H);J&&z.addPopoutGroup(J,{popoutUrl:"/popout.html",onDidOpen:({window:ne})=>{re(ne),ue();const $=V.get(H);ne.document.title=$?`${lt($)} — ADHDev`:"ADHDev — Popout"}})},[V,re]),ye=i.useCallback(H=>{const z=k.current,J=z==null?void 0:z.getPanel(H);if(!z||!J)return;const ne=z.groups.filter($=>{var G;try{return((G=$.element)==null?void 0:G.ownerDocument)===document}catch{return!0}});ne.length>0?J.api.moveTo({group:ne[0],position:"center"}):J.api.moveTo({position:"center"}),J.api.setActive()},[]),q=i.useCallback(H=>{var ne;const z=k.current;if(!z)return!1;const J=z.getPanel(H);if(!J)return!1;try{return((ne=J.group.element)==null?void 0:ne.ownerDocument)!==document}catch{return!1}},[]),he=i.useCallback(H=>{q(H)&&ye(H),u(H)},[q,ye,u]),fe=i.useCallback(H=>{const z=k.current,J=z==null?void 0:z.getPanel(H);!z||!J||z.addFloatingGroup(J,{width:600,height:500})},[]),we=i.useCallback(H=>{var J;const z=(J=k.current)==null?void 0:J.getPanel(H);if(!z)return!1;try{return z.group.model.location.type==="floating"}catch{return!1}},[]),xe=i.useCallback(()=>{var z,J;const H=(J=(z=k.current)==null?void 0:z.activePanel)==null?void 0:J.id;return!H||_t(H)?null:V.has(H)?H:null},[V]),Se=i.useCallback(H=>{const z=k.current,J=z==null?void 0:z.getPanel(H);if(!z||!J)return;const ne=z.groups.filter($=>{try{return $.model.location.type==="grid"}catch{return!0}});ne.length>0?J.api.moveTo({group:ne[0],position:"center"}):J.api.moveTo({position:"center"}),J.api.setActive()},[]),Q=i.useCallback(()=>{var G;const H=k.current;if(!H)return;const J=H.groups.filter(ee=>{var ae;try{return((ae=ee.element)==null?void 0:ae.ownerDocument)===document&&ee.model.location.type==="grid"}catch{return!1}})[0]||null,ne=[...H.panels];for(const ee of ne){const ae=(G=ee.group.element)==null?void 0:G.ownerDocument,je=ee.group.model.location.type;ae===document&&je==="grid"||(J&&J.id!==ee.group.id?ee.api.moveTo({group:J,position:"center"}):ee.api.moveTo({position:"center"}))}const $=H.activePanel;$&&($.group.model.openPanel($),$.api.setActive()),fa(document)},[]),ue=i.useCallback(()=>{var z,J;const H=k.current;if(H)for(const ne of H.groups){const $=(z=ne.element)==null?void 0:z.ownerDocument;if(!$||$===document)continue;const G=$.getElementById("dv-popout-window");if(!(G instanceof HTMLElement))continue;let ee=null,ae=$.title||"ADHDev",je="Popout workspace";const _e=ne.activePanel;if(_e)if(ee=_e.id,_t(_e.id)){const Te=((J=_e.params)==null?void 0:J.routeId)||_e.id.slice(7),Ye=Et([...V.values()],Te);ae=_c(Ye),je=Ye!=null&&Ye.machineName?`Remote view · ${Ye.machineName}`:"Remote view"}else{const Te=V.get(_e.id);ae=Te?lt(Te):_e.title||_e.id,je=Te?ds(Te):"Dockview panel"}$.title=`${ae} — ADHDev`;const De=Array.from($.querySelectorAll("#adhdev-popout-header"));for(const Te of De)Te.remove();const Ae=$.createElement("div");Ae.id="adhdev-popout-header",$.body.appendChild(Ae),Ae.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(";")),Ae.innerHTML=`
55
+ <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
56
+ <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
57
+ <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${al(ae)}</div>
58
+ <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${al(je)}</div>
59
+ </div>
60
+ <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
61
+ <button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
62
+ <button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
63
+ </div>
64
+ `,G.style.top="52px",G.style.height="calc(100% - 52px)";const Ee=Ae.querySelector("[data-adhdev-popout-focus]");Ee&&(Ee.onclick=()=>{window.focus()});const Oe=Ae.querySelector("[data-adhdev-popout-dock]");Oe&&(Oe.disabled=!ee,Oe.style.opacity=ee?"1":"0.5",Oe.style.cursor=ee?"pointer":"default",Oe.onclick=()=>{var Te;ee&&ye(ee),(Te=$.defaultView)==null||Te.focus()})}},[V,ye]),oe=i.useCallback(H=>{var ne;const z=k.current,J=z==null?void 0:z.getPanel(H);if(!(!z||!J)){J.group.model.openPanel(J),J.api.setActive(),pe(H,"dockview-shortcut");try{const $=J.group.model.location;$.type==="popout"?$.getWindow().focus():fa((ne=J.group.element)==null?void 0:ne.ownerDocument)}catch{}}},[pe]),me=i.useCallback(H=>{const z=k.current,J=z==null?void 0:z.activePanel,ne=(z==null?void 0:z.activeGroup)||(J==null?void 0:J.group);if(!z||!J||!ne)return;const $=ne.panels||[];if($.length<=1)return;const G=$.findIndex(je=>je.id===J.id);if(G<0)return;const ee=(G+H+$.length)%$.length,ae=$[ee];ae&&(ae.group.model.openPanel(ae),ae.api.setActive(),_t(ae.id)||pe(ae.id,"dockview-shortcut"))},[pe]),le=i.useCallback(H=>{var Ee;const z=k.current,J=(z==null?void 0:z.activeGroup)||((Ee=z==null?void 0:z.activePanel)==null?void 0:Ee.group);if(!z||!J)return;const ne=z.groups||[],$=ne.find(Oe=>Oe.id===J.id);if(!$)return;const G=$.element.getBoundingClientRect(),ee=G.left+G.width/2,ae=G.top+G.height/2,je=(Oe,Te,Ye,Je)=>Math.max(0,Math.min(Te,Je)-Math.max(Oe,Ye)),_e=Oe=>{const Te=Oe.element.getBoundingClientRect(),Ye=Te.left+Te.width/2,Je=Te.top+Te.height/2;let ft=0,ht=0,it=0,ut=!1;if(H==="left"?(ut=Ye<ee,ft=Math.max(0,G.left-Te.right),ht=Math.abs(Je-ae),it=je(G.top,G.bottom,Te.top,Te.bottom)):H==="right"?(ut=Ye>ee,ft=Math.max(0,Te.left-G.right),ht=Math.abs(Je-ae),it=je(G.top,G.bottom,Te.top,Te.bottom)):H==="above"?(ut=Je<ae,ft=Math.max(0,G.top-Te.bottom),ht=Math.abs(Ye-ee),it=je(G.left,G.right,Te.left,Te.right)):(ut=Je>ae,ft=Math.max(0,Te.top-G.bottom),ht=Math.abs(Ye-ee),it=je(G.left,G.right,Te.left,Te.right)),!ut)return Number.POSITIVE_INFINITY;const We=it>0?0:120;return ft*3+ht+We};let De=null,Ae=Number.POSITIVE_INFINITY;for(const Oe of ne){if(Oe.id===$.id)continue;const Te=_e(Oe);Number.isFinite(Te)&&(Te>=Ae||(Ae=Te,De=Oe))}return De||void 0},[]),P=i.useCallback(H=>{var ne;const z=le(H);if(!z)return;const J=z.activePanel||z.panels[0];J&&(z.model.openPanel(J),J.api.setActive(),_t(J.id)||pe(J.id,"dockview-focus"),fa((ne=z.element)==null?void 0:ne.ownerDocument))},[le,pe]),U=i.useCallback((H,z)=>{const J=k.current,ne=J==null?void 0:J.activePanel,$=(J==null?void 0:J.activeGroup)||(ne==null?void 0:ne.group);if(!J||!ne||!$)return;let G=le(H);!G&&(z!=null&&z.createGroupIfMissing)&&(G=J.addGroup({referenceGroup:$,direction:H})),G&&(ne.api.moveTo({group:G,position:"center"}),ne.group.model.openPanel(ne),ne.api.setActive(),_t(ne.id)||pe(ne.id,z!=null&&z.createGroupIfMissing?"dockview-split":"dockview-move"))},[le,pe]),{isMac:ce,tabShortcuts:te,shortcutListening:ie,setShortcutListening:se,saveShortcuts:ve}=Cd({sortedTabKeys:e.map(H=>H.tabKey),onFocus:ge,onSelectTab:oe}),Ie=i.useCallback(()=>{var J;const H=k.current;if(!H)return;const z=H.activePanel;if(z){if(_t(z.id)){const ne=((J=z.params)==null?void 0:J.routeId)||z.id.slice(7),$=Et(e,ne);$!=null&&$.tabKey&&se($.tabKey);return}V.has(z.id)&&se(z.id)}},[V,oe,se,e]),Me=i.useCallback(H=>{const z=[];return H.metaKey&&z.push(ce?"⌘":"Meta"),H.ctrlKey&&z.push("Ctrl"),H.altKey&&z.push(ce?"⌥":"Alt"),H.shiftKey&&H.key.length!==1&&z.push(ce?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(H.key)?null:(z.push(Md(H.key)),z.join("+"))},[ce]),B=i.useCallback(H=>{var z,J;switch(H){case"splitActiveTabRight":U("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":U("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const ne=xe();ne&&fe(ne);return}case"popoutActiveTab":{const ne=xe();ne&&ke(ne);return}case"dockActiveTab":{const ne=xe();if(!ne)return;q(ne)?ye(ne):we(ne)&&Se(ne);return}case"focusLeftPane":P("left");return;case"focusRightPane":P("right");return;case"focusUpPane":P("above");return;case"focusDownPane":P("below");return;case"moveActiveTabToLeftPane":U("left");return;case"moveActiveTabToRightPane":U("right");return;case"moveActiveTabToUpPane":U("above");return;case"moveActiveTabToDownPane":U("below");return;case"selectPreviousGroupTab":me(-1);return;case"selectNextGroupTab":me(1);return;case"setActiveTabShortcut":Ie();return;case"hideCurrentTab":{const ne=(J=(z=k.current)==null?void 0:z.activePanel)==null?void 0:J.id;ne&&!_t(ne)&&he(ne);return}default:return}},[me,Se,P,fe,xe,he,we,q,ye,U,ke,Ie]);i.useEffect(()=>{if(!C)return;const H=C.sourceDocument,z=H.defaultView??window,J=ne=>{const $=H.querySelector("[data-dockview-tab-context-menu]");$&&$.contains(ne.target)||I(null)};return z.addEventListener("mousedown",J,!0),z!==window&&window.addEventListener("mousedown",()=>I(null),!0),()=>{z.removeEventListener("mousedown",J,!0),z!==window&&window.removeEventListener("mousedown",()=>I(null),!0)}},[C]);const Ne=i.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:V,hasDetachedConversationPanels:Y,ides:r,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:f,liveSessionInboxState:S,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:he,userName:m,scrollToBottomRequest:N,tabShortcuts:te,openTabContextMenu:({x:H,y:z,tabKey:J,sourceDocument:ne})=>I({x:H,y:z,tabKey:J,sourceDocument:ne??document}),popoutTab:ke,moveTabBackToMain:ye,isTabInPopout:q,floatTab:fe,isTabFloating:we}),[n,s,V,Y,r,l,c,f,S,a,o,he,m,N,te,ke,ye,q,fe,we]),Re=C?Bg({isTabInPopout:q(C.tabKey),isTabFloating:we(C.tabKey),tabShortcut:te[C.tabKey],actionShortcuts:h}):[],Fe=i.useCallback(H=>{var ne;const z=k.current;if((((ne=z==null?void 0:z.activePanel)==null?void 0:ne.id)??null)===H.id){H.group.model.openPanel(H);return}H.group.model.openPanel(H),H.api.setActive()},[]),He=i.useCallback((H,z="requested-tab")=>{if(!H)return!1;const J=k.current;if(!J)return!1;const ne=J.getPanel(H);return ne?(Fe(ne),pe(H,z),x==null||x(),!0):!1},[Fe,x,pe]),Ge=i.useCallback(()=>{if(F.current)return!1;const H=He(W.current,"stored-layout-restore");return H&&(F.current=!0),H},[He]),qe=i.useCallback(()=>{var z;const H=k.current;H&&fb(w,{activeTabId:((z=H.activePanel)==null?void 0:z.id)??null,layout:H.toJSON()})},[w]),et=i.useCallback(()=>{xb(w,E.current)},[w]),dt=i.useCallback(H=>{var ne,$,G,ee;const z=k.current;if(!z)return{kind:"grid"};const J=z.toJSON();for(const ae of J.floatingGroups||[])if(($=(ne=ae.data)==null?void 0:ne.views)!=null&&$.includes(H)&&ae.position)return{kind:"floating",position:ae.position};for(const ae of J.popoutGroups||[])if((ee=(G=ae.data)==null?void 0:G.views)!=null&&ee.includes(H))return{kind:"popout",position:ae.position,popoutUrl:ae.url};return{kind:"grid"}},[]),pt=i.useCallback(H=>{const z=k.current;if(!z)return;const J=z.getPanel(H),ne=E.current[H];if(!J||!ne||ne.kind==="grid")return;if(J.group.model.location.type===ne.kind){delete E.current[H],et();return}if(ne.kind==="floating"){z.addFloatingGroup(J,{x:ne.position.left??24,y:ne.position.top??24,width:ne.position.width,height:ne.position.height}),delete E.current[H],et();return}delete E.current[H],et()},[et]);i.useEffect(()=>(g==null||g({setShortcutForActiveTab:Ie,restoreHiddenTabToSavedLocation:pt,activateConversationTab:oe,resetAllPanelsToMain:Q,activatePreviousTabInGroup:()=>me(-1),activateNextTabInGroup:()=>me(1),floatActiveTab:()=>{const H=xe();H&&fe(H)},popoutActiveTab:()=>{const H=xe();H&&ke(H)},dockActiveTab:()=>{const H=xe();H&&(q(H)?ye(H):we(H)&&Se(H))},splitActiveTabRight:()=>U("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>U("below",{createGroupIfMissing:!0}),focusLeftPane:()=>P("left"),focusRightPane:()=>P("right"),focusUpPane:()=>P("above"),focusDownPane:()=>P("below"),moveActiveTabToLeftPane:()=>U("left"),moveActiveTabToRightPane:()=>U("right"),moveActiveTabToUpPane:()=>U("above"),moveActiveTabToDownPane:()=>U("below")}),()=>g==null?void 0:g(null)),[me,Se,fe,P,xe,we,q,U,ye,ke,g,Q,pt,oe,Ie]),i.useEffect(()=>()=>{var H;(H=O.current)==null||H.call(O),O.current=null},[]);const bt=i.useCallback(H=>{var J,ne;k.current=H.api,(J=O.current)==null||J.call(O),O.current=null;const z=pb(w);if(W.current=(z==null?void 0:z.activeTabId)??null,z!=null&&z.layout&&H.api.fromJSON(z.layout,{reuseExistingPanels:!1}),T.current=tl({hasStoredLayout:!!(z!=null&&z.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),T.current||(il(H.api,e),ll(H.api,e,y)),H.api.totalPanels===0&&e.length>0){const $=Vg(H.api,e,b);if($){const G=H.api.getPanel($);G&&Fe(G)}}else!T.current&&!He(b)&&Ge();if(R.current=!0,H.api.onDidActivePanelChange($=>{var ee;if(W.current=($==null?void 0:$.id)??null,F.current=!0,ue(),$&&_t($.id)){const ae=((ee=$.params)==null?void 0:ee.routeId)||$.id.slice(7),je=Et(e,ae);v((je==null?void 0:je.tabKey)??null),qe();return}if(v(($==null?void 0:$.id)??null),qe(),!$)return;const G=V.get($.id);(G==null?void 0:G.streamSource)==="agent-stream"&&G.agentType&&L(G.routeId,xc(),{agentType:G.agentType,...G.sessionId&&{targetSessionId:G.sessionId}}).catch(()=>{})}),H.api.onDidLayoutChange(()=>{qe(),ue(),_($=>$+1)}),Wg()){const $=Ae=>({clientX:Ae.clientX,clientY:Ae.clientY}),G=Ae=>{const Ee=Ae==null?void 0:Ae.getBoundingClientRect();return Ee?{left:Ee.left,right:Ee.right,top:Ee.top,bottom:Ee.bottom}:null},ee=Ae=>{var Oe;const Ee=(Oe=j.current)==null?void 0:Oe.getBoundingClientRect();return Ee?Ae.clientX<Ee.left||Ae.clientX>Ee.right||Ae.clientY<Ee.top||Ae.clientY>Ee.bottom:!1},ae=Fg({detachDelayMs:Rd,onDetach:({panelId:Ae,clientX:Ee,clientY:Oe})=>{var it,ut;const Te=H.api.getPanel(Ae);if(!Te)return;try{if(Te.group.model.location.type!=="grid")return}catch{return}const Ye=(it=j.current)==null?void 0:it.getBoundingClientRect(),Je=(ut=Te.group.element)==null?void 0:ut.getBoundingClientRect(),ft=Math.round(Math.min(Math.max((Je==null?void 0:Je.width)??600,360),720)),ht=Math.round(Math.min(Math.max((Je==null?void 0:Je.height)??500,260),640));H.api.addFloatingGroup(Te,{x:Ye?Math.max(0,Ee-Ye.left-32):void 0,y:Ye?Math.max(0,Oe-Ye.top-18):void 0,width:ft,height:ht}),Te.api.setActive(),qe(),ue(),_(We=>We+1)}}),je=[H.api.onWillDragPanel(Ae=>{if(!(Ae.nativeEvent.defaultPrevented||Ae.nativeEvent.shiftKey)){try{if(Ae.panel.group.model.location.type!=="grid")return}catch{return}ae.startDrag({panelId:Ae.panel.id,selfPanelBounds:G(Ae.panel.group.element),...$(Ae.nativeEvent)})}}),H.api.onWillShowOverlay(Ae=>{if(ae.hasDetached()){Ae.preventDefault();return}ae.markDockTarget($(Ae.nativeEvent))}),H.api.onWillDrop(Ae=>{if(ae.hasDetached()){Ae.preventDefault(),ae.endDrag();return}ae.markDockTarget($(Ae.nativeEvent))}),H.api.onDidDrop(()=>ae.endDrag()),H.api.onUnhandledDragOverEvent(Ae=>{ae.isDragging()&&ae.markSelfPanel($(Ae.nativeEvent))})],_e=Ae=>{if(!ae.isDragging())return;const Ee=$(Ae);ee(Ee)&&ae.markNonSelfPanel(Ee)},De=()=>ae.endDrag();window.addEventListener("dragover",_e,!0),window.addEventListener("drop",De,!0),window.addEventListener("dragend",De,!0),O.current=()=>{ae.dispose();for(const Ae of je)Ae.dispose();window.removeEventListener("dragover",_e,!0),window.removeEventListener("drop",De,!0),window.removeEventListener("dragend",De,!0)}}H.api.onDidAddGroup($=>{requestAnimationFrame(()=>{var G,ee;try{const ae=(G=$.element)==null?void 0:G.ownerDocument;if(!ae||ae===document)return;(ee=ae.getElementById("dv-popout-window"))==null||ee.classList.add("adhdev-dockview");const je=document.documentElement.getAttribute("data-theme");je&&ae.documentElement.setAttribute("data-theme",je),ae.body.className=document.body.className;const _e=document.documentElement.getAttribute("style");_e&&ae.documentElement.setAttribute("style",_e)}catch{}ue(),_(ae=>ae+1)})}),v(((ne=H.api.activePanel)==null?void 0:ne.id)??null)},[Fe,He,V,r,d,w,v,qe,b,y,L,ue,e]);i.useLayoutEffect(()=>{const H=k.current;if(!H||!R.current||T.current&&tl({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;T.current&&(T.current=!1);const z=D.current,J=new Set(z),ne=e.map(De=>De.tabKey),$=new Set(ne),G=Og({previousVisibleConversationCount:z.length,visibleConversationCount:e.length,ides:r});let ee=!1;for(const De of z)$.has(De)||G||(E.current[De]=dt(De),ee=!0);ee&&et(),G||(il(H,e),ll(H,e,y));const ae=ne.filter(De=>!J.has(De));let je=!1;for(const De of ae){const Ae=H.getPanel(De),Ee=E.current[De];if(!Ae||!Ee||Ee.kind==="grid")continue;if(Ae.group.model.location.type===Ee.kind){delete E.current[De],je=!0;continue}if(Ee.kind==="floating"){H.addFloatingGroup(Ae,{x:Ee.position.left??24,y:Ee.position.top??24,width:Ee.position.width,height:Ee.position.height}),delete E.current[De],je=!0;continue}}if(je&&et(),D.current=ne,b&&He(b))return;!H.activePanel&&H.panels[0]&&Fe(H.panels[0]),!!(H.activePanel&&H.getPanel(H.activePanel.id))||Ge()},[Fe,He,Ge,r,d,et,dt,b,y,e]),i.useEffect(()=>{R.current&&He(b)},[He,b]),i.useEffect(()=>{const H=J=>{const ne=J.target;if(!ne)return;const $=ne.querySelector("[data-tab-key]")||ne.closest("[data-tab-key]");if($){const G=$.getAttribute("data-tab-key");if(G&&J.dataTransfer){const ee=ne.closest(".dv-tab")||$.closest(".dv-tab")||$;J.dataTransfer.effectAllowed="move",J.dataTransfer.setData("text/tab-key",G),ee instanceof HTMLElement&&J.dataTransfer.setDragImage(ee,Math.max(12,Math.round(ee.clientWidth/2)),Math.max(10,Math.round(ee.clientHeight/2)))}}};window.addEventListener("dragstart",H);const z=ol(k.current);for(const J of z)J.addEventListener("dragstart",H);return()=>{window.removeEventListener("dragstart",H);for(const J of z)J.removeEventListener("dragstart",H)}},[K]),i.useEffect(()=>{var z;const H=(z=j.current)==null?void 0:z.querySelector(".adhdev-dockview");H instanceof HTMLElement&&ha(H,A),de(),ue()},[ue,de,A]),i.useEffect(()=>{ue()},[ue]),i.useEffect(()=>{const H=z=>{if(z.defaultPrevented||ie)return;const J=Me(z);if(!J)return;const ne=z.metaKey||z.ctrlKey||z.altKey;Ja(z.target)&&!ne||kn(ce).setActiveTabShortcut!==J||(z.preventDefault(),z.stopPropagation(),Ie())};return window.addEventListener("keydown",H,!0),()=>window.removeEventListener("keydown",H,!0)},[Me,ce,ie,Ie]),i.useEffect(()=>{const H=j.current;if(!H)return;const z=J=>{var ae,je;if(!J.isTrusted)return;const ne=(je=(ae=J.target)==null?void 0:ae.closest)==null?void 0:je.call(ae,".dv-scrollable");if(!ne)return;J.preventDefault(),J.stopPropagation();const $=Math.abs(J.deltaX),G=Math.abs(J.deltaY),ee=$>G?J.deltaX:J.deltaY;ne.dispatchEvent(new WheelEvent("wheel",{deltaY:ee,deltaMode:J.deltaMode,bubbles:!1,cancelable:!0}))};return H.addEventListener("wheel",z,{passive:!1,capture:!0}),()=>H.removeEventListener("wheel",z,{capture:!0})},[]),i.useEffect(()=>{const H=ol(k.current);if(H.length===0)return;const z=H.map(J=>{let ne=[],$=null;const G=()=>{$!=null&&J.clearTimeout($),$=null,ne=[]},ee=()=>{$!=null&&J.clearTimeout($),$=J.setTimeout(()=>{$=null,ne=[]},1200)},ae=_e=>{if(!_e.ctrlKey&&!_e.metaKey&&!_e.altKey)return;const De=Me(_e);if(!De)return;const Ae=Nd();for(const[Ee,Oe]of Object.entries(Ae))if(e.some(Te=>Te.tabKey===Ee)&&Oe===De){_e.preventDefault(),oe(Ee);return}},je=_e=>{if(_e.defaultPrevented||ie)return;const De=Me(_e);if(!De)return;const Ae=_e.metaKey||_e.ctrlKey||_e.altKey;if(Ja(_e.target))return;const Ee=kn(ce),Oe=Object.entries(Ee).filter(([We,$t])=>!!$t&&(We==="splitActiveTabRight"||We==="splitActiveTabDown"||We==="floatActiveTab"||We==="popoutActiveTab"||We==="dockActiveTab"||We==="focusLeftPane"||We==="focusRightPane"||We==="focusUpPane"||We==="focusDownPane"||We==="moveActiveTabToLeftPane"||We==="moveActiveTabToRightPane"||We==="moveActiveTabToUpPane"||We==="moveActiveTabToDownPane"||We==="selectPreviousGroupTab"||We==="selectNextGroupTab"||We==="setActiveTabShortcut"||We==="hideCurrentTab")),Te=Ae?[De]:[...ne.slice(-1),De].slice(-2),Ye=Te.join(" "),Je=Te[Te.length-1],ft=Oe.find(([,We])=>We===Ye);if(ft){_e.preventDefault(),G(),B(ft[0]);return}if(Oe.some(([,We])=>We.startsWith(`${Ye} `))){_e.preventDefault(),ne=Te,ee();return}const it=Oe.find(([,We])=>We===Je);if(it){_e.preventDefault(),G(),B(it[0]);return}if(Oe.some(([,We])=>We.startsWith(`${Je} `))){_e.preventDefault(),ne=[Je],ee();return}G()};return J.addEventListener("keydown",ae),J.addEventListener("keydown",je),()=>{G(),J.removeEventListener("keydown",ae),J.removeEventListener("keydown",je)}});return()=>{for(const J of z)J()}},[Me,ce,K,oe,ie,B,e]);const Ce=A==="light"?La:Ra,Ue=((rt=(ze=(Qe=k.current)==null?void 0:Qe.activePanel)==null?void 0:ze.group.element)==null?void 0:rt.ownerDocument)??document;return t.jsxs(_d.Provider,{value:Ne,children:[t.jsx("div",{ref:j,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(Su,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:Gg,remote:qg},defaultTabComponent:Xg,watermarkComponent:Yg,onReady:bt,singleTabMode:"default",tabAnimation:"smooth",theme:Ce,popoutUrl:"/popout.html"})}),C&&xr.createPortal(t.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:C.x,top:C.y},children:Re.map(H=>{if(H.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},H.id);let z=t.jsx(Nm,{size:13,className:"shrink-0 opacity-70"}),J=()=>{};switch(H.id){case"dockInWindow":case"dockBackToGrid":z=t.jsx(Im,{size:13,className:"shrink-0 opacity-70"}),J=()=>{Se(C.tabKey),I(null)};break;case"moveBackToMain":z=t.jsx(Sm,{size:13,className:"shrink-0 opacity-70"}),J=()=>{ye(C.tabKey),I(null)};break;case"floatAsPanel":z=t.jsx(Cm,{size:13,className:"shrink-0 opacity-70"}),J=()=>{fe(C.tabKey),I(null)};break;case"openInNewWindow":z=t.jsx(km,{size:13,className:"shrink-0 opacity-70"}),J=()=>{ke(C.tabKey),I(null)};break;case"setShortcut":J=ne=>{ne.stopPropagation(),se(C.tabKey),I(null)};break;case"removeShortcut":z=t.jsx(gt,{size:13,className:"shrink-0 opacity-70"}),J=()=>{const ne={...te};delete ne[C.tabKey],ve(ne),I(null)};break;case"hideTab":z=t.jsx(lo,{size:13,className:"shrink-0 opacity-70"}),J=()=>{he(C.tabKey),I(null)};break}return t.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 ${H.tone==="muted"?"text-text-muted":""}`,onMouseDown:Ug,onClick:J,children:[z,t.jsx("span",{className:"flex-1 min-w-0",children:H.label}),H.shortcut?t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:H.shortcut}):null]},H.id)})}),C.sourceDocument.body),ie&&xr.createPortal(t.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:()=>se(null),children:t.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:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",ce?"⌘+1":"Ctrl+1",", ",ce?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),Ue.body)]})}const Pd="adhdev-recent-launch-args-v1",Qg=8;function Dd(e){return String(e||"").trim().replace(/\s+/g," ")}function Wo(e,s){return`${e.trim()}::${s.trim()}`}function Ho(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Pd)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function Ed(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Pd,JSON.stringify(e))}catch{}}function Qa(e,s){var o;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((o=Ho().byKey[Wo(r,n)])==null?void 0:o.items)||[]}function $d(e,s,r){var u;const n=String(e||"").trim(),a=String(s||"").trim(),o=Dd(r);if(!n||!a||!o)return;const l=Ho(),c=Wo(n,a),d=((u=l.byKey[c])==null?void 0:u.items)||[],m=[o,...d.filter(h=>h!==o)].slice(0,Qg);l.byKey[c]={items:m},Ed(l)}function Zg(e,s,r){var u;const n=String(e||"").trim(),a=String(s||"").trim(),o=Dd(r);if(!n||!a||!o)return;const l=Ho(),c=Wo(n,a),m=(((u=l.byKey[c])==null?void 0:u.items)||[]).filter(h=>h!==o);m.length>0?l.byKey[c]={items:m}:delete l.byKey[c],Ed(l)}function Bd(e){return!e.hasLoadedInitialResults&&!e.isLoading}function nn({title:e,description:s,action:r,children:n,className:a="",contentClassName:o=""}){return t.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),s&&t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:s})]}),r?t.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?t.jsx("div",{className:s||r?`mt-3 ${o}`.trim():o,children:n}):null]})}function ey({savedSessionsLoading:e,savedSessionsLoaded:s,savedSessionsCount:r=0}){return e?"Refreshing saved history…":s?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 Od({busy:e,savedSessionsLoading:s,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:l,onOpenHistory:c,onClearSelection:d}){const m=o?jd(o):null,u=ey({savedSessionsLoading:s,savedSessionsLoaded:n,savedSessionsCount:a});return t.jsxs(nn,{title:"Saved history",description:To(),action:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||s,onClick:l,children:s?"Loading…":"Refresh"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:c,children:Kh()})]}),children:[m?t.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:t.jsxs("div",{className:"flex items-start justify-between gap-2",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),t.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:m.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:m.providerSessionId}),t.jsx("div",{className:"mt-1",children:m.metaLine}),m.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:m.updatedLabel}),m.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:m.preview})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:d,disabled:e,children:"Clear"})]})}):t.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:u}),r&&t.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function Kd({setup:e,providerName:s,className:r=""}){return e?t.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${r}`,children:[t.jsxs("div",{className:"font-semibold",children:["Manual MCP setup required",s?` for ${s}`:""]}),e.instructions&&t.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),t.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-text-muted",children:[e.serverName&&t.jsxs("span",{children:["Server: ",t.jsx("code",{children:e.serverName})]}),e.configFormat&&t.jsxs("span",{children:["Format: ",t.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&t.jsxs("span",{children:["Config path: ",t.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&t.jsx("span",{children:"Start a fresh CLI session after editing config."})]}),e.template&&t.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 ty({workspaceMode:e,activeKind:s,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:o,onSelect:l}){return e==="mesh"?null:t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:r},{id:"ide",label:"IDE",enabled:n},{id:"acp",label:"ACP",enabled:a}].map(c=>t.jsx("button",{type:"button",className:`btn btn-sm ${s===c.id?"btn-primary":"btn-secondary"}`,onClick:()=>l(c.id),disabled:!c.enabled||o,children:c.label},c.id))})]})}function xa(e){var n;if(!e)return null;const s=e.availableProviders||[];return s.some(a=>ws(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":s.some(a=>ws(a,"acp"))?"acp":null}function Gr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function sy({machines:e,ides:s,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:l,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var We,$t;const u=Sr(),h=i.useMemo(()=>[...e].sort(bo),[e]),[g,v]=i.useState(((We=h[0])==null?void 0:We.id)||""),f=i.useMemo(()=>h.find(Z=>Z.id===g)||h[0],[g,h]),p=i.useMemo(()=>((f==null?void 0:f.workspaces)||[]).map(Z=>({id:Z.id,path:Z.path,label:Z.label})),[f]),b=(f==null?void 0:f.defaultWorkspaceId)||null,[y,x]=i.useState("workspace"),[N,S]=i.useState(""),[w,A]=i.useState(""),[L,k]=i.useState([]),[j,O]=i.useState(""),[R,T]=i.useState(!1),[F,W]=i.useState(null),[D,C]=i.useState(""),[I,K]=i.useState(xa(h[0])),[_,E]=i.useState(""),[V,Y]=i.useState(""),[ge,pe]=i.useState([]),[re,de]=i.useState(""),[ke,ye]=i.useState([]),[q,he]=i.useState(!1),[fe,we]=i.useState(!1),[xe,Se]=i.useState(""),[Q,ue]=i.useState(!1),[oe,me]=i.useState(()=>jt()),[le,P]=i.useState(null),[U,ce]=i.useState(!1),[te,ie]=i.useState(""),[se,ve]=i.useState(null),[Ie,Me]=i.useState(!1),[B,Ne]=i.useState(""),[Re,Fe]=i.useState([]),[He,Ge]=i.useState(!1),[qe,et]=i.useState(""),[dt,pt]=i.useState(!1),bt=i.useRef(null),Ce=i.useRef(0);i.useEffect(()=>{var Z;!g&&((Z=h[0])!=null&&Z.id)&&v(h[0].id)},[g,h]),i.useEffect(()=>{!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||u(f.id,{minFreshMs:3e4}).catch(()=>{})},[u,f]);const Ue=i.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(Z=>ws(Z,"cli")),[f]),Qe=i.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(Z=>ws(Z,"acp")),[f]),ze=i.useMemo(()=>((f==null?void 0:f.detectedIdes)||[]).map(Z=>({id:Z.type,label:Z.name||Z.type,meta:Z.running?"Detected locally":"Available to open"})),[f]),rt=i.useMemo(()=>I==="cli"?Ue.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"CLI provider"})):I==="acp"?Qe.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"ACP provider"})):ze,[Qe,I,Ue,ze]),H=i.useMemo(()=>L.find(Z=>Z.id===j)||null,[L,j]),z=i.useMemo(()=>Ue.find(Z=>Z.type===_)||null,[Ue,_]),J=i.useMemo(()=>hd(z==null?void 0:z.meshCoordinator,{meshId:(H==null?void 0:H.id)||"",workspace:(H==null?void 0:H.workspace)||""}),[z,H]),ne=se||J,$=i.useCallback(async Z=>{T(!0),C("");try{const Pe=await c(Z);k(Pe),O(M=>{var X;return Pe.some(be=>be.id===M)?M:((X=Pe[0])==null?void 0:X.id)||""}),W(Z)}catch(Pe){k([]),O(""),W(Z),C(Pe instanceof Error?Pe.message:"Could not load meshes")}finally{T(!1)}},[c]);i.useEffect(()=>{var Pe;if(!f)return;if(bt.current!==f.id){bt.current=f.id,x("workspace"),S(b||((Pe=p[0])==null?void 0:Pe.id)||"__home__"),A(""),k([]),O(""),W(null),C(""),K(xa(f)),E(""),Y(""),de(""),ye([]),we(!1),Se(""),me(jt()),ie(""),ve(null);return}S(M=>{var X;return M==="__custom__"||M==="__home__"||p.some(be=>be.id===M)?M:b||((X=p[0])==null?void 0:X.id)||"__home__"}),K(M=>M==="ide"&&ze.length>0||M==="cli"&&Ue.length>0||M==="acp"&&Qe.length>0?M:xa(f))},[Qe.length,Ue.length,b,ze.length,f,p]),i.useEffect(()=>{!f||y!=="mesh"||F===f.id||R||$(f.id)},[$,F,R,f,y]),i.useEffect(()=>{y==="mesh"&&I!=="cli"&&Ue.length>0&&K("cli")},[I,Ue.length,y]),i.useEffect(()=>{var Z;I&&(rt.some(Pe=>Pe.id===_)||E(((Z=rt[0])==null?void 0:Z.id)||""))},[I,rt,_]),i.useEffect(()=>{ve(null)},[f==null?void 0:f.id,j,_,y]);const G=i.useCallback(async(Z,Pe)=>{const M=Ce.current+1;return Ce.current=M,he(!0),Se(""),m(Z,Pe).then(X=>{Ce.current===M&&ye(X)}).catch(X=>{Ce.current===M&&(ye([]),Se(X instanceof Error?X.message:"Could not load saved sessions"))}).finally(()=>{Ce.current===M&&(he(!1),we(!0))})},[m]),ee=i.useCallback((Z,Pe)=>{pe(Qa(Z,Pe))},[]);i.useEffect(()=>{Ce.current+=1,de(""),me(jt()),!f||!_||I==="ide"?pe([]):ee(f.id,_),we(!1),ye([]),Se(""),he(!1)},[I,ee,G,f,_]),i.useEffect(()=>{if(!re)return;const Z=ke.find(Pe=>Pe.providerSessionId===re);Z!=null&&Z.canResume||de("")},[ke,re]);const ae=N==="__custom__"?w.trim():N==="__home__"?"":(($t=p.find(Z=>Z.id===N))==null?void 0:$t.path)||"",je=i.useMemo(()=>f?s.filter(Z=>Z.id!==f.id&&Z.daemonId===f.id).map(Z=>Z.workspace):[],[s,f]),_e=i.useMemo(()=>((f==null?void 0:f.recentLaunches)||[]).map(Z=>Z.workspace),[f]),De=i.useCallback(Z=>{const Pe=String(Z.workspace||"").trim();if(!Pe)return;const M=p.find(X=>Gr(X.path)===Gr(Pe));if(M){S(M.id),A("");return}S("__custom__"),A(Pe)},[p]),Ae=i.useCallback(Z=>{const Pe=String(Z.workspace||"").trim();if(!Pe)return{workspaceId:null,workspacePath:null};const M=p.find(X=>Gr(X.path)===Gr(Pe));return M?{workspaceId:M.id,workspacePath:null}:{workspaceId:null,workspacePath:Pe}},[p]),Ee=i.useMemo(()=>ke.find(Z=>Z.providerSessionId===re)||null,[ke,re]),Oe=i.useMemo(()=>{var Pe;if(I!=="cli"||!f||!_)return null;const Z=((Pe=Ue.find(M=>M.type===_))==null?void 0:Pe.displayName)||_;return{routeId:f.id,daemonId:f.id,providerSessionId:re||void 0,transport:"pty",mode:"chat",agentName:Z,agentType:_,status:"idle",title:Z,messages:[],ideType:_,workspaceName:ae,workspacePath:ae,displayPrimary:Z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${f.id}:${_}`,machineName:Ct(f,{fallbackId:f.id})}},[I,Ue,ae,f,re,_]),Te=i.useCallback(()=>{var Pe;if(!f)return;S("__custom__"),Me(!0),et("");const Z=Dn(f.platform,Pn(w.trim(),ae,je,_e,f.defaultWorkspacePath,(Pe=p.find(M=>M.id===b))==null?void 0:Pe.path,p.map(M=>M.path)));Ge(!0),n(f.id,Z).then(M=>{Ne(M.path),A(M.path),Fe(M.directories)}).catch(M=>{et(M instanceof Error?M.message:"Could not load folder")}).finally(()=>Ge(!1))},[w,b,_e,je,n,ae,f,p]),Ye=i.useCallback(Z=>{f&&(Ge(!0),et(""),n(f.id,Z).then(Pe=>{Ne(Pe.path),A(Pe.path),Fe(Pe.directories)}).catch(Pe=>{et(Pe instanceof Error?Pe.message:"Could not load folder")}).finally(()=>Ge(!1)))},[n,f]),Je=i.useCallback(async()=>{if(!f||!ae)return;pt(!0),ie("");const Z=await a(f.id,ae);if(pt(!1),!Z.ok){ie(Z.error||"Could not save workspace");return}ie("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,ae,f]),ft=i.useCallback(async()=>{if(!f)return;if(y==="mesh"){if(!j||!_)return;ce(!0),ie(""),ve(null);const M=await d(f.id,j,_);if(ce(!1),!M.ok){if(M.code==="mesh_coordinator_manual_mcp_setup_required"&&M.manualSetup){ve(M.manualSetup),ie("Manual MCP setup required before this provider can act as mesh coordinator.");return}ie(M.error||"Could not start mesh coordinator");return}r();return}if(!I||!_)return;ce(!0),ie("");const Z=V.trim()?V.trim().split(/\s+/).filter(Boolean):[],Pe=I==="ide"?await o(f.id,_,{workspacePath:ae||null}):await l(f.id,I,_,{workspaceId:N!=="__home__"&&N!=="__custom__"?N:null,workspacePath:N==="__custom__"&&ae||null,resumeSessionId:I==="cli"&&re?re:null,cliArgs:Z});if(ce(!1),!Pe.ok){ie(Pe.error||"Could not start session");return}I!=="ide"&&V.trim()&&($d(f.id,_,V),ee(f.id,_)),r()},[I,V,ee,r,o,d,l,ae,f,j,re,_,N,y]),ht=y==="mesh"?"Start mesh coordinator":I?Ec(I,I==="cli"&&!!re):"Start",it=y==="mesh"?"Starting coordinator…":I?$c(I,I==="cli"&&!!re):"Starting…",ut=h.length>5;return f?t.jsxs(t.Fragment,{children:[t.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:t.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:[t.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:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),t.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."})]}),t.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:t.jsx(gt,{size:16})})]}),t.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:[t.jsx(nn,{title:"Machine",children:ut?t.jsx("select",{"aria-label":"Machine",value:f.id,onChange:Z=>v(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:U,children:h.map(Z=>t.jsx("option",{value:Z.id,children:Ct(Z,{fallbackId:Z.id})},Z.id))}):t.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:h.map(Z=>{const Pe=Ct(Z,{fallbackId:Z.id}),M=f.id===Z.id;return t.jsxs("button",{type:"button","aria-label":`Select machine ${Pe}`,"aria-pressed":M,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${M?"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:()=>v(Z.id),disabled:U,title:Pe,children:[t.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${Z.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),t.jsx("span",{className:"truncate",children:Pe})]},Z.id)})})}),t.jsxs(nn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:y==="workspace"?t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Te,disabled:U,children:"Browse…"}):void 0,children:[t.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=>t.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:()=>{x(Z.id),ie(""),Z.id==="mesh"&&f&&F!==f.id&&!R&&$(f.id)},disabled:U,children:[t.jsx("div",{className:"text-sm font-semibold",children:Z.label}),t.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:Z.desc})]},Z.id))}),y==="workspace"?t.jsxs(t.Fragment,{children:[t.jsxs("select",{value:N,onChange:Z=>{const Pe=Z.target.value;S(Pe),Pe==="__custom__"?Te():ie("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:U,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),p.map(Z=>t.jsxs("option",{value:Z.id,children:[Z.id===b?"⭐ ":"",An(Z.path,Z.label)||Z.path]},Z.id)),t.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:N==="__home__"?"Launch without a workspace.":ae||"Select a workspace folder."}),N==="__custom__"&&ae&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Te,disabled:U,children:[t.jsx(gs,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Je,disabled:U||dt,children:dt?"Saving…":"Save workspace"})]})]}):t.jsxs("div",{className:"space-y-3",children:[R&&t.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!R&&D&&t.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:D}),!R&&!D&&L.length===0&&t.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."}),L.length>0&&t.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:L.map(Z=>t.jsxs("button",{type:"button",role:"radio","aria-checked":j===Z.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${j===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>O(Z.id),disabled:U,children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.name}),t.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&&t.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",Z.workspace]})]},Z.id))}),H&&t.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),t.jsx(ty,{workspaceMode:y,activeKind:I,cliEnabled:Ue.length>0,ideEnabled:ze.length>0,acpEnabled:Qe.length>0,busy:U,onSelect:K}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.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"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[rt.map(Z=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${_===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>E(Z.id),disabled:U,children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Z.meta})]},Z.id)),rt.length===0&&t.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"&&ne&&t.jsx(Kd,{setup:ne,providerName:(z==null?void 0:z.displayName)||(z==null?void 0:z.name)||_}),y!=="mesh"&&I!=="ide"&&t.jsxs(nn,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:V,onChange:Z=>Y(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:U}),ge.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:ge.map(Z=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>Y(Z),disabled:U,title:Z,children:Z},Z))})]}),y!=="mesh"&&I==="cli"&&t.jsx(Od,{busy:U,savedSessionsLoading:q,savedSessionsError:xe,selectedSession:Ee,onRefresh:()=>{!f||!_||G(f.id,_)},onOpenHistory:()=>{!f||!_||(ue(!0),Bd({hasLoadedInitialResults:fe,isLoading:q})&&G(f.id,_))},onClearSelection:()=>de("")}),te&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${te.includes("saved")||te.includes("requested")||te.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:te})]}),t.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:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:r,disabled:U,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:ft,disabled:U||(y==="mesh"?!j||!_||I!=="cli"||R:!I||!_||N==="__custom__"&&!ae),children:[t.jsx(uo,{size:14}),U?it:ht]})]})]})}),Ie&&t.jsx($n,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:B,directories:Re,busy:He,error:qe,onClose:()=>Me(!1),onNavigate:Ye,onConfirm:Z=>{A(Z),Ne(Z),S("__custom__"),Me(!1)}}),Q&&Oe&&t.jsx(Lo,{activeConv:Oe,ides:[],isCreatingChat:!1,isRefreshingHistory:q,savedSessions:ke,isSavedSessionsLoading:q,isResumingSavedSessionId:le,savedHistoryFilters:oe,missingWorkspaceResumePath:ae||null,onSavedHistoryFiltersChange:me,onClose:()=>ue(!1),onNewChat:()=>{de(""),ue(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!f||!_||G(f.id,_)},onResumeSavedSession:Z=>{if(!f||!_||le||!Z.canResume)return;const Pe=Ae(Z);de(Z.providerSessionId),De(Z),P(Z.providerSessionId),ue(!1),ce(!0),ie(""),l(f.id,"cli",_,{workspaceId:Pe.workspaceId,workspacePath:Pe.workspacePath,resumeSessionId:Z.providerSessionId}).then(M=>{if(!M.ok){ie(M.error||"Could not resume session");return}r()}).finally(()=>{ce(!1),P(M=>M===Z.providerSessionId?null:M)})}})]}):null}function ry(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function ny(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function cl(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 dl(e){return e.length===0?"unknown":e.reduce((s,r)=>cl(r)>cl(s)?r:s)}function ay(e){var o,l,c,d,m;const s=new Map,r=new Map;for(const u of e){const h=(l=(o=u.git)==null?void 0:o.branch)==null?void 0:l.trim();h&&(r.set(h,(r.get(h)??0)+1),(c=u.git)!=null&&c.upstream&&s.set(h,(s.get(h)??0)+1))}const n=[...s.entries()].sort((u,h)=>{if(h[1]!==u[1])return h[1]-u[1];const g=["main","master","develop","dev"],v=g.indexOf(u[0]),f=g.indexOf(h[0]);return v!==-1||f!==-1?v===-1?1:f===-1?-1:v-f:u[0].localeCompare(h[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((m=[...r.entries()].sort((u,h)=>h[1]-u[1])[0])==null?void 0:m[0])??null}function oy(e,s){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&&s&&n.branch!==s&&!n.upstream&&r.push(`No upstream tracking for ${n.branch}`),e.error&&r.push(e.error),r):(r.push("Not a git repository"),r):(r.push("No git status available"),r)}function iy(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function Fd(e){var g;const s=ay(e.nodes),r=[],n=[],a=[],o=new Map;for(const v of e.nodes){const f=v.git,p=(f==null?void 0:f.branch)??null,b=ry(f),y=oy(v,s),x={id:v.nodeId,type:y.length>0?"orphanNode":"worktreeNode",label:v.machineLabel||v.nodeId.slice(0,8),workspace:v.workspace,branch:p,machineLabel:v.machineLabel||null,health:v.health,ahead:(f==null?void 0:f.ahead)??0,behind:(f==null?void 0:f.behind)??0,dirty:b,dirtyFiles:ny(f),hasConflicts:(f==null?void 0:f.hasConflicts)??!1,activeSessionCount:((g=v.activeSessions)==null?void 0:g.length)??0,activeSessions:v.activeSessions??[],providers:v.providers??[],isOrphan:y.length>0,orphanReasons:y,error:v.error,nextStepHint:y[0],parentNodeId:null,submodulePath:null,submoduleCommit:(f==null?void 0:f.headCommit)??null,outOfSync:!1,source:v};if(r.push(x),p){const N=o.get(p)??[];N.push(x.id),o.set(p,N)}for(const N of(f==null?void 0:f.submodules)??[]){const S=`${x.id}::submodule::${N.path}`,w=N.path.split("/").filter(Boolean).pop()||N.path;r.push({id:S,type:"submoduleNode",label:w,workspace:N.repoPath,branch:null,machineLabel:x.machineLabel,health:iy(N),ahead:0,behind:0,dirty:N.dirty,dirtyFiles:N.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],error:N.error,nextStepHint:N.error||(N.outOfSync?`${N.path} is out of sync with the parent checkout`:N.dirty?`${N.path} has local changes`:`${N.path} is in sync with the parent checkout`),parentNodeId:x.id,submodulePath:N.path,submoduleCommit:N.commit,outOfSync:N.outOfSync,source:{kind:"synthetic-submodule",parentNodeId:x.id,parentWorkspace:v.workspace,submodule:N}}),n.push({id:`${x.id}--${S}`,source:x.id,target:S,type:"submoduleLink",label:N.outOfSync?"submodule out of sync":"submodule"})}}const l=s?`__branch_${s}`:null;if(l&&s){const f=(o.get(s)??[]).map(b=>r.find(y=>y.id===b)).filter(Boolean),p={id:l,type:"defaultBranchNode",label:s,workspace:e.repoIdentity,branch:s,machineLabel:"default branch",health:dl(f.map(b=>b.health)),ahead:0,behind:0,dirty:f.some(b=>b.dirty),dirtyFiles:f.reduce((b,y)=>b+y.dirtyFiles,0),hasConflicts:f.some(b=>b.hasConflicts),activeSessionCount:f.reduce((b,y)=>b+y.activeSessionCount,0),activeSessions:f.flatMap(b=>b.activeSessions),providers:[...new Set(f.flatMap(b=>b.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:f.length>0?`${f.length} workspace(s) currently on ${s}`:"No workspaces currently checked out to the default branch",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,source:{nodeId:l,machineLabel:s,workspace:e.repoIdentity,health:dl(f.map(b=>b.health)),providers:[],activeSessions:[]}};r.push(p);for(const b of r)if(!(b.id===l||b.type==="submoduleNode")){if(b.branch===s){n.push({id:`${l}--${b.id}`,source:l,target:b.id,type:"parentBranch",label:"checked out"});continue}if(b.branch){n.push({id:`${l}--${b.id}`,source:l,target:b.id,type:b.isOrphan?"orphanLink":"parentBranch",label:b.branch});continue}b.isOrphan&&n.push({id:`${l}--${b.id}`,source:l,target:b.id,type:"orphanLink",label:"detached"})}}for(const[v,f]of o){if(f.length<2)continue;const p=f.map(b=>r.find(y=>y.id===b)).filter(Boolean);p.sort((b,y)=>b.label.localeCompare(y.label));for(let b=1;b<p.length;b+=1)n.push({id:`wt_${p[b-1].id}--${p[b].id}`,source:p[b-1].id,target:p[b].id,type:"worktreeLink",label:b===1?`${v} peers`:void 0})}const c=r.filter(v=>v.type!=="defaultBranchNode"),d=c.filter(v=>v.isOrphan).length,m=c.filter(v=>v.hasConflicts).length,u=c.filter(v=>v.health==="offline").length,h=c.filter(v=>v.type==="submoduleNode"&&v.outOfSync).length;return d>0&&a.push(`${d} workspace(s) need attention before safe coordination`),m>0&&a.push(`${m} workspace(s) report merge conflicts`),u>0&&a.push(`${u} node(s) are currently offline`),h>0&&a.push(`${h} submodule(s) are out of sync with their parent checkout`),s||a.push("Could not infer a default branch from live mesh status"),{meshId:e.meshId,meshName:e.meshName,repoIdentity:e.repoIdentity,refreshedAt:e.refreshedAt,nodes:r,edges:n,stats:{totalNodes:c.length,onlineNodes:c.filter(v=>v.health==="online").length,dirtyNodes:c.filter(v=>v.dirty).length,orphanNodes:d,errorNodes:c.filter(v=>!!v.error||v.outOfSync).length,offlineNodes:u,totalActiveSessions:c.reduce((v,f)=>v+f.activeSessionCount,0)},warnings:a}}function Rt({label:e,value:s}){return s==null||s===""?null:t.jsxs("div",{className:"flex justify-between gap-3 text-[11px] py-0.5 border-b border-border-subtle/50",children:[t.jsx("span",{className:"text-text-muted",children:e}),t.jsx("span",{className:"text-right break-all text-text-secondary font-medium",children:String(s)})]})}function ly({health:e}){const s={online:"bg-green-500/10 text-green-400 border-green-500/20",dirty:"bg-yellow-500/10 text-yellow-400 border-yellow-500/20",degraded:"bg-red-500/10 text-red-400 border-red-500/20",wrong_branch:"bg-purple-500/10 text-purple-400 border-purple-500/20",offline:"bg-gray-500/10 text-gray-400 border-gray-500/20",unknown:"bg-gray-500/10 text-gray-400 border-gray-500/20"};return t.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] border ${s[e]||s.unknown}`,children:e})}function Za({node:e,onClose:s}){if(!e)return t.jsx("div",{className:"w-full max-w-full rounded-xl border border-border-subtle bg-bg-panel p-4 text-text-muted text-xs md:w-64",children:"Select a node to view details."});const r=e.type==="submoduleNode";return t.jsxs("div",{className:"w-full max-w-full rounded-xl border border-border-subtle bg-bg-panel p-4 flex flex-col gap-2 shadow-lg md:w-64",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary truncate",children:e.label}),s&&t.jsx("button",{onClick:s,className:"text-text-muted hover:text-text-primary text-xs",children:"✕"})]}),t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx(ly,{health:e.health}),r&&t.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-violet-500/10 text-violet-300 border border-violet-500/20",children:"Submodule"}),e.dirty&&t.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-yellow-500/10 text-yellow-400 border border-yellow-500/20",children:"Dirty"}),e.outOfSync&&t.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-red-500/10 text-red-400 border border-red-500/20",children:"Out of sync"}),e.hasConflicts&&t.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-red-500/10 text-red-400 border border-red-500/20",children:"Conflict"}),e.isOrphan&&t.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-red-500/10 text-red-400 border border-red-500/20",children:"Orphan"})]}),t.jsxs("div",{className:"flex flex-col gap-0.5 mt-1",children:[t.jsx(Rt,{label:"Workspace",value:e.workspace}),t.jsx(Rt,{label:"Branch",value:e.branch}),t.jsx(Rt,{label:"Submodule path",value:e.submodulePath??null}),t.jsx(Rt,{label:"Submodule commit",value:e.submoduleCommit??null}),t.jsx(Rt,{label:"Parent node",value:r&&(e.machineLabel||e.parentNodeId)||null}),t.jsx(Rt,{label:"Ahead",value:!r&&e.ahead>0?`+${e.ahead}`:null}),t.jsx(Rt,{label:"Behind",value:!r&&e.behind>0?`-${e.behind}`:null}),t.jsx(Rt,{label:"Dirty files",value:e.dirtyFiles>0?e.dirtyFiles:null}),t.jsx(Rt,{label:"Active sessions",value:e.activeSessionCount>0?e.activeSessionCount:null}),t.jsx(Rt,{label:"Providers",value:r?null:e.providers.join(", ")||null}),t.jsx(Rt,{label:"Error",value:e.error??null})]}),e.orphanReasons.length>0&&t.jsxs("div",{className:"mt-1",children:[t.jsx("div",{className:"text-[10px] font-semibold text-red-400 mb-1",children:"Orphan reasons"}),t.jsx("ul",{className:"list-disc list-inside text-[10px] text-red-300 space-y-0.5",children:e.orphanReasons.map((n,a)=>t.jsx("li",{children:n},a))})]}),e.nextStepHint&&t.jsxs("div",{className:"mt-1 px-2 py-1.5 rounded bg-blue-500/10 border border-blue-500/20 text-[10px] text-blue-300",children:["💡 ",e.nextStepHint]})]})}const ul=380,ml=240,pl=176,fl=220,cy=44;function dy(e,s){const r=s?"border-cyan-400/70 shadow-[0_0_0_1px_rgba(34,211,238,0.35),0_24px_60px_rgba(8,145,178,0.18)]":"border-border-subtle shadow-[0_18px_48px_rgba(3,7,18,0.22)]";switch(e){case"online":return`${r} bg-emerald-500/8`;case"dirty":return`${r} bg-amber-500/8`;case"degraded":return`${r} bg-rose-500/10`;case"wrong_branch":return`${r} bg-violet-500/10`;case"offline":return`${r} bg-slate-500/12`;default:return`${r} bg-bg-panel`}}function Xt(e){switch(e){case"health":return"border-white/10 bg-white/6 text-text-secondary";case"dirty":return"border-amber-400/25 bg-amber-500/10 text-amber-200";case"conflict":return"border-rose-400/25 bg-rose-500/10 text-rose-200";case"orphan":return"border-fuchsia-400/25 bg-fuchsia-500/10 text-fuchsia-200";case"submodule":return"border-violet-400/25 bg-violet-500/10 text-violet-100";case"meta":default:return"border-cyan-400/20 bg-cyan-500/8 text-cyan-100"}}function Wd(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 uy(e){return e.replace(/_/g," ")}function my({data:e,selected:s}){const r=e.graphNode,n=r.type==="defaultBranchNode",a=r.type==="submoduleNode",o=n?"default branch anchor":a?r.submodulePath||"submodule checkout":r.machineLabel||r.workspace,l=r.submoduleCommit?r.submoduleCommit.slice(0,7):null;return t.jsxs("div",{className:`${a?"w-[224px]":"w-[240px]"} rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all ${dy(r.health,s)}`,children:[t.jsx(ti,{type:"target",position:si.Top,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"truncate text-sm font-semibold text-text-primary",children:r.label}),t.jsx("div",{className:"truncate text-[11px] text-text-muted",children:o})]}),t.jsx("span",{className:"mt-0.5 h-2.5 w-2.5 shrink-0 rounded-full",style:{backgroundColor:Wd(r.health)},"aria-hidden":!0})]}),t.jsxs("div",{className:"mt-3 flex flex-wrap gap-1.5 text-[10px]",children:[t.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${Xt("health")}`,children:uy(r.health)}),a&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Xt("submodule")}`,children:"submodule"}),r.branch&&!a&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Xt("meta")}`,children:r.branch}),l&&a&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Xt("meta")}`,children:l}),r.dirty&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Xt("dirty")}`,children:a?"local changes":`${r.dirtyFiles} dirty`}),r.outOfSync&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Xt("conflict")}`,children:"out of sync"}),r.hasConflicts&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Xt("conflict")}`,children:"conflicts"}),r.isOrphan&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Xt("orphan")}`,children:"needs attention"})]}),a?t.jsxs("div",{className:"mt-3 grid grid-cols-2 gap-2 text-[11px] text-text-secondary",children:[t.jsxs("div",{className:"rounded-xl border border-white/6 bg-black/10 px-2.5 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.12em] text-text-muted",children:"Parent node"}),t.jsx("div",{className:"mt-1 truncate font-medium text-text-primary",children:r.machineLabel||"mesh node"})]}),t.jsxs("div",{className:"rounded-xl border border-white/6 bg-black/10 px-2.5 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.12em] text-text-muted",children:"State"}),t.jsx("div",{className:"mt-1 font-medium text-text-primary",children:r.outOfSync?"Out of sync":r.dirty?"Dirty":"Synced"})]})]}):t.jsxs("div",{className:"mt-3 grid grid-cols-2 gap-2 text-[11px] text-text-secondary",children:[t.jsxs("div",{className:"rounded-xl border border-white/6 bg-black/10 px-2.5 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.12em] text-text-muted",children:"Sessions"}),t.jsx("div",{className:"mt-1 font-medium text-text-primary",children:r.activeSessionCount})]}),t.jsxs("div",{className:"rounded-xl border border-white/6 bg-black/10 px-2.5 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.12em] text-text-muted",children:"Git drift"}),t.jsxs("div",{className:"mt-1 font-medium text-text-primary",children:["+",r.ahead," / -",r.behind]})]})]}),r.nextStepHint&&t.jsx("div",{className:"mt-3 rounded-xl border border-cyan-400/15 bg-cyan-500/8 px-3 py-2 text-[10px] leading-4 text-cyan-50/90",children:r.nextStepHint}),t.jsx(ti,{type:"source",position:si.Bottom,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const py={meshNode:my};function ba(e,s){return e.type==="defaultBranchNode"&&s.type!=="defaultBranchNode"?-1:s.type==="defaultBranchNode"&&e.type!=="defaultBranchNode"||e.type==="submoduleNode"&&s.type!=="submoduleNode"?1:s.type==="submoduleNode"&&e.type!=="submoduleNode"?-1:e.branch&&s.branch&&e.branch!==s.branch?e.branch.localeCompare(s.branch):e.branch&&!s.branch?-1:!e.branch&&s.branch?1:e.label.localeCompare(s.label)}function fy(e){const s=[...e.nodes].sort(ba),r=s.find(f=>f.type==="defaultBranchNode")??null,n=new Map;for(const f of s){if(f.type!=="submoduleNode"||!f.parentNodeId)continue;const p=n.get(f.parentNodeId)??[];p.push(f),n.set(f.parentNodeId,p)}const a=s.filter(f=>f.id!==(r==null?void 0:r.id)&&f.type!=="submoduleNode"),o=new Map,l=[];for(const f of a){if(f.isOrphan||!f.branch){l.push(f);continue}const p=f.branch,b=o.get(p)??[];b.push(f),o.set(p,b)}const c=[...o.entries()].sort(([f],[p])=>r!=null&&r.branch&&f===r.branch&&p!==r.branch?-1:r!=null&&r.branch&&p===r.branch&&f!==r.branch?1:f.localeCompare(p));l.length>0&&c.push(["__orphans__",[...l].sort(ba)]),c.length===0&&c.push(["__nodes__",[]]);const d=[],m=c.length,u=Math.max(1,m-1)*ul,h=r?0:80,g=r?ml:0;r&&d.push({id:r.id,type:"meshNode",position:{x:u/2,y:h},data:{graphNode:r},selected:!1,draggable:!1,selectable:!0}),c.forEach(([f,p],b)=>{const y=b*ul,x=p.length>0?p:a.length>0?a:[];let N=g;x.forEach(S=>{d.push({id:S.id,type:"meshNode",position:{x:y,y:N},data:{graphNode:S},selected:!1,draggable:!1,selectable:!0});const w=[...n.get(S.id)??[]].sort(ba);if(w.length>0){w.forEach((A,L)=>{d.push({id:A.id,type:"meshNode",position:{x:y,y:N+fl+L*pl},data:{graphNode:A},selected:!1,draggable:!1,selectable:!0})}),N+=fl+w.length*pl+cy;return}N+=ml}),f==="__nodes__"&&a.length===0&&r&&d.push({id:`${r.id}__placeholder`,type:"meshNode",position:{x:y,y:g},data:{graphNode:{id:`${r.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:e.repoIdentity,branch:r.branch,machineLabel:null,health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],nextStepHint:"Waiting for worktree nodes to report live mesh status.",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,source:{nodeId:`${r.id}__placeholder`,machineLabel:null,workspace:e.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}},selected:!1,draggable:!1,selectable:!1})});const v=e.edges.map(f=>({id:f.id,source:f.source,target:f.target,label:f.label,type:f.type==="worktreeLink"||f.type==="submoduleLink"?"smoothstep":"bezier",animated:f.type==="orphanLink",markerEnd:{type:Mu.ArrowClosed,width:f.type==="submoduleLink"?16:18,height:f.type==="submoduleLink"?16:18,color:hl(f)},style:{stroke:hl(f),strokeWidth:f.type==="orphanLink"?2.25:f.type==="submoduleLink"?1.7:f.type==="worktreeLink"?1.8:2,strokeDasharray:f.type==="orphanLink"?"5 4":f.type==="submoduleLink"?"4 3":void 0},labelStyle:{fill:"var(--text-secondary, #cbd5e1)",fontSize:10,fontWeight:600},labelBgStyle:{fill:"rgba(2, 6, 23, 0.86)",fillOpacity:1,stroke:"rgba(148, 163, 184, 0.2)"},labelBgPadding:[5,3],labelBgBorderRadius:6}));return{nodes:d,edges:v}}function hl(e){switch(e.type){case"parentBranch":return"#38bdf8";case"worktreeLink":return"#a78bfa";case"sessionLink":return"#34d399";case"orphanLink":return"#f97316";case"submoduleLink":return"#c084fc";default:return"#64748b"}}function Hd({data:e,selectedNodeId:s=null,onNodeClick:r}){const n=i.useMemo(()=>fy(e),[e]),a=i.useMemo(()=>n.nodes.map(o=>({...o,selected:o.id===s})),[n.nodes,s]);return t.jsxs("div",{className:"relative h-full min-h-[560px] overflow-hidden rounded-2xl border border-border-subtle bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",children:[t.jsxs("div",{className:"absolute left-4 top-4 z-10 flex flex-wrap gap-2 text-[11px] text-text-secondary",children:[t.jsxs("span",{className:"rounded-full border border-white/10 bg-black/25 px-3 py-1",children:[e.stats.totalNodes," node",e.stats.totalNodes===1?"":"s"]}),t.jsxs("span",{className:"rounded-full border border-white/10 bg-black/25 px-3 py-1",children:[e.stats.totalActiveSessions," active session",e.stats.totalActiveSessions===1?"":"s"]}),e.stats.orphanNodes>0&&t.jsxs("span",{className:"rounded-full border border-orange-400/25 bg-orange-500/12 px-3 py-1 text-orange-100",children:[e.stats.orphanNodes," need attention"]})]}),t.jsxs(Nu,{nodes:a,edges:n.edges,nodeTypes:py,fitView:!0,fitViewOptions:{padding:.28,maxZoom:1.02},minZoom:.25,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!1,zoomOnScroll:!1,zoomOnPinch:!1,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(o,l)=>r==null?void 0:r(l.data.graphNode),className:"h-full w-full",colorMode:"dark",proOptions:{hideAttribution:!0},children:[t.jsx(Cu,{className:"!bottom-4 !right-4 !bg-slate-950/85 !border !border-white/10 !rounded-xl",nodeColor:o=>Wd(o.data.graphNode.health)}),t.jsx(Iu,{className:"!bottom-4 !left-4 !shadow-lg",showInteractive:!1}),t.jsx(Tu,{variant:Au.Dots,gap:18,size:1.2,color:"rgba(148, 163, 184, 0.22)"})]})]})}function hy(e){const s=(e==null?void 0:e.result)??e,r=[e==null?void 0:e.status,s==null?void 0:s.status,s,e];for(const n of r)if(n&&Array.isArray(n.nodes)&&typeof n.meshId=="string")return n;return null}function xy({activeConv:e,sendDaemonCommand:s,onClose:r}){var N;const n=typeof((N=e.settings)==null?void 0:N.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null,a=e.daemonId??null,[o,l]=i.useState(null),[c,d]=i.useState(null),[m,u]=i.useState(!1),[h,g]=i.useState(null),[v,f]=i.useState(null),p=i.useCallback(async()=>{if(!a||!n){g("This coordinator does not expose a live mesh id."),l(null);return}u(!0),g(null);try{const S=await s(a,"mesh_status",{meshId:n}),w=hy(S);if(!w){l(null),g("mesh_status returned an unexpected payload.");return}const A=Fd(w);l(A),d(L=>{var k,j;return L?A.nodes.some(O=>O.id===L)?L:((j=A.nodes[0])==null?void 0:j.id)??null:((k=A.nodes[0])==null?void 0:k.id)??null}),f(new Date().toISOString())}catch(S){l(null),g(S instanceof Error?S.message:"Failed to load live mesh status")}finally{u(!1)}},[a,n,s]);i.useEffect(()=>{p()},[p]),i.useEffect(()=>{const S=w=>{w.key==="Escape"&&r()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[r]);const b=i.useMemo(()=>!o||!c?null:o.nodes.find(S=>S.id===c)??null,[o,c]),y=(o==null?void 0:o.meshName)||n||"Repo Mesh",x=v?new Date(v).toLocaleTimeString():null;return t.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center bg-[#030617]/[0.58] p-0 md:p-4 backdrop-blur-md",onClick:r,children:t.jsxs("div",{role:"dialog","aria-modal":"true",className:"flex h-[100dvh] w-full flex-col overflow-hidden bg-slate-950 md:h-[min(88vh,920px)] md:max-w-[min(1280px,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)]",onClick:S=>S.stopPropagation(),children:[t.jsxs("div",{className:"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",children:[t.jsx("div",{className:"min-w-0 flex-1",children:t.jsxs("div",{className:"flex items-center gap-3",children:[t.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:t.jsx(Qt,{size:18})}),t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx("h2",{className:"truncate text-lg font-semibold text-white md:text-xl",children:y}),t.jsx("span",{className:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-300",children:"Coordinator graph"})]}),t.jsxs("p",{className:"mt-1 truncate text-sm text-slate-400",children:[lt(e),e.workspaceName?` · ${e.workspaceName}`:"",o!=null&&o.repoIdentity?` · ${o.repoIdentity}`:""]})]})]})}),t.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[x&&t.jsxs("span",{className:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",children:["Refreshed ",x]}),t.jsx("button",{type:"button",onClick:p,disabled:m,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:m?"Refreshing…":"Refresh"}),t.jsx("button",{type:"button",onClick:r,className:"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","aria-label":"Close mesh graph",children:t.jsx(gt,{size:16})})]})]}),h&&t.jsx("div",{className:"shrink-0 border-b border-rose-400/20 bg-rose-500/12 px-4 py-2 text-sm text-rose-200 md:px-5",children:h}),t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] md:flex-row",children:[t.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-3 overflow-hidden px-4 py-4 md:px-5 md:py-5",children:[(o==null?void 0:o.warnings)&&o.warnings.length>0&&t.jsx("div",{className:"flex flex-wrap gap-2",children:o.warnings.map(S=>t.jsx("span",{className:"rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1.5 text-xs text-amber-100",children:S},S))}),t.jsx("div",{className:"min-h-0 flex-1",children:o?t.jsx(Hd,{data:o,selectedNodeId:c,onNodeClick:S=>d(S.id)}):t.jsx("div",{className:"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",children:m?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet."})}),!b&&t.jsx("div",{className:"rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2 text-xs text-slate-300 md:hidden",children:"Tap a node to inspect workspace, session, and git details."})]}),b&&t.jsx("div",{className:"border-t border-white/10 px-4 py-4 md:hidden",children:t.jsx("div",{className:"max-h-[38vh] overflow-y-auto",children:t.jsx(Za,{node:b,onClose:()=>d(null)})})}),t.jsx("div",{className:"hidden w-full shrink-0 border-t border-white/10 px-4 py-4 md:block md:w-[320px] md:border-l md:border-t-0 md:px-5 md:py-5",children:t.jsx(Za,{node:b,onClose:b?()=>d(null):void 0})})]})]})})}function by(e,s){const{sendCommand:r}=yt(),[n,a]=i.useState(null),[o,l]=i.useState(!1);i.useEffect(()=>{if(!e||!s){a(null);return}l(!0),r(e,"git_remote_url",{workspace:s}).then(d=>{const m=(d==null?void 0:d.result)??d;a(typeof(m==null?void 0:m.remoteUrl)=="string"?m.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>l(!1))},[e,s,r]);const c=gy(n);return{remoteUrl:n,githubUrl:c,loading:o}}function gy(e){if(!e)return null;const s=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(s)return`https://github.com/${s[1]}`;const r=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return r?`https://github.com/${r[1]}`:null}const Ud=5e3;function yy(e){return`git:${e}`}function vy({workspace:e,includeDiffSummary:s=!1,intervalMs:r=Ud}){return{type:"subscribe",topic:"workspace.git",key:yy(e),params:{workspace:e,includeDiffSummary:s,intervalMs:r}}}function Uo(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function js(e,s){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 s}function wy(e){const s=Uo(e);return(s==null?void 0:s.success)===!1?{status:null,error:js(s,"Git status request failed")}:s!=null&&s.status?{status:s.status,error:null}:{status:null,error:js(s,"Git status response did not include status")}}function jy(e){const s=Uo(e);return(s==null?void 0:s.success)===!1?{diffSummary:null,error:js(s,"Git diff summary request failed")}:s!=null&&s.diffSummary?{diffSummary:s.diffSummary,error:null}:{diffSummary:null,error:js(s,"Git diff summary response did not include diffSummary")}}function ga(e){return e===void 0||typeof e=="boolean"}function ky(e){if(!e||typeof e!="object")return!1;const s=e;return typeof s.path=="string"&&typeof s.diff=="string"&&ga(s.binary)&&ga(s.truncated)&&ga(s.staged)}function Sy(e){const s=Uo(e);return(s==null?void 0:s.success)===!1?{diff:null,error:js(s,"Git file diff request failed")}:ky(s==null?void 0:s.diff)?{diff:s.diff,error:null}:{diff:null,error:js(s,"Git file diff response did not include a valid diff object")}}function Ny({daemonId:e,workspace:s,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Ud}){const{sendCommand:o,sendData:l}=yt(),c=typeof s=="string"?s.trim():"",d=!!(r&&e&&c),[m,u]=i.useState(null),[h,g]=i.useState(null),[v,f]=i.useState(!1),[p,b]=i.useState(null),y=i.useCallback(async()=>{if(!(!d||!e||!c)){f(!0),b(null);try{const N=wy(await o(e,"git_status",{workspace:c}));if(N.error){u(null),g(null),b(N.error);return}if(u(N.status),!n){g(null);return}const S=jy(await o(e,"git_diff_summary",{workspace:c}));if(S.error){g(null),b(S.error);return}g(S.diffSummary)}catch(N){b(js(N,"Git status request failed"))}finally{f(!1)}}},[d,e,n,o,c]),x=i.useMemo(()=>c?vy({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return i.useEffect(()=>{if(!d||!e||!c||!x){u(null),g(null),f(!1),b(null);return}const N=l?zt.subscribe({sendData:l},e,x,S=>{var w,A;S.workspace===c&&(u(S.status),g(S.diffSummary??null),b(((w=S.status)==null?void 0:w.error)||((A=S.diffSummary)==null?void 0:A.error)||null),f(!1))},{retryIntervalMs:1e3}):null;return y(),()=>{N==null||N()}},[d,e,y,x,l,c]),{status:m,diffSummary:h,loading:v,error:p,refresh:y}}const Cy={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},Iy={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 Ty(e){const s=e.lastIndexOf("/");return s>0?e.slice(0,s):""}function Ay({files:e,truncated:s,onFileClick:r,selectedPath:n,className:a=""}){return e.length===0?t.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:"No changed files."}):t.jsxs("div",{className:`flex flex-col ${a}`,children:[t.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(o=>{const l=n===o.path,c=Cy[o.status]??"?",d=Iy[o.status]??"text-zinc-400",m=Ty(o.path),u=xl(o.path),h=o.staged?t.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return t.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${l?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(o),children:[t.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:o.status,children:c}),t.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&t.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),t.jsx("span",{className:"text-text-primary",children:u}),o.oldPath&&t.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",xl(o.oldPath)]}),h]}),!o.binary&&(o.insertions>0||o.deletions>0)&&t.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&t.jsxs("span",{className:"text-emerald-500",children:["+",o.insertions]}),o.insertions>0&&o.deletions>0&&t.jsx("span",{className:"text-text-secondary",children:" "}),o.deletions>0&&t.jsxs("span",{className:"text-red-400",children:["-",o.deletions]})]}),o.binary&&t.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${o.path}-${o.staged?"S":"U"}`)})}),s&&t.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",t.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function My(e,s){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"),t.jsx("div",{className:`px-3 ${r}`,children:t.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},s)}function Ly({diff:e,binary:s,truncated:r,loading:n,error:a,className:o=""}){const l=i.useRef(null);if(i.useEffect(()=>{l.current&&(l.current.scrollTop=0)},[e]),n)return t.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${o}`,children:"Loading diff…"});if(a)return t.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${o}`,children:a});if(s)return t.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"Binary file — diff not available."});if(!e)return t.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"No diff available."});const c=e.split(`
65
+ `);return t.jsxs("div",{ref:l,className:`overflow-auto ${o}`,children:[t.jsx("div",{className:"py-1",children:c.map((d,m)=>My(d,m))}),r&&t.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary border-t border-border/30",children:["Diff truncated — run ",t.jsx("code",{className:"font-mono",children:"git diff"})," locally for full output."]})]})}function Ry(e,s){const r=[`Branch: ${e||"unknown"}`];r.push(`Changed: ${s.files.length} file(s) +${s.totalInsertions}/-${s.totalDeletions}`);const n={};for(const a of s.files)n[a.status]||(n[a.status]=[]),n[a.status].push(a.path);for(const[a,o]of Object.entries(n))r.push(`${a}: ${o.slice(0,5).join(", ")}${o.length>5?` (+${o.length-5} more)`:""}`);return r.join(`
66
+ `)}function zd({daemonId:e,workspace:s,onClose:r}){const{sendCommand:n}=yt(),{status:a,diffSummary:o,loading:l,error:c,refresh:d}=Ny({daemonId:e,workspace:s,includeDiffSummary:!0}),[m,u]=i.useState(null),[h,g]=i.useState(null),[v,f]=i.useState(""),[p,b]=i.useState(!1),[y,x]=i.useState(!1),[N,S]=i.useState(null),[w,A]=i.useState(null),{githubUrl:L}=by(e,s),k=i.useCallback(async W=>{if(!((m==null?void 0:m.path)===W.path&&!m.loading)){u({path:W.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const D=await n(e,"git_diff_file",{workspace:s,path:W.path,staged:W.staged}),C=Sy(D);if(C.error||!C.diff){u({path:W.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C.error??"Failed to load diff"});return}u({path:W.path,diff:C.diff.diff,binary:C.diff.binary??!1,truncated:C.diff.truncated??!1,loading:!1,error:null})}catch(D){const C=D instanceof Error?D.message:"Failed to load diff";u({path:W.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C})}}},[e,n,m,s]),j=i.useCallback(W=>{f(""),b(!1),S(null),A(null),g(W)},[]),O=i.useCallback(()=>{g(null),S(null),x(!1)},[]),R=i.useCallback(async()=>{var W,D,C;if(h){x(!0),S(null);try{let I;h==="checkpoint"?I=await n(e,"git_checkpoint",{workspace:s,message:v,includeUntracked:p}):h==="stash"?I=await n(e,"git_stash_push",{workspace:s,message:v,includeUntracked:p}):h==="stash_pop"?I=await n(e,"git_stash_pop",{workspace:s}):h==="checkout_files"&&m&&(I=await n(e,"git_checkout_files",{workspace:s,paths:[m.path]}));const K=(I==null?void 0:I.result)??I;if((K==null?void 0:K.success)===!1||K!=null&&K.error){S((K==null?void 0:K.error)??"Action failed"),x(!1);return}h==="checkpoint"?A(`Checkpoint created: ${((D=(W=K==null?void 0:K.checkpoint)==null?void 0:W.commit)==null?void 0:D.slice(0,7))??"done"}`):h==="stash"?A(`Stashed as ${((C=K==null?void 0:K.stash)==null?void 0:C.stashRef)??"stash@{0}"}`):h==="stash_pop"?A("Stash restored"):(A("File reverted"),u(null)),g(null),await d()}catch(I){S(I instanceof Error?I.message:"Action failed")}finally{x(!1)}}},[h,n,e,s,v,p,m,d]),T=!!(a!=null&&a.hasConflicts),F=a?a.staged+a.modified+a.untracked+a.deleted+a.renamed:null;return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:W=>{W.target===W.currentTarget&&r()},children:t.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:[t.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[t.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),t.jsx("p",{className:"truncate text-xs text-text-secondary",children:s}),L&&t.jsx("a",{href:`${L}/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 ↗"})]}),t.jsx("button",{onClick:d,disabled:l,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),t.jsx("button",{onClick:r,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:t.jsx(gt,{className:"h-4 w-4"})})]}),a&&t.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&&t.jsxs("span",{title:a.headMessage??void 0,children:[t.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&t.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&t.jsxs("span",{className:"text-orange-400",children:["↑",a.ahead," ahead"]}),a.behind>0&&t.jsxs("span",{className:"text-orange-400",children:["↓",a.behind," behind"]}),a.staged>0&&t.jsxs("span",{className:"text-emerald-400",children:[a.staged," staged"]}),a.modified>0&&t.jsxs("span",{children:[a.modified," modified"]}),a.untracked>0&&t.jsxs("span",{children:[a.untracked," untracked"]}),a.deleted>0&&t.jsxs("span",{className:"text-red-400",children:[a.deleted," deleted"]}),a.stashCount>0&&t.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&t.jsx("span",{className:"font-bold text-red-400",children:"conflicts"}),F===0&&!a.error&&t.jsx("span",{className:"text-emerald-500",children:"clean"}),o&&o.files.length>0&&t.jsxs("span",{className:"text-text-secondary",children:[o.files.length," file",o.files.length!==1?"s":"",o.totalInsertions>0&&t.jsxs("span",{className:"text-emerald-500",children:[" +",o.totalInsertions]}),o.totalDeletions>0&&t.jsxs("span",{className:"text-red-400",children:[" -",o.totalDeletions]})]})]}),c&&t.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}),t.jsxs("div",{className:"flex min-h-0 flex-1",children:[t.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[l&&!o&&t.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),o&&t.jsx(Ay,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:k}),!l&&!o&&!c&&t.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),t.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:m?t.jsx(Ly,{diff:m.diff,binary:m.binary,truncated:m.truncated,loading:m.loading,error:m.error,className:"h-full"}):t.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),w&&t.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:[t.jsx("span",{children:w}),t.jsx("button",{onClick:()=>A(null),className:"ml-2 text-emerald-400 hover:text-text-primary",children:"×"})]}),t.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[t.jsx("button",{onClick:()=>j("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"}),t.jsx("button",{onClick:()=>j("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"}),t.jsx("button",{onClick:()=>j("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"}),t.jsx("button",{onClick:()=>j("checkout_files"),disabled:!m,title:m?`Revert changes to ${m.path}`:"Select a file to revert",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkout selected"}),o&&o.files.length>0&&t.jsx("button",{onClick:()=>{const W=Ry((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(W),A("Copied to clipboard"),setTimeout(()=>A(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),h&&t.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:t.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[t.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[h==="checkpoint"&&"Create checkpoint commit",h==="stash"&&"Stash changes",h==="stash_pop"&&"Restore latest stash?",h==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(h==="checkpoint"||h==="stash")&&t.jsxs(t.Fragment,{children:[t.jsx("input",{type:"text",value:v,onChange:W=>f(W.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}),t.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[t.jsx("input",{type:"checkbox",checked:p,onChange:W=>b(W.target.checked)}),"Include untracked files"]})]}),N&&t.jsx("p",{className:"text-xs text-red-400",children:N}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.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"}),t.jsx("button",{onClick:R,disabled:y||(h==="checkpoint"||h==="stash")&&!v.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 _y({isMobile:e,showMobileChatMode:s,visibleConversationCount:r}){const[n,a]=i.useState(!1),[o,l]=i.useState(!1),[c,d]=i.useState(!1),[m,u]=i.useState(!1),[h,g]=i.useState(!1),[v,f]=i.useState("quickstart"),[p,b]=i.useState("workspace"),y=i.useMemo(()=>!s&&!e,[s,e]),x=i.useCallback(k=>{a(k),k&&l(!1)},[]),N=i.useCallback(k=>{l(k),k&&a(!1)},[]),S=i.useCallback(()=>{f(r===0?"quickstart":"shortcuts"),b("workspace"),d(!0),a(!1),l(!1)},[r]),w=i.useCallback(()=>{d(!1)},[]),A=i.useCallback(()=>{u(!0)},[]),L=i.useCallback(()=>{u(!1)},[]);return i.useEffect(()=>{if(!y){g(!1);return}g(!0);const k=window.setTimeout(()=>{g(!1)},1e4);return()=>window.clearTimeout(k)},[y]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:m,guideNudgeVisible:h,guideTab:v,shortcutSection:p,isDesktopDashboard:y,setGuideTab:f,setShortcutSection:b,handleInboxOpenChange:x,handleHiddenOpenChange:N,handleOpenShortcutHelp:S,closeShortcutHelp:w,openNewSession:A,closeNewSession:L}}function Py(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 Dy(e){return e instanceof Error?e.message:String(e||"")}function Ey(e){const s=Dy(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function $y({showMobileChatMode:e,isMobile:s,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:l,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:h,ides:g,actionLogs:v,sendDaemonCommand:f,setActionLogs:p,setCliViewModeOverrides:b,isStandalone:y,initialDataLoaded:x,userName:N,requestedMobileTabKey:S,onRequestedMobileTabConsumed:w,requestedMachineId:A,onRequestedMachineConsumed:L,requestedMobileSection:k,onRequestedMobileSectionConsumed:j,containerRef:O,isSplitMode:R,numGroups:T,groupSizes:F,groupedConvs:W,clearedTabs:D,focusedGroup:C,focusGroup:I,moveTabToGroup:K,splitTabRelative:_,closeGroup:E,handleResizeStart:V,groupActiveTabIds:Y,setGroupActiveTab:ge,groupTabOrders:pe,setGroupTabOrder:re,toggleHiddenTab:de,visibleConversations:ke,requestedDesktopTabKey:ye,onRequestedDesktopTabConsumed:q,onDesktopActiveTabChange:he,onRequestScrollToBottom:fe,onHideConversation:we,onShowHiddenConversation:xe,onShowAllHiddenConversations:Se,scrollToBottomRequest:Q,machineEntries:ue,layoutProfile:oe,onBrowseMachineDirectory:me,onSaveMachineWorkspace:le,onLaunchMachineIde:P,onLaunchMachineProvider:U,onListMachineMeshes:ce,onLaunchMeshCoordinator:te,onListMachineSavedSessions:ie,notifications:se,notificationUnreadCount:ve,liveSessionInboxState:Ie,onMarkNotificationRead:Me,onMarkNotificationUnread:B,onDeleteNotification:Ne}){const Re=wt.useRef(null),{inboxOpen:Fe,hiddenOpen:He,shortcutHelpOpen:Ge,newSessionOpen:qe,guideNudgeVisible:et,guideTab:dt,shortcutSection:pt,isDesktopDashboard:bt,setGuideTab:Ce,setShortcutSection:Ue,handleInboxOpenChange:Qe,handleHiddenOpenChange:ze,handleOpenShortcutHelp:rt,closeShortcutHelp:H,openNewSession:z,closeNewSession:J}=_y({isMobile:s,showMobileChatMode:e,visibleConversationCount:ke.length}),[ne,$]=wt.useState(null),[G,ee]=wt.useState(null),ae=wt.useCallback((M,X)=>{$({daemonId:M,workspace:X})},[]),je=wt.useCallback(M=>{ee(M)},[]),_e=wt.useCallback(M=>{var X;xr.flushSync(()=>{xe(M)}),(X=Re.current)==null||X.restoreHiddenTabToSavedLocation(M.tabKey)},[xe]),De=wt.useCallback(M=>{var be;const X=u.find($e=>Fa($e,M))||h.find($e=>Fa($e,M));X&&(h.some($e=>$e.tabKey===X.tabKey)&&_e(X),he(X.tabKey),(be=Re.current)==null||be.activateConversationTab(X.tabKey),fe(X.tabKey,"notification-open")),Me(M.id),Qe(!1)},[_e,h,u,he,Me,fe]),Ae=wt.useCallback(()=>{var X;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((X=Re.current)==null||X.resetAllPanelsToMain(),ze(!1))},[ze]),Ee=wt.useCallback(async M=>{var Be;if(!r)return;const X=(Be=r.modalButtons)==null?void 0:Be[M];if(!X)return;const be=Bs(r);if(!be)return;const $e=X.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Le=/^(run|approve|accept|yes|allow|always|proceed|save)/.test($e);try{await f(be,"resolve_action",{button:X,action:Le?"approve":"reject",buttonIndex:M,...cs(r)})}catch(tt){Ey(tt)||console.error("[Shortcut approval] Failed:",tt)}},[r,f]),{isMac:Oe,actionDefinitions:Te,actionShortcuts:Ye,shortcutListening:Je,shortcutListeningDraft:ft,setShortcutListening:ht,setShortcutListeningDraft:it,saveShortcuts:ut}=$g({enabled:bt&&!Ge,onTrigger:M=>{var X,be,$e,Le,Be,tt,Nt,mt,qt,Ir,Tr,Ar,Mr,Lr,Rr,_r;if(M==="openShortcutHelp"){rt();return}if(M==="openNewSession"){z();return}if(M==="hideCurrentTab"){r&&we(r);return}if(M==="toggleHiddenTabs"){ze(!He);return}if(M==="openHistoryForActiveTab"){r&&!Ze(r)&&o(r);return}if(M==="openRemoteForActiveTab"){r&&!st(r)&&!Ze(r)&&l(r);return}if(M==="splitActiveTabRight"){(X=Re.current)==null||X.splitActiveTabRight();return}if(M==="splitActiveTabDown"){(be=Re.current)==null||be.splitActiveTabDown();return}if(M==="floatActiveTab"){($e=Re.current)==null||$e.floatActiveTab();return}if(M==="popoutActiveTab"){(Le=Re.current)==null||Le.popoutActiveTab();return}if(M==="dockActiveTab"){(Be=Re.current)==null||Be.dockActiveTab();return}if(M==="focusLeftPane"){(tt=Re.current)==null||tt.focusLeftPane();return}if(M==="focusRightPane"){(Nt=Re.current)==null||Nt.focusRightPane();return}if(M==="focusUpPane"){(mt=Re.current)==null||mt.focusUpPane();return}if(M==="focusDownPane"){(qt=Re.current)==null||qt.focusDownPane();return}if(M==="moveActiveTabToLeftPane"){(Ir=Re.current)==null||Ir.moveActiveTabToLeftPane();return}if(M==="moveActiveTabToRightPane"){(Tr=Re.current)==null||Tr.moveActiveTabToRightPane();return}if(M==="moveActiveTabToUpPane"){(Ar=Re.current)==null||Ar.moveActiveTabToUpPane();return}if(M==="moveActiveTabToDownPane"){(Mr=Re.current)==null||Mr.moveActiveTabToDownPane();return}if(M==="triggerPrimaryApprovalAction"){Ee(0);return}if(M==="triggerSecondaryApprovalAction"){Ee(1);return}if(M==="triggerTertiaryApprovalAction"){Ee(2);return}if(M==="setActiveTabShortcut"){(Lr=Re.current)==null||Lr.setShortcutForActiveTab();return}if(M==="selectPreviousGroupTab"){(Rr=Re.current)==null||Rr.activatePreviousTabInGroup();return}if(M==="selectNextGroupTab"){(_r=Re.current)==null||_r.activateNextTabInGroup();return}!r||!st(r)||Ze(r)||M==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),We=wt.useCallback(()=>{H(),ht(null),it([])},[H,ht,it]),$t=wt.useMemo(()=>pt==="all"?Te:Te.filter(M=>Py(M)===pt),[Te,pt]),Z=wt.useCallback(()=>{const M=Object.fromEntries(Te.map(X=>[X.id,""]));ut(M)},[Te,ut]),Pe=wt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const M=Object.fromEntries(Te.map(X=>[X.id,X.defaultShortcut]));ut(M)},[Te,ut]);return wt.useEffect(()=>{const M=X=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?X.metaKey&&X.key.toLowerCase()==="w":X.ctrlKey&&X.key.toLowerCase()==="w")&&(X.preventDefault(),r&&we&&we(r))};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[r,we]),wt.useEffect(()=>{if(!Ge||Je)return;const M=X=>{X.key==="Escape"&&(X.preventDefault(),We())};return window.addEventListener("keydown",M,!0),()=>window.removeEventListener("keydown",M,!0)},[We,Ge,Je]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(Ph,{activeConv:r,wsStatus:n,isConnected:a,conversations:ke,hiddenConversations:h,onOpenHistory:o,onHideConversation:we,onShowConversation:_e,onShowAllHidden:Se,onResetPanelsToMain:Ae,notifications:se,notificationUnreadCount:ve,onOpenNotification:De,onMarkNotificationRead:Me,onMarkNotificationUnread:B,onDeleteNotification:Ne,inboxOpen:Fe,onInboxOpenChange:Qe,hiddenOpen:He,onHiddenOpenChange:ze,onOpenNewSession:s?void 0:z,onOpenDashboardGuide:rt,guideNudgeVisible:et,actionShortcuts:Ye,onOpenRemote:()=>{!r||st(r)||Ze(r)||l(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:ae,onOpenMeshGraph:je}),e?t.jsx(Ng,{conversations:u,hiddenConversations:h,ides:g,actionLogs:v,sendDaemonCommand:f,setActionLogs:p,setCliViewModeOverrides:b,isStandalone:y,userName:N,requestedActiveTabKey:S,onRequestedActiveTabConsumed:w,requestedMachineId:A,onRequestedMachineConsumed:L,requestedMobileSection:k,onRequestedMobileSectionConsumed:j,onOpenHistory:o,onOpenRemote:l,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Se,onHideConversation:we,onOpenMeshGraph:je,onOpenNewSession:z,liveSessionInboxState:Ie}):s?t.jsx(_g,{containerRef:O,isSplitMode:R,numGroups:T,groupSizes:F,groupedConvs:W,clearedTabs:D,ides:g,actionLogs:v,sendDaemonCommand:f,setActionLogs:p,isStandalone:y,hasRegisteredMachines:ue.length>0,userName:N,focusedGroup:C,focusGroup:I,moveTabToGroup:K,splitTabRelative:_,closeGroup:E,handleResizeStart:V,groupActiveTabIds:Y,setGroupActiveTab:ge,groupTabOrders:pe,setGroupTabOrder:re,toggleHiddenTab:de,onOpenNewSession:z,allowTabShortcuts:!1,liveSessionInboxState:Ie}):t.jsx(Jg,{visibleConversations:ke,clearedTabs:D,ides:g,actionLogs:v,sendDaemonCommand:f,setActionLogs:p,isStandalone:y,hasRegisteredMachines:ue.length>0,initialDataLoaded:x,userName:N,toggleHiddenTab:de,actionShortcuts:Ye,registerActionHandlers:M=>{Re.current=M},onActiveTabChange:he,requestedActiveTabKey:ye,onRequestedActiveTabConsumed:q,onRequestScrollToBottom:fe,scrollToBottomRequest:Q,onOpenNewSession:z,liveSessionInboxState:Ie,layoutProfile:oe}),qe&&t.jsx(sy,{machines:ue,ides:g,onClose:J,onBrowseDirectory:me,onSaveWorkspace:le,onLaunchIde:P,onLaunchProvider:U,onListMeshes:ce,onLaunchMeshCoordinator:te,onListSavedSessions:ie}),G&&t.jsx(xy,{activeConv:G,sendDaemonCommand:f,onClose:()=>ee(null)}),ne&&t.jsx(zd,{daemonId:ne.daemonId,workspace:ne.workspace,onClose:()=>$(null)}),Ge&&t.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:We,children:t.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:M=>M.stopPropagation(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),t.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."})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:We,"aria-label":"Close dashboard guide",children:t.jsx(gt,{size:14})})]}),t.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(M=>t.jsx("button",{type:"button",className:`btn btn-sm ${dt===M.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ce(M.id),children:M.label},M.id))}),dt==="overview"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Oe?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),dt==="quickstart"&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),t.jsxs("div",{children:[t.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."]})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]})]})]})]}),dt==="shortcuts"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[t.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(M=>t.jsx("button",{type:"button",className:`btn btn-sm ${pt===M.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ue(M.id),children:M.label},M.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Z,children:"Disable all"}),t.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"})]})]}),t.jsx("div",{className:"space-y-2",children:$t.map(M=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${Je===M.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:M.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:M.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:M.defaultShortcut})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t.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:Je===M.id?ft.length>0?`${ft.join(" ")} ...`:"Listening...":Ye[M.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{ht(M.id),it([])},children:Je===M.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const X={...Ye};X[M.id]="",ut(X)},children:"Disable"})]})]})},M.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Oe?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",", or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs."]})]})]})})]})}const ya=[{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 By({onClose:e}){const[s,r]=i.useState(0),n=ya[s],a=s===ya.length-1;return t.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:[t.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:[t.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:t.jsx(gt,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:ya.map((o,l)=>t.jsx("div",{style:{width:l===s?24:8,height:8,borderRadius:4,background:l===s?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},l))}),t.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),t.jsxs("div",{style:{textAlign:"center"},children:[t.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[t.jsx("span",{children:n.icon})," ",n.title]}),t.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&t.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:[t.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&t.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 →"})]}),t.jsx("div",{className:"flex justify-end items-center mt-6",children:t.jsx("button",{onClick:()=>a?e():r(o=>o+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),t.jsx("style",{children:`
67
+ @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
68
+ @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
69
+ `})]})}function Oy({hasExtensions:e,ideName:s,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?t.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[t.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:s}),n.map(o=>{const l=r===o.tabKey,c=o.status==="waiting_approval",d=o.status==="generating";return t.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${l?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(o.tabKey),children:[t.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&&t.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 Ky({ideData:e,allIdes:s,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,l]=i.useState(()=>a||"native"),c=i.useMemo(()=>Oc(s),[s]),d=i.useMemo(()=>e?Ro(e,{machineNames:c,connectionStates:r,defaultConnectionState:"new"}):[],[e,c,r]),m=i.useMemo(()=>d.find(p=>p.streamSource==="native"),[d]),u=i.useMemo(()=>d.filter(p=>p.streamSource==="agent-stream"),[d]),h=i.useMemo(()=>e?Et(d,e.id):null,[d,e]);i.useEffect(()=>{a&&l(a)},[a]),i.useEffect(()=>{if(a||!h)return;const p=h.streamSource==="native"?"native":h.tabKey;!p||o===p||o==="native"&&l(p)},[o,h,a]),i.useEffect(()=>{var p;o!=="native"&&(u.some(b=>b.tabKey===o)||l(((p=u[0])==null?void 0:p.tabKey)||"native"))},[o,u]),i.useEffect(()=>{o==="native"&&(m||u[0]&&l(u[0].tabKey))},[o,m,u]);const g=i.useMemo(()=>o==="native"&&m?m:u.find(p=>p.tabKey===o)||h||m||u[0],[o,m,h,u]),v=i.useMemo(()=>u.map(p=>({tabKey:p.tabKey,title:Rc(p)||n,status:p.status})),[u,n]),f=i.useCallback(p=>{if(p)return d.find(b=>Fa(b,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[d]);return{activeChatTab:o,setActiveChatTab:l,activeConv:g,conversations:d,extensionTabs:v,hasExtensions:v.length>0,resolveConversationByTarget:f}}function Fy({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:l,isStandalone:c,userName:d,onOpenHistory:m,onConversationChange:u,onClose:h}){const[g,v]=i.useState("split"),[f,p]=i.useState(()=>ts(e)?"native":e.tabKey),b=i.useRef(null),y=i.useMemo(()=>s||r.find(I=>I.id===e.routeId),[e.routeId,s,r]),x=i.useMemo(()=>ot((y==null?void 0:y.type)||""),[y==null?void 0:y.type]),{conversations:N,extensionTabs:S,hasExtensions:w}=Ky({ideData:y,allIdes:r,connectionStates:n,ideName:x||"IDE",preferredTabKey:ts(e)?void 0:e.tabKey}),A=i.useMemo(()=>y?Et(N,y.id):null,[y,N]);i.useEffect(()=>{const I=b.current,K={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(b.current=K,!(I&&I.routeId===K.routeId&&I.tabKey===K.tabKey&&I.streamSource===K.streamSource)){if(ts(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),i.useEffect(()=>{if(f==="native"){if(N.some(I=>I.streamSource==="native"))return;(A==null?void 0:A.streamSource)==="agent-stream"&&p(A.tabKey);return}if(!N.some(I=>I.tabKey===f)){if((A==null?void 0:A.streamSource)==="agent-stream"){p(A.tabKey);return}p("native")}},[N,f,A]);const L=i.useMemo(()=>f==="native"?N.find(I=>I.streamSource==="native")||e:N.find(I=>I.tabKey===f)||e,[e,N,f]),k=Qc(L),j=i.useMemo(()=>k.status||k.modalMessage||k.modalButtons?{...L,...k.status?{status:k.status}:{},...k.modalMessage!==void 0?{modalMessage:k.modalMessage}:{},...k.modalButtons!==void 0?{modalButtons:k.modalButtons}:{}}:L,[L,k]),O=kr(j),R=Ln({sendDaemonCommand:o,activeConv:j,setActionLogs:l,isStandalone:c}),{connScreenshot:T,screenshotUsage:F,handleRemoteAction:W}=Id({doId:O,targetSessionId:hc(j),connState:j.connectionState||"new",viewMode:g}),D=i.useMemo(()=>a.filter(I=>I.routeId===j.tabKey),[a,j.tabKey]);i.useEffect(()=>{u==null||u(j)},[j,u]),i.useEffect(()=>{const I=K=>{K.key==="Escape"&&h()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[h]);const C=i.useCallback(I=>{I.stopPropagation()},[]);return t.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:h,children:t.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:C,children:[t.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:[t.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[t.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:t.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:[t.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(It,{size:16})}),t.jsx("span",{className:"truncate",children:vo(L)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,children:"Close"})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[t.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(I=>{const K=g===I;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${K?"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:()=>v(I),title:I==="split"?"Split view":"Remote only",children:I==="split"?t.jsx(um,{size:15}):t.jsx(It,{size:15})},I)})}),t.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),t.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>m(L),title:"Chat History",children:[t.jsx(io,{size:14,className:"md:mr-1.5"}),t.jsx("span",{className:"hidden md:inline",children:"History"})]}),t.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:h,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${g==="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:[g!=="remote"&&t.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${g==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[t.jsx(Oy,{hasExtensions:w,ideName:x||"IDE",activeChatTab:f,extensionTabs:S,onSelectTab:p}),t.jsx(tc,{activeConv:j,onModalButton:R.handleModalButton}),t.jsx(Ha,{activeConv:j,ideEntry:y,showMetaChips:!1,handleSendChat:R.handleSendChat,isSendingChat:R.isSendingChat,sendFeedbackMessage:R.sendFeedbackMessage,handleFocusAgent:R.handleFocusAgent,isFocusingAgent:R.isFocusingAgent,actionLogs:D,userName:d})]}),t.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${g==="split"?"order-1 md:order-2":""}`,children:t.jsx(Zl,{addLog:()=>{},connState:j.connectionState||"new",connScreenshot:T,screenshotUsage:F,transportType:j.transport,onAction:W})})]})]})})}function Wy({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=kh(e);return t.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:[t.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.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:[t.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[t.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",o,"?"]}),t.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:s?"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."})]}),t.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s&&t.jsx("button",{onClick:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),t.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"}),t.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function Hy({historyModal:e,remoteDialog:s,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o}){var l;return t.jsxs(t.Fragment,{children:[t.jsx(Th,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&t.jsx(Lo,{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}),s.conversation&&t.jsx(Fy,{activeConv:s.conversation,ideEntry:s.ideEntry,ides:s.ides,connectionStates:s.connectionStates,actionLogs:s.actionLogs,sendDaemonCommand:s.sendDaemonCommand,setActionLogs:s.setActionLogs,isStandalone:s.isStandalone,userName:s.userName,onOpenHistory:s.onOpenHistory,onConversationChange:s.onConversationChange,onClose:s.onClose}),r.open&&r.targetConv&&(st(r.targetConv)||Ze(r.targetConv))&&t.jsx(Wy,{activeConv:r.targetConv,canSaveAndStop:st(r.targetConv)&&!Ze(r.targetConv)&&!!((l=r.targetConv.resume)!=null&&l.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),t.jsx(Bc,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),o.open&&t.jsx(By,{onClose:o.onClose})]})}function Uy({daemons:e,targetVersion:s,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:o}){return e.length===0?null:t.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:[t.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:t.jsx(wr,{size:14})}),t.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[t.jsxs("span",{children:[r?"Daemon update required":"Update available",s?t.jsxs(t.Fragment,{children:[": ",t.jsxs("strong",{children:["v",s]})]}):null]}),e.map(l=>{const c=Ct(l,{fallbackId:l.id}),d=n[l.id],m=l.version||l.daemonVersion||"unknown",u=l.versionUpdateRequired===!0,g=md(l)==="preview"?"Update to preview":u?"Update now":"Upgrade";return t.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:[t.jsx("span",{className:"font-medium text-text-primary",children:c}),t.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),u&&t.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),d==="upgrading"?t.jsx("span",{className:"text-[10px] animate-pulse",style:{color:u?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):d==="done"?t.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="error"?t.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(l.id),children:"retry"}):t.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:u?"var(--status-danger)":"var(--status-warning)",background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(l.id),children:g})]},l.id)})]}),!r&&t.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:t.jsx(gt,{size:16})})]})}function zy(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function Vy(e){const s=e.machine;return typeof(s==null?void 0:s.cpus)!="number"||typeof(s==null?void 0:s.totalMem)!="number"||typeof(s==null?void 0:s.arch)!="string"||typeof(s==null?void 0:s.release)!="string"}function Gy(e){return{metadataDaemonIds:e.map(s=>s.id),runtimeDaemonIds:e.filter(s=>Vy(s)).map(s=>s.id)}}function qy(){var Jo,Qo,Zo,ei;const{sendCommand:e}=yt(),s=Sr(),r=Jc(),n=no(),a=Hs(),[o,l]=Lu(),c=o.get("activeTab"),d=((Jo=n.state)==null?void 0:Jo.openRemoteForTabKey)||null,m=((Qo=n.state)==null?void 0:Qo.openMachineId)||null,u=((Zo=n.state)==null?void 0:Zo.mobileSection)||null,h=Tc(),g=h.ides||[],v=h.initialLoaded??!0,{updateRouteChats:f,setToasts:p}=h,[b,y]=i.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),x=h.toasts||[],N=h.wsStatus||"connected",S=h.isConnected??!0,w=h.connectionStates||{},A=h.showReconnected||!1,{layoutProfile:L,groupAssignments:k,updateGroupAssignments:j,focusedGroup:O,updateFocusedGroup:R,focusGroup:T,groupActiveTabIds:F,updateGroupActiveTabIds:W,setGroupActiveTab:D,groupTabOrders:C,updateGroupTabOrders:I,setGroupTabOrder:K,groupSizes:_,updateGroupSizes:E,isMobile:V,hasHydratedStoredLayout:Y,hydrateStoredLayout:ge,focusConversationTab:pe}=yb(),[re,de]=i.useState(()=>Eo());i.useEffect(()=>Lx(de),[]);const ke=i.useMemo(()=>zy({isMobile:V,mobileViewMode:re}),[V,re]),[ye,q]=i.useState([]),[he,fe]=i.useState({}),[we,xe]=i.useState({});jr("Dashboard",{ideCount:g.length,toastCount:x.length,focusedGroup:O,groupCount:Object.keys(k).length,actionLogCount:ye.length});const Se=i.useMemo(()=>g.filter(Ve=>Ve.type==="adhdev-daemon").sort(bo),[g]),Q=Se[0],ue=!!Q;i.useEffect(()=>{const{metadataDaemonIds:Ve,runtimeDaemonIds:Lt}=Gy(Se);for(const Vs of Ve)s(Vs,{minFreshMs:3e4}).catch(()=>{});for(const Vs of Lt)r(Vs,{minFreshMs:3e4}).catch(()=>{})},[s,r,Se]);const oe=(Q==null?void 0:Q.terminalBackend)||null,me=Q?Ct(Q,{fallbackId:Q.id}):null,le=(Q==null?void 0:Q.id)||null,P=i.useMemo(()=>zx(g,he),[g,he]),{hiddenTabs:U,autoHiddenTabs:ce,autoHideTarget:te,hideTarget:ie,toggleTarget:se,showTarget:ve,showAllTabs:Ie}=Ux(),{conversations:Me,visibleConversations:B,visibleTabKeys:Ne,resolveConversationBySessionId:Re,resolveConversationByTarget:Fe}=nb({ides:P,connectionStates:w,clearedTabs:we,hiddenTabs:U}),He=i.useMemo(()=>new Map(Me.map(Ve=>[Ve.tabKey,Ve])),[Me]),Ge=i.useMemo(()=>Hx(Me,U,ce),[Me,U,ce]);i.useEffect(()=>{for(const Ve of Ge)te(Ve)},[Ge,te]),eh(B,ke),i.useEffect(()=>{Object.keys(he).length!==0&&fe(Ve=>Vx(Ve,g))},[g,he]);const qe=i.useMemo(()=>ip(g),[g]),{notifications:et,unreadCount:dt}=Db({conversations:Me,liveSessionInboxState:qe}),{handleMarkDashboardNotificationRead:pt,handleMarkDashboardNotificationUnread:bt,handleDeleteDashboardNotification:Ce}=Eb({notifications:et,sendDaemonCommand:e}),{containerRef:Ue,normalizedGroupAssignments:Qe,numGroups:ze,isSplitMode:rt,groupedConvs:H,moveTabToGroup:z,closeGroup:J,handleResizeStart:ne,splitTabRelative:$}=Cb({groupAssignments:k,updateGroupAssignments:j,updateFocusedGroup:R,updateGroupActiveTabIds:W,updateGroupTabOrders:I,groupSizes:_,updateGroupSizes:E,isMobile:V,visibleConversations:B,visibleTabKeys:Ne}),{activeConv:G,openDesktopConversation:ee,requestScrollToBottom:ae,scrollToBottomRequest:je,setDesktopActiveTab:_e}=Jb({isMobile:V,conversations:Me,visibleConversations:B,groupActiveTabIds:F,focusedGroup:O,groupedConvs:H,setSearchParams:l});eg({activeConv:G,isMobile:V,liveSessionInboxState:qe,sendDaemonCommand:e});const{requestedDesktopTabKey:De,requestedMobileTabKey:Ae,consumeRequestedActiveTab:Ee}=ab({isMobile:V,urlActiveTab:c,resolveConversationBySessionId:Re,setSearchParams:l}),{remoteDialogConv:Oe,remoteDialogIdeEntry:Te,remoteDialogActiveConv:Ye,setRemoteDialogActiveConv:Je,openRemoteDialog:ft,closeRemoteDialog:ht,cliStopDialogOpen:it,cliStopTargetConv:ut,requestCliStop:We,cancelCliStop:$t,confirmCliStop:Z}=rg({isMobile:V,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:De,conversations:Me,ides:g,resolveConversationByTarget:Fe,activeConv:G,sendDaemonCommand:e}),{historyModalOpen:Pe,openHistoryModal:M,closeHistoryModal:X,historyTargetConv:be,isSavedSessionHistoryTarget:$e,isHistoryCreatingChat:Le,isHistoryRefreshingHistory:Be,handleHistorySwitchSession:tt,handleHistoryNewChat:Nt,handleHistoryRefresh:mt,savedHistorySessions:qt,savedHistoryFilters:Ir,setSavedHistoryFilters:Tr,missingWorkspaceResumePath:Ar,isSavedHistoryLoading:Mr,resumingSavedHistorySessionId:Lr,handleRefreshSavedHistory:Rr,handleResumeSavedHistorySession:_r}=tg({activeConv:G,remoteDialogConv:Oe,remoteDialogActiveConv:Ye,ides:g,sendDaemonCommand:e,updateRouteChats:f,setToasts:p,setClearedTabs:xe,setSearchParams:l}),Xd=i.useMemo(()=>B,[B]),Pr=V&&re==="chat",Jd=i.useMemo(()=>Me.filter(Ve=>_n(U,Ve)),[Me,U]),qo=i.useCallback(Ve=>{const Lt=new URLSearchParams(o);Lt.set("activeTab",Ve),l(Lt,{replace:!0})},[o,l]),{trackPendingLaunch:Qd}=Gb({ides:g,conversations:Me,onOpenSession:qo}),{handleBrowseMachineDirectory:Zd,handleSaveMachineWorkspace:eu,handleLaunchMachineIde:tu,handleLaunchMachineProvider:su,handleListMachineMeshes:ru,handleLaunchMeshCoordinator:nu,handleListMachineSavedSessions:au,setActiveCliViewMode:ou}=qb({sendDaemonCommand:e,trackPendingLaunch:Qd,onOpenSession:qo,activeConv:G,ides:g,setCliViewModeOverrides:fe});Gx({visibleConversations:B,clearedTabs:we,setClearedTabs:xe,setActionLogs:q}),ob({ides:g,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Fe});const{isRefreshingHistory:iu,handleRefreshHistory:lu}=ud({sendDaemonCommand:e,activeConv:G,chats:(ei=g.find(Ve=>Ve.id===(G==null?void 0:G.routeId)))==null?void 0:ei.chats,updateRouteChats:f,setToasts:p,setClearedTabs:xe});wb({urlActiveTab:V&&!Pr?c:null,conversations:Me,resolveConversationBySessionId:Re,normalizedGroupAssignments:Qe,hasHydratedStoredLayout:V&&!Pr?Y:!0,hydrateStoredLayout:V&&!Pr?ge:()=>{},focusConversationTab:pe,setSearchParams:l,historyModalOpen:Pe,activeConv:G,isRefreshingHistory:iu,ides:g,handleRefreshHistory:lu});const cu=i.useMemo(()=>!G||!st(G)||Ze(G)?null:zs(G),[G]),{versionMismatchDaemons:du,hasRequiredVersionDaemons:Yo,targetVersion:uu,versionBannerDismissed:mu,setVersionBannerDismissed:pu,upgradingDaemons:fu,handleBannerUpgrade:hu}=Tb({ides:g,sendDaemonCommand:e}),Xo=i.useCallback(Ve=>{ve(Ve),ee(Ve)},[ee,ve]),xu=i.useCallback(Ve=>{ie(Ve)},[ie]);return t.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[t.jsx(Ah,{terminalBackend:oe,isStandalone:ue,machineLabel:me,machineKey:le}),(!mu||Yo)&&t.jsx(Uy,{daemons:du,targetVersion:uu,required:Yo,upgradingDaemons:fu,onUpgrade:hu,onDismiss:()=>pu(!0)}),t.jsx($y,{showMobileChatMode:Pr,isMobile:V,activeConv:G,wsStatus:N,isConnected:S,onOpenHistory:Ve=>{Ve&&Je(Ve),M()},onOpenRemote:ft,onStopCli:We,activeCliViewMode:cu,onSetActiveCliViewMode:ou,mobileChatConversations:Xd,ides:g,actionLogs:ye,sendDaemonCommand:e,setActionLogs:q,setCliViewModeOverrides:fe,isStandalone:ue,initialDataLoaded:v,userName:h.userName,requestedMobileTabKey:Ae,onRequestedMobileTabConsumed:Ee,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:Ue,isSplitMode:rt,numGroups:ze,groupSizes:_,groupedConvs:H,clearedTabs:we,focusedGroup:O,focusGroup:T,moveTabToGroup:z,splitTabRelative:$,closeGroup:J,handleResizeStart:ne,groupActiveTabIds:F,setGroupActiveTab:D,groupTabOrders:C,setGroupTabOrder:K,toggleHiddenTab:Ve=>se(He.get(Ve)||{tabKey:Ve}),visibleConversations:B,hiddenConversations:Jd,requestedDesktopTabKey:De,onRequestedDesktopTabConsumed:Ee,onDesktopActiveTabChange:_e,onRequestScrollToBottom:ae,onHideConversation:xu,onShowHiddenConversation:Xo,onShowAllHiddenConversations:Ie,scrollToBottomRequest:je,machineEntries:Se,layoutProfile:L,onBrowseMachineDirectory:Zd,onSaveMachineWorkspace:eu,onLaunchMachineIde:tu,onLaunchMachineProvider:su,onListMachineMeshes:ru,onLaunchMeshCoordinator:nu,onListMachineSavedSessions:au,notifications:et,notificationUnreadCount:dt,liveSessionInboxState:qe,onMarkNotificationRead:pt,onMarkNotificationUnread:bt,onDeleteNotification:Ce}),t.jsx("style",{children:`
70
+ body { overflow: hidden; overscroll-behavior: none; }
71
+ `}),t.jsx(Hy,{historyModal:{open:Pe,targetConv:be,ides:g,isCreatingChat:Le,isRefreshingHistory:$e?!1:Be,savedSessions:qt,savedHistoryFilters:Ir,missingWorkspaceResumePath:Ar||null,onSavedHistoryFiltersChange:Tr,isSavedSessionsLoading:Mr,isResumingSavedSessionId:Lr,onClose:X,onNewChat:Nt,onSwitchSession:tt,onRefreshHistory:$e?Rr:mt,onResumeSavedSession:_r},remoteDialog:{conversation:Oe,ideEntry:Te,ides:g,connectionStates:w,actionLogs:ye,sendDaemonCommand:e,setActionLogs:q,isStandalone:ue,userName:h.userName,onOpenHistory:Ve=>{Ve&&Je(Ve),M()},onConversationChange:Je,onClose:ht},cliStopDialog:{open:it,targetConv:ut,onCancel:$t,onStopNow:async()=>{await Z("hard")},onSaveAndStop:async()=>{await Z("save")}},connectionBanner:{wsStatus:N,showReconnected:A,loginUrl:h.connectionLoginUrl,onReconnect:h.retryServerConnection},toastOverlay:{toasts:x,onDismiss:Ve=>p(Lt=>Lt.filter(Vs=>Vs.id!==Ve)),onClick:Ve=>{if(Ve.targetKey){const Lt=Fe(Ve.targetKey);Lt&&(pe(Lt.tabKey,Qe),Xo(Lt),ae(Lt.tabKey,"toast-open"))}}},onboarding:{open:b,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}y(!1)}}})]})}function Yy({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[o,l]=i.useState([]),[c,d]=i.useState(null),[m,u]=i.useState(null),[h,g]=i.useState(!1),[v,f]=i.useState(null),[p,b]=i.useState(!1),[y,x]=i.useState(""),N=i.useRef(null),S=i.useCallback(_=>{N.current=_},[]),w=i.useCallback((_,E,V=!1)=>{l(Y=>[...Y.slice(-100),{timestamp:Date.now(),level:_,message:E}]),setTimeout(()=>{var Y;return(Y=a.current)==null?void 0:Y.scrollIntoView({behavior:"smooth"})},100),V&&nt.showToast(E,_==="error"||_==="warn"?"warning":"success")},[a]),A=i.useCallback(_=>{const E=_ instanceof Error?_.message:String(_||"");return E.includes("P2P command timeout")||E.includes("P2P not connected")||E.includes("P2P not available")},[]),L=i.useCallback(async(_,E)=>{var V;if(!e||c)return!1;d(_),w("info",`Launching ${ot(_)}${E!=null&&E.workspace?` in ${E.workspace}`:""}...`);try{const Y={ideType:_,enableCdp:!0};(V=E==null?void 0:E.workspace)!=null&&V.trim()?Y.workspace=E.workspace.trim():E!=null&&E.useDefaultWorkspace&&(Y.useDefaultWorkspace=!0);const ge=await r(e,"launch_ide",Y);return w(ge!=null&&ge.success?"info":"error",ge!=null&&ge.success?`${ot(_)} launched`:`Failed: ${ge==null?void 0:ge.error}`,!0),!!(ge!=null&&ge.success)}catch(Y){return w("error",`Launch error: ${Y.message}`,!0),!1}finally{d(null)}},[e,c,w,r]),k=i.useCallback(async _=>{if(!e)return{success:!1};const{cliType:E,dir:V,workspaceId:Y,useDefaultWorkspace:ge,useHome:pe,argsStr:re,model:de,resumeSessionId:ke}=_;if(!E)return w("warn","Select a CLI or ACP provider first",!0),{success:!1};const ye=re?re.split(/\s+/).filter(Boolean):void 0,q=(V==null?void 0:V.trim())||(Y?"(saved id)":ge?"(default workspace)":pe?"(home)":"");w("info",`Launching ${E}${q?` in ${q}`:""}${de?` (model: ${de})`:""}...`),u(E);try{const he={cliType:E,cliArgs:ye,initialModel:de||void 0};V!=null&&V.trim()?he.dir=V.trim():Y?he.workspaceId=Y:ge?he.useDefaultWorkspace=!0:pe&&(he.useHome=!0),ke&&(he.resumeSessionId=ke);const fe=await r(e,"launch_cli",he),we=(fe==null?void 0:fe.result)||fe;return fe!=null&&fe.success?(w("info",`${E} launched`,!0),(we==null?void 0:we.launchSource)==="home"?w("info","📂 Running in home directory (explicit choice)"):(we==null?void 0:we.launchSource)==="defaultWorkspace"&&w("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:we==null?void 0:we.sessionId}):(w("error",`Failed: ${(fe==null?void 0:fe.error)||(we==null?void 0:we.error)}`,!0),(fe==null?void 0:fe.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&f({cliType:E,argsStr:re,model:de}),{success:!1,sessionId:we==null?void 0:we.sessionId})}catch(he){return A(he)?(w("warn",`${E} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(w("error",`Launch error: ${he.message}`,!0),{success:!1})}finally{u(null)}},[e,w,A,r]),j=i.useCallback(async(_,E,V,Y)=>e?_?E.trim()?k({cliType:_,dir:E,argsStr:V,model:Y}):(f({cliType:_,argsStr:V,model:Y}),{success:!1}):(w("warn","Select a provider",!0),{success:!1}):{success:!1},[e,w,k]),O=i.useCallback(async(_,E,V)=>{if(e&&window.confirm(`Stop ${_}?
72
+ This will terminate the process.`))try{const Y=await r(e,"stop_cli",{cliType:_,dir:E,targetSessionId:V});Y!=null&&Y.success?w("info",`${_} stopped`,!0):w("error",`Stop failed: ${(Y==null?void 0:Y.error)||"Unknown error"}`,!0)}catch(Y){w("error",`Stop failed: ${Y.message}`,!0)}},[e,w,r]),R=i.useCallback(async _=>{try{await r(_.daemonId,"restart_ide",{ideType:_.type}),w("info",`${ot(_.type)} restart initiated`,!0)}catch(E){w("error",`Restart failed: ${E.message}`,!0)}},[w,r]),T=i.useCallback(async _=>{if(window.confirm(`Stop ${ot(_.type)}?
73
+ This will disconnect CDP and optionally kill the process.`))try{const E=await r(_.daemonId,"stop_ide",{ideType:_.type,killProcess:!0});E!=null&&E.success?w("info",`${ot(_.type)} stopped`,!0):w("error",`Stop failed: ${(E==null?void 0:E.error)||"Unknown error"}`,!0)}catch(E){w("error",`Stop failed: ${E.message}`,!0)}},[w,r]),F=i.useCallback(async()=>{if(e)try{const _=await r(e,"detect_ides",{});w("info",`Found ${((_==null?void 0:_.result)||[]).length} IDE(s)`,!0)}catch(_){w("error",`Detection failed: ${_.message}`,!0)}},[e,w,r]),W=i.useCallback(async _=>{if(!e||!_.trim())return!1;g(!0);try{const E=await r(e,"workspace_add",{path:_.trim()});return E!=null&&E.success?(w("info",`Workspace added: ${_.trim()}`),!0):(w("error",(E==null?void 0:E.error)||"workspace_add failed"),!1)}catch(E){return w("error",E.message),!1}finally{g(!1)}},[e,w,r]),D=i.useCallback(async _=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){g(!0);try{const E=await r(e,"workspace_remove",{id:_});E!=null&&E.success?w("info","Workspace removed",!0):w("error",(E==null?void 0:E.error)||"workspace_remove failed",!0)}catch(E){w("error",E.message,!0)}finally{g(!1)}}},[e,w,r]),C=i.useCallback(async _=>{var E;if(e){g(!0);try{const V=await r(e,"workspace_set_default",_===null?{clear:!0}:{id:_});if(V!=null&&V.success){w("info",_?"Default workspace updated":"Default workspace cleared",!0);const Y=typeof V.defaultWorkspacePath=="string"?V.defaultWorkspacePath:"";Y&&((E=N.current)==null||E.call(N,Y))}else w("error",(V==null?void 0:V.error)||"workspace_set_default failed",!0)}catch(V){w("error",V.message,!0)}finally{g(!1)}}},[e,w,r]),I=i.useCallback(async _=>{var V;if(!e||!_.trim())return;const E=_.trim();g(!0);try{const Y=await r(e,"workspace_set_default",{path:E});Y!=null&&Y.success?(w("info","Default workspace set from history"),(V=N.current)==null||V.call(N,E)):w("error",(Y==null?void 0:Y.error)||"Could not set default (path missing on disk?)")}catch(Y){w("error",Y.message)}finally{g(!1)}},[e,w,r]),K=i.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:y}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:y})}catch(_){w("warn",`Live nickname updated, but account sync failed: ${_.message}`)}w("info",`Nickname set to "${y||"(cleared)"}"`),b(!1)}catch(_){w("error",`Failed: ${_.message}`)}},[e,y,s,w,n,r]);return{logs:o,launchingIde:c,launchingAgentType:m,workspaceBusy:h,launchPick:v,setLaunchPick:f,editingNickname:p,setEditingNickname:b,nicknameInput:y,setNicknameInput:x,addLog:w,handleLaunchIde:L,runLaunchCliCore:k,handleLaunchCli:j,handleStopCli:O,handleRestartIde:R,handleStopIde:T,handleDetectIdes:F,handleWorkspaceAdd:W,handleWorkspaceRemove:D,handleWorkspaceSetDefault:C,handleWorkspaceResumePath:I,handleSaveNickname:K,setOnDefaultWorkspaceChanged:S}}function Xy({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:l}){var R;const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:m,handleWorkspaceSetDefault:u}=o,[h,g]=i.useState(!1),[v,f]=i.useState(""),[p,b]=i.useState([]),[y,x]=i.useState(!1),[N,S]=i.useState(""),w=i.useCallback(async T=>{x(!0),S("");try{const F=await En(l,e,T);f(F.path),b(F.directories)}catch(F){S(F instanceof Error?F.message:"Could not load folder")}finally{x(!1)}},[e,l]),A=i.useCallback(()=>{g(!0);const T=[...r.map(W=>W.workspace),...n.map(W=>W.workspace),...a.map(W=>W.workspace)],F=Dn(s.platform,Pn(T,s.defaultWorkspacePath,(s.workspaces||[]).map(W=>W.path)));w(F)},[a,n,r,w,s.defaultWorkspacePath,s.platform,s.workspaces]),L=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,k=s.availableMem??s.freeMem??s.totalMem,j=L&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-k)/s.totalMem*100))):0,O=((R=s.loadavg)==null?void 0:R[0])||0;return t.jsxs("div",{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[t.jsx(Er,{icon:t.jsx(Ul,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?pp(s.uptime):"Waiting…"}),t.jsx(Er,{icon:t.jsx(It,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(Er,{icon:t.jsx(co,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(Er,{icon:t.jsx(pm,{size:16}),label:"ACPs",value:`${a.length}`})]}),t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),t.jsxs("div",{className:"flex gap-6",children:[t.jsx(xi,{value:L?Math.min(Math.round(O/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:L?`${O.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(xi,{value:j,max:100,label:"Memory",color:"#3b82f6",detail:L?`${Gn(s.totalMem-k)} / ${Gn(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Gn(s.totalMem)} total`})]})]}),t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[t.jsx(gs,{size:14})," Workspaces"]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[t.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),t.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:c,value:s.defaultWorkspaceId||"",onChange:T=>void u(T.target.value===""?null:T.target.value),children:[t.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(T=>t.jsx("option",{value:T.id,children:T.label||T.path},T.id))]}),s.defaultWorkspacePath&&t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:s.defaultWorkspacePath,children:s.defaultWorkspacePath})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded transition-colors text-xs",disabled:c,onClick:A,children:"Select workspace…"}),t.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(s.workspaces||[]).length>0&&t.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(s.workspaces||[]).map(T=>t.jsxs("li",{className:"flex items-start gap-2 text-[11px] text-text-muted rounded-lg border border-border-subtle bg-bg-primary px-2.5 py-2",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[T.id===s.defaultWorkspaceId&&t.jsx("span",{className:"text-[10px]",children:"⭐"}),t.jsx("span",{className:"font-medium text-text-primary truncate",children:An(T.path,T.label)})]}),t.jsx("div",{className:"font-mono truncate text-[10px]",title:T.path,children:T.path})]}),t.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void m(T.id),children:"Remove"})]},T.id))})]}),h&&t.jsx($n,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:v,directories:p,busy:y,error:N,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:T=>{w(T)},onConfirm:T=>{(async()=>{if(!T)return;await d(T)&&g(!1)})()}})]})}function Jy(e){if(!e||typeof e!="object")return null;const s=e,r=s.result&&typeof s.result=="object"?s.result:s;return!r.settings||typeof r.settings!="object"?null:{settings:r.settings,values:r.values&&typeof r.values=="object"?r.values:{}}}function Qy(e,s,r){const n=[];for(const[a,o]of Object.entries(e.settings)){const l=r!=null&&r.filterSchema?r.filterSchema(o):o;if(l.length===0)continue;const c=s.find(d=>d.type===a);n.push({type:a,displayName:(c==null?void 0:c.displayName)||a,icon:(c==null?void 0:c.icon)||"",category:(c==null?void 0:c.category)||"unknown",schema:l,values:e.values[a]||{}})}return n}function va(e){if(!e||typeof e!="object")return!1;const s=e;return(s.sourceMode==="normal"||s.sourceMode==="no-upstream")&&typeof s.disableUpstream=="boolean"&&(s.explicitProviderDir===null||typeof s.explicitProviderDir=="string")&&typeof s.userDir=="string"&&typeof s.upstreamDir=="string"&&Array.isArray(s.providerRoots)}function bl(e){if(!e||typeof e!="object")return null;if(va(e))return e;const s=e,r=s.result;return va(r)?r:va(s.sourceConfig)?s.sourceConfig:null}function Zy(e){const s=e.trim();return s||null}const gl=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],e0=[{value:"codex-cli",label:"Codex CLI",desc:"OpenAI o3/gpt-5.4",color:"#22c55e"},{value:"claude-cli",label:"Claude Code",desc:"Anthropic Claude",color:"#a855f7"},{value:"gemini-cli",label:"Gemini CLI",desc:"Google Gemini",color:"#3b82f6"}];function t0({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[a,o]=i.useState("config"),[l,c]=i.useState("codex-cli"),[d,m]=i.useState([]),[u,h]=i.useState(""),[g,v]=i.useState([]),[f,p]=i.useState(""),b=i.useRef(null),y=i.useRef(null),x=k=>{m(j=>j.includes(k)?j.filter(O=>O!==k):[...j,k])},N=()=>m([...gl]),S=()=>m([]);i.useEffect(()=>{var k;(k=b.current)==null||k.scrollIntoView({behavior:"smooth"})},[g]),i.useEffect(()=>()=>{y.current&&clearInterval(y.current)},[]);const w=i.useCallback(()=>{y.current&&clearInterval(y.current),y.current=setInterval(async()=>{try{const k=await r(e,"provider_auto_fix_status",{providerType:s.type});(k==null?void 0:k.running)===!1&&a==="running"&&(o("done"),v(j=>[...j,`
74
+ ✅ Auto-fix completed!`]),y.current&&clearInterval(y.current))}catch{}},3e3)},[e,s.type,r,a]),A=async()=>{if(d.length!==0){o("running"),v(["🚀 Starting auto-fix...",`Agent: ${l}`,`Scripts: ${d.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),p("");try{const k=await r(e,"provider_auto_fix",{providerType:s.type,functions:d,agent:l,...u?{comment:u}:{}});k!=null&&k.success&&(k!=null&&k.started||k!=null&&k.running)?(v(j=>[...j,"✅ Agent started. Monitoring progress..."]),w()):(o("error"),p((k==null?void 0:k.error)||"Failed to start auto-fix"))}catch(k){o("error"),p((k==null?void 0:k.message)||"Connection failed")}}},L=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),v(k=>[...k,`
75
+ ⚠️ Auto-fix cancelled.`]),o("done"),y.current&&clearInterval(y.current)}catch{}};return t.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:t.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:k=>k.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:s.icon||"🔧"}),t.jsxs("div",{children:[t.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",s.displayName]}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),t.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),t.jsx("div",{className:"flex gap-2",children:e0.map(k=>t.jsxs("button",{onClick:()=>c(k.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:l===k.value?k.color+"66":"var(--border-subtle)",background:l===k.value?k.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:l===k.value?k.color:"var(--text-primary)"},children:k.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:k.desc})]},k.value))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:N,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),t.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),t.jsx("button",{onClick:S,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:gl.map(k=>t.jsxs("button",{onClick:()=>x(k),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(k)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(k)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(k)?"#a78bfa":"var(--text-secondary)"},children:[d.includes(k)?"☑ ":"☐ ",k]},k))})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",t.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),t.jsx("textarea",{value:u,onChange:k=>h(k.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[g.map((k,j)=>t.jsx("div",{className:k.startsWith("✅")?"text-green-400":"",style:k.startsWith("❌")||k.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:k},j)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:b})]}),f&&t.jsx("div",{className:"mt-2 px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:f})]})]}),t.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[t.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&d.length>0&&`${d.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),t.jsxs("div",{className:"flex gap-2",children:[a==="config"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:A,disabled:d.length===0,className:"machine-btn",style:{background:d.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:d.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:d.length>0?"#a78bfa":void 0,opacity:d.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&t.jsx("button",{onClick:L,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{o("config"),v([]),p("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function s0({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var w;const o=s.filter(A=>A.category==="ide"),[l,c]=i.useState(((w=o[0])==null?void 0:w.type)||""),[d,m]=i.useState(""),[u,h]=i.useState(""),[g,v]=i.useState(!1),[f,p]=i.useState(""),[b,y]=i.useState(!1),x=A=>{const L=A.toLowerCase().replace(/[^a-z0-9-]/g,"");m(L),(!u||u===N(d))&&h(N(L))},N=A=>A.split("-").map(L=>L.charAt(0).toUpperCase()+L.slice(1)).join(" "),S=async()=>{if(!(!d||!u||!l)){v(!0),p("");try{const A=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:l});A!=null&&A.success||A!=null&&A.created?(y(!0),a==null||a(d)):p((A==null?void 0:A.error)||"Failed to create provider")}catch(A){p((A==null?void 0:A.message)||"Connection failed")}v(!1)}};return t.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:t.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:A=>A.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[t.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:b?t.jsxs("div",{className:"text-center py-6",children:[t.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),t.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[t.jsx("code",{className:"text-violet-400",children:d})," has been created at ",t.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",t.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," or use Auto-Fix to implement scripts."]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:o.map(A=>t.jsxs("button",{onClick:()=>c(A.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:l===A.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:l===A.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:A.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:l===A.type?"#a78bfa":"var(--text-secondary)"},children:A.displayName})]},A.type))})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),t.jsx("input",{value:d,onChange:A=>x(A.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),t.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",t.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",d||"...","/"]})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),t.jsx("input",{value:u,onChange:A=>h(A.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),f&&t.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:f})]})}),t.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:b?t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:S,disabled:!d||!u||g,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||g?.4:1},children:g?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function yl(e){return e==="cli"||e==="acp"}function r0(e){switch(e){case"detected":return"Detected";case"not_detected":return"Not detected";case"enabled_unchecked":return"Enabled, not checked";case"disabled":return"Disabled";default:return"Disabled"}}function n0(e){switch(e){case"detected":return"bg-green-500/[0.10] border-green-500/25 text-green-400";case"not_detected":return"bg-red-500/[0.10] border-red-500/25 text-red-400";case"enabled_unchecked":return"bg-yellow-500/[0.10] border-yellow-500/25 text-yellow-400";case"disabled":default:return"bg-white/[0.04] border-white/[0.10] text-text-muted"}}function vl(e){if(!e)return"No result yet";const s=e.stage||"check",r=e.ok?"OK":"Failed",n=e.message||e.path||e.command||"";return n?`${s}: ${r} — ${n}`:`${s}: ${r}`}function a0({machineId:e,providers:s,sendDaemonCommand:r}){var W;const[n,a]=i.useState([]),[o,l]=i.useState(!1),[c,d]=i.useState(null),[m,u]=i.useState("all"),[h,g]=i.useState(null),[v,f]=i.useState(!1),[p,b]=i.useState(null),[y,x]=i.useState("normal"),[N,S]=i.useState(""),[w,A]=i.useState(!1),L=i.useCallback(async()=>{if(e)try{const D=await r(e,"get_provider_source_config",{}),C=bl(D);C&&(b(C),x(C.sourceMode),S(C.explicitProviderDir||""))}catch{}},[e,r]),k=i.useCallback(async()=>{if(e){l(!0);try{const D=await r(e,"get_provider_settings",{}),C=Jy(D);if(C){const I=Qy(C,s,{filterSchema:K=>K.filter(_=>_.key!=="enabled")});I.sort((K,_)=>K.category.localeCompare(_.category)||K.displayName.localeCompare(_.displayName)),a(I)}}catch{}l(!1)}},[e,s,r]);i.useEffect(()=>{n.length===0&&k(),p||L()},[]);const j=async(D,C,I)=>{d(`${D}.${C}`),a(K=>K.map(_=>_.type===D?{..._,values:{..._.values,[C]:I}}:_));try{const K=await r(e,"set_provider_setting",{providerType:D,key:C,value:I});K!=null&&K.success||k()}catch{k()}d(null)},O=async(D,C)=>{await j(D,"enabled",C),await k()},R=async D=>{d(`${D}.detect`);try{await r(e,"detect_provider",{providerType:D})}finally{await k(),d(null)}},T=async D=>{await j(D,"executablePath",""),await j(D,"executableArgs",""),await k()},F=async()=>{A(!0);try{const D=await r(e,"set_provider_source_config",{providerSourceMode:y,providerDir:Zy(N)}),C=bl(D);C?(b(C),x(C.sourceMode),S(C.explicitProviderDir||"")):await L(),await k()}catch{await L()}A(!1)};return t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-4",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(D=>t.jsx("button",{onClick:()=>u(D),className:`machine-btn text-[10px] px-2 py-0.5 ${m===D?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:D.toUpperCase()},D))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>f(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),t.jsx("button",{onClick:k,disabled:o,className:"machine-btn",children:o?"⏳ Loading...":"↻ Refresh"})]})]}),t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Running CLI sessions refresh provider scripts/config; process binary changes still apply on next launch."})]}),t.jsx("button",{onClick:L,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),t.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),t.jsxs("select",{value:y,onChange:D=>x(D.target.value),className:"machine-input text-[11px]",children:[t.jsx("option",{value:"normal",children:"normal"}),t.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),t.jsx("input",{type:"text",value:N,onChange:D=>S(D.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void F(),disabled:w,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:w?"Applying…":"Apply + Reload"})]}),t.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(p==null?void 0:p.userDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(p==null?void 0:p.upstreamDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((W=p==null?void 0:p.providerRoots)==null?void 0:W.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(D=>D.category===m).length>1&&(()=>{const D=n.filter(_=>_.category===m),C=new Map;for(const _ of D)for(const E of _.schema){if(E.type!=="boolean")continue;const V=C.get(E.key),Y=!!(_.values[E.key]??E.default);V?(V.onCount+=Y?1:0,V.total+=1):C.set(E.key,{label:E.label||E.key,onCount:Y?1:0,total:1})}const I=[...C.entries()].filter(([,_])=>_.total===D.length);if(I.length===0)return null;const K=async(_,E)=>{for(const V of D)await j(V.type,_,E)};return t.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[t.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",m.toUpperCase()," providers (",D.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:I.map(([_,E])=>{const V=E.onCount===E.total,Y=E.onCount===0;return t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:"text-text-secondary font-medium",children:E.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",E.onCount,"/",E.total,")"]}),t.jsx("button",{onClick:()=>void K(_,!0),disabled:V,className:`machine-btn text-[9px] px-1.5 py-px ${V?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void K(_,!1),disabled:Y,className:`machine-btn text-[9px] px-1.5 py-px ${Y?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},_)})})]})})(),o&&n.length===0?t.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):t.jsx("div",{className:"flex flex-col gap-2",children:n.filter(D=>m==="all"||D.category===m).map(D=>t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[t.jsx("span",{className:"text-lg",children:D.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:D.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:D.category==="acp"?"rgba(139,92,246,0.08)":D.category==="cli"?"rgba(59,130,246,0.08)":D.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:D.category==="acp"?"#a78bfa":D.category==="cli"?"#60a5fa":D.category==="ide"?"#86efac":"var(--status-warning)"},children:D.category}),yl(D.category)&&(()=>{const C=s.find(_=>_.type===D.type),I=(C==null?void 0:C.enabled)===!0||D.values.enabled===!0,K=(C==null?void 0:C.machineStatus)||(I?"enabled_unchecked":"disabled");return t.jsxs(t.Fragment,{children:[t.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${n0(K)}`,children:r0(K)}),t.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[t.jsx("button",{onClick:()=>void O(D.type,!I),disabled:c===`${D.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${I?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:I?"Disable":"Enable"}),t.jsx("button",{onClick:()=>void R(D.type),disabled:!I||c===`${D.type}.detect`,title:I?"Run detection for the configured executable":"Enable this provider before detection",className:`machine-btn text-[9px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${I?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),t.jsx("button",{onClick:()=>void T(D.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),D.category==="ide"&&t.jsx("button",{onClick:()=>g(s.find(C=>C.type===D.type)||{type:D.type,name:D.displayName,displayName:D.displayName,icon:D.icon,category:D.category}),className:"ml-auto machine-btn text-[9px] px-2 py-0.5 bg-violet-500/[0.06] border-violet-500/20 text-violet-400 hover:bg-violet-500/[0.12]",children:"🔧 Auto-Fix"})]}),yl(D.category)&&(()=>{const C=s.find(I=>I.type===D.type);return t.jsxs("div",{className:"mb-2.5 grid gap-1 rounded-lg border border-white/[0.06] bg-bg-primary/40 px-3 py-2 text-[10px] text-text-muted",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:"Detection:"})," ",vl(C==null?void 0:C.lastDetection)]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",vl(C==null?void 0:C.lastVerification)]}),t.jsx("div",{className:"text-[9px] text-text-muted",children:"Supported catalog entry only becomes launchable after Enable + Detect succeeds. Custom executable path/args below are machine-local overrides."})]})})(),t.jsx("div",{className:"flex flex-col gap-2",children:D.schema.map(C=>t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[C.label||C.key,c===`${D.type}.${C.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),C.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:C.description})]}),t.jsx("div",{className:"shrink-0",children:C.type==="boolean"?t.jsx("button",{onClick:()=>j(D.type,C.key,!(D.values[C.key]??C.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:D.values[C.key]??C.default?"#8b5cf6":"var(--border-subtle)"},children:t.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:D.values[C.key]??C.default?21:3}})}):C.type==="number"?t.jsx("input",{type:"number",value:Number(D.values[C.key]??C.default??0)||0,min:C.min,max:C.max,onChange:I=>{const K=parseInt(I.target.value)||0;C.min!==void 0&&K<C.min||C.max!==void 0&&K>C.max||j(D.type,C.key,K)},className:"machine-input w-20 text-center text-[11px]"}):C.type==="select"&&C.options?t.jsx("select",{value:String(D.values[C.key]??C.default??""),onChange:I=>j(D.type,C.key,I.target.value),className:"machine-input text-[11px]",children:C.options.map(I=>t.jsx("option",{value:I,children:I},I))}):t.jsx("input",{type:"text",value:String(D.values[C.key]??C.default??""),onBlur:I=>j(D.type,C.key,I.target.value),className:"machine-input w-[120px] text-[11px]"})})]},C.key))})]},D.type))}),h&&t.jsx(t0,{machineId:e,provider:h,sendDaemonCommand:r,onClose:()=>g(null)}),v&&t.jsx(s0,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>f(!1),onCreated:()=>{f(!1),k()}})]})}const o0=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function i0({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function l0(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function c0(e){return e.trim().toLowerCase()}function On(e,s){const r=c0(s);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function zo(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Ws(e,s=220){const r=zo(e);return r?r.length>s?`${r.slice(0,s)}…`:r:""}function d0(e){const s=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(s))return{kind:s.length>0?"structured":"empty",entries:s.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 s=="string"){const r=s.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function u0(e,s){return e.filter(r=>On([r.level,r.message],s))}function wl(e){return`${e.timestamp}:${e.level}:${e.message}`}function m0(e,s,r=300){if(s.entries.length>0){const n=new Map;for(const l of e.entries)n.set(wl(l),l);for(const l of s.entries)n.set(wl(l),l);const a=Array.from(n.values()).sort((l,c)=>l.timestamp-c.timestamp).slice(-r),o=a.reduce((l,c)=>Math.max(l,Number(c.timestamp||0)),e.lastTs);return{entries:a,kind:"structured",rawText:"",lastTs:o}}return s.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:s.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function p0(e,s,r=120){if(s.length===0)return e;const n=new Map;for(const a of e)n.set(a.id,a);for(const a of s)n.set(a.id,a);return Array.from(n.values()).sort((a,o)=>a.ts-o.ts).slice(-r)}function f0(e,s){return e.split(`
76
+ `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>On([r],s))}function h0(e,s){return e.filter(r=>On([r.level,r.category,r.stage,r.interactionId,zo(r.payload)],s))}function x0(e,s){return e.filter(r=>On([r.kind,r.topic,r.interactionId,zo(r.payload)],s))}function jl(e){return e==="warn"||e==="error"}function b0({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){return{all:e.length+s.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=>jl(a.level)).length+r.filter(a=>jl(a.level)).length}}function g0({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(o=>`${new Date(o.timestamp).toISOString()} ${o.level.toUpperCase()} ${o.message}`)].join(`
77
+ `)):s.length>0&&a.push(["[daemon logs]",...s].join(`
78
+ `)),r.length>0&&a.push(["[trace]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${Ws(o.payload,500)}`.trim())].join(`
79
+ `)),n.length>0&&a.push(["[browser events]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${Ws(o.payload,500)}`.trim())].join(`
80
+ `)),a.join(`
81
+
82
+ `)}function y0({machineId:e,sendDaemonCommand:s}){const[r,n]=i.useState([]),[a,o]=i.useState("empty"),[l,c]=i.useState(""),[d,m]=i.useState([]),[u,h]=i.useState([]),[g,v]=i.useState(null),[f,p]=i.useState(!0),[b,y]=i.useState("info"),[x,N]=i.useState("all"),[S,w]=i.useState(!0),[A,L]=i.useState(!0),[k,j]=i.useState(""),[O,R]=i.useState(""),[T,F]=i.useState(0),W=i.useRef(0),D=i.useRef(0),C=i.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),I=i.useRef([]),K=i.useCallback(()=>{const re={entries:[],kind:"empty",rawText:"",lastTs:0};C.current=re,W.current=0,n([]),c(""),o("empty"),w(!0)},[]),_=i.useCallback(()=>{I.current=[],D.current=0,m([]),L(!0)},[]),E=i.useCallback(re=>{re!==b&&(K(),y(re))},[b,K]),V=i.useCallback(re=>{N(de=>de===re?de:re)},[]),Y=i.useCallback(()=>{K(),_(),h([]),v(null),j(""),R(""),Ps.clear()},[K,_]),ge=i.useCallback(()=>{F(re=>re+1)},[]),pe=i.useCallback(async()=>{if(!e)return;const re=W.current,de=D.current,[ke,ye]=await Promise.allSettled([s(e,"get_logs",{count:200,minLevel:b,since:re}),s(e,"get_debug_trace",i0({count:120,since:de,category:x}))]);if(ke.status==="fulfilled"){const q=ke.value,he=(q==null?void 0:q.result)||q,fe=d0(he),we=m0(C.current,fe,300);C.current=we,W.current=we.lastTs,w(!1),j((q==null?void 0:q.success)===!1?String((q==null?void 0:q.error)||"Could not load daemon logs"):""),o(we.kind),c(we.rawText),n(we.entries)}else w(!1),j(ke.reason instanceof Error?ke.reason.message:"Could not load daemon logs");if(ye.status==="fulfilled"){const q=ye.value,he=(q==null?void 0:q.result)||q;if((q==null?void 0:q.success)===!1)R(String((q==null?void 0:q.error)||"Could not load daemon trace"));else if(Array.isArray(he==null?void 0:he.trace)){const fe=he.trace,we=p0(I.current,fe,120),xe=fe.reduce((Se,Q)=>Math.max(Se,Number(Q.ts||0)),de);I.current=we,xe>de&&(D.current=xe),R(""),m(we)}else R("");L(!1)}else L(!1),R(ye.reason instanceof Error?ye.reason.message:"Could not load daemon trace");h(Ps.list({limit:120})),v(Date.now())},[b,e,s,x]);return i.useEffect(()=>{_()},[_,x]),i.useEffect(()=>{if(!e||(pe(),!f))return;const re=setInterval(()=>{pe()},3e3);return()=>clearInterval(re)},[f,pe,e,T]),{daemonLogs:r,daemonLogKind:a,daemonRawText:l,debugTrace:d,webEvents:u,lastUpdatedAt:g,autoRefresh:f,logLevel:b,traceCategory:x,daemonLoading:S,traceLoading:A,daemonFetchError:k,traceFetchError:O,setAutoRefresh:p,setLogLevel:E,setTraceCategory:V,refresh:ge,clear:Y}}function v0({daemonLoading:e,traceLoading:s,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:l,traceCount:c,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":o>0||l>0?"ok":"empty",detail:r||(a==="text"?`${l} raw file-fallback line(s)`:`${o} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:n?"error":s?"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 kl(e){return e==="warn"||e==="error"}function w0(e){const s=e.toLowerCase();return/\[(err|error)\]/i.test(e)||s.includes(" error ")||s.includes(" failed")?"error":/\[(wrn|warn|warning)\]/i.test(e)||s.includes(" warning ")||s.includes(" timeout")?"warn":/\[(dbg|debug)\]/i.test(e)?"debug":"info"}function j0(e,s){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+s}function Sl(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function k0(e){const s=Ws(e.payload,320);return s?`${e.category}.${e.stage} ${s}`:`${e.category}.${e.stage}`}function S0(e){const s=Ws(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return s?`${e.kind}${r} ${s}`:`${e.kind}${r}`}function N0({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){const a=[];return e.forEach((o,l)=>{a.push({id:`daemon-log-${o.timestamp}-${l}`,source:"daemon_log",ts:Number(o.timestamp||0),severity:o.level,message:o.message,raw:o.message})}),n.forEach(o=>{a.push({id:`browser-event-${o.id}`,source:"browser_event",ts:Number(o.ts||0),severity:"info",message:S0(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:k0(o),category:o.category,stage:o.stage,interactionId:o.interactionId,payload:o.payload})}),s.forEach((o,l)=>{a.push({id:`raw-file-${l}`,source:"raw_file",ts:j0(o,l),severity:w0(o),message:o,raw:o})}),a.sort((o,l)=>o.ts!==l.ts?o.ts-l.ts:Sl(o.source)-Sl(l.source))}function C0(e){return`${e.source}:${e.severity}:${e.message}`}function I0(e){const s=e.filter(n=>kl(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!kl(n.severity))continue;const a=C0(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:s.length,latestIssue:s[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 T0(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Nl(e){const s=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${T0(e.ts)} ${e.severity.toUpperCase()} ${e.source}${s}${r} ${e.message}`.trim()}function A0({events:e,summary:s,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${s.totalCount}`,`issue_events: ${s.issueCount}`].join(`
83
+ `)),a.push(["[source status]",...r.map(l=>`${l.label}: ${l.status} - ${l.detail}`)].join(`
84
+ `)),s.latestIssue&&a.push(["[latest issue]",Nl(s.latestIssue)].join(`
85
+ `)),s.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...s.repeatedPatterns.map(l=>`${l.count}x ${l.severity.toUpperCase()} ${l.source} ${l.message}`)].join(`
86
+ `));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(Nl):["No diagnostic events captured."]].join(`
87
+ `)),a.join(`
88
+
89
+ `)}function M0(e,s){return s==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):s==="info"?e.filter(r=>r.level!=="debug"):e}function L0(e,s){return s==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):s==="info"?e.filter(r=>r.level!=="debug"):e}function R0({daemonLogs:e,daemonRawText:s,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:l,searchQuery:c,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:h}){const g=l0(n,o),v=u0(e,c),f=f0(s,c),p=h0(g,c),b=x0(a,c),y=M0(v,l),x=l==="all"?f:[],N=L0(p,l),S=l==="issues"?[]:b,w=b0({daemonLogs:v,daemonRawLines:f,trace:p,webEvents:b}),A=N0({daemonLogs:y,daemonRawLines:x,trace:N,webEvents:S}),L=I0(A),k=v0({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:h,daemonLogKind:r,daemonLogsCount:v.length,daemonRawLineCount:f.length,traceCount:p.length,webEventCount:b.length});return{filteredDaemonLogs:v,filteredDaemonRawLines:f,filteredTraceEntries:p,filteredWebEvents:b,visibleDaemonLogs:y,visibleDaemonRawLines:x,visibleTraceEntries:N,visibleWebEvents:S,quickFilterCounts:w,diagnosticEvents:A,diagnosticsSummary:L,sourceStates:k}}function _0(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Vd(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function eo(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 wa(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 Vo(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function P0({event:e}){return t.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${eo(e.severity)}`,children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:Vd(e.ts)}),t.jsx("span",{children:e.severity.toUpperCase()}),t.jsx("span",{children:Vo(e.source)}),e.category&&e.stage&&t.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&t.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&t.jsxs("span",{children:["ix=",e.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function D0({quickFilter:e,quickFilterCounts:s,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:l,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:m,onClear:u}){return t.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),t.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${s.info})`},{id:"issues",label:`Issues (${s.issues})`},{id:"all",label:`All (${s.all})`}].map(h=>t.jsx("button",{type:"button",onClick:()=>a(h.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===h.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:h.label},h.id))}),t.jsx("input",{value:r,onChange:h=>o(h.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{onClick:l,className:"machine-btn",children:"Copy diagnostics"}),t.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),t.jsx("button",{onClick:d,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),t.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function E0({logLevel:e,traceCategory:s,onLogLevelChange:r,onTraceCategoryChange:n}){return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-3",children:t.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(a=>t.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))]}),t.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:o0.map(a=>t.jsx("button",{onClick:()=>n(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${s===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function $0({diagnosticsSummary:e,diagnosticEventsCount:s,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:l,traceFetchError:c}){var u,h;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((h=e.latestIssue)==null?void 0:h.severity)==="warn"?"warning":"good",m=l||c?"danger":o?"good":"neutral";return t.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[t.jsxs("div",{className:`rounded-xl border p-3 ${wa(e.issueCount>0?"warning":"good")}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[s," visible event(s) · ",e.issueCount," issue signal(s)"]}),t.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"})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${wa(d)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[Vo(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),t.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:Vd(e.latestIssue.ts)})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${wa(m)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:l||c?"Needs attention":o?"Live polling every 3s":"Paused"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",_0(a)]}),t.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(g=>t.jsxs("div",{children:[g.label,": ",g.status]},g.id))})]})]})}function B0({patterns:e}){return e.length===0?null:t.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),t.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(s=>t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[t.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[s.count,"× ",s.severity.toUpperCase()," · ",Vo(s.source)]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:s.message})]},s.key))})]})}function O0({streams:e,sectionsOpen:s,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:l,visibleWebEvents:c,quickFilter:d,searchQuery:m}){return t.jsxs("div",{className:"grid gap-3",children:[t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.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:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:s.timeline?"Hide":"Show"})]}),s.timeline&&t.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&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&t.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&t.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&t.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(u=>t.jsx(P0,{event:u},u.id))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.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:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),t.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)`})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:s.daemon?"Hide":"Show"})]}),s.daemon&&t.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&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&t.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&t.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&&t.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&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((u,h)=>t.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${h}`)),e.daemonLogKind!=="text"&&a.map((u,h)=>t.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${eo(u.level)}`,children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),t.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"}),t.jsx("span",{className:"break-words",children:u.message})]},`log-${h}`))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.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:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[l.length," visible trace event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:s.trace?"Hide":"Show"})]}),s.trace&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&l.length===0&&!e.traceFetchError&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&l.length===0&&t.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&l.length===0&&!e.traceFetchError&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No trace entries match the current search.":e.traceCategory==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),l.map(u=>t.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${eo(u.level)}`,children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),t.jsx("span",{children:u.level.toUpperCase()}),t.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&t.jsxs("span",{children:["ix=",u.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Ws(u.payload,360)||"No payload"})]},u.id))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.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:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible browser event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:s.web?"Hide":"Show"})]}),s.web&&t.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&&t.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=>t.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),t.jsx("span",{children:u.kind}),u.topic&&t.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&t.jsxs("span",{children:["ix=",u.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Ws(u.payload,360)||"No payload"})]},u.id))]})]})]})}function K0({machineId:e,sendDaemonCommand:s}){const r=y0({machineId:e,sendDaemonCommand:s}),[n,a]=i.useState("info"),[o,l]=i.useState(""),[c,d]=i.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=i.useRef(null),u=i.useRef(!1),h=i.useMemo(()=>R0({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:o,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,o,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);i.useEffect(()=>{if(r.autoRefresh&&h.diagnosticEvents.length>0){const f=u.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:f}),u.current=!0},50)}},[h.diagnosticEvents.length,r.autoRefresh]);const g=i.useCallback(async()=>{var p;const f=g0({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!f.trim()){nt.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(f)),nt.showToast("Copied visible logs to clipboard.","success")}catch(b){nt.showToast(b instanceof Error?b.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),v=i.useCallback(async()=>{var p;const f=A0({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(f)),nt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(b){nt.showToast(b instanceof Error?b.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return t.jsxs("div",{className:"space-y-4",children:[t.jsx(D0,{quickFilter:n,quickFilterCounts:h.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:l,onCopyDiagnostics:()=>{v()},onCopyVisible:()=>{g()},onToggleAutoRefresh:()=>r.setAutoRefresh(f=>!f),onRefresh:r.refresh,onClear:r.clear}),t.jsx(E0,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),t.jsx($0,{diagnosticsSummary:h.diagnosticsSummary,diagnosticEventsCount:h.diagnosticEvents.length,sourceStates:h.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),t.jsx(B0,{patterns:h.diagnosticsSummary.repeatedPatterns}),t.jsx(O0,{streams:r,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:n,searchQuery:o}),t.jsx("div",{ref:m})]})}function F0(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 Gd(e){const s=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return s?s==="auto_resumed"?"restored after restart":s==="resume_failed"?"restore failed":s==="host_restart_interrupted"?"host restart interrupted":s==="orphan_snapshot"?"snapshot recovered":s.replace(/_/g," "):null}function W0(e){var a;const s=[],r=[],n=[];for(const o of e||[]){const l=String((o==null?void 0:o.lifecycle)||"").trim(),c=Gd((o==null?void 0:o.meta)||void 0),d=((a=o==null?void 0:o.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(l)?s.push(o):(l==="stopped"||l==="failed")&&(d||c)?r.push(o):n.push(o)}return{liveRuntimes:s,recoverySnapshots:r,inactiveRecords:n}}function H0(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function ja(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 ka(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Sa(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Cl(e){if(!e)return"unknown";const s=Date.now()-e,r=Math.max(0,Math.round(s/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 U0(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function z0(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 V0(e){var r;const s=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}`;s.set(o,(s.get(o)||0)+1)}return Array.from(s.values()).filter(n=>n>1).length}function G0({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=i.useState(""),[o,l]=i.useState(null),[c,d]=i.useState(!1),m=Bx(e,{enabled:!!e,includeSessions:!0,limit:Ci,intervalMs:Pf}),u=m.diagnostics,h=m.loading,g=m.applyDiagnostics,v=i.useMemo(()=>F0({diagnostics:u,loading:h,refreshing:c,error:n}),[u,h,c,n]),f=i.useMemo(()=>new Map(s.map(R=>[R.sessionId||R.id,R])),[s]),p=i.useCallback(async()=>{if(e){d(!0);try{const R=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Ci}),T=ka(R);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Could not load hosted runtime diagnostics");g(T.diagnostics||T.result||null),a("")}catch(R){const T=R instanceof Error?R.message:"Could not load hosted runtime diagnostics";a(T)}finally{d(!1)}}},[g,e,r]);i.useEffect(()=>{!e||u||h||c||p()},[u,h,e,p,c]);const b=i.useCallback(async(R,T)=>{const F=`${R}:${T.sessionId}`;if(!(R==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
90
+ This will terminate the hosted runtime.`))){l(F);try{const W=await r(e,R,{sessionId:T.sessionId}),D=ka(W);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Session host action failed");const C=R==="session_host_resume_session"?"resumed":R==="session_host_restart_session"?"restarted":"stopped";nt.showToast(`Session host ${C}: ${T.displayName}`,"success"),await p()}catch(W){const D=W instanceof Error?W.message:"Session host action failed";nt.showToast(D,"warning"),a(D)}finally{l(W=>W===F?null:W)}}},[e,p,r]),y=i.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
91
+ The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){l("session_host_prune_duplicate_sessions");try{const T=await r(e,"session_host_prune_duplicate_sessions",{}),F=ka(T);if(!(F!=null&&F.success))throw new Error((F==null?void 0:F.error)||"Duplicate prune failed");const W=F.result||{},D=Array.isArray(W.prunedSessionIds)?W.prunedSessionIds.length:0,C=typeof W.duplicateGroupCount=="number"?W.duplicateGroupCount:0;nt.showToast(`Pruned ${D} duplicate runtime(s) across ${C} group(s)`,"success"),await p()}catch(T){const F=T instanceof Error?T.message:"Duplicate prune failed";nt.showToast(F,"warning"),a(F)}finally{l(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,p,r]),x=i.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((R,T)=>(T.lastActivityAt||0)-(R.lastActivityAt||0)),[u==null?void 0:u.sessions]),N=i.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:W0(x),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,x]),S=N.liveRuntimes,w=N.recoverySnapshots,A=N.inactiveRecords,L=i.useMemo(()=>V0(S),[S]),k=i.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),j=i.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(R=>R.level==="warn"||R.level==="error")||null,[u==null?void 0:u.recentLogs]),O=(R,T)=>{var V;const F=o===`session_host_resume_session:${R.sessionId}`,W=o===`session_host_restart_session:${R.sessionId}`,D=o===`session_host_stop_session:${R.sessionId}`,C=Gd(R.meta),I=f.get(R.sessionId),K=R.attachedClients.length===1?"1 client":`${R.attachedClients.length} clients`,_=T==="recovery"?"Recover":"Resume",E=H0(T);return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:R.displayName||(I==null?void 0:I.cliName)||R.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${z0(R.lifecycle)}`,children:R.lifecycle}),C&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:C})]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:"text-text-primary/90",children:R.workspaceLabel||(I==null?void 0:I.runtimeWorkspaceLabel)||R.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:R.runtimeKey}),R.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",R.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((V=R.writeOwner)==null?void 0:V.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:U0(R.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(Kl,{size:11})," ",K]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",Cl(R.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",E]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[T==="recovery"&&(R.lifecycle==="interrupted"||R.lifecycle==="failed"||R.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{b("session_host_resume_session",R)},children:F?`${_}ing…`:_}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{b("session_host_restart_session",R)},children:W?"Restarting…":"Restart"}),T==="live"&&(R.lifecycle==="running"||R.lifecycle==="starting"||R.lifecycle==="interrupted")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{b("session_host_stop_session",R)},children:D?"Stopping…":"Stop"})]})]})},R.sessionId)};return t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[t.jsx(es,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Oh()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[L>0&&t.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 (${L})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${v.toneClass}`,children:v.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:h||c,children:[t.jsx(wr,{size:13}),h||c?"Refreshing…":"Refresh"]})]})]}),n&&!u&&t.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:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(gr,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),u&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:w.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),t.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Cl(u.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Sa(u.hostStartedAt)})]})]}),j&&t.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:[t.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[t.jsx(gr,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:j.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Sa(j.timestamp),j.sessionId?` · ${j.sessionId}`:""]})]}),t.jsxs("div",{className:"mb-4 space-y-4",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(co,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ja("live")}),S.length===0?t.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."}):t.jsx("div",{className:"space-y-2",children:S.map(R=>O(R,"live"))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(es,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ja("recovery")}),w.length===0?t.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."}):t.jsx("div",{className:"space-y-2",children:w.map(R=>O(R,"recovery"))})]}),A.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ja("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:A.map(R=>O(R,"inactive"))})]})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),k.length===0?t.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."}):t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:k.map(R=>{var F;const T=x.find(W=>W.sessionId===R.sessionId);return t.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary font-medium",children:(T==null?void 0:T.displayName)||((F=f.get(R.sessionId))==null?void 0:F.cliName)||R.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[R.action,R.lifecycle?` · ${R.lifecycle}`:"",R.detail?` · ${R.detail}`:"",R.error?` · ${R.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${R.success===!1?"text-red-300":"text-text-secondary"}`,children:Sa(R.timestamp)})]},`${R.sessionId}:${R.timestamp}:${R.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function q0({machine:e,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return t.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:t.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:[t.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),t.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."}),t.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?t.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=>t.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:s.cliType,workspaceId:o.id,argsStr:s.argsStr,model:s.model})},children:[t.jsx("span",{className:"font-medium text-text-primary block truncate",children:o.label||o.path}),t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:o.path})]},o.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:s.cliType,useDefaultWorkspace:!0,argsStr:s.argsStr,model:s.model})},children:"Default workspace"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:s.cliType,useHome:!0,argsStr:s.argsStr,model:s.model})},children:"Home directory"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function Na({icon:e,children:s}){return t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,t.jsx("span",{children:s})]})}function Ca({children:e,className:s=""}){return t.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${s}`,children:e})}function Y0({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:l}){const c=n.slice(0,6),d=r.slice(0,4),m="0.9.81",u=md(e),h=Ts(e,m),g=pr(e,h),v=u==="preview"?"Update to preview":"Update daemon";return t.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&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Na,{icon:t.jsx(Vt,{size:13}),children:"Current Chats"}),t.jsx(Ca,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(f=>{const p=Ya(f);return t.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>l(f),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:lt(f)}),p>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:In(p)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:vs(f)})]},f.tabKey)})})})]}),d.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Na,{icon:t.jsx(Ul,{size:13}),children:"Recent Launches"}),t.jsx(Ca,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(f=>{const{metaText:p,updatedLabel:b}=kd(f);return t.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(f),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:f.label}),b&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:b})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:p})]},f.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Na,{icon:t.jsx(gr,{size:13}),children:"Daemon Update"}),t.jsx(Ca,{className:"border-amber-500/20 bg-amber-500/5",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:g?"Daemon update required":"Version mismatch detected"}),t.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[g?"This machine is on an incompatible daemon version. Update it before starting more sessions.":u==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",h&&t.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",h,u?` (${u})`:""]})]}),t.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:[t.jsx(wr,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:v})]})]})})]})]})}function X0(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function J0({machine:e,selectedWorkspace:s,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:o,onCustomPathChange:l,onOpenBrowseDialog:c}){return t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:s,onChange:d=>{const m=d.target.value;if(o(m),m==="__custom__"&&a){c();return}m!=="__custom__"&&l("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(e.workspaces||[]).length>0?t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(d=>t.jsxs("option",{value:d.id,children:[d.id===e.defaultWorkspaceId?"⭐ ":"",An(d.path,d.label)]},d.id)),t.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]}):t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),t.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),s==="__custom__"&&(a?t.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:c,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:d=>l(d.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),t.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:s==="__custom__"?r?t.jsx("span",{className:"font-mono truncate block",title:r,children:r}):a?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:s===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const Q0={ide:{label:"IDE",plural:"IDEs",accent:"border-blue-500/[0.12]"},cli:{label:"CLI",plural:"CLIs",accent:"border-violet-500/[0.12]"},acp:{label:"ACP Agent",plural:"ACP agents",accent:"border-emerald-500/[0.12]"}};function qr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ia({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:l,sendDaemonCommand:c,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const h=Hs(),{handleLaunchIde:g,handleStopCli:v,handleRestartIde:f,handleStopIde:p,handleDetectIdes:b,launchingIde:y,launchingAgentType:x,addLog:N}=l,[S,w]=i.useState(null),A=i.useCallback(M=>{M&&h(ss(M))},[h]),L=Q0[e],k=e==="ide",j=e==="acp",O=i.useMemo(()=>n.filter(M=>ws(M,e)),[e,n]),R=i.useMemo(()=>new Map(O.map(M=>[M.type,M.displayName||M.type])),[O]),[T,F]=i.useState(""),[W,D]=i.useState(""),[C,I]=i.useState([]),[K,_]=i.useState(""),[E,V]=i.useState(""),[Y,ge]=i.useState([]),[pe,re]=i.useState(!1),[de,ke]=i.useState(!1),[ye,q]=i.useState(""),[he,fe]=i.useState(!1),[we,xe]=i.useState(()=>jt()),[Se,Q]=i.useState(null),[ue,oe]=i.useState(m?"__custom__":d||s.defaultWorkspaceId||""),[me,le]=i.useState(m||""),[P,U]=i.useState([]),[ce,te]=i.useState(!1),[ie,se]=i.useState(""),[ve,Ie]=i.useState([]),[Me,B]=i.useState(!1),[Ne,Re]=i.useState(""),Fe=i.useRef(null),[He,Ge]=i.useState(null),qe=i.useRef("__home__"),[et,dt]=i.useState("__home__"),[pt,bt]=i.useState(!1),Ce=i.useRef(0),Ue=P.filter(M=>!a.some(X=>X.type===M&&xt(X.status)!=="stopped")),Qe=i.useRef({});i.useEffect(()=>{s.defaultWorkspaceId&&!ue&&oe(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),i.useEffect(()=>{if(m){oe("__custom__"),le(m);return}d&&(oe(d),le(""))},[d,m]),i.useEffect(()=>{k||T&&(O.some(M=>M.type===T)||(F(""),V("")))},[O,k,T]);const ze=(()=>{if(ue==="__custom__")return me.trim();if(!ue)return"";const M=(s.workspaces||[]).find(X=>X.id===ue);return(M==null?void 0:M.path)||""})(),rt=i.useCallback(M=>{const X=Qe.current[M];X&&(clearTimeout(X),delete Qe.current[M]),U(be=>be.includes(M)?be.filter($e=>$e!==M):be)},[]),H=i.useRef(new Set),z=i.useCallback(async M=>{if(c){B(!0),Re("");try{const X=await En(c,r,M);se(X.path),le(X.path),Ie(X.directories)}catch(X){Re(X instanceof Error?X.message:"Could not load folder")}finally{B(!1)}}},[r,c]),J=i.useCallback(()=>{if(!c)return;oe("__custom__"),te(!0);const M=a.map(be=>be.workspace),X=Dn(s.platform,Pn(me.trim(),ze,m,M,s.defaultWorkspacePath,(s.workspaces||[]).map(be=>be.path)));z(X)},[me,m,z,s.defaultWorkspacePath,s.platform,s.workspaces,a,ze,c]),ne=i.useCallback(M=>{const X=String(M.workspace||"").trim();if(!X)return;const be=(s.workspaces||[]).find($e=>qr($e.path)===qr(X));if(be){oe(be.id),le("");return}oe("__custom__"),le(X)},[s.workspaces]),$=i.useCallback(M=>{const X=String(M.workspace||"").trim();if(!X)return{workspaceId:null,workspacePath:"",useHome:!0};const be=(s.workspaces||[]).find($e=>qr($e.path)===qr(X));return be?{workspaceId:be.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:X,useHome:!1}},[s.workspaces]),G=i.useCallback(async M=>{if(!c||!M||e!=="cli"){ge([]),re(!1),ke(!1),q("");return}const X=Ce.current+1;Ce.current=X,re(!0),q("");try{const be=await c(r,"list_saved_sessions",{providerType:M,kind:"cli",limit:30});if(Ce.current!==X)return;const $e=(be==null?void 0:be.result)??be;ge(Array.isArray($e==null?void 0:$e.sessions)?$e.sessions:[])}catch(be){if(Ce.current!==X)return;ge([]),q(be instanceof Error?be.message:"Could not load saved sessions")}finally{Ce.current===X&&(re(!1),ke(!0))}},[e,r,c]),ee=i.useMemo(()=>{if(e!=="cli"||!T)return null;const M=R.get(T)||T;return{routeId:r,daemonId:r,providerSessionId:E||void 0,transport:"pty",mode:"chat",agentName:M,agentType:T,status:"idle",title:M,messages:[],ideType:T,workspaceName:ze,workspacePath:ze,displayPrimary:M,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${T}`}},[e,r,R,ze,E,T]),ae=i.useCallback(M=>{if(e==="ide"||!M){I([]);return}I(Qa(r,M))},[e,r]),je=i.useCallback((M,X)=>{e==="ide"||!M||(Zg(r,M,X),I(Qa(r,M)))},[e,r]);i.useEffect(()=>{Ce.current+=1,V(""),ae(T),ke(!1),ge([]),q(""),re(!1)},[e,ae,G,T]);const _e=i.useMemo(()=>Y.find(M=>M.providerSessionId===E)||null,[Y,E]);i.useEffect(()=>{if(!E)return;const M=Y.find(X=>X.providerSessionId===E);M!=null&&M.canResume||V("")},[Y,E]);const De=i.useCallback((M,X)=>{Fe.current=X,qe.current=M.selectedWorkspaceKey||"__home__",dt(M.selectedWorkspaceKey||"__home__"),Ge(M)},[]),Ae=i.useCallback(()=>{Fe.current&&(bt(!0),Fe.current().finally(()=>{Fe.current=null,bt(!1),Ge(null)}))},[]),Ee=i.useCallback(M=>{if(!M)return;U(be=>be.includes(M)?be:[...be,M]);const X=Qe.current[M];X&&clearTimeout(X),Qe.current[M]=setTimeout(()=>{U(be=>be.includes(M)?be.filter($e=>$e!==M):be),delete Qe.current[M]},2e4)},[]);i.useEffect(()=>{for(const X of a)xt(X.status)!=="stopped"&&(P.includes(X.type)&&!H.current.has(X.type)&&(H.current.add(X.type),N("info",`${R.get(X.type)||X.type} launched`,!0)),rt(X.type));const M=new Set(a.filter(X=>xt(X.status)!=="stopped").map(X=>X.type));H.current.forEach(X=>{!P.includes(X)&&!M.has(X)&&H.current.delete(X)})},[N,rt,a,P,R]),i.useEffect(()=>()=>{Object.values(Qe.current).forEach(clearTimeout),Qe.current={}},[]);const[Oe,Te]=i.useState({}),[Ye,Je]=i.useState(null);i.useEffect(()=>{if(!k||!r||!c)return;(async()=>{try{const X=await c(r,"get_ide_extensions",{}),be=(X==null?void 0:X.result)||X;be!=null&&be.success&&(be!=null&&be.ideExtensions)&&Te(be.ideExtensions)}catch{}})()},[k,r,c]);const ft=M=>k?ot(M.type):e==="cli"?M.cliName:M.acpName,ht=k?s.detectedIdes||[]:[],it=i.useCallback(async M=>{const X=(M==null?void 0:M.type)||T,be=(M==null?void 0:M.workspacePath)??ze;if(k){await g(X,be?{workspace:be}:void 0)&&Ee(X);return}const $e=await l.runLaunchCliCore({cliType:X,dir:M!=null&&M.workspaceId?void 0:be||void 0,workspaceId:(M==null?void 0:M.workspaceId)||void 0,useHome:(M==null?void 0:M.useHome)||!(M!=null&&M.workspaceId)&&!be,argsStr:(M==null?void 0:M.argsStr)??(W||void 0),model:(M==null?void 0:M.model)??(j&&K||void 0),resumeSessionId:(M==null?void 0:M.resumeSessionId)||!j&&e==="cli"&&X===T&&E||void 0});if($e.success||$e.pending){const Le=(M==null?void 0:M.argsStr)??W;!k&&(Le!=null&&Le.trim())&&($d(r,X,Le),ae(X)),Ee(X),$e.success&&$e.sessionId&&A($e.sessionId)}},[l,g,j,k,W,K,ae,Ee,r,A,ze,E,T]),ut=Ec(k?"ide":j?"acp":"cli",!k&&!j&&!!E),We=$c(k?"ide":j?"acp":"cli",!k&&!j&&!!E),$t=()=>{var Le;const M=k?ot(T):R.get(T)||T,X=!k&&!j&&!!E,{options:be,selectedKey:$e}=xs({machine:s,currentWorkspaceId:ue&&ue!=="__custom__"?ue:null,currentWorkspacePath:ze});De({title:X?Ao(M):us("start-fresh",M),description:X?Mo():ms("start-fresh"),confirmLabel:ut,busyLabel:We,workspaceOptions:be,selectedWorkspaceKey:$e,details:[{label:"Mode",value:L.label},{label:"Provider",value:M},...!k&&e==="cli"&&E?[{label:"Resume",value:((Le=Y.find(Be=>Be.providerSessionId===E))==null?void 0:Le.title)||E}]:[],...!k&&W.trim()?[{label:"Arguments",value:W.trim()}]:[],...j&&K.trim()?[{label:"Model",value:K.trim()}]:[]]},async()=>{const Be=be.find(tt=>tt.key===qe.current);Be!=null&&Be.workspaceId?(oe(Be.workspaceId),le("")):Be!=null&&Be.workspacePath?(oe("__custom__"),le(Be.workspacePath)):(oe(""),le("")),await it({workspaceId:(Be==null?void 0:Be.workspaceId)??null,workspacePath:(Be==null?void 0:Be.workspacePath)??"",useHome:!(Be!=null&&Be.workspaceId)&&!(Be!=null&&Be.workspacePath)})})},Z=M=>{k?p(M):v(M.type,M.workspace,M.id)},Pe=i.useCallback(async(M,X,be=!1)=>{if(M.mode===X){be&&M.sessionId&&A(M.sessionId);return}if(!c||!M.sessionId){be&&M.sessionId&&A(M.sessionId);return}try{await c(r,"set_cli_view_mode",{targetSessionId:M.sessionId,cliType:M.type,mode:X}),be&&A(M.sessionId)}catch($e){const Le=rd($e);sd($e)?console.warn(Le?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",$e instanceof Error?$e.message:String($e)):console.error("Failed to switch CLI view mode:",$e)}},[r,A,c]);return t.jsxs("div",{children:[t.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${L.accent} relative overflow-hidden`,children:[t.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[t.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",L.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?ht.length>0?ht.map(M=>{const X=a.find(tt=>(tt.type||"").toLowerCase()===(M.type||"").toLowerCase()&&xt(tt.status)!=="stopped"),be=M.running||!!X,$e=!!X&&X.cdpConnected,Le=P.includes(M.type||M.id||""),Be=T===(M.type||"");return t.jsxs("button",{onClick:()=>{if($e&&X){const tt=X.sessionId;tt?h(ss(tt),{state:{openRemoteForTabKey:tt}}):h("/dashboard",{state:{openRemoteForTabKey:X.id}});return}Le||F(tt=>tt===(M.type||"")?"":M.type||"")},disabled:!!y||Le,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${$e?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Be?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:y&&y!==M.type?.4:1},children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:o(M.type)}),be&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${$e?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:M.name||ot(M.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${$e?"text-green-400":Le?"text-orange-400":Be?"text-accent-primary":"text-text-muted"}`,children:$e?"Open Session":Le?"Starting...":Be?"Configure":"Select"})]})]},M.type)}):t.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",t.jsxs("button",{onClick:b,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[t.jsx(lm,{size:14})," Scan System"]})]}):O.length>0?O.map(M=>{const X=T===M.type,be=P.includes(M.type),Le=!!a.find(Be=>Be.type===M.type&&xt(Be.status)!=="stopped");return t.jsxs("button",{onClick:()=>F(Be=>Be===M.type?"":M.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${X?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:M.icon}),Le&&t.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:M.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${be?"text-orange-400":X?"text-accent-primary":"text-text-muted"}`,children:be?"Starting...":X?"Configure":"Select"})]})]},M.type)}):t.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",t.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),T&&(k?ht.find(M=>M.type===T):O.find(M=>M.type===T))&&t.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:k?ot(T):R.get(T)||T})]}),t.jsx(J0,{machine:s,selectedWorkspace:ue,resolvedWorkspacePath:ze,customPath:me,canBrowse:!!c,onWorkspaceChange:oe,onCustomPathChange:le,onOpenBrowseDialog:J}),!k&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!j&&e==="cli"&&t.jsx(Od,{busy:!!x||!!y||P.includes(T),savedSessionsLoading:pe,savedSessionsError:ye,savedSessionsLoaded:de,savedSessionsCount:Y.length,selectedSession:_e,onRefresh:()=>void G(T),onOpenHistory:()=>{T&&(fe(!0),Bd({hasLoadedInitialResults:de,isLoading:pe})&&G(T))},onClearSelection:()=>V("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[j&&t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),t.jsx("input",{type:"text",placeholder:"Leave empty for default",value:K,onChange:M=>_(M.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),t.jsx("input",{type:"text",placeholder:"Optional flags...",value:W,onChange:M=>D(M.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),C.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:C.map(M=>t.jsxs("div",{className:"inline-flex max-w-full items-stretch overflow-hidden rounded-md border border-[#ffffff1a] bg-bg-tertiary text-xs text-text-secondary transition-colors hover:border-accent-primary/40 hover:text-text-primary",title:M,children:[t.jsx("button",{type:"button",className:"min-w-0 max-w-[220px] truncate px-2.5 py-1.5 text-left",onClick:()=>D(M),children:M}),t.jsx("button",{type:"button",className:"flex items-center justify-center border-l border-[#ffffff1a] px-1.5 text-text-muted transition-colors hover:bg-status-error/10 hover:text-status-error focus:outline-none focus:ring-1 focus:ring-status-error/50",onClick:()=>je(T,M),"aria-label":`Remove startup arguments: ${M}`,title:"Remove startup arguments",children:t.jsx(gt,{size:12})})]},M))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:$t,disabled:!!x||!!y||P.includes(T),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:x===T||y===T?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+P.filter(M=>!a.some(X=>X.type===M&&xt(X.status)!=="stopped")).length,")"]}),a.length===0&&Ue.length===0?t.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",L.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ue.map(M=>t.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:o(M)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?ot(M):R.get(M)||M}),t.jsx("div",{className:"text-[11px] text-text-muted",children:x===M?"Launching process...":"Waiting for process and session to register..."})]})]}),t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${M}`)),a.map(M=>{const X=k?M:null,be=!k&&!j?M:null,$e=xt(M.status);return t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center mb-2",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:o(M.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[ft(M),(X==null?void 0:X.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",X.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex min-w-0 flex-wrap items-center gap-2",children:[t.jsx("span",{className:"truncate",children:M.workspace||"—"}),u&&M.git&&M.workspace?t.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:Le=>{Le.stopPropagation(),u(M.daemonId??r,M.workspace)},children:t.jsx(Os,{git:M.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):t.jsx(Os,{git:M.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(be==null?void 0:be.mode)&&t.jsx("span",{className:be.mode==="chat"?"text-violet-400":"text-text-secondary",children:be.mode==="chat"?"Chat view":"Terminal view"})]}),be&&(be.runtimeKey||be.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[be.runtimeKey&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),t.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",be.runtimeKey]}),t.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Le;(Le=navigator.clipboard)==null||Le.writeText(`adhdev attach ${be.runtimeKey}`),w(be.runtimeKey||null),window.setTimeout(()=>{w(Be=>Be===be.runtimeKey?null:Be)},1200)},children:S===be.runtimeKey?"Copied":"Copy"})]}),be.runtimeWriteOwner&&t.jsx("span",{style:{color:be.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:be.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:X0(be.runtimeWriteOwner)})]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${$e==="stopped"?"bg-red-500/[0.08] text-red-500":$e==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:$e}),k&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Le=M.sessionId;if(Le){h(ss(Le),{state:{openRemoteForTabKey:Le}});return}h("/dashboard",{state:{openRemoteForTabKey:M.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:t.jsx(It,{size:13})}),t.jsx("button",{onClick:()=>{const Le=M.workspace||"",{options:Be,selectedKey:tt}=xs({machine:s,currentWorkspacePath:Le});De({title:us("restart-ide",ot(M.type)),description:ms("restart-ide"),confirmLabel:Ks("restart-ide"),busyLabel:Fs("restart-ide"),workspaceOptions:Be,selectedWorkspaceKey:tt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:ot(M.type)}]},async()=>{const Nt=Be.find(qt=>qt.key===qe.current),mt=(Nt==null?void 0:Nt.workspacePath)??"";if(mt&&mt!==Le){await it({type:M.type,workspacePath:mt});return}await f(M)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:t.jsx(wr,{size:14})})]}),j&&t.jsx("button",{onClick:()=>{const Le=M.sessionId;Le&&A(Le)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!M.sessionId,children:t.jsx(Vt,{size:14})}),be&&$e!=="stopped"&&t.jsxs(t.Fragment,{children:[be.mode&&t.jsx(Co,{mode:be.mode,onChange:Le=>void Pe(be,Le,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Le=M.sessionId;Le&&A(Le)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!M.sessionId,children:be.mode==="chat"?t.jsx(Vt,{size:14}):t.jsx(It,{size:13})})]}),$e==="stopped"?t.jsx("button",{onClick:()=>{const Le=M.workspace||"",Be=k?ot(M.type):ft(M),{options:tt,selectedKey:Nt}=xs({machine:s,currentWorkspacePath:Le});De({title:us("restart-stopped",Be),description:ms("restart-stopped"),confirmLabel:Ks("restart-stopped"),busyLabel:Fs("restart-stopped"),workspaceOptions:tt,selectedWorkspaceKey:Nt,details:[{label:"Mode",value:L.label},{label:"Provider",value:Be}]},async()=>{const mt=tt.find(qt=>qt.key===qe.current);await it({type:M.type,workspaceId:(mt==null?void 0:mt.workspaceId)??null,workspacePath:(mt==null?void 0:mt.workspacePath)??"",useHome:!(mt!=null&&mt.workspaceId)&&!(mt!=null&&mt.workspacePath)})})},disabled:P.includes(M.type),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-green-500/20 text-green-400 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",title:"Restart",children:P.includes(M.type)?"⏳":t.jsx(uo,{size:14})}):t.jsx("button",{onClick:()=>Z(M),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:t.jsx(gt,{size:14})})]})]}),X&&X.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:X.aiAgents.map(Le=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${pn(Le.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Le.name," · ",xt(Le.status)]},Le.id))}),X&&(Oe[X.type]||[]).length>0&&c&&t.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[t.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:(Oe[X.type]||[]).map(Le=>t.jsxs("button",{disabled:Ye===`${X.type}.${Le.type}`,onClick:async()=>{const Be=`${X.type}.${Le.type}`;Je(Be);try{await c(r,"set_ide_extension",{ideType:X.type,extensionType:Le.type,enabled:!Le.enabled}),Te(tt=>({...tt,[X.type]:(tt[X.type]||[]).map(Nt=>Nt.type===Le.type?{...Nt,enabled:!Nt.enabled}:Nt)}))}catch(tt){console.error("Extension toggle failed:",tt)}finally{Je(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${Le.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Le.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Le.name,t.jsx("span",{className:"text-[9px] font-normal",children:Le.enabled?"ON":"OFF"})]},Le.type))})]})]},M.id)})]}),ce&&c&&t.jsx($n,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:ie,directories:ve,busy:Me,error:Ne,confirmLabel:"Use this folder",onClose:()=>te(!1),onNavigate:M=>{z(M)},onConfirm:M=>{le(M),oe("__custom__"),te(!1)}}),He&&t.jsx(Ko,{title:He.title,description:He.description,details:He.details,workspaceOptions:He.workspaceOptions,selectedWorkspaceKey:et,onWorkspaceChange:M=>{qe.current=M,dt(M)},confirmLabel:He.confirmLabel,busyLabel:He.busyLabel,busy:pt,onConfirm:Ae,onCancel:()=>{Fe.current=null,Ge(null)}}),he&&ee&&t.jsx(Lo,{activeConv:ee,ides:[],isCreatingChat:!1,isRefreshingHistory:pe,savedSessions:Y,isSavedSessionsLoading:pe,isResumingSavedSessionId:Se,savedHistoryFilters:we,missingWorkspaceResumePath:ze||null,onSavedHistoryFiltersChange:xe,onClose:()=>fe(!1),onNewChat:()=>{V(""),fe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{G(T)},onResumeSavedSession:M=>{if(!M.canResume||Se)return;const X=$(M);V(M.providerSessionId),ne(M),Q(M.providerSessionId),fe(!1),it({type:M.providerType,workspaceId:X.workspaceId,workspacePath:X.workspacePath,useHome:X.useHome,resumeSessionId:M.providerSessionId}).finally(()=>{Q(be=>be===M.providerSessionId?null:be)})}})]})}const Il=[{id:"ide",label:"IDE",helper:"Open a graphical workspace and attach CDP"},{id:"cli",label:"CLI",helper:"Launch a terminal-first workspace on this machine"},{id:"acp",label:"ACP",helper:"Launch an ACP-backed workspace on this machine"}];function Z0({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:l,getIcon:c,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:h,onOpenGitDialog:g}){var b;const[v,f]=i.useState(d);i.useEffect(()=>{f(d)},[d]);const p=i.useMemo(()=>({ide:n.length,cli:a.length,acp:o.length}),[n.length,a.length,o.length]);return t.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[t.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),t.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),t.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[t.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:Il.map(y=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${v===y.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>f(y.id),children:[t.jsx("span",{children:y.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${v===y.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:p[y.id]})]},y.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(b=Il.find(y=>y.id===v))==null?void 0:b.helper})]}),v==="ide"&&t.jsx(Ia,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:g}),v==="cli"&&t.jsx(Ia,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:g}),v==="acp"&&t.jsx(Ia,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:o,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:g})]})}function ev({onNicknameSynced:e}={}){var le,P,U,ce,te,ie,se,ve,Ie,Me;const{id:s}=Ru(),r=Hs(),n=no(),{sendCommand:a}=yt(),o=Sr(),l=Jc(),c=Tc(),d=c.ides||[],m=c.initialLoaded??!0,u=d.find(B=>B.id===s&&B.type==="adhdev-daemon"),h=d.some(B=>B.type==="adhdev-daemon"),g=s?(le=c.connectionRetryStatuses)==null?void 0:le[s]:void 0,v=!!(g!=null&&g.blocked),[f,p]=i.useState("workspace"),[b,y]=i.useState(null),x=i.useCallback((B,Ne)=>{y({daemonId:B,workspace:Ne})},[]),[N,S]=i.useState("ide"),w=i.useRef(null),[A,L]=i.useState(null),k=i.useRef("__home__"),[j,O]=i.useState("__home__"),[R,T]=i.useState(!1),F=i.useRef(null);i.useEffect(()=>{!s||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||o(s,{minFreshMs:3e4}).catch(()=>{})},[o,u,s]),i.useEffect(()=>{if(!s||!u||f!=="overview")return;const B=u.machine;(typeof(B==null?void 0:B.cpus)!="number"||typeof(B==null?void 0:B.totalMem)!="number"||typeof(B==null?void 0:B.arch)!="string"||typeof(B==null?void 0:B.release)!="string")&&l(s,{minFreshMs:3e4}).catch(()=>{})},[f,l,u,s]),$x(s&&f==="overview"?[s]:[],{enabled:f==="overview",intervalMs:Mf});const W=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},D=Yy({machineId:s,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:F});i.useEffect(()=>nt.onToast(Ne=>{c.setToasts(Fe=>{if(Fe.some(qe=>qe.message===Ne.message&&Ne.timestamp-qe.timestamp<3e3))return Fe;const Ge={id:Ne.id,message:Ne.message,type:Ne.type,timestamp:Ne.timestamp,targetKey:Ne.targetKey,actions:Ne.actions};return[...Fe.slice(-4),Ge]});const Re=Ne.duration||5e3;setTimeout(()=>c.setToasts(Fe=>Fe.filter(He=>He.id!==Ne.id)),Re)}),[c]);const C=(u==null?void 0:u.availableProviders)||[],I={};for(const B of C)I[B.type]=B.icon;const K=B=>I[B]||"",_=u?{id:u.id,hostname:sc(u,{fallbackId:u.id}),platform:((P=u.machine)==null?void 0:P.platform)||"unknown",arch:((U=u.machine)==null?void 0:U.arch)||"",cpus:((ce=u.machine)==null?void 0:ce.cpus)||0,totalMem:((te=u.machine)==null?void 0:te.totalMem)||0,freeMem:(ie=u.machine)==null?void 0:ie.freeMem,availableMem:(se=u.machine)==null?void 0:se.availableMem,loadavg:(ve=u.machine)==null?void 0:ve.loadavg,uptime:(Ie=u.machine)==null?void 0:Ie.uptime,release:((Me=u.machine)==null?void 0:Me.release)||"",cdpConnected:!!u.cdpConnected,machineNickname:u.machineNickname||null,p2p:u.p2p?{screenshotActive:!1,...u.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:u.detectedIdes||[],workspaces:u.workspaces||[],defaultWorkspaceId:u.defaultWorkspaceId??u.activeWorkspaceId??null,defaultWorkspacePath:u.defaultWorkspacePath??u.activeWorkspacePath??null}:null,E=d.filter(B=>B.daemonId===s&&B.type!=="adhdev-daemon").filter(B=>!yr(B)&&!Ls(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,version:B.version||"",instanceId:B.instanceId||"",status:B.status,workspace:B.workspace||null,terminals:B.terminals||0,aiAgents:wp(B.aiAgents||(B.agents||[]).map(Ne=>({id:Ne.name,name:Ne.name,status:Ne.status,version:Ne.version}))),activeChat:B.activeChat||null,chats:B.chats||[],childSessions:B.childSessions||[],cdpConnected:B.cdpConnected||!1,daemonId:s,lastMessageAt:B.lastMessageAt})),V=d.filter(B=>B.daemonId===s&&yr(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,cliName:B.cliName||B.type,status:B.status,workspace:B.workspace||"",activeChat:B.activeChat||null,providerSessionId:B.providerSessionId,mode:B.mode,runtimeKey:B.runtimeKey,runtimeDisplayName:B.runtimeDisplayName,runtimeWorkspaceLabel:B.runtimeWorkspaceLabel,runtimeWriteOwner:B.runtimeWriteOwner||null,runtimeAttachedClients:B.runtimeAttachedClients||[],daemonId:s,lastMessageAt:B.lastMessageAt})),Y=d.filter(B=>B.daemonId===s&&Ls(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,acpName:B.cliName||B.type,status:B.status,workspace:B.workspace||"",activeChat:B.activeChat||null,providerSessionId:B.providerSessionId,daemonId:s,lastMessageAt:B.lastMessageAt})),ge=u?Ct(u,{fallbackId:s}):"",pe="workspace",re=n.state,de=re==null?void 0:re.initialMachineTab,ke=re==null?void 0:re.initialWorkspaceCategory,ye=re==null?void 0:re.initialWorkspaceId,q=re==null?void 0:re.initialWorkspacePath,he=de==="ides"||de==="clis"||de==="acps"?"workspace":de||pe,fe=de==="ides"?"ide":de==="clis"?"cli":de==="acps"?"acp":ke,we=[...E.map(B=>{var Ne;return{id:`ide:${B.type}:${B.workspace||""}`,label:((Ne=B.activeChat)==null?void 0:Ne.title)||B.type,kind:"ide",providerType:B.type,subtitle:B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:B.lastMessageAt||0}}),...V.map(B=>{var Ne;return{id:`cli:${B.type}:${B.workspace||""}`,label:((Ne=B.activeChat)==null?void 0:Ne.title)||B.cliName,kind:"cli",providerType:B.type,providerSessionId:B.providerSessionId,subtitle:B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:B.lastMessageAt||0}}),...Y.map(B=>{var Ne;return{id:`acp:${B.type}:${B.workspace||""}`,label:((Ne=B.activeChat)==null?void 0:Ne.title)||B.acpName,kind:"acp",providerType:B.type,providerSessionId:B.providerSessionId,subtitle:ys(B.summaryMetadata)||B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:B.lastMessageAt||0}})].sort((B,Ne)=>(Ne.lastLaunchedAt||0)-(B.lastLaunchedAt||0)),xe=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(B=>({id:B.id,label:B.title||B.providerName||B.providerType,kind:B.kind,providerType:B.providerType,providerSessionId:B.providerSessionId,subtitle:ys(B.summaryMetadata)||B.workspace||void 0,workspace:B.workspace,summaryMetadata:B.summaryMetadata,lastLaunchedAt:B.lastLaunchedAt})):we,Se=i.useMemo(()=>{var Ne;const B=((Ne=c.connectionStates)==null?void 0:Ne[s||""])||void 0;return d.filter(Re=>Re.daemonId===s&&Re.type!=="adhdev-daemon").flatMap(Re=>Ro(Re,{connectionStates:s&&B?{[s]:B}:void 0,defaultConnectionState:B})).filter(Re=>!(Re.transport==="pty"&&Re.mode==="terminal")).sort((Re,Fe)=>Ya(Fe)-Ya(Re))},[d,c.connectionStates,s]),Q=i.useCallback(B=>{const Ne=xd(B);Ne&&r(ss(Ne))},[r]),ue=i.useCallback(()=>{w.current&&(T(!0),w.current().finally(()=>{w.current=null,T(!1),L(null)}))},[]),oe=i.useCallback(B=>{if(!_)return;const{options:Ne,selectedKey:Re}=xs({machine:_,currentWorkspacePath:B.workspace}),Fe=async()=>{S(B.kind),p("workspace")};w.current=async()=>{const He=Ne.find(et=>et.key===k.current),Ge=(He==null?void 0:He.workspacePath)??null,qe=(He==null?void 0:He.workspaceId)??null;if(B.kind==="ide"&&B.providerType){await D.handleLaunchIde(B.providerType,Ge?{workspace:Ge}:void 0);return}if((B.kind==="cli"||B.kind==="acp")&&B.providerType){await D.runLaunchCliCore({cliType:B.providerType,dir:qe?void 0:Ge||"",workspaceId:qe||void 0,model:B.kind==="acp"&&nc(B.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:B.providerSessionId});return}await Fe()},k.current=Re,O(Re),L({title:B.kind==="ide"?us("restart-ide",B.label):B.providerSessionId?Ao(B.label):us("start-fresh",B.label),description:B.kind==="ide"?ms("restart-ide"):B.providerSessionId?Mo():ms("start-fresh"),confirmLabel:B.kind==="ide"?Ks("restart-ide"):B.providerSessionId?gn(!0):Ks("start-fresh"),busyLabel:B.kind==="ide"?Fs("restart-ide"):B.providerSessionId?Io(!0):Fs("start-fresh"),workspaceOptions:Ne,details:[{label:"Mode",value:B.kind.toUpperCase()},...B.providerType?[{label:"Provider",value:B.providerType}]:[]]})},[D,_]);if(i.useEffect(()=>{p(he)},[pe,he,s]),i.useEffect(()=>{fe&&S(fe)},[fe,s]),!_)return m?t.jsxs("div",{className:"p-10 text-center text-text-muted",children:[t.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),t.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),t.jsx("button",{onClick:W,className:"machine-btn-back",children:"← Back"})]}):t.jsx("div",{className:"p-10 text-center text-text-muted",children:t.jsx("p",{children:"⏳ Loading machine..."})});const me=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(It,{size:14})," Workspace"]}),count:E.length+V.length+Y.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(es,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Nn,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(dm,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(om,{size:14})," Logs"]})}];return t.jsxs("div",{className:"flex flex-col h-full",children:[t.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:[t.jsx("div",{className:"flex items-center justify-between w-full",children:t.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[t.jsx("button",{onClick:W,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:"←"}),t.jsxs("div",{className:"flex flex-col min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[D.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:D.nicknameInput,onChange:B=>D.setNicknameInput(B.target.value),onKeyDown:B=>{B.key==="Enter"&&D.handleSaveNickname(),B.key==="Escape"&&D.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]"}),t.jsx("button",{onClick:D.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"}),t.jsx("button",{onClick:()=>D.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"})]}):t.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{D.setEditingNickname(!0),D.setNicknameInput(_.machineNickname||"")},title:"Click to set nickname",children:ge}),v?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),c.retryConnection&&s&&t.jsx("button",{onClick:()=>c.retryConnection(s),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"})]}):t.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"})]}),t.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:[t.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[_.platform," · ",_.arch]}),t.jsxs("span",{children:[_.cpus," cores"]}),(u==null?void 0:u.version)&&t.jsxs("span",{children:["v",u.version]}),_.p2p.available&&t.jsxs("span",{children:["P2P ",_.p2p.state==="connected"?"connected":_.p2p.state]}),_.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:_.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:me.map(B=>t.jsxs("button",{onClick:()=>p(B.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===B.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[B.label,B.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===B.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:B.count})]},B.id))})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:t.jsx("div",{className:"max-w-7xl mx-auto h-full",children:t.jsxs("div",{className:"h-full",children:[f==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(Y0,{machineEntry:u,providers:C,recentLaunches:xe,currentConversations:Se,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",pd(u))}catch{}},onOpenRecent:oe,onOpenConversation:Q}),t.jsx(Z0,{machine:_,machineId:s,providers:C,ideSessions:E,cliSessions:V,acpSessions:Y,actions:D,getIcon:K,initialCategory:N,initialWorkspaceId:ye,initialWorkspacePath:q,sendDaemonCommand:a,onOpenGitDialog:x})]}),f==="providers"&&t.jsx(a0,{machineId:s,providers:C,sendDaemonCommand:a}),f==="overview"&&t.jsx(Xy,{machineId:s,machine:_,ideSessions:E,cliSessions:V,acpSessions:Y,actions:D,sendDaemonCommand:a}),f==="session-host"&&t.jsx(G0,{machineId:s,cliSessions:V,sendDaemonCommand:a}),f==="logs"&&t.jsx(K0,{machineId:s,sendDaemonCommand:a})]})})}),D.launchPick&&_&&t.jsx(q0,{machine:_,launchPick:D.launchPick,actions:D}),A&&t.jsx(Ko,{title:A.title,description:A.description,details:A.details,workspaceOptions:A.workspaceOptions,selectedWorkspaceKey:j,onWorkspaceChange:B=>{k.current=B,O(B)},confirmLabel:A.confirmLabel,busyLabel:A.busyLabel,busy:R,onConfirm:ue,onCancel:()=>{w.current=null,L(null)}}),b&&t.jsx(zd,{daemonId:b.daemonId,workspace:b.workspace,onClose:()=>y(null)}),t.jsx(Bc,{toasts:c.toasts||[],onDismiss:B=>c.setToasts(Ne=>Ne.filter(Re=>Re.id!==B)),onClickToast:B=>{B.targetKey&&r(ss(B.targetKey))}}),t.jsx("style",{children:`
92
+ @keyframes toast-in {
93
+ from { opacity: 0; transform: translateX(40px); }
94
+ to { opacity: 1; transform: translateX(0); }
95
+ }
96
+ `})]})}const Yr=[{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."}],tv={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function an(e){var n;const s=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return s.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function sv(e){const s=an(e);return s.length?{configured:!0,label:s.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"launch not ready unless an explicit provider is selected"}}function rv(e,s){return s.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function nv(e){const s=e.assignedSessionId||e.sessionId||"unassigned session",r=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${s}: ${r}`}function av(e,s){return[...Array.isArray(s==null?void 0:s.cliSessions)?s.cliSessions:[],...Array.isArray(s==null?void 0:s.acpSessions)?s.acpSessions:[],...Array.isArray(s==null?void 0:s.sessions)?s.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 Ta(e){return{...tv,...(e==null?void 0:e.policy)||{}}}function ov({meshId:e,availableCliAgents:s}){const r=s.find(a=>{const o=a.id.toLowerCase(),l=a.name.toLowerCase();return o==="hermes-cli"||o.includes("hermes")||l.includes("hermes")}),n=hd(r==null?void 0:r.meshCoordinator,{meshId:e});return n?t.jsx(vt,{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:t.jsx(Kd,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function iv(){var le;const{sendCommand:e}=yt(),{ides:s}=rs(),r=s.find(P=>P.daemonMode||P.type==="adhdev-daemon"),n=(r==null?void 0:r.id)||"",a=[];let o=[];if(r){const P=r.availableProviders||[];o=Jh(P);for(const U of P)U.category==="cli"&&a.push({id:U.type||U.id,name:U.displayName||U.name||U.type,meshCoordinator:U.meshCoordinator})}const[l,c]=i.useState([]),[d,m]=i.useState(null),[u,h]=i.useState(!0),[g,v]=i.useState(null),[f,p]=i.useState(!1),[b,y]=i.useState(null),[x,N]=i.useState({}),[S,w]=i.useState([]),[A,L]=i.useState(null),[k,j]=i.useState(null),[O,R]=i.useState(!1),[T,F]=i.useState(null),[W,D]=i.useState(null),[C,I]=i.useState(!1),[K,_]=i.useState(""),[E,V]=i.useState(""),[Y,ge]=i.useState(!1),[pe,re]=i.useState(""),[de,ke]=i.useState([]),ye=l.find(P=>P.id===d)||null;i.useEffect(()=>{N(Object.fromEntries(((ye==null?void 0:ye.nodes)||[]).map(P=>[P.id,an(P)])))},[ye]),i.useEffect(()=>{const P=Qh(o);Y&&de.length===0&&P.length>0&&ke(P)},[Y,o,de.length]),i.useEffect(()=>{const P=new Set(((ye==null?void 0:ye.nodes)||[]).map(U=>U.id));A&&!P.has(A)&&L(null)},[ye,A]);const q=i.useCallback(async()=>{if(n){h(!0);try{const P=await e(n,"list_meshes");P!=null&&P.success?(c(P.meshes||[]),v(null)):v((P==null?void 0:P.error)||"Failed to load meshes")}catch(P){v((P==null?void 0:P.message)||"Failed to load meshes")}finally{h(!1)}}},[n,e]),he=i.useCallback(async P=>{if(!n||!P){w([]);return}try{const U=await e(n,"get_mesh_queue",{meshId:P});U!=null&&U.success?w(Array.isArray(U.queue)?U.queue:[]):w([])}catch{w([])}},[n,e]);i.useEffect(()=>{q()},[q]),i.useEffect(()=>{he(d)},[he,d]);async function fe(){if(!(!n||!d))try{R(!0),F(null);const P=await e(n,"mesh_status",{meshId:d});if(P!=null&&P.success){const U=P.status||P.result||P;if(U&&typeof U=="object"){const ce=Fd(U);j(ce)}else F("Invalid mesh_status response format")}else F((P==null?void 0:P.error)||"mesh_status failed")}catch(P){F((P==null?void 0:P.message)||"Failed to load mesh graph")}finally{R(!1)}}i.useEffect(()=>{d&&(j(null),F(null),D(null),fe())},[d]);async function we(){var P;if(!(!n||!K.trim()))try{const U=await e(n,"create_mesh",{name:K.trim(),repoIdentity:E.trim()||void 0});U!=null&&U.success?(I(!1),_(""),V(""),await q(),m(((P=U.mesh)==null?void 0:P.id)||null)):v((U==null?void 0:U.error)||"Create failed")}catch(U){v((U==null?void 0:U.message)||"Create failed")}}async function xe(P){if(!(!n||!confirm("Delete this mesh?")))try{await e(n,"delete_mesh",{meshId:P}),m(null),await q()}catch(U){v((U==null?void 0:U.message)||"Delete failed")}}async function Se(){if(!(!n||!d||!pe.trim()))try{const P=await e(n,"add_mesh_node",{meshId:d,workspace:pe.trim(),providerPriority:Ua(de,o)});P!=null&&P.success?(ge(!1),re(""),ke([]),await q(),await he(d)):v((P==null?void 0:P.error)||"Add node failed")}catch(P){v((P==null?void 0:P.message)||"Add node failed")}}async function Q(P){var te;if(!n||!d)return;const U=Ta(ye),ce=((te=Yr.find(ie=>ie.value===U.sessionCleanupOnNodeRemove))==null?void 0:te.label)||"Preserve history and runtimes";if(confirm(`Remove this node?
97
+
98
+ Node removal cleanup policy: ${ce}`))try{await e(n,"remove_mesh_node",{meshId:d,nodeId:P}),A===P&&L(null),await q(),await he(d)}catch(ie){v((ie==null?void 0:ie.message)||"Remove node failed")}}async function ue(P){if(!n||!d)return;const U={...Ta(ye),...P};try{p(!0),v(null);const ce=await e(n,"update_mesh",{meshId:d,policy:U});if((ce==null?void 0:ce.success)===!1){v(ce.error||"Policy update failed");return}await q()}catch(ce){v((ce==null?void 0:ce.message)||"Policy update failed")}finally{p(!1)}}async function oe(P){if(!n||!d)return;const U=Ua(x[P.id]||an(P),o),ce={...P.policy||{}};delete ce.provider_priority,U.length?ce.providerPriority=U:delete ce.providerPriority;try{y(P.id),v(null);const te=await e(n,"update_mesh_node",{meshId:d,nodeId:P.id,policy:ce});if((te==null?void 0:te.success)===!1){v(te.error||"Node policy update failed");return}await q()}catch(te){v((te==null?void 0:te.message)||"Node policy update failed")}finally{y(null)}}if(!n)return t.jsx(mr,{icon:t.jsx(Qt,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:t.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})});if(!ye)return t.jsxs(mr,{icon:t.jsx(Qt,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>I(!0),children:"+ Create Mesh"}),children:[g&&t.jsx(Ms,{variant:"error",className:"mb-4",children:g}),C&&t.jsx(vt,{title:"New Mesh",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(Tt,{label:"Name",children:t.jsx(ta,{value:K,onChange:P=>_(P.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),t.jsx(Tt,{label:"Repo Identity (optional)",children:t.jsx(ta,{value:E,onChange:P=>V(P.target.value),placeholder:"github.com/user/repo"})}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:we,disabled:!K.trim(),children:"Create"}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>I(!1),children:"Cancel"})]})]})}),u?t.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):l.length===0?t.jsx(yn,{icon:t.jsx(Qt,{}),title:"No meshes",description:"Create a mesh to get started."}):t.jsx("div",{className:"flex flex-col gap-2",children:l.map(P=>t.jsxs("button",{className:"text-left w-full p-4 rounded-xl border border-border-subtle bg-bg-panel hover:border-accent-primary/40 transition-colors",onClick:()=>m(P.id),children:[t.jsx("div",{className:"font-semibold text-sm",children:P.name}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:P.repoIdentity||"No repo identity"}),t.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[P.nodes.length," node(s)"]})]},P.id))})]});const me=Ta(ye);return t.jsxs(mr,{icon:t.jsx(Qt,{}),title:ye.name,subtitle:ye.repoIdentity||"Repo Mesh",actions:t.jsxs("div",{className:"flex gap-2",children:[t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(null),children:"← Back"}),t.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>xe(ye.id),children:"Delete"})]}),children:[g&&t.jsx(Ms,{variant:"error",className:"mb-4",children:g}),t.jsxs(vt,{title:"Policy",description:"Coordinator safety defaults and node-removal session cleanup behavior for this local mesh.",children:[t.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[t.jsx(Tt,{label:"Checkpoint before task",children:t.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:me.requirePreTaskCheckpoint?"yes":"no",onChange:P=>ue({requirePreTaskCheckpoint:P.target.value==="yes"}),disabled:f,children:[t.jsx("option",{value:"no",children:"No"}),t.jsx("option",{value:"yes",children:"Yes"})]})}),t.jsx(Tt,{label:"Checkpoint after task",children:t.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:me.requirePostTaskCheckpoint?"yes":"no",onChange:P=>ue({requirePostTaskCheckpoint:P.target.value==="yes"}),disabled:f,children:[t.jsx("option",{value:"yes",children:"Yes"}),t.jsx("option",{value:"no",children:"No"})]})}),t.jsx(Tt,{label:"Push approval",children:t.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:me.requireApprovalForPush?"required":"not_required",onChange:P=>ue({requireApprovalForPush:P.target.value==="required"}),disabled:f,children:[t.jsx("option",{value:"required",children:"Require approval before push"}),t.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),t.jsx(Tt,{label:"Destructive git approval",children:t.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:me.requireApprovalForDestructiveGit?"required":"not_required",onChange:P=>ue({requireApprovalForDestructiveGit:P.target.value==="required"}),disabled:f,children:[t.jsx("option",{value:"required",children:"Require approval"}),t.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),t.jsx(Tt,{label:"Dirty workspace behavior",children:t.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:me.dirtyWorkspaceBehavior||"warn",onChange:P=>ue({dirtyWorkspaceBehavior:P.target.value}),disabled:f,children:[t.jsx("option",{value:"warn",children:"Warn and continue"}),t.jsx("option",{value:"block",children:"Block task"}),t.jsx("option",{value:"checkpoint_then_continue",children:"Checkpoint then continue"})]})}),t.jsx(Tt,{label:"Max parallel tasks",children:t.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(me.maxParallelTasks??2),onChange:P=>ue({maxParallelTasks:Number(P.target.value)}),disabled:f,children:[1,2,3,4,5,6,7,8].map(P=>t.jsx("option",{value:P,children:P},P))})})]}),t.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[t.jsx(Tt,{label:"Node removal session cleanup",hint:"Separate transcript cleanup from runtime/process cleanup. Preserve is safest when completed work may need review.",children:t.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:me.sessionCleanupOnNodeRemove||"preserve",onChange:P=>ue({sessionCleanupOnNodeRemove:P.target.value}),disabled:f,children:Yr.map(P=>t.jsx("option",{value:P.value,children:P.label},P.value))})}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((le=Yr.find(P=>P.value===me.sessionCleanupOnNodeRemove))==null?void 0:le.description)||Yr[0].description})]}),f&&t.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),t.jsxs(vt,{title:"Visualization",description:"Live mesh topology: branches, worktrees, sessions, and orphan detection.",children:[t.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500"}),"healthy"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{className:"w-2 h-2 rounded-full bg-amber-500"}),"dirty"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{className:"w-2 h-2 rounded-full bg-red-500"}),"error"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{className:"w-2 h-2 rounded-full bg-gray-500"}),"offline"]})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:fe,disabled:O,children:O?"Loading...":"Refresh Graph"})]}),T&&t.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:T}),k?t.jsxs("div",{className:"flex gap-4",style:{minHeight:420},children:[t.jsx("div",{className:"flex-1 rounded-xl border border-border-subtle bg-bg-secondary overflow-hidden",style:{minHeight:420},children:t.jsx(Hd,{data:k,onNodeClick:P=>D(U=>(U==null?void 0:U.id)===P.id?null:P),selectedNodeId:(W==null?void 0:W.id)||null})}),W&&t.jsx("div",{className:"w-80 shrink-0",children:t.jsx(Za,{node:W,onClose:()=>D(null)})})]}):t.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:O?"Loading graph...":"Refresh the graph to view mesh topology."})]}),t.jsxs(vt,{title:"Nodes",description:"Workspaces participating in this mesh.",children:[t.jsx("div",{className:"flex justify-end mb-3",children:t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>ge(!0),children:"+ Add Node"})}),Y&&t.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass",children:[t.jsxs("div",{className:"flex justify-between items-center mb-3",children:[t.jsx("h4",{className:"text-sm font-bold",children:"Add Node"}),t.jsx("button",{onClick:()=>ge(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:t.jsx(gt,{size:16})})]}),t.jsx(Tt,{label:"Workspace Path",children:t.jsx(ta,{value:pe,onChange:P=>re(P.target.value),placeholder:"/Users/dev/projects/myapp",autoFocus:!0})}),t.jsx(Tt,{label:"Provider Priority",hint:"Order used when launching without an explicit provider. Empty means fail closed unless a provider is selected explicitly.",children:t.jsx($i,{value:de,availableProviders:o,onChange:ke})}),t.jsxs("div",{className:"flex gap-2 mt-3",children:[t.jsx("button",{onClick:Se,disabled:!pe.trim(),className:"btn btn-primary btn-sm",children:"Add"}),t.jsx("button",{onClick:()=>ge(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),ye.nodes.length===0?t.jsx(yn,{icon:t.jsx(gs,{}),title:"No nodes",description:"Add a workspace to this mesh."}):t.jsx("div",{className:"flex flex-col gap-2",children:ye.nodes.map(P=>{const U=an(P),ce=sv(P),te=rv(P,S),ie=av(P,r),se=A===P.id;return t.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary cursor-pointer transition-colors ${se?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`,role:"button",tabIndex:0,onClick:()=>L(se?null:P.id),onKeyDown:ve=>{(ve.key==="Enter"||ve.key===" ")&&(ve.preventDefault(),L(se?null:P.id))},children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"text-sm font-medium",children:P.workspace.split("/").pop()}),te.length>0&&t.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:[te.length," active task",te.length===1?"":"s"]})]}),t.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:P.workspace}),t.jsx("div",{className:"mt-3 max-w-2xl",onClick:ve=>ve.stopPropagation(),children:t.jsxs(Tt,{label:"Provider priority",hint:"Used when launches omit an explicit provider. Empty keeps fail-closed behavior until a provider is selected manually.",children:[t.jsx($i,{value:x[P.id]??U,availableProviders:o,onChange:ve=>N(Ie=>({...Ie,[P.id]:ve})),disabled:b===P.id,saveButton:t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:ve=>{ve.stopPropagation(),oe(P)},disabled:b===P.id,children:b===P.id?"Saving...":"Save policy"})}),t.jsxs("div",{className:"mt-2 text-[12px]",children:[t.jsx("span",{className:"text-text-muted",children:"Effective provider priority: "}),t.jsx("span",{className:ce.configured?"text-text-primary font-mono":"text-amber-400",children:ce.label}),ce.launchBlockedMessage&&t.jsxs("span",{className:"ml-2 text-amber-400",children:["(",ce.launchBlockedMessage,")"]})]})]})})]}),t.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:ve=>{ve.stopPropagation(),Q(P.id)},children:t.jsx(gt,{size:14})})]}),se&&t.jsxs("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[t.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-text-secondary",children:"Node ID:"})," ",t.jsx("span",{className:"font-mono",children:P.id})]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",t.jsx("span",{className:ce.configured?"text-green-400":"text-amber-400",children:ce.configured?"yes":"provider priority not configured"})]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-secondary",children:"Repo root:"})," ",t.jsx("span",{className:"font-mono",children:P.repoRoot||P.workspace})]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",ie.length]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-secondary",children:"Branch / git:"})," not loaded in standalone list view"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-secondary",children:"Health:"})," ",te.length>0||ie.length>0?"active":"idle/unknown"]})]}),t.jsxs("div",{className:"mt-3",children:[t.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),te.length===0?t.jsx("div",{children:"No active assigned queue task for this node."}):t.jsx("ul",{className:"m-0 pl-4",children:te.map(ve=>t.jsx("li",{className:"font-mono",children:nv(ve)},ve.id))})]}),ie.length>0&&t.jsxs("div",{className:"mt-3",children:[t.jsx("div",{className:"text-text-secondary mb-1",children:"Active sessions"}),t.jsx("ul",{className:"m-0 pl-4",children:ie.map(ve=>t.jsxs("li",{className:"font-mono",children:[ve.provider," / ",ve.status," / ",ve.id]},ve.id))})]})]})]},P.id)})})]}),t.jsx(ov,{meshId:ye.id,availableCliAgents:a})]})}function Go(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function lv(e){if(typeof window>"u")return e;const s=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=Go();return r&&!s.searchParams.has("token")&&s.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?s.toString():`${s.pathname}${s.search}${s.hash}`}async function Bt(e,s){return await fetch(lv(e),{credentials:"same-origin",...s})}function qd(){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 cv{constructor(){Xe(this,"adapters",new Map);Xe(this,"states",new Map);Xe(this,"runtimeListeners",new Map);Xe(this,"screenshotCallbacks",new Map);Xe(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}onScreenshot(s,r){return this.screenshotCallbacks.set(s,r),()=>{this.screenshotCallbacks.delete(s)}}emitScreenshot(s,r){this.screenshotCallbacks.forEach(n=>n(s,r))}onStatus(s){return this.statusCallbacks.add(s),()=>{this.statusCallbacks.delete(s)}}emitStatus(s,r){this.statusCallbacks.forEach(n=>n(s,r))}emitRuntimeSnapshot(s,r,n=0,a=!1,o,l){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:a,cols:o,rows:l})}emitSessionOutput(s,r,n){!s||typeof r!="string"||!r||this.emitRuntimeEvent(s,{type:"session_output",sessionId:s,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(s,r){const n=this.runtimeListeners.get(s)||new Set;return n.add(r),this.runtimeListeners.set(s,n),()=>{const a=this.runtimeListeners.get(s);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(s))}}async requestRuntimeSnapshot(s,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 Bt(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const l=await o.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof l.seq=="number"?l.seq:0,text:typeof l.text=="string"?l.text:"",truncated:!!l.truncated,cols:typeof l.cols=="number"?l.cols:void 0,rows:typeof l.rows=="number"?l.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(a=>a(r))}}const Wt=new cv;function dv(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Go();return r?`${s}?token=${encodeURIComponent(r)}`:s}const Xr=dv(),Tl=3e3,uv=3e4;let Pt=null,mv=0;const Sn=new Map;let os=null,hr=null;function Al(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function nr(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function pv(e){return e==="connected"?"connected":e}async function on(e,s,r){const n=Wc(e,r||{}),a=Pt;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++mv}_${Date.now()}`;return new Promise((l,c)=>{const d=setTimeout(()=>{Sn.delete(o),c(new Error(`WS command timeout: ${s}`))},3e4);Sn.set(o,{resolve:m=>{clearTimeout(d),l(m)},reject:m=>{clearTimeout(d),c(m)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function to(e,s){const r=Pt;if(!r||r.readyState!==WebSocket.OPEN||!s||s.type!=="subscribe"&&s.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}function fv(e,s,r){const n=Pt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Wc(e,{sessionId:s,targetSessionId:s,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}class hv{constructor(s){Xe(this,"daemonId");Xe(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Pt==null?void 0:Pt.readyState)===WebSocket.OPEN}get connectionState(){return(Pt==null?void 0:Pt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return on(this.daemonId,s,r)}async sendInput(s,r){return on(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,os&&(clearInterval(os),os=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await on(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());Wt.emitScreenshot(this.daemonId,a)}}catch{}};r(),os=setInterval(r,2e3)}stopScreenshots(s){os&&(clearInterval(os),os=null)}}let Mt=null;function xv(e){return(!Mt||Mt.daemonId!==e)&&(Mt=new hv(e)),Mt}function bv({children:e}){const s=i.useRef(br()),r=br();s.current=r;const{setUserName:n}=rs(),a=i.useRef(n);a.current=n;const o=i.useRef(null),l=i.useRef(null),[,c]=i.useState("disconnected"),d=i.useCallback((p,b)=>{c(p),hr==null||hr(p,b)},[]),m=i.useRef(null),u=i.useRef(),h=i.useRef(Tl),g=i.useRef(!0),v=i.useRef(!1),f=i.useRef("initial_connect");return i.useEffect(()=>{g.current=!0,v.current=!1;function p(){var x,N;if(!g.current||((x=m.current)==null?void 0:x.readyState)===WebSocket.OPEN||((N=m.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Xr}...`),nr("connect_attempt",{url:Xr,reason:f.current,delayMs:h.current});let y;try{y=new WebSocket(Xr)}catch(S){console.error("[Standalone WS] Failed to create WebSocket:",S),b();return}m.current=y,y.onopen=()=>{if(!g.current){y.close();return}d("connected"),h.current=Tl,nr("open",{url:Xr,reason:f.current}),zt.resubscribeAll({sendData:to}),console.log("[Standalone WS] Connected")},Pt=y,y.onmessage=S=>{var w,A;try{const L=JSON.parse(S.data);if((L.type==="command_result"||L.type==="error")&&L.requestId){const k=Sn.get(L.requestId);k&&(Sn.delete(L.requestId),L.type==="error"?k.reject(new Error(((w=L.data)==null?void 0:w.message)||"Command failed")):k.resolve(L.data));return}if(L.type==="session_output"){const k=L.sessionId||L.cliId||L.cliType;k&&Wt.emitSessionOutput(k,typeof L.data=="string"?L.data:"",typeof L.seq=="number"?L.seq:void 0);return}if(L.type==="runtime_snapshot"){Wt.emitRuntimeSnapshot(L.sessionId,typeof L.text=="string"?L.text:"",typeof L.seq=="number"?L.seq:0,!!L.truncated,typeof L.cols=="number"?L.cols:void 0,typeof L.rows=="number"?L.rows:void 0);return}if(L.type==="topic_update"){const k=L.update;k&&zt.publish(k);return}if(L.type==="status"||L.type==="initial_state"){const k=L.data;if(!k)return;const{injectEntries:j,markLoaded:O,getIdes:R}=s.current,T=k.instanceId||"standalone",F=R().find(C=>C.id===T),W=xv(T);Wt.register(T,W),Wt.setState(T,"connected"),d("connected",T),Wt.emitStatus(T,k);const D=bn(k,{daemonId:T,existingDaemon:F,existingEntries:R()});Al("ws_status",{type:L.type,daemonId:T,sessions:(k.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(k.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Al("entries",{daemonId:T,entries:D.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),D.length>0&&j(D,{authoritativeDaemonIds:[T]}),O(),l.current!==T&&((A=o.current)==null||A.call(o),l.current=T,o.current=zt.subscribe({sendData:to},T,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${T}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const I=s.current.getIdes(),K=I.find(E=>E.id===T),_=bn(C.status,{daemonId:T,existingDaemon:K,existingEntries:I,timestamp:C.timestamp});_.length>0&&s.current.injectEntries(_,{authoritativeDaemonIds:[T]}),C.userName&&a.current&&a.current(C.userName)}))}}catch(L){console.error("[Standalone WS] Parse error:",L)}},y.onclose=S=>{g.current&&(Mt==null||Mt.stopScreenshots(),Mt&&Wt.setState(Mt.daemonId,"disconnected"),d("disconnected"),m.current=null,f.current=`close:${S.code}${S.wasClean?":clean":":unclean"}`,nr("close",{code:S.code,reason:S.reason||"",wasClean:S.wasClean}),b())},y.onerror=S=>{v.current||!g.current||(f.current="error",nr("error",{message:S instanceof Event?"event":String(S),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",S))}}function b(){if(!g.current)return;clearTimeout(u.current);const y=h.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),nr("schedule_reconnect",{reason:f.current,delayMs:y}),u.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,uv),p()},y)}return p(),()=>{var y;g.current=!1,v.current=!0,(y=o.current)==null||y.call(o),o.current=null,l.current=null,clearTimeout(u.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,Pt=null),Mt&&(Mt.stopScreenshots(),Wt.unregister(Mt.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function gv({children:e}){const[s,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(hr=(l,c)=>{r(l),c&&a(c)},()=>{hr=null}),[]);const o=i.useMemo(()=>{const l=s==="connected",c=pv(s),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:s,isConnected:l,connectionStates:d}},[s,n]);return t.jsx(Yu,{connectionOverrides:o,children:t.jsx(bv,{children:e})})}const Yd="adhdev_standalone_font_preferences",bs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Kn=[{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"}],vr=[{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"}],yv=new Set(Kn.map(e=>e.id)),vv=new Set(vr.map(e=>e.id));function Kt(e){const s=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:ln("chat",s.chat),code:ln("code",s.code),terminal:ln("terminal",s.terminal)}}function ln(e,s){const r=bs[e],n=s&&typeof s=="object"&&!Array.isArray(s)?s:{},a=typeof n.preset=="string"?n.preset.trim():"",o=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?yv:vv).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function cn(e,s){var a;const r=ln(e,s);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?Kn:vr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function wv(e){const s=Kt(e),r=cn("chat",s.chat),n=cn("code",s.code),a=cn("terminal",s.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function ls(e,s=document.documentElement){const r=Kt(e),n=wv(r);s.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))s.style.setProperty(a,o);return r}function so(e){const s=Kt(e);try{localStorage.setItem(Yd,JSON.stringify(s))}catch{}return s}function jv(){try{const e=localStorage.getItem(Yd);if(e)return Kt(JSON.parse(e))}catch{}return bs}function kv(){return ls(jv())}function ar(e,s){var n;const r=e==="chat"?Kn:vr;return((n=r.find(a=>a.id===s))==null?void 0:n.label)||r[0].label}const Sv=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Ol,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(es,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:t.jsx(Es,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:t.jsx(Nn,{}),label:"Settings"}];function Nv({children:e}){const s=Hs(),r=no(),n=i.useMemo(()=>Sv.map(o=>({...o,active:r.pathname.startsWith(o.path),onSelect:()=>s(o.path)})),[r.pathname,s]),a=i.useMemo(()=>[{id:"docs",label:t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Docs"}),t.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:t.jsx(Fl,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:t.jsx(Wl,{}),active:r.pathname==="/about",onSelect:()=>s("/about"),title:"About"}],[r.pathname,s]);return t.jsx(cx,{brand:({collapsed:o})=>t.jsxs(t.Fragment,{children:[t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!o&&t.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:o})=>o?null:t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.81"]}),footerActions:({collapsed:o,toggleCollapsed:l})=>t.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":"mt-1"}`,onClick:l,title:o?"Expand sidebar":"Collapse sidebar",children:[t.jsx("span",{className:"nav-icon text-base",children:o?"›":"‹"}),!o&&t.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const Cv=[{icon:t.jsx(es,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Vt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(Hl,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(It,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(Es,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(Fl,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Iv=[{icon:t.jsx(mm,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Ol,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(Cn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(am,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(Kl,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(im,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Tv=[{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 Av(){return t.jsxs(mr,{icon:t.jsx(Wl,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:t.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:[t.jsx(vt,{children:t.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[t.jsxs("div",{className:"max-w-2xl",children:[t.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),t.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."}),t.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."})]}),t.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[t.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 ↗"}),t.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 ↗"}),t.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 ↗"})]})]})}),t.jsx(vt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Cv.map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.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]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(vt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:t.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Hc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:zc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Uc.map(e=>`${e.icon} ${e.name}`)}].map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[t.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),t.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(s=>t.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:s},s))})]},e.label))})}),t.jsx(vt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Iv.map(e=>t.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.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]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(vt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:t.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:t.jsxs("table",{className:"w-full text-[13px]",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"bg-bg-secondary",children:[t.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),t.jsx("tbody",{children:Tv.map((e,s)=>t.jsxs("tr",{className:s%2===0?"bg-bg-glass":"bg-transparent",children:[t.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?t.jsx("span",{className:"text-emerald-500",children:"✓"}):t.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:t.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),t.jsx(yn,{icon:t.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:t.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[t.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),t.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[t.jsx(jm,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Aa(e,s,r){return{...e,[s]:r}}function Ma({surface:e,title:s,description:r,value:n,options:a,onChange:o}){return t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-text-primary",children:s}),t.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:l=>{const c=l.target.value;o(c==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:c})},children:a.map(l=>t.jsx("option",{value:l.id,children:l.label},l.id))}),n.preset==="custom"&&t.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:l=>o({preset:"custom",customFamily:l.target.value})}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:[t.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",t.jsx("span",{className:"font-mono break-all",children:cn(e,n)})]})]})]})}function Mv({value:e,savedValue:s,saving:r=!1,error:n,notice:a,onChange:o,onSave:l,onResetToSaved:c,onResetToDefaults:d}){const m=JSON.stringify(e)!==JSON.stringify(s);return t.jsxs("div",{className:"flex flex-col gap-4",children:[t.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&&t.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&&t.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}),t.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[t.jsx(Ma,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Kn,onChange:u=>o(Aa(e,"chat",u))}),t.jsx(Ma,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:vr,onChange:u=>o(Aa(e,"code",u))}),t.jsx(Ma,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:vr,onChange:u=>o(Aa(e,"terminal",u))})]}),t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),t.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",ar("chat",e.chat.preset)," · Code: ",ar("code",e.code.preset)," · Terminal: ",ar("terminal",e.terminal.preset)]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",ar("chat",bs.chat.preset)," / ",ar("code",bs.code.preset)]})]}),t.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:t.jsxs("div",{className:"chat-container-content",children:[t.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:t.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[t.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[t.jsx("span",{className:"chat-sender",children:"Hermes"}),t.jsx("span",{className:"chat-time",children:"now"})]}),t.jsxs("div",{className:"chat-markdown",children:[t.jsxs("p",{children:["Readable prose, ",t.jsx("strong",{children:"bold text"}),", and ",t.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),t.jsx("pre",{children:t.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),t.jsxs("div",{className:"chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"▸"}),t.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),t.jsxs("div",{className:"chat-msg-terminal",children:[t.jsx("div",{className:"chat-msg-header",children:"Terminal"}),t.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:l,disabled:r||!m,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),t.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"}),t.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 Lv(){const{ides:e}=rs(),s=e.find(q=>q.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=yt(),{userName:a}=rs(),[o,l]=i.useState(a||""),[c,d]=i.useState(null),[m,u]=i.useState(null),[h,g]=i.useState(bs),[v,f]=i.useState(!1),[p,b]=i.useState(""),[y,x]=i.useState(""),[N,S]=i.useState("127.0.0.1"),[w,A]=i.useState(""),[L,k]=i.useState(""),[j,O]=i.useState(""),[R,T]=i.useState(""),[F,W]=i.useState(""),[D,C]=i.useState(!1),I=async()=>{const he=await(await Bt("/auth/session")).json();d(he)},K=async()=>{const he=await(await Bt("/api/v1/standalone/preferences")).json();u(he),S(he.standaloneBindHost);const fe=Kt(he.standaloneFontPreferences);g(fe),ls(fe),so(fe)};i.useEffect(()=>{a!==void 0&&l(a)},[a]),i.useEffect(()=>{Promise.all([I(),K()]).catch(q=>{T(q instanceof Error?q.message:String(q))})},[]),i.useEffect(()=>{ls(h)},[h]);const _=q=>{const he=q.target.value.trim();s!=null&&s.id&&he!==a&&n(s.id,"set_user_name",{userName:he}).catch(console.error)},[E,V]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),Y=q=>{V(q);try{localStorage.setItem("adhdev_sound",q?"1":"0")}catch{}},ge=async()=>{b(""),x(""),f(!0);try{const q=Kt(h),he=await Bt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:q})}),fe=await he.json();if(!he.ok)throw new Error((fe==null?void 0:fe.error)||"Failed to save standalone font preferences");const we=Kt(fe.standaloneFontPreferences);u(fe),g(we),ls(we),so(we),x("Standalone chat fonts saved for this self-hosted dashboard.")}catch(q){b(q instanceof Error?q.message:String(q))}finally{f(!1)}},pe=()=>{const q=Kt(m==null?void 0:m.standaloneFontPreferences);b(""),x(""),g(q),ls(q)},re=()=>{b(""),x(""),g(bs),ls(bs)},de=async()=>{T(""),W(""),C(!0);try{const q=await Bt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:N})}),he=await q.json();if(!q.ok)throw new Error((he==null?void 0:he.error)||"Failed to save standalone network preference");u(he),S(he.standaloneBindHost),W(he.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{C(!1)}},ke=async()=>{if(T(""),W(""),L.trim().length<4){T("Password must be at least 4 characters.");return}if(L!==j){T("New password and confirmation do not match.");return}C(!0);try{const q=await Bt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,newPassword:L})}),he=await q.json();if(!q.ok)throw new Error((he==null?void 0:he.error)||"Failed to save password");d(he),await K(),A(""),k(""),O(""),W(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),qd()}catch(q){T(q instanceof Error?q.message:String(q))}finally{C(!1)}},ye=async()=>{T(""),W(""),C(!0);try{const q=await Bt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,clear:!0})}),he=await q.json();if(!q.ok)throw new Error((he==null?void 0:he.error)||"Failed to clear password");d(he),await K(),A(""),k(""),O(""),W("Standalone password disabled.")}catch(q){T(q instanceof Error?q.message:String(q))}finally{C(!1)}};return t.jsxs(mr,{icon:t.jsx(Nn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(Ms,{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)&&t.jsx(Ms,{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."}),t.jsx(vt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:t.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[t.jsx("span",{className:"text-text-muted",children:"Version"}),t.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.81"]}),t.jsx("span",{className:"text-text-muted",children:"Status"}),t.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),t.jsx("span",{className:"text-text-muted",children:"Current bind"}),t.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Default bind"}),t.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.standaloneBindHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Auth"}),t.jsx("span",{className:"text-xs",children:c!=null&&c.hasPasswordAuth?"Password enabled":c!=null&&c.hasTokenAuth?"Token enabled":"No auth configured"})]})}),t.jsx(vt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.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."}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.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:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:N==="127.0.0.1",onChange:()=>S("127.0.0.1")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),t.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."})]})]}),t.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:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:N==="0.0.0.0",onChange:()=>S("0.0.0.0")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),t.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."})]})]})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:()=>{de()},disabled:D,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:D?"Saving…":"Save default network mode"}),t.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","."]})]})]})}),t.jsx(vt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.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."}),R&&t.jsx(Ms,{variant:"error",children:R}),F&&t.jsx(Ms,{variant:"success",children:F}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.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:w,onChange:q=>A(q.target.value)}),t.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:L,onChange:q=>k(q.target.value)}),t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:j,onChange:q=>O(q.target.value)})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{ke()},disabled:D,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:D?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&t.jsx("button",{type:"button",onClick:()=>{ye()},disabled:D,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"})]})]})}),t.jsx(vt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?t.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):t.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(q=>t.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:`w-2 h-2 rounded-full ${q.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:q.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:q.type})]},q.type))})}),t.jsx(vt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(gx,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(vt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),t.jsx(jx,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),t.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."}),t.jsx(Mx,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),t.jsx(Mv,{value:h,savedValue:Kt(m==null?void 0:m.standaloneFontPreferences),saving:v,error:p,notice:y,onChange:g,onSave:()=>{ge()},onResetToSaved:pe,onResetToDefaults:re})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),t.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."}),t.jsx(_x,{})]})]})}),t.jsx(vt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(hx,{}),t.jsx(is,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(wm,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:Y})]})}),t.jsx(vt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:t.jsx("div",{className:"flex flex-col gap-3",children:t.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:[t.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[t.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[t.jsx(nm,{size:16,className:"text-text-secondary"})," Display Name"]}),t.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),t.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:o,onChange:q=>l(q.target.value),onBlur:_,onKeyDown:q=>{q.key==="Enter"&&q.currentTarget.blur()}})]})})})]})}ix();Tx();kv();const Rv=$l({baseUrl:"",getToken:Go});function _v({children:e}){const[s,r]=i.useState(null),[n,a]=i.useState(!0),[o,l]=i.useState(""),[c,d]=i.useState(""),[m,u]=i.useState(!1),h=async()=>{a(!0),d("");try{const f=await(await Bt("/auth/session")).json();r(f)}catch(v){d(v instanceof Error?v.message:String(v))}finally{a(!1)}};i.useEffect(()=>{h()},[]),i.useEffect(()=>{if(!s||s.required&&!s.authenticated)return;let v=!1;return(async()=>{try{const f=await Bt("/api/v1/standalone/preferences");if(!f.ok)return;const p=await f.json();if(v)return;const b=Kt(p.standaloneFontPreferences);ls(b),so(b)}catch{}})(),()=>{v=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const g=async v=>{v.preventDefault(),u(!0),d("");try{const f=await Bt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),p=await f.json();if(!f.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),l(""),qd()}catch(f){d(f instanceof Error?f.message:String(f))}finally{u(!1)}};return n?t.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):s?!s.required||s.authenticated?t.jsx(t.Fragment,{children:e}):t.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:t.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:[t.jsxs("div",{children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),t.jsx("p",{className:"text-sm text-text-muted mt-1",children:s.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."})]}),s.hasPasswordAuth?t.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[t.jsx("input",{type:"password",value:o,onChange:v=>l(v.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}),t.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"})]}):t.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&&t.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})]})}):t.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 Ml(){const{ides:e,initialLoaded:s}=rs();if(!s)return t.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?t.jsx(_a,{to:`/machines/${r.id}`,replace:!0}):t.jsx(_a,{to:"/dashboard",replace:!0})}function Pv(){const e=i.useMemo(()=>({sendCommand:on,sendData:to,sendPtyInput:fv}),[]);return t.jsx(_u,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(Qu,{client:Rv,children:t.jsx(_v,{children:t.jsx(gv,{children:t.jsx(em,{value:e,children:t.jsx(Nv,{children:t.jsxs(Pu,{children:[t.jsx(Yt,{path:"/dashboard",element:t.jsx(qy,{})}),t.jsx(Yt,{path:"/machine",element:t.jsx(Ml,{})}),t.jsx(Yt,{path:"/machines/:id",element:t.jsx(ev,{})}),t.jsx(Yt,{path:"/machines",element:t.jsx(Ml,{})}),t.jsx(Yt,{path:"/about",element:t.jsx(Av,{})}),t.jsx(Yt,{path:"/settings",element:t.jsx(Lv,{})}),t.jsx(Yt,{path:"/mesh",element:t.jsx(iv,{})}),t.jsx(Yt,{path:"*",element:t.jsx(_a,{to:"/dashboard",replace:!0})})]})})})})})})})}bh({connectionManager:Wt});Du(document.getElementById("root")).render(t.jsx(Pv,{}));