@adhdev/daemon-standalone 0.9.76-rc.49 → 0.9.76-rc.50
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.
- package/package.json +1 -1
- package/public/assets/index-B2Vx7PG3.js +96 -0
- package/public/index.html +1 -1
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-BeBmUW3m.js","assets/vendor-CLec0455.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
var _d=Object.defineProperty;var Dd=(e,t,r)=>t in e?_d(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Xe=(e,t,r)=>Dd(e,typeof t!="symbol"?t+"":t,r);import{r as i,j as s,M as Ua,a as Ed,b as $d,c as Bd,R as Ct,d as cr,t as Wd,e as Kd,u as Ws,D as Od,f as ya,g as va,h as za,i as Fd,k as Hd,B as Ud,l as zd,m as qt,N as wa,n as Vd}from"./vendor-CLec0455.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).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 Gd(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),r=[];return{record(n){const a={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...n,payload:n.payload?{...n.payload}:{}};return r.push(a),r.length>t&&r.splice(0,r.length-t),a},list(n={}){const a=Math.max(1,Math.floor(n.limit||100));return r.filter(o=>!n.interactionId||o.interactionId===n.interactionId).filter(o=>!n.topic||o.topic===n.topic).filter(o=>!n.kind||o.kind===n.kind).slice(-a).map(o=>({...o,payload:o.payload?{...o.payload}:{}}))},clear(){r.splice(0,r.length)}}}const As=Gd();function Oo(e){const t={};for(const r of e)r.transport&&(t[r.transport]=(t[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:t}}function qd(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Yd(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function sc(e,t){if(!e)return t??null;if(!t)return e??null;const r=Yd(e,"messages"),n=r?Array.isArray(e.messages)?e.messages:[]:t.messages,a={...t,...e,activeModal:e.activeModal??null,inputContent:e.inputContent??t.inputContent};return r?{...a,messages:n}:a}function Zs(e,t){const r=qd(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(t==null?void 0:t.parentSessionId)??null,providerSessionId:e.providerSessionId??(t==null?void 0:t.providerSessionId),providerName:r??(t==null?void 0:t.providerName)??(t==null?void 0:t.cliName)??(t==null?void 0:t.type)??e.providerName??e.providerType,title:e.title??(t==null?void 0:t.title)??r??(t==null?void 0:t.providerName)??e.providerName??e.providerType,workspace:e.workspace??(t==null?void 0:t.workspace)??null,mode:e.mode??(t==null?void 0:t.mode),capabilities:e.capabilities??(t==null?void 0:t.sessionCapabilities)??(t==null?void 0:t.capabilities)??[],cdpConnected:e.cdpConnected??(t==null?void 0:t.cdpConnected),activeChat:sc(e.activeChat,t==null?void 0:t.activeChat),controlValues:e.controlValues??(t==null?void 0:t.controlValues),providerControls:e.providerControls??(t==null?void 0:t.providerControls),summaryMetadata:e.summaryMetadata??(t==null?void 0:t.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(t==null?void 0:t.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(t==null?void 0:t.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(t==null?void 0:t.lastMessagePreview),lastMessageRole:e.lastMessageRole??(t==null?void 0:t.lastMessageRole),lastMessageAt:e.lastMessageAt??(t==null?void 0:t.lastMessageAt),lastMessageHash:e.lastMessageHash??(t==null?void 0:t.lastMessageHash),unread:e.unread??(t==null?void 0:t.unread),lastSeenAt:e.lastSeenAt??(t==null?void 0:t.lastSeenAt),inboxBucket:e.inboxBucket??(t==null?void 0:t.inboxBucket),completionMarker:e.completionMarker??(t==null?void 0:t.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(t==null?void 0:t.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(t==null?void 0:t.surfaceHidden),resume:e.resume??(t==null?void 0:t.resume),runtimeKey:e.runtimeKey??(t==null?void 0:t.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(t==null?void 0:t.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(t==null?void 0:t.runtimeWorkspaceLabel),settings:e.settings??(t==null?void 0:t.settings)}}function rc(e,t,r){if(!(t!=null&&t.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const n=t.map(a=>{const o=e.find(c=>c.id===a.id);return o?Zs(a,o):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(t.map(o=>o.id));for(const o of e)a.has(o.id)||n.push(o)}return n}function Fo(e){return!!e&&typeof e=="object"&&"text"in e}function Va(e,t){const r=(t==null?void 0:t.joiner)??" ",n=(t==null?void 0:t.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(o=>typeof o=="string"?o:Fo(o)?String(o.text||""):"").join(r):Fo(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Rs(e){return Va(e,{normalizeWhitespace:!0})}const nc=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}),ac=i.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Ho(e){var r,n;let t=0;return e.activeChat!==void 0&&(t+=4),(r=e.childSessions)!=null&&r.length&&(t+=2),e.workspace&&(t+=1),e.machine&&(t+=1),(n=e.agents)!=null&&n.length&&(t+=1),t}function oc(e,t,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=t.version??r.version??e.version,o=t.serverVersion??e.serverVersion??r.serverVersion,c=t.versionMismatch===!0||e.versionMismatch===!0,l=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,d=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),o&&(n.serverVersion=o),d&&(n.versionUpdateReason=d),a&&o&&a===o?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||c&&a&&o&&a!==o)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function Xd(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function Ln(e){if(!e||typeof e!="object")return"";const t=e,r=Xd(Rs(t.content).slice(0,512));return[String(t.id||""),String(t._localId||""),String(t._turnKey||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),r].join(":")}function Jd(e,t){if(!Array.isArray(e))return e;if(t!=null&&t.has(e))return{count:e.length,sharedRef:!0};let r=2166136261;for(const n of e){const a=Ln(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:Ln(e[0]),last:Ln(e[e.length-1])}}function ja(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function ka(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(ja(e)&&ja(t)){const c=e.messages;Array.isArray(c)&&c===t.messages&&r.add(c)}if(Array.isArray(e)&&Array.isArray(t)){const c=Math.min(e.length,t.length);for(let l=0;l<c;l+=1)ka(e[l],t[l],r);return}const n=e,a=t,o=new Set([...Object.keys(n),...Object.keys(a)]);for(const c of o)c!=="messages"&&ka(n[c],a[c],r)}function tr(e,t){return Array.isArray(e)?e.map(r=>tr(r,t)):!e||typeof e!="object"?e:ja(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Jd(a,t):tr(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,tr(n,t)]))}function Qd(e,t){try{const r=new WeakSet;return ka(e,t,r),JSON.stringify(tr(e,r))===JSON.stringify(tr(t,r))}catch{return!1}}function Sa(e,t,r){return Qd(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function ic(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Zd(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Uo(e,t,r,n){var l;const a=(l=t.chats)!=null&&l.length?t.chats:e.chats,o=rc(e.childSessions,t.childSessions,{preserveMissing:n}),c=sc(t.activeChat,e.activeChat);return oc(e,t,{...e,...t,chats:a,childSessions:o,activeChat:c,_lastUpdate:r})}function eu(e,t,r){var a,o;const n={};t.status&&t.status!==e.status&&(n.status=t.status),t.cdpConnected!==void 0&&(n.cdpConnected=t.cdpConnected),t.childSessions!==void 0&&(n.childSessions=rc(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(n.chats=t.chats);for(const c 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"])Zd(n,t,c);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function tu(e,t,r,n){const a=eu(e,t,n),o=Object.keys(a).length>0?oc(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return Sa(e,o,r)}function su(e){const t=new Set(e.map(o=>o.id)),r=new Set,n=new Set,a=new Set;for(const o of e){const c=ic(o);c&&r.add(c),c&&o.type!=="adhdev-daemon"&&n.add(c),c&&o.type==="adhdev-daemon"&&o._sessionListAuthoritative&&a.add(c)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function ru(e,t,r,n,a,o){return!a.has(t)||!o.has(t)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function nu(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function au(e,t,r){var u,f;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(x=>({...x,_lastUpdate:n}));const o=new Map;for(const x of t)o.set(x.id,x);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:m}=su(e);for(const x of e){const S=o.get(x.id);if(!S){o.set(x.id,{...x,_lastUpdate:n});continue}const g=Ho(x),p=Ho(S),y=ic(x),b=!a.has(y);if(g>p){const N=Uo(S,x,n,b);o.set(x.id,Sa(S,N,n));continue}if(g<p){o.set(x.id,tu(S,x,n,b));continue}const h=x.timestamp||n,C=S._lastUpdate||S.timestamp||0;if(h>=C){const N=Uo(S,x,n,b);o.set(x.id,Sa(S,N,n));continue}(u=x.chats)!=null&&u.length&&!((f=S.chats)!=null&&f.length)&&o.set(x.id,{...S,chats:x.chats})}for(const[x,S]of o){const g=S.daemonId||x.split(":")[0];if(!l.has(g))continue;if(a.has(g)&&m.has(g)&&!c.has(x)){o.delete(x);continue}const p=n-(S._lastUpdate||S.timestamp||0);ru(S,g,p,c,a,d)&&o.delete(x)}for(const[x,S]of o){const g=S.daemonId||x.split(":")[0];if(nu(S,g,l,d,o))continue;n-(S._lastUpdate||S.timestamp||0)>3e5&&S.status!=="online"&&o.delete(x)}return Array.from(o.values())}function ou(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function iu({children:e,connectionOverrides:t}){const[r,n]=i.useState([]),[a,o]=i.useState(!1),[c,l]=i.useState([]),[d,m]=i.useState(void 0),u=i.useRef(r);i.useEffect(()=>{u.current=r},[r]);const f=i.useCallback((b,h)=>{n(C=>{let N=!1;const v=C.map(M=>M.id!==b||M.chats===h?M:(N=!0,{...M,chats:h}));return N?v:C})},[]),x=i.useCallback((b,h)=>{n(C=>{const N=C.length===0?b:au(b,C,h),v=!ou(C,N);return v&&As.record({kind:"dashboard.entries_applied",payload:{incoming:Oo(b),next:Oo(N)}}),v?N:C})},[]),S=i.useCallback(()=>o(!0),[]),g=i.useMemo(()=>({injectEntries:x,markLoaded:S,getIdes:()=>u.current}),[x,S]),p=t,y=i.useMemo(()=>({ides:r,updateRouteChats:f,initialLoaded:a,toasts:c,setToasts:l,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,f,a,c,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 s.jsx(ac.Provider,{value:g,children:s.jsx(nc.Provider,{value:y,children:e})})}function Zt(){return i.useContext(nc)}function lr(){return i.useContext(ac)}function cc(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${t}${l.startsWith("/")?"":"/"}${l}`}function o(l){const d=r==null?void 0:r(),m=a(l),u=l.startsWith("http")?new URL(m):new URL(m,typeof window<"u"?window.location.origin:"http://localhost");return d&&u.searchParams.set("token",d),!l.startsWith("http")&&!t?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function c(l,d={}){const m={"Content-Type":"application/json",...d.headers||{}},u=r==null?void 0:r();u&&(m.Authorization=`Bearer ${u}`);const f=a(l),x=new AbortController,S=setTimeout(()=>x.abort(),15e3);try{const g=await fetch(f,{...d,headers:m,signal:x.signal});if(g.status===401)throw n==null||n(),new Error("Unauthorized");if(!g.ok){const p=await g.json().catch(()=>({error:g.statusText}));throw new Error(p.error||`API Error: ${g.status}`)}return g.json()}finally{clearTimeout(S)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,d,m={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),execTerminal:(l,d,m)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:m})}),sendAgentMessage:(l,d,m)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:m})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,d,m)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:m?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,d,m={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),getMuxEventsUrl:l=>o(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>o(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const cu=cc({baseUrl:"http://localhost:3847"}),lu=i.createContext(cu);function du({client:e,children:t}){return s.jsx(lu.Provider,{value:e,children:t})}const uu={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},lc=i.createContext(uu);function mu({value:e,children:t}){return s.jsx(lc.Provider,{value:e,children:t})}function gt(){return i.useContext(lc)}function fu(e){let t=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)t^=n.charCodeAt(a),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function pu(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function hu(e){return e?fu([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),pu(e.content)]):""}const Fe={size:18};function dc({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function Ga({size:e=Fe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function Xt({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),s.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),s.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),s.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function uc({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"9",cy:"7",r:"4"}),s.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),s.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function xu({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function bu({size:e=Fe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function mc({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),s.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),s.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),s.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function gu({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),s.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),s.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),s.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),s.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function xn({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function fc({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),s.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function yu({size:e=Fe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function zt({size:e=Fe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Mt({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function qa({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("polyline",{points:"14 2 14 8 20 8"}),s.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),s.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function vu({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function ps({size:e=Fe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function fr({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function dr({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),s.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Ls({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M12 22v-5"}),s.jsx("path",{d:"M9 8V2"}),s.jsx("path",{d:"M15 8V2"}),s.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function Sr({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"5",r:"2"}),s.jsx("circle",{cx:"5",cy:"19",r:"2"}),s.jsx("circle",{cx:"19",cy:"19",r:"2"}),s.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),s.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),s.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function pc({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Ya({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),s.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),s.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function hc({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function wu({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),s.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),s.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function Xa({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"4 17 10 11 4 5"}),s.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function ju({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Ja({size:e=Fe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function xc({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function vt({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function ku({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),s.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),s.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),s.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function Su({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),s.jsx("path",{d:"M12 2v6"}),s.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Nu({size:e=Fe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function Cu({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),s.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function bn({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function Tu({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"5"}),s.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),s.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),s.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),s.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),s.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),s.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),s.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),s.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function Mu({size:e=Fe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function Iu({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Au({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),s.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Ru({size:e=Fe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function Lu({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),s.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function Pu({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function _u({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),s.jsx("path",{d:"M13 2h9v9"}),s.jsx("path",{d:"M22 2L13 11"})]})}function Du({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function Eu({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),s.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),s.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),s.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),s.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),s.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),s.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),s.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),s.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),s.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function $u({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function Bu({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const bc=[Ed,{singleTilde:!1}],gc=[bc,$d,Bd],Wu=[bc],Qa=200,Ku=80,zo=650,Hs=new Map;function en(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function Ou(e,t){if(!Array.isArray(e)||e.length===0)return"0:empty";const r=String(t||"").trim();if(r)return`${e.length}:${r}`;const n=e[e.length-1];return`${e.length}:${hu(n)}`}function Fu(e,t,r,n){return e||!t?!1:en(r,n)}function Hu({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=Ku,bottomThresholdPx:a=Qa}){const o=Math.max(0,Number(e)||0),c=Math.max(0,Number(t)||0),l=Math.max(0,Number(r)||0);return Math.max(0,c-l)<=0?{showTop:!1,showBottom:!1}:{showTop:o>n,showBottom:Math.max(0,c-o-l)>a}}function Uu(e){return Hu({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function er(e,t=Qa){return!!e&&e.fromBottom>=t}function zu(e,t){return en(e,t)?!er(e):!0}function Vu({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function Gu({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function Pn(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function yc(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function qu(e,t,r){return Number(e.receivedAt||r[tn(e,t)]||0)||0}function Yu(e){const t=typeof e.role=="string"?e.role.trim().toLowerCase():"",r=typeof e.kind=="string"?e.kind.trim().toLowerCase():t==="tool"?"tool":"standard",n=e.meta,a=typeof(n==null?void 0:n.visibility)=="string"?n.visibility.trim().toLowerCase():"";return a==="chat"||a==="visible"?!0:!(t==="tool"||(t==="assistant"||!t)&&(r==="tool"||r==="terminal"))}function vc(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Xu(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function Nr(e,t){if(!e)return t;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||t}catch{return e.split(/[\\/]/).filter(Boolean).pop()||t}}function _n(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 Vo(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):vc(e)?s.jsx(Ua,{remarkPlugins:gc,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function Cr({parts:e,renderAsPreformatted:t}){return s.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return s.jsx("div",{children:Vo(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=_n(r);return a?s.jsx("img",{src:a,alt:Nr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=_n(r);return a?s.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=_n(r);return a?s.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"},`video-${n}`):r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:Nr(r.uri,"video")},`video-link-${n}`):null}if(r.type==="resource_link")return r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:r.name||Nr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=Nr(r.resource.uri,"resource");if(r.resource.text)return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[s.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),Vo(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return s.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${n}`)}return null})})}function tn(e,t){const r=e,n=Va(e.content,{joiner:`
|
|
3
|
+
`});return[e.id?`id:${e.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",e.role?`role:${e.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${t}`].filter(Boolean).join("|")}const Ju=i.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(Ua,{remarkPlugins:Wu,children:t.text}),s.jsx("span",{className:"action-time",children:yc(t.timestamp)})]})},(e,t)=>e.log===t.log),Qu=i.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:c,onToggleTextExpanded:l}){var I,j,w;const d=(t.role||"").toLowerCase(),m=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),f=Xu(t.content)?t.content:null,x=!!(f!=null&&f.some($=>$.type!=="text")),S=Va(t.content,{joiner:`
|
|
4
|
+
`});if(u==="thought"){const $=typeof((I=t.meta)==null?void 0:I.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(Nu,{size:13}),s.jsx("span",{children:$})]}),s.jsx("div",{className:"chat-msg-body",children:S})]})}if(u==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool",children:[s.jsxs("div",{className:"chat-msg-tool-meta","aria-label":"Tool message",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),s.jsx("span",{className:"tool-label",children:"Tool"})]}),x&&f?s.jsx("div",{className:"tool-text w-full",children:s.jsx(Cr,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:S})]});if(u==="terminal"){const $=(j=t.meta)!=null&&j.isRunning?"⏳":"✅",P=typeof((w=t.meta)==null?void 0:w.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:$}),s.jsx("span",{children:P})]}),x&&f?s.jsx("div",{className:"chat-msg-body",children:s.jsx(Cr,{parts:f,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:S})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:x&&f?s.jsx(Cr,{parts:f,renderAsPreformatted:!1}):S.slice(0,100)});const g=t.meta,y=(typeof(g==null?void 0:g.renderMode)=="string"?g.renderMode.trim():"")==="preformatted",b=S,h=!1,C=b,N=y,v=!N&&vc(C),M=["chat-message-row",m?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:M,children:(b||x||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${b||x?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:m?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:yc(r)})]}),(b||x)&&s.jsx("div",{className:"chat-markdown",children:x&&f?s.jsx(Cr,{parts:f,renderAsPreformatted:N}):N?s.jsx("pre",{className:"chat-preformatted",children:C}):v?s.jsx(Ua,{remarkPlugins:gc,children:C}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:C})}),h]})})},(e,t)=>e.message===t.message&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),Zu=i.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:o=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:d={},lastMessageHash:m,emptyState:u,onLoadMore:f,isLoadingMore:x,hasMoreHistory:S,hiddenLiveCount:g=0,loadError:p,scrollToBottomRequestNonce:y,isVisible:b=!0},h){const C=i.useRef(null),N=i.useRef(null),v=i.useRef(null),M=i.useRef(0),I=i.useRef(""),j=i.useRef(""),w=i.useRef(!1),$=i.useRef(null),P=i.useRef(!1),T=i.useRef(null),F=i.useRef(!1),[H,L]=i.useState(new Set),[k,A]=i.useState({showTop:!1,showBottom:!1}),K=i.useRef(!1),_=i.useRef(!1),D=i.useRef(b),O=i.useRef(b),X=i.useRef(null);O.current=b;const ge=()=>{const Q=C.current;return Q?Q.scrollHeight-Q.scrollTop-Q.clientHeight<Qa:!0},ce=i.useCallback(()=>{const Q=C.current,fe=Q?Uu(Q):{showTop:!1,showBottom:!1};A(J=>J.showTop===fe.showTop&&J.showBottom===fe.showBottom?J:fe)},[]),ee=i.useCallback((Q="auto")=>{var J;const fe=C.current;fe&&(fe.scrollTo({top:fe.scrollHeight,behavior:Q}),(J=fe.ownerDocument.defaultView)==null||J.requestAnimationFrame(()=>ce()))},[ce]),z=i.useCallback((Q="auto")=>{var J;const fe=C.current;fe&&(fe.scrollTo({top:0,behavior:Q}),(J=fe.ownerDocument.defaultView)==null||J.requestAnimationFrame(()=>ce()))},[ce]),de=i.useCallback(()=>{var Te;const Q=C.current,fe=(Te=window.getSelection)==null?void 0:Te.call(window);if(!Q||!fe||fe.rangeCount===0||fe.isCollapsed){F.current=!1;return}const J=fe.anchorNode,Ae=fe.focusNode;F.current=!!(J&&Ae&&Q.contains(J)&&Q.contains(Ae))},[]),pe=i.useMemo(()=>t.filter(Yu),[t]),Y=pe.length===t.length?m:void 0,ie=Ou(pe,Y),ye=i.useCallback(()=>{const Q=C.current;if(!Q||!l||!O.current)return;const fe={top:Q.scrollTop,fromBottom:Math.max(0,Q.scrollHeight-Q.scrollTop-Q.clientHeight),messageFingerprint:ie};X.current={contextKey:l,snapshot:fe},Hs.set(l,fe)},[l,ie]),re=i.useCallback((Q="auto")=>{$.current!=null&&cancelAnimationFrame($.current),$.current=requestAnimationFrame(()=>{$.current=null,ee(Q)})},[ee]),me=i.useCallback(()=>{K.current=!1,P.current=!0,_.current=!0,T.current!=null&&window.clearTimeout(T.current),T.current=window.setTimeout(()=>{P.current=!1,T.current=null},zo)},[]);i.useEffect(()=>{const Q=!w.current,fe=j.current!==l;if(j.current=l,Q||fe){w.current=!0;const Ae=l?Hs.get(l):null,Te=!!Ae&&en(Ae,ie);K.current=Te?er(Ae):!1,P.current=zu(Ae,ie),F.current||(Te?requestAnimationFrame(()=>{const $e=C.current;$e&&(Pn($e,Ae),K.current=er(Ae),ce(),_.current=!0)}):re("auto")),M.current=pe.length,I.current=ie;return}pe.length>M.current;const J=ie!==I.current;Vu({hasSelection:F.current,userScrolledUp:K.current,hasChatContentChanged:J})&&re("auto"),M.current=pe.length,I.current=ie},[ie,l,pe.length,re,ce]),i.useEffect(()=>{y&&(me(),F.current||re("auto"))},[me,re,y]),i.useEffect(()=>{const Q=D.current;Q&&!b&&ye(),O.current=b,D.current=b;const fe=l?Hs.get(l):null;if(Fu(Q,b,fe,ie)){if(!fe)return;K.current=er(fe),P.current=!1,F.current||requestAnimationFrame(()=>{const J=C.current;J&&(Pn(J,fe),ce())});return}},[b,l,ie,me,ye,re,ce]),i.useEffect(()=>()=>{const Q=X.current;Q&&Hs.set(Q.contextKey,Q.snapshot),$.current!=null&&cancelAnimationFrame($.current),T.current!=null&&window.clearTimeout(T.current)},[]),i.useEffect(()=>{const Q=N.current,fe=C.current;if(!Q||!fe)return;const J=()=>{T.current!=null&&window.clearTimeout(T.current),T.current=window.setTimeout(()=>{P.current=!1,T.current=null},zo)},Ae=new ResizeObserver(()=>{ce();const Te=P.current;Gu({hasSelection:F.current,userScrolledUp:K.current,contextAutoScrollActive:Te})&&(re("auto"),Te&&J())});return Ae.observe(Q),fe!==Q&&Ae.observe(fe),()=>{Ae.disconnect(),T.current!=null&&(window.clearTimeout(T.current),T.current=null)}},[re,l,ce]),i.useImperativeHandle(h,()=>({scrollToBottom:(Q="smooth")=>{ee(Q)}}),[ee]),i.useEffect(()=>{const Q=C.current;if(!Q)return;let fe;const J=()=>{ye(),clearTimeout(fe),fe=setTimeout(()=>{K.current=!ge(),ce()},50)};return Q.addEventListener("scroll",J,{passive:!0}),()=>{Q.removeEventListener("scroll",J),clearTimeout(fe)}},[ye,ce]),i.useEffect(()=>(document.addEventListener("selectionchange",de),()=>document.removeEventListener("selectionchange",de)),[de]);const ke=i.useRef(0),xe=i.useRef(!1);i.useEffect(()=>{const Q=C.current;if(!Q||!xe.current||ke.current===0)return;const fe=Q.scrollHeight-ke.current;fe>0&&(Q.scrollTop=fe),ce(),ye(),ke.current=0,xe.current=!1},[pe.length,ye,ce]),i.useEffect(()=>{if(_.current||!l)return;const Q=Hs.get(l),fe=C.current;if(!(!Q||!fe)){if(!en(Q,ie)){ee("auto"),_.current=!0;return}Pn(fe,Q),K.current=er(Q),ce(),_.current=!0}},[l,ie,pe.length,ee,ce]);const ve=()=>{const Q=C.current;Q&&(ke.current=Q.scrollHeight),xe.current=!0,f==null||f()},te=()=>{K.current=!0,z("smooth"),ye()},he=()=>{me(),ee("smooth"),ye()},le=i.useMemo(()=>{const Q=pe.map((Te,$e)=>({type:"message",data:Te,index:$e,ts:qu(Te,$e,d)}));if(!r||r.length===0)return Q;const fe=[...r].sort((Te,$e)=>Te.timestamp-$e.timestamp).map((Te,$e)=>({type:"action",data:Te,index:$e,ts:Te.timestamp})),J=[];let Ae=0;for(const Te of Q){for(;Ae<fe.length&&Te.ts>0&&fe[Ae].ts<Te.ts;)J.push(fe[Ae++]);J.push(Te)}for(;Ae<fe.length;)J.push(fe[Ae++]);return J},[pe,r,d]),ue=g>0||!!S,oe=g>0?`↑ Show ${Math.min(g,80)} earlier messages${g>80?` (${g} hidden)`:""}`:p?`↻ ${p}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:C,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:N,className:"chat-container-content",children:[x&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),ue&&!x&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:ve,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${p&&g===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:oe})}),le.length===0&&!ue&&(u||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),le.map(Q=>{if(Q.type==="action"){const B=Q.data;return s.jsx(Ju,{log:B},`action-${Q.index}`)}const fe=Q.data,J=Q.index,Ae=tn(fe,J),Te=fe.receivedAt||d[Ae],$e=`${l}-${Ae}`,Ue=H.has($e);return s.jsx(Qu,{message:fe,receivedAt:Te,agentName:n,userName:a,isCliMode:o,isTextExpanded:Ue,onToggleTextExpanded:()=>L(B=>{const Se=new Set(B);return Ue?Se.delete($e):Se.add($e),Se})},`msg-${Ae}`)}),c&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),s.jsx("div",{className:"min-h-10",ref:v})]})}),(k.showTop||k.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[k.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:te,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),k.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:he,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),em=i.memo(Zu,(e,t)=>e.messages===t.messages&&e.actionLogs===t.actionLogs&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isWorking===t.isWorking&&e.contextKey===t.contextKey&&e.receivedAtMap===t.receivedAtMap&&e.lastMessageHash===t.lastMessageHash&&e.emptyState===t.emptyState&&e.onLoadMore===t.onLoadMore&&e.isLoadingMore===t.isLoadingMore&&e.hasMoreHistory===t.hasMoreHistory&&e.hiddenLiveCount===t.hiddenLiveCount&&e.loadError===t.loadError&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isVisible===t.isVisible),tm="modulepreload",sm=function(e){return"/"+e},Go={},rm=function(t,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=Promise.allSettled(r.map(d=>{if(d=sm(d),d in Go)return;Go[d]=!0;const m=d.endsWith(".css"),u=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":tm,m||(f.as="script"),f.crossOrigin="",f.href=d,l&&f.setAttribute("nonce",l),document.head.appendChild(f),m)return new Promise((x,S)=>{f.addEventListener("load",x),f.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return a.then(c=>{for(const l of c||[])l.status==="rejected"&&o(l.reason);return t().catch(o)})};let qo=!1;const wc=i.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:o="measured"},c)=>{const l=i.useRef(null),[d,m]=i.useState(null),u=i.useRef([]),f=i.useRef(!1),x=i.useRef(!1),S=i.useRef(!1),g=i.useRef(!1),p=()=>{const y=l.current;if(y){f.current&&(y.clear(),f.current=!1);for(const b of u.current)y.write(b.data,b.onProcessed);u.current=[],x.current&&(y.fit(),x.current=!1),S.current&&(y.bumpResize(),S.current=!1),g.current&&(y.scrollToTop(),g.current=!1)}};return i.useImperativeHandle(c,()=>({write:(y,b)=>{l.current?l.current.write(y,b):u.current.push({data:y,onProcessed:b})},clear:()=>{l.current?l.current.clear():(u.current=[],f.current=!0)},reset:()=>{l.current&&typeof l.current.reset=="function"?l.current.reset():(u.current=[],f.current=!0)},resize:(y,b)=>{l.current&&typeof l.current.resize=="function"&&l.current.resize(y,b)},fit:()=>{l.current?l.current.fit():x.current=!0},bumpResize:()=>{l.current?l.current.bumpResize():S.current=!0},scrollToTop:()=>{l.current?l.current.scrollToTop():g.current=!0},getSelection:()=>{var y,b;return((b=(y=l.current)==null?void 0:y.getSelection)==null?void 0:b.call(y))||""},getVisibleText:()=>{var y,b;return((b=(y=l.current)==null?void 0:y.getVisibleText)==null?void 0:b.call(y))||""}}),[]),i.useEffect(()=>{d&&p()},[d]),i.useEffect(()=>{let y=!1;return rm(()=>import("./terminal-BeBmUW3m.js"),__vite__mapDeps([0,1,2])).then(b=>{qo||(qo=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),y||m(()=>b.GhosttyTerminalView)}).catch(b=>{console.error("[CliTerminal] failed to load terminal renderer",b)}),()=>{y=!0}},[]),d?s.jsx(d,{ref:l,onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:o,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});wc.displayName="CliTerminal";function Tr({label:e,value:t,sub:r,icon:n}){return s.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsx("span",{className:"text-base flex items-center",children:n}),s.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),s.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:t}),r&&s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function Yo({value:e,max:t,label:r,color:n="#8b5cf6",detail:a,compact:o=!1}){const c=t>0?Math.min(Math.round(e/t*100),100):0,l=c>85?"#ef4444":c>60?"var(--status-warning)":n;return o?s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-0.5",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),s.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[c,"%"]})]}),s.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${c}%`,background:l}})})]}):s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-1.5",children:[s.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),s.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[c,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${c}%`,background:`linear-gradient(90deg, ${l}, ${l}cc)`}})}),a&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function nm({cursorPos:e,viewportRef:t,imgRef:r}){var h;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(h=t.current)==null?void 0:h.getBoundingClientRect();if(!o)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,d=c/l,m=a.width/a.height;let u,f,x,S;d>m?(u=a.width,f=a.width/d,x=0,S=(a.height-f)/2):(f=a.height,u=a.height*d,x=(a.width-u)/2,S=0);const g=a.left-o.left+x+u*e.nx,p=a.top-o.top+S+f*e.ny,y=Math.max(8,Math.min(o.width-8,g)),b=Math.max(8,Math.min(o.height-8,p));return s.jsxs("div",{style:{position:"absolute",left:y-8,top:b-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[s.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function am({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:c,setImeText:l,handleImeSubmit:d,isConnActive:m,zoom:u,isMobile:f,mobileFillZoom:x,onZoomOut:S,onZoomReset:g,onZoomIn:p,transportType:y,screenshotUsage:b,lastActionStatus:h}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:C=>C.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[s.jsxs("div",{onClick:t,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{n(C=>!C),o(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&s.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:s.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:C=>C.stopPropagation(),onChange:C=>l(C.target.value),onKeyDown:C=>{d(C)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{o(C=>!C),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:m?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:m?"#22c55e":"#eab308",boxShadow:m?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:m?"#22c55e":"#eab308"},children:m?"Connected":"WS"})]}),u>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),y==="direct"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),y==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),b&&b.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:b.budgetExhausted?"#ef4444":"#c4b5fd",background:b.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:b.budgetExhausted?"TURN blocked":`TURN ${b.dailyUsedMinutes}/${b.dailyBudgetMinutes}m`}),h&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:h})]})]}),a&&s.jsxs("div",{onTouchStart:C=>C.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",u<=(f?x:1)+.01?f?"FILL":"FIT":`${Math.round(u*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:C=>{C.stopPropagation(),S()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:C=>{C.stopPropagation(),g()},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:f?"FILL":"FIT"}),s.jsx("button",{onClick:C=>{C.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 om({waitingLabel:e,waitingHint:t,transportType:r}){return s.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[s.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-white/10 bg-white/[0.04] shadow-[0_10px_30px_rgba(0,0,0,0.35)]",style:{animation:"remote-float 2.8s ease-in-out infinite"},children:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),s.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),s.jsx("div",{className:"text-[11px] text-white/40",children:t}),r==="relay"&&s.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function im(){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 Xo(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 pr(e,t){const r=i.useRef(null),n=i.useRef(0);i.useEffect(()=>{if(!im())return;n.current+=1;const a=r.current;if(!a){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([c,l])=>[c,Xo(l)]))}),r.current=t;return}const o=Object.keys({...a,...t}).filter(c=>!Object.is(a[c],t[c]));o.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:o,snapshot:Object.fromEntries(o.map(c=>[c,Xo(t[c])]))}),r.current=t})}function cm({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:c,panXRef:l,panYRef:d,setPanX:m,setPanY:u,setZoom:f,lastWheelTimeRef:x,onAction:S,setLastActionStatus:g,spawnRippleFromNormalized:p,clampPan:y,isMobile:b,mobileFillZoom:h}){const[C,N]=i.useState(null),v=i.useRef(null),M=i.useRef(null),I=i.useRef(null),j=i.useRef(!1),w=i.useRef(null),$=i.useRef(0),P=i.useRef(null),T=i.useRef(1),F=i.useRef({x:0,y:0}),H=i.useRef(!1),L=i.useRef(n),k=i.useRef(S),A=30,K=550,_=18,D=60,O=400,X=12,ge=()=>{if(v.current)return;const z={nx:.5,ny:.5};v.current=z,N(z)};return i.useEffect(()=>{L.current=n,n==="mouse"&&ge()},[n]),i.useEffect(()=>{k.current=S},[S]),i.useEffect(()=>{const z=e.current;if(!z)return;const de=me=>{if(!r.current)return null;const ke=r.current.getBoundingClientRect();return!ke.width||!ke.height?null:{nx:Math.max(0,Math.min(1,(me.clientX-ke.left)/ke.width)),ny:Math.max(0,Math.min(1,(me.clientY-ke.top)/ke.height))}},pe=(me,ke)=>{if(!r.current)return{dnx:0,dny:0};const xe=r.current,ve=xe.getBoundingClientRect(),te=xe.naturalWidth||ve.width,he=xe.naturalHeight||ve.height,le=te/he,ue=ve.width/ve.height;let oe,Q;return le>ue?(oe=ve.width,Q=ve.width/le):(Q=ve.height,oe=ve.height*le),{dnx:me/oe,dny:ke/Q}},Y=(me,ke,xe)=>{if(xe<=1.05)return;const ve=-(me-.5)*100,te=-(ke-.5)*100,he=y(ve,te,xe);(Math.abs(he.x-l.current)>.1||Math.abs(he.y-d.current)>.1)&&(m(he.x),u(he.y),l.current=he.x,d.current=he.y)},ie=me=>{const ke=t.current;if(ke&&me.target instanceof Node&&ke.contains(me.target))me.preventDefault();else return;if(me.touches.length===1){const xe=me.touches[0];M.current={x:xe.clientX,y:xe.clientY,time:Date.now()},I.current={x:xe.clientX,y:xe.clientY},H.current||(j.current=!1),w.current=setTimeout(()=>{if(!j.current&&!H.current)if(j.current=!0,L.current==="mouse"){const ve=v.current||{nx:.5,ny:.5};g("Right Click"),p(ve.nx,ve.ny,"right"),k.current("input_click",{...ve,button:"right"}).catch(()=>{})}else{const ve=de(xe);ve&&(g("Right Click"),p(ve.nx,ve.ny,"right"),k.current("input_click",{...ve,button:"right"}).catch(()=>{}))}},500);return}if(me.touches.length===2){w.current&&clearTimeout(w.current),j.current=!0,H.current=!0;const xe=me.touches[1].clientX-me.touches[0].clientX,ve=me.touches[1].clientY-me.touches[0].clientY;P.current=Math.sqrt(xe*xe+ve*ve),T.current=c.current,F.current={x:(me.touches[0].clientX+me.touches[1].clientX)/2,y:(me.touches[0].clientY+me.touches[1].clientY)/2}}},ye=me=>{const ke=t.current;if(ke&&me.target instanceof Node&&ke.contains(me.target)&&me.preventDefault(),me.touches.length===1&&I.current){const xe=me.touches[0],ve=xe.clientX-I.current.x,te=xe.clientY-I.current.y;if(!j.current&&M.current){const he=xe.clientX-M.current.x,le=xe.clientY-M.current.y;Math.sqrt(he*he+le*le)>8&&(j.current=!0,w.current&&clearTimeout(w.current))}if(j.current)if(L.current==="mouse"){const he=pe(ve,te),le=v.current||{nx:.5,ny:.5},ue=Math.max(0,Math.min(1,le.nx+he.dnx)),oe=Math.max(0,Math.min(1,le.ny+he.dny));v.current={nx:ue,ny:oe},N({nx:ue,ny:oe}),g(`Cursor: ${Math.round(ue*100)}%, ${Math.round(oe*100)}%`),Y(ue,oe,c.current);const Q=Date.now();Q-x.current>=30&&(x.current=Q,k.current("input_mouseMoved",{nx:ue,ny:oe}).catch(()=>{}))}else if(c.current>1){const he=t.current;if(he){const le=he.clientWidth,ue=he.clientHeight,oe=l.current+ve/le*100,Q=d.current+te/ue*100,fe=y(oe,Q,c.current);m(fe.x),u(fe.y),l.current=fe.x,d.current=fe.y}}else{const he=de(xe);if(he){const le=Date.now();le-x.current>=40&&(x.current=le,g("Scroll"),k.current("input_wheel",{nx:he.nx,ny:he.ny,deltaX:Math.round(-ve*2.5),deltaY:Math.round(-te*2.5)}).catch(()=>{}))}}I.current={x:xe.clientX,y:xe.clientY};return}if(me.touches.length===2&&P.current!==null){const xe=me.touches[1].clientX-me.touches[0].clientX,ve=me.touches[1].clientY-me.touches[0].clientY,he=Math.sqrt(xe*xe+ve*ve)/P.current,le=(me.touches[0].clientX+me.touches[1].clientX)/2,ue=(me.touches[0].clientY+me.touches[1].clientY)/2,oe=le-F.current.x,Q=ue-F.current.y,fe=Math.abs(he-1)>.03;if(L.current==="mouse"){if(fe){const J=Math.max(o,Math.min(5,T.current*he));f(J),c.current=J}else if(Math.abs(oe)>2||Math.abs(Q)>2){const J=v.current||{nx:.5,ny:.5},Ae=Date.now();Ae-x.current>=30&&(x.current=Ae,g("Scroll"),k.current("input_wheel",{nx:J.nx,ny:J.ny,deltaX:Math.round(-oe*3),deltaY:Math.round(-Q*3)}).catch(()=>{}))}}else{const J=Math.max(o,Math.min(5,T.current*he));f(J),c.current=J;const Ae=t.current;if(Ae&&J>1){const Te=Ae.clientWidth,$e=Ae.clientHeight,Ue=l.current+oe/Te*100,B=d.current+Q/$e*100,Se=y(Ue,B,J);m(Se.x),u(Se.y),l.current=Se.x,d.current=Se.y}}F.current={x:le,y:ue}}},re=me=>{var ke;if(w.current&&clearTimeout(w.current),P.current=null,me.touches.length===1&&H.current){const xe=me.touches[0];M.current={x:xe.clientX,y:xe.clientY,time:Date.now()},I.current={x:xe.clientX,y:xe.clientY},j.current=!0;return}if(me.touches.length===0){if(H.current){H.current=!1,j.current=!1;return}if(me.changedTouches.length===1){const xe=me.changedTouches[0],ve=Date.now(),te=ve-(((ke=M.current)==null?void 0:ke.time)||0),he=M.current?xe.clientX-M.current.x:0,le=M.current?xe.clientY-M.current.y:0,ue=Math.sqrt(he*he+le*le);if(L.current==="mouse"){if(te<A||te>K||ue>_){j.current=!1;return}const oe=v.current||de(xe);oe&&(g(`Click: ${Math.round(oe.nx*100)}%, ${Math.round(oe.ny*100)}%`),p(oe.nx,oe.ny,"left"),k.current("input_click",{...oe}).catch(()=>{}))}else{if(j.current){j.current=!1;return}if(te<D||te>O||ue>X){j.current=!1;return}const oe=de(xe);if(!oe)return;ve-$.current<300?(g("Double tap"),p(oe.nx,oe.ny,"double"),k.current("input_click",{...oe,clickCount:2}).catch(()=>{}),$.current=0):(g(`Tap: ${Math.round(oe.nx*100)}%, ${Math.round(oe.ny*100)}%`),p(oe.nx,oe.ny,"left"),k.current("input_click",{...oe}).catch(()=>{}),$.current=ve)}}j.current=!1}};return z.addEventListener("touchstart",ie,{passive:!1}),z.addEventListener("touchmove",ye,{passive:!1}),z.addEventListener("touchend",re,{passive:!1}),()=>{z.removeEventListener("touchstart",ie),z.removeEventListener("touchmove",ye),z.removeEventListener("touchend",re),w.current&&clearTimeout(w.current)}},[e,t,r,o,c,l,d,m,u,f,x,g,p,y]),{cursorPos:C,cursorPosRef:v,handleToggleInputMode:()=>{a(z=>{const de=z==="touch"?"mouse":"touch";return de==="mouse"&&ge(),de})},handleZoomReset:()=>{const z=b?h:1;f(z),c.current=z,m(0),u(0),l.current=0,d.current=0}}}function jc({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:o}){const c=i.useRef(null),l=i.useRef(null),d=i.useRef(null),[m,u]=i.useState(null),[f,x]=i.useState(""),[,S]=i.useState(!1),[g,p]=i.useState([]),y=i.useRef(0),[b,h]=i.useState(!1),[C,N]=i.useState(!1),v=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[M,I]=i.useState(v?"mouse":"touch"),[j,w]=i.useState(1),$=i.useRef(!1),[P,T]=i.useState(1),[F,H]=i.useState(0),[L,k]=i.useState(0);pr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:M,zoom:P,panX:F,panY:L,isMenuOpen:b,isImeOpen:C});const A=i.useRef(0),K=i.useRef(P),_=i.useRef(F),D=i.useRef(L);i.useEffect(()=>{K.current=P},[P]),i.useEffect(()=>{_.current=F},[F]),i.useEffect(()=>{D.current=L},[L]),i.useEffect(()=>{var te;(te=c.current)==null||te.focus()},[]);const O=r==="connected",X=n,ge=O?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ce=O?"The remote stream is warming up":"Waiting for the remote stream to catch up";i.useEffect(()=>{if(!v||$.current||!X)return;const te=d.current,he=l.current;if(!te||!he)return;const le=()=>{const ue=he.clientWidth,oe=he.clientHeight,Q=te.naturalWidth,fe=te.naturalHeight;if(!Q||!fe||!ue||!oe)return;const J=Math.min(ue/Q,oe/fe),Te=Math.max(ue/Q,oe/fe)/J;Te>1.01&&(w(Te),T(Te),K.current=Te),$.current=!0};te.complete&&te.naturalWidth?le():te.addEventListener("load",le,{once:!0})},[X,v]);const ee=.5;i.useEffect(()=>{P<=ee&&(H(0),k(0))},[P,ee]);const z=(te,he,le)=>{if(le<=ee)return{x:0,y:0};const ue=(le-1)/(2*le)*100,oe=(le-1)/(2*le)*100;return{x:Math.max(-ue,Math.min(ue,te)),y:Math.max(-oe,Math.min(oe,he))}},de=(te,he)=>{if(!d.current)return null;const le=d.current.getBoundingClientRect();return!le.width||!le.height?null:{nx:Math.max(0,Math.min(1,(te-le.left)/le.width)),ny:Math.max(0,Math.min(1,(he-le.top)/le.height))}},pe=(te,he,le)=>{const ue=l.current;if(!ue)return;const oe=ue.getBoundingClientRect(),Q=++y.current;p(fe=>[...fe,{id:Q,x:te-oe.left,y:he-oe.top,type:le}]),setTimeout(()=>p(fe=>fe.filter(J=>J.id!==Q)),600)},Y=(te,he,le)=>{const ue=d.current,oe=l.current;if(!ue||!oe)return;const Q=ue.getBoundingClientRect(),fe=oe.getBoundingClientRect(),J=ue.naturalWidth||Q.width,Ae=ue.naturalHeight||Q.height,Te=J/Ae,$e=Q.width/Q.height;let Ue,B,Se,Me;Te>$e?(Ue=Q.width,B=Q.width/Te,Se=0,Me=(Q.height-B)/2):(B=Q.height,Ue=Q.height*Te,Se=(Q.width-Ue)/2,Me=0);const De=Q.left-fe.left+Se+Ue*te,We=Q.top-fe.top+Me+B*he,He=++y.current;p(Je=>[...Je,{id:He,x:De,y:We,type:le}]),setTimeout(()=>p(Je=>Je.filter(st=>st.id!==He)),600)},ie=async te=>{var le;const he=de(te.clientX,te.clientY);if(he){u(`Click: ${Math.round(he.nx*100)}%, ${Math.round(he.ny*100)}%`),pe(te.clientX,te.clientY,"left"),(le=c.current)==null||le.focus();try{const ue=await e("input_click",{nx:he.nx,ny:he.ny});ue!=null&&ue.success||t(`❌ Click failed: ${ue==null?void 0:ue.error}`)}catch(ue){t(`❌ Click error: ${ue.message||ue}`)}}},ye=async(te,he,le,ue=0)=>{try{await e("input_key",{type:le?"char":"keyDown",key:te,code:he,text:le?te:void 0,unmodifiedText:le?te:void 0,modifiers:ue})}catch(oe){t(`❌ Key error: ${oe.message||oe}`)}},re=async te=>{if(te.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(te.key)&&te.preventDefault();let le=0;te.altKey&&(le|=1),te.ctrlKey&&(le|=2),te.metaKey&&(le|=4),te.shiftKey&&(le|=8),u(`Key: ${te.key}`),await ye(te.key,te.code,te.key.length===1,le)},me=async te=>{if(te.key==="Enter"){if(te.nativeEvent.isComposing)return;if(f){const he=f;x(""),u(`IME Sent: ${he}`);try{const le=await e("input_type",{text:he});le!=null&&le.success||t(`❌ IME error: ${le==null?void 0:le.error}`)}catch(le){t(`❌ IME error: ${le.message}`)}}else u("Key: Enter"),await ye("Enter","Enter",!1)}};i.useEffect(()=>{const te=c.current;if(!te)return;const he=le=>{var ue;if((ue=d.current)!=null&&ue.contains(le.target)){le.preventDefault();const oe=Date.now();if(oe-A.current<40)return;A.current=oe;const Q=de(le.clientX,le.clientY);if(!Q)return;u(`Scroll: ${Math.round(le.deltaY)}`),e("input_wheel",{nx:Q.nx,ny:Q.ny,deltaX:Math.round(le.deltaX),deltaY:Math.round(le.deltaY)}).catch(()=>{})}};return te.addEventListener("wheel",he,{passive:!1}),()=>te.removeEventListener("wheel",he)},[e]);const{cursorPos:ke,handleToggleInputMode:xe,handleZoomReset:ve}=cm({containerRef:c,viewportRef:l,imgRef:d,inputMode:M,setInputMode:I,minZoom:ee,zoomRef:K,panXRef:_,panYRef:D,setPanX:H,setPanY:k,setZoom:T,lastWheelTimeRef:A,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:Y,clampPan:z,isMobile:v,mobileFillZoom:j});return s.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:re,onContextMenu:te=>te.preventDefault(),onFocus:()=>S(!0),onBlur:()=>S(!1),tabIndex:0,children:[s.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[X?s.jsx("img",{ref:d,src:X,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${P}) translate(${F}%, ${L}%)`,transformOrigin:"center center",cursor:M==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ie,onContextMenu:te=>te.preventDefault(),onDragStart:te=>te.preventDefault()}):s.jsx(om,{waitingLabel:ge,waitingHint:ce,transportType:o}),M==="mouse"&&X&&s.jsx(nm,{cursorPos:ke,viewportRef:l,imgRef:d}),g.map(te=>{const le={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[te.type];return s.jsxs("div",{style:{position:"absolute",left:te.x,top:te.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.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}}),s.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}})]},te.id)})]}),s.jsx(am,{inputMode:M,onToggleInputMode:xe,isImeOpen:C,setIsImeOpen:N,isMenuOpen:b,setIsMenuOpen:h,imeText:f,setImeText:x,handleImeSubmit:me,isConnActive:O,zoom:P,isMobile:v,mobileFillZoom:j,onZoomOut:()=>T(te=>Math.max(.5,te-.25)),onZoomReset:ve,onZoomIn:()=>T(te=>Math.min(5,te+.25)),transportType:o,screenshotUsage:a,lastActionStatus:m}),s.jsx("style",{children:`
|
|
5
|
+
@keyframes slideUp {
|
|
6
|
+
from { opacity: 0; transform: translateY(6px); }
|
|
7
|
+
to { opacity: 1; transform: translateY(0); }
|
|
8
|
+
}
|
|
9
|
+
@keyframes slideUpSidebar {
|
|
10
|
+
from { opacity: 0; transform: translateY(6px); }
|
|
11
|
+
to { opacity: 1; transform: translateY(0); }
|
|
12
|
+
}
|
|
13
|
+
@keyframes click-ripple-ring {
|
|
14
|
+
0% { transform: scale(0.3); opacity: 1; }
|
|
15
|
+
100% { transform: scale(2.2); opacity: 0; }
|
|
16
|
+
}
|
|
17
|
+
@keyframes click-ripple-dot {
|
|
18
|
+
0% { transform: scale(1); opacity: 0.9; }
|
|
19
|
+
50% { transform: scale(1.8); opacity: 0.6; }
|
|
20
|
+
100% { transform: scale(0.5); opacity: 0; }
|
|
21
|
+
}
|
|
22
|
+
@keyframes remote-float {
|
|
23
|
+
0% { transform: translateY(0px); }
|
|
24
|
+
50% { transform: translateY(-7px); }
|
|
25
|
+
100% { transform: translateY(0px); }
|
|
26
|
+
}
|
|
27
|
+
`})]})}function gn(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,o=Date.now()-e,c=Math.floor(o/1e3);if(c<a)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const d=Math.floor(l/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 kc=e=>gn(e);function lm(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 Ks(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function dm(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...lm(a)})};for(const n of e)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const a of n.childSessions||[])r(a.id,a)}return t}function sn(e,t){if(e.sessionId){const r=t.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,completionMarker:"",seenCompletionMarker:""}}function yn(e,t,r){const n=sn(e,t),a=Ks(e),o=a.isReconnecting,c=a.isConnecting,l=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"||l,x=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:x,requiresAction:m,isWorking:u,isReconnecting:o,isConnecting:c,isGenerating:l,isWaiting:d,inboxBucket:m?"needs_attention":u?"working":x?"task_complete":"idle"}}function um(e,t,r){return yn(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Sc({activeConv:e,onModalButton:t}){const[r,n]=i.useState(null);if(i.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Ks(e).isWaiting||!e.modalButtons)return null;const o=l=>{r||(n(l),t(l))},c=l=>l.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return s.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&s.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[s.jsx(dr,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,d)=>{const m=c(l).toLowerCase(),u=/^(run|approve|accept|yes|allow|always)/.test(m),f=/^(reject|deny|delete|remove|abort)/.test(m),x=r===l,S=r!==null;return s.jsx("button",{onClick:()=>o(l),disabled:S,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${u?"font-extrabold":f?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${S&&!x?"opacity-40":"opacity-100"} ${S?"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)"}:f?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:x?"⏳ ...":c(l)},d)})})]})]})}const Za="adhdev_controls_bar_visible",Na="adhdev:controlsbarvisibilitychange";function Dn(e){if(!e)return!1;try{return e.getItem(Za)==="1"}catch{return!1}}function mm(e,t){if(t)try{t.setItem(Za,e?"1":"0")}catch{}}function fm(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Na,{detail:{visible:e}}))}function eo(){const[e,t]=i.useState(()=>typeof window>"u"?!1:Dn(window.localStorage)),r=i.useRef(e),n=i.useCallback((c,l=!0)=>{r.current=c,t(c),typeof window<"u"&&mm(c,window.localStorage),l&&fm(c)},[]);i.useEffect(()=>{const c=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:Dn(window.localStorage);r.current=u,t(u)},l=d=>{if(d.key!==Za)return;const m=Dn(window.localStorage);r.current=m,t(m)};return window.addEventListener(Na,c),window.addEventListener("storage",l),()=>{window.removeEventListener(Na,c),window.removeEventListener("storage",l)}},[]);const a=i.useCallback(c=>{n(c)},[n]),o=i.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:o}}var pm=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function hm(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function bt(e,t){if(hm(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":pm.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 rn(e){return bt(e)==="generating"}function Jo(e,t){return bt(e,t)==="waiting_approval"}function it(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function xm(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const r=Math.floor(t/60),n=t%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const a=Math.floor(r/24),o=r%24;return`${a}d ${o}h`}function En(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function vn(e,t){const r=typeof t=="string"?t.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const a=n.replace(/[\\/]+$/,""),o=a.split(/[\\/]/).filter(Boolean);return o[o.length-1]||a}function bm(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const t=e.split("_"),r=t[t.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function gm(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function ym(e){return bm(e.trim().replace(/\.local$/i,""))}function vm(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function Nc(e,t={}){var a,o;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(o=e.system)==null?void 0:o.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!gm(c));if(r&&r!=="Unknown")return ym(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Tt(e,t={}){return vm(e)||Nc(e,t)}function Cc(e){return!e||!Array.isArray(e.items)?[]:e.items.map(t=>String((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim()).filter(Boolean)}function Tc(e,t,r={}){const n=String(t).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(o=>String((o==null?void 0:o.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function hs(e,t){return Cc(e).join(" · ")}function ur(e){return e.transport==="pty"}function Ts(e){return e.transport==="acp"}function wm(e,t){var r,n;return(r=t==null?void 0:t.providerLabels)!=null&&r[e]?t.providerLabels[e]:(n=t==null?void 0:t.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:it(e)}function Qo(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),c=it(r||"").trim().toLowerCase();return n===a||n===o||n===c}function jm(e,t=[],r=[]){var d,m,u,f;const n=bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(n==="waiting_approval")return"waiting_approval";if(n==="generating")return"generating";const a=t.find(x=>Jo(x.status,{activeModal:x.activeModal})||rn(x.status));if(a)return bt(a.status,{activeModal:a.activeModal});const o=r.find(x=>Jo(x.status,{activeModal:x.activeModal})||rn(x.status));if(o)return bt(o.status,{activeModal:o.activeModal});if(n&&n!=="idle")return n;const c=bt((d=t[0])==null?void 0:d.status,{activeModal:(m=t[0])==null?void 0:m.activeModal});if(c!=="idle")return c;const l=bt((u=r[0])==null?void 0:u.status,{activeModal:(f=r[0])==null?void 0:f.activeModal});return l!=="idle"?l:"idle"}function km(e){return bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Sm(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),o=t.get(a),c=bt(n.status);if(!o){t.set(a,{...n,status:c});continue}const l=r.indexOf(o.status||"idle"),d=r.indexOf(c||"idle");d>=0&&(l<0||d<l)&&t.set(a,{...n,status:c})}return Array.from(t.values())}function Nm(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function Cm(e){var r,n;const t=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return t&&Nm(t.receivedAt)||0}function Tm(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Ca(e){return Math.max(Tm(e),Cm(e.activeChat))}function Mm(e,t,r,n,a,o){const c=t-e;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:a.localeCompare(o)}function to(e,t){return Mm(Ca(e),Ca(t),Tt(e,{fallbackId:e.id}),Tt(t,{fallbackId:t.id}),e.id,t.id)}const Mc="adhdev_notification_prefs",Zo={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Im(){try{const e=localStorage.getItem(Mc);if(e){const t=JSON.parse(e);return{...Zo,...t}}}catch{}return{...Zo}}function Am(e){try{localStorage.setItem(Mc,JSON.stringify(e))}catch{}}let Ft=Im(),Fr=[];function Rm(){Fr.forEach(e=>e())}function Lm(e){Ft={...Ft,...e},Am(Ft),Rm()}function Pm(){const[,e]=i.useState(0);i.useEffect(()=>{const r=()=>e(n=>n+1);return Fr.push(r),()=>{Fr=Fr.filter(n=>n!==r)}},[]);const t=i.useCallback(r=>{Lm(r)},[]);return[{...Ft},t]}function sr(e){if(!Ft.globalEnabled)return!1;switch(e){case"disconnect":return Ft.disconnectAlert;case"completion":return Ft.completionAlert;case"approval":return Ft.approvalAlert;case"browser":return Ft.browserNotifications;default:return!0}}const _m={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Ic(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Ac(){return"Notification"in window&&Notification.permission==="granted"}let es=null;function Dm(e){return e!==!1}async function Em(){if(es!==null)return es;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return es=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(es=!!await e.pushManager.getSubscription(),es):(es=!1,!1)}catch{return es=!1,!1}}function Ta(e,t,r){if(Ac())try{const n=new Notification(e,{body:t,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function $m(e,t={}){const r={..._m,...t},n=i.useRef(new Map),a=i.useRef(0),[o,c]=i.useState(null);i.useEffect(()=>{let d=!1;return Em().then(m=>{d||c(m)}),()=>{d=!0}},[]);const l=i.useCallback((d,m,u)=>{const f=Date.now();f-a.current<r.throttleMs||(a.current=f,Ta(d,m,u))},[r.throttleMs]);i.useEffect(()=>{var d;if(!(!r.enabled||!Ac())&&sr("browser")&&!Dm(o)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,bt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const u=n.current.get(m.id),f=bt(m.status,{activeModal:m.activeModal}),x=m.name||m.id;if(r.onApproval&&sr("approval")&&f==="waiting_approval"&&u!=="waiting_approval"){const S=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";l(`🔔 ${x} — Approval needed`,S.slice(0,120),`approval-${m.id}`)}r.onComplete&&sr("completion")&&rn(u)&&f==="idle"&&l(`✅ ${x} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&f==="error"&&u!=="error"&&l(`⚠️ ${x} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,f)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,l])}const Bm=/^(run|approve|accept|yes|allow|always)/,Wm=/^(run|approve|accept|yes|allow|always|proceed|save)/,Km=/^(reject|deny|delete|remove|abort|cancel|no)/;function so(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Om(e){const t=so(e).toLowerCase();return Bm.test(t)?"primary":Km.test(t)?"danger":"default"}function Fm(e){return Wm.test(so(e).toLowerCase())?"approve":"reject"}function Hm(e){return e.map((t,r)=>({label:so(t),variant:Om(t),action:Fm(t),button:t,buttonIndex:r}))}function Um(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function zm(e,t,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,t,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,t,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class Vm{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(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,o]of this.dedupMap)r-o>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(o=>o.id===t.daemonId&&o.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const o=this.ides.find(c=>c.id===a&&c.type==="adhdev-daemon");if(o)return o}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}handleRawEvent(t,r){var g;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),o=n||t.daemonId||"",c=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),l=`${o}:${t.event}:${c}`;if(this.isDuplicate(l))return;for(const p of this.statusEventCallbacks)p(t);const d=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(d==null?void 0:d.type)||"";let u=it(m);const f=this.resolveOwningDaemon(t);if(f){const p=Tt(f,{fallbackId:f.id});p&&(u=!m||m==="adhdev-daemon"?p:`${p}/${u}`)}let x="",S="info";if(t.event==="agent:generating_completed"){const p=t.duration?` (${t.duration}s)`:"";x=`✅ ${u} agent task completed${p}`,S="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started")if(t.event==="agent:waiting_approval"){if(x=`⚡ ${u} approval needed`,S="warning",(g=t.modalButtons)!=null&&g.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(t);if(!p)return;const y=this.resolveActionFn,b=Hm(t.modalButtons).map(N=>({label:N.label,variant:N.variant,onClick:()=>{y(p,"resolve_action",{action:N.action,button:N.button,buttonIndex:N.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),h=Um(u,t.modalMessage,x),C=Date.now();this.emitToast({id:C,message:h,type:S,timestamp:C,targetKey:n||p,actions:b,duration:15e3}),x=""}}else if(t.event==="monitor:long_generating"){const p=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";x=`⚠️ ${u} agent is taking a long time${p}`,S="warning",sr("browser")&&!document.hasFocus()&&Ta(`⚠️ ${u} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const p=t.requesterName||"A team member",y=t.requestId,b=t.orgId;if(x=`👁️ ${p} wants to view your session`,S="warning",y&&b&&this.viewRequestRespondFn){const h=Date.now(),C=zm(b,y,this.viewRequestRespondFn,(N,v)=>console.error(`[EventManager] ${N} view request failed:`,v));this.emitToast({id:h,message:x,type:S,timestamp:h,actions:C,duration:3e4}),x=""}sr("browser")&&!document.hasFocus()&&Ta("👁️ View Request",`${p} wants to view your session`,`view-request-${y}`)}else t.event==="team:view_request_approved"?(x="✅ View request approved",S="success"):t.event==="team:view_request_rejected"&&(x=`❌ ${t.targetName||"Team member"} declined your view request`,S="warning");if(x){const p=Date.now();this.emitToast({id:p,message:x,type:S,timestamp:p,targetKey:n||t.daemonId,duration:5e3})}}}const nt=new Vm,ei=new Map;function nn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ms(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function wn(e){return nn(e)?nn(e.result)?e.result:e:null}function Gm(e){const t=wn(e);return!t||!nn(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function Mr(e){const t=wn(e);return!t||!nn(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Us(e){const t=wn(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Ir(e){const t=wn(e);return!!t&&t.success===!1}function qm(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";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 Ym(e,t){return e&&Ms(e.currentValue)?e.currentValue:t}function Xm(e,t){return Ms(t)?Ms(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Jm(e,t){var o,c;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(Ms(l))return l}const n=(o=t.controlValues)==null?void 0:o[e];if(Ms(n))return n;const a=(c=t.defaultValues)==null?void 0:c[e];return Ms(a)?a:void 0}function Hr(e,t){return e.options||t[e.id]||[]}const Qm={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 Zm(e,t,r){var n;return((n=Qm[t])==null?void 0:n.has(r.id))===!0}function ro(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Zm(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function $n(e,t){return{value:t}}function ef(e,t,r){var a;return r?((a=Hr(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const tf={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function sf({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:c}){const{sendCommand:l}=gt(),d=`${e}:${t||n}`,m=tf[n]||"#94a3b8",[u,f]=i.useState({}),x=i.useRef({}),S=i.useRef(c);x.current=u,S.current=c;const g=i.useRef(0),p={};for(const A of o||[])A.defaultValue!==void 0&&(p[A.id]=A.defaultValue);const y={...p,...c||{},...Date.now()<g.current?u:{}};i.useEffect(()=>{c&&Date.now()>g.current&&f({})},[c]);const[b,h]=i.useState(ei.get(d)||{}),[C,N]=i.useState(null),[v,M]=i.useState(null),I=i.useCallback(async(A,K={})=>{const _={...K,...t&&{targetSessionId:t}};return await l(e,A,_)},[e,t,l]),j=i.useCallback(async(A,K={})=>{const _=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await I("invoke_provider_script",{..._,scriptName:A,...K})},[I,n,r,t]),w=i.useCallback((A,K,_)=>{const D=Ym(_,K);f(O=>({...O,[A.id]:D})),qm(_==null?void 0:_.effects)},[]),$=i.useCallback((A,K)=>{f(_=>{const D={..._};return K===void 0?delete D[A.id]:D[A.id]=K,D}),g.current=0},[]);if(!o||o.length===0)return null;const P=ro(o,{hostIdeType:r,providerType:n});if(P.length===0)return null;const T=async A=>{if(C===A.id){N(null);return}if(Hr(A,b).length>0){N(A.id);return}if(A.dynamic&&A.listScript){M(A.id);try{const _=await j(A.listScript,{}),D=Gm(_);if(!D){const ge=Us(_);ge&&nt.showToast(ge,"warning");return}const O=D.options;h(ge=>{const ce={...ge,[A.id]:O};return ei.set(d,ce),ce});const X=Jm(A.id,{localOverrideUntil:g.current,localValues:x.current,controlValues:S.current,defaultValues:p});if(Xm(X,D.currentValue)){const ge=D.currentValue;f(ce=>({...ce,[A.id]:ge}))}N(A.id)}catch(_){const D=_ instanceof Error?_.message:`Could not load ${A.label}`;nt.showToast(D,"warning")}finally{M(null)}}},F=async(A,K)=>{N(null);const _=(c==null?void 0:c[A.id])??p[A.id];f(D=>({...D,[A.id]:K})),g.current=Date.now()+5e3;try{if(!A.setScript)return;const D=await j(A.setScript,$n(A,K)),O=Mr(D);if(O&&!O.ok||Ir(D))throw new Error((O==null?void 0:O.error)||Us(D)||`Could not update ${A.label}`);w(A,K,O)}catch(D){$(A,_);const O=D instanceof Error?D.message:`Could not update ${A.label}`;nt.showToast(O,"warning")}},H=async A=>{const K=Hr(A,b).map(ce=>ce.value);if(K.length===0)return;const _=String(y[A.id]||""),O=(K.indexOf(_)+1)%K.length,X=K[O];if(typeof X!="string")return;const ge=(c==null?void 0:c[A.id])??p[A.id];f(ce=>({...ce,[A.id]:X})),g.current=Date.now()+5e3;try{if(!A.setScript)return;const ce=await j(A.setScript,$n(A,X)),ee=Mr(ce);if(ee&&!ee.ok||Ir(ce))throw new Error((ee==null?void 0:ee.error)||Us(ce)||`Could not update ${A.label}`);w(A,X,ee)}catch(ce){$(A,ge);const ee=ce instanceof Error?ce.message:`Could not update ${A.label}`;nt.showToast(ee,"warning")}},L=async A=>{const _=!y[A.id],D=(c==null?void 0:c[A.id])??p[A.id];f(O=>({...O,[A.id]:_})),g.current=Date.now()+5e3;try{if(!A.setScript)return;const O=await j(A.setScript,$n(A,_)),X=Mr(O);if(X&&!X.ok||Ir(O))throw new Error((X==null?void 0:X.error)||Us(O)||`Could not update ${A.label}`);w(A,_,X)}catch(O){$(A,D);const X=O instanceof Error?O.message:`Could not update ${A.label}`;nt.showToast(X,"warning")}},k=async A=>{if(!A.invokeScript)return;if(A.confirmMessage){const _=[A.confirmTitle,A.confirmMessage,A.confirmLabel].filter(O=>typeof O=="string"&&O.trim().length>0);if(!window.confirm(_.join(`
|
|
28
|
+
|
|
29
|
+
`)))return}const K=(c==null?void 0:c[A.id])??p[A.id];try{const _=await j(A.invokeScript),D=Mr(_);if(D&&!D.ok||Ir(_))throw new Error((D==null?void 0:D.error)||Us(_)||`Could not run ${A.label}`);D&&w(A,K??!0,D)}catch(_){$(A,K);const D=_ instanceof Error?_.message:`Could not run ${A.label}`;nt.showToast(D,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${m}33`,background:`${m}12`,color:m},children:a}),P.map(A=>{const K=String(y[A.id]||""),_=ef(A,b,K),D=C===A.id,O=v===A.id,X=Hr(A,b),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(A.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${ge} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:D?`${m}55`:"var(--border-default)",background:D?`${m}10`:"var(--surface-tertiary)",color:K?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void T(A),title:A.label,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:O?"Loading…":_||A.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),D&&X.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>N(null)}),s.jsxs("div",{className:"absolute bottom-full left-0 z-[60] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[s.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:A.label}),X.map(ce=>s.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-[12px] transition-colors",style:{background:ce.value===K?`${m}14`:"transparent",color:ce.value===K?"var(--text-primary)":"var(--text-secondary)",borderLeft:ce.value===K?`2px solid ${m}`:"2px solid transparent"},title:ce.description||ce.label,onMouseEnter:ee=>{ee.currentTarget.style.background=`${m}10`},onMouseLeave:ee=>{ee.currentTarget.style.background=ce.value===K?`${m}14`:"transparent"},onClick:()=>void F(A,ce.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ce.label}),ce.value===K&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},ce.value))]})]})]},A.id);case"cycle":return s.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 H(A),title:`Click to cycle: ${X.map(ce=>ce.label).join(" → ")}`,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:_||A.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},A.id);case"toggle":return s.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 L(A),"aria-pressed":!!K,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),A.label]},A.id);case"action":return s.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 k(A),children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:A.resultDisplay==="inline"&&K?`${A.label}: ${K}`:A.label})]},A.id);case"display":return s.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:K?"var(--text-primary)":"var(--text-muted)"},children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:K?`${A.label}: ${K}`:A.label})]},A.id);default:return null}})]})})}function rf({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:c,controls:l,controlValues:d}){const{isVisible:m}=eo(),u=ro(l,{hostIdeType:a,providerType:o});return!e||t||u.length===0||!m?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(sf,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:c,controls:u,controlValues:d})})}function nf({hasDraft:e,isBusy:t=!1}){return!e||t}const Rc=i.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,onSend:c,isActive:l=!0,showControlsToggle:d=!1,animateVisibility:m=!0,onControlsToggle:u}){const f=i.useRef(null),[x,S]=i.useState(""),g=i.useRef(!1),{isVisible:p,toggleVisibility:y}=eo();i.useEffect(()=>{S("")},[t]),i.useEffect(()=>{var h;l&&((h=f.current)==null||h.focus({preventScroll:!0}))},[t,l]);const b=async()=>{const h=x.trim();if(!(!h||a)&&!g.current){g.current=!0;try{await c(h)!==!1&&S("")}finally{g.current=!1}}};return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"transition-all duration-200 ease-out":""].filter(Boolean).join(" "),style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[s.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[d&&s.jsx("button",{type:"button",onClick:()=>{y(),u==null||u()},"aria-label":p?"Hide controls":"Show controls","aria-pressed":p,title:p?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:s.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("input",{ref:f,type:"text",placeholder:o||`Send message to ${r}...`,value:x,onChange:h=>S(h.target.value),onPaste:h=>{const C=h.clipboardData.getData("text");C&&S(N=>N+C),h.preventDefault()},onKeyDown:h=>{if(h.key==="Enter"){if(h.nativeEvent.isComposing){h.preventDefault();return}h.preventDefault(),b()}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),s.jsx("button",{onClick:()=>{b()},disabled:nf({hasDraft:!!x.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${x.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:x.trim()&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:x.trim()?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),o&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:o})]})}),tt=e=>e.transport==="pty",Os=(e,t)=>tt(e)?e.mode||"terminal":"chat",Lc=(e,t)=>tt(e)&&Os(e)==="terminal",Ze=e=>e.transport==="acp",af=180;function Jt(e){return e.streamSource!=="agent-stream"}function ys(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Pc(e){return e.machineName||""}function hr(e){return ys(e)}function Kt(e){return e.agentType||""}function an(e){return e.hostIdeType||""}function no(e){return e.displayPrimary||e.agentName||"Agent"}function _c(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function of(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Dc(e){const t=of(e),r=Rs(t==null?void 0:t.content),n=Rs(e.lastMessagePreview);return r||n||""}function cf(e,t=af){const r=Rs(e);if(!r||t<=0)return"";const n=Array.from(r);return n.length<=t?r:`${n.slice(0,Math.max(0,t-1)).join("").trimEnd()}…`}function lf(e){return cf(Dc(e)||e.displaySecondary||"")}function Ec(e){return[e.displaySecondary,Pc(e)].filter(Boolean)}function Ps(e){return e.agentName||it(Kt(e))}function df(e){var t,r;if(!Jt(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return it(an(e)||Kt(e))}function $c(e){return Jt(e)?e.sessionId:e.nativeSessionId}function ti(e){return Jt(e)?"native":e.tabKey}function uf(e){return e.sessionId}function mf(e,t){if(t)return Jt(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function ff(e,t){const r=Kt(e),n=Jt(e),a=tt(e)||Ze(e),o=n?a?Ps(e)||(t==null?void 0:t.cliName)||it(an(e)||r):t!=null&&t.type?it(t.type):it(an(e)||r):Ps(e);return{isNativeConversation:n,isCli:tt(e),isAcp:Ze(e),isCliTerminal:Lc(e),providerType:r,displayLabel:o,targetEntry:mf(e,t)}}function as(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:tt(e)||Ze(e)?{agentType:Kt(e)}:e.streamSource==="agent-stream"?{agentType:Kt(e)}:t}function _s(e){return e?hr(e):""}function zs(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function ao(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function pf(e){const t=e instanceof Error?e.message:String(e||""),r=t.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.":t||"Unable to send message right now."}function Bc(){return"select_session"}function hf(){return"open_panel"}function xf({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function bf(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function si(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function on(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function oo(e){return e instanceof Error?e.message:String(e||"")}function ri(e){const t=oo(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function ni(e,t){const r=oo(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function jn({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,o]=i.useState(!1),[c,l]=i.useState(!1),[d,m]=i.useState(null),u=i.useRef(!1),f=i.useRef(null);i.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const x=i.useCallback(async y=>{if(!t||u.current)return!1;const b=y.trim(),h=ao(t);if(xf({hasMessage:!!b,blockedMessage:h,sendInFlight:u.current}))return h&&m(h),!1;const C=Date.now(),N={tabKey:t.tabKey,message:b,timestamp:C};if(bf(f.current,N))return m(null),!0;u.current=!0,l(!0),m(null),f.current=N;try{const v=_s(t);if(!v)return f.current=si(f.current,N),m("Unable to send message right now."),!1;const M=await e(v,"send_chat",{message:b,...as(t)}),I=on(M);if(I!=null&&I.deduplicated)return m(null),!0;if((I==null?void 0:I.sent)===!1)throw new Error((I==null?void 0:I.error)||"Send failed");if((I==null?void 0:I.success)===!1)throw new Error((I==null?void 0:I.error)||"Send failed");return m(null),!0}catch(v){const M=oo(v);return M.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",M):console.warn("Send blocked/failed",v),f.current=si(f.current,N),m(pf(v)),!1}finally{u.current=!1,l(!1)}},[t,e]),S=i.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(y){console.error("Relaunch failed",y)}},[t,e]),g=i.useCallback(async y=>{if(t)try{const h=(t.modalButtons||[]).indexOf(y),C=y.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),N=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(C),v=_s(t);if(!v)return;const M=await e(v,"resolve_action",{button:y,action:N?"approve":"reject",...h>=0&&{buttonIndex:h},...as(t)}),I=on(M);I.success||r(j=>[...j,{routeId:t.tabKey,text:ni(y,I==null?void 0:I.error),timestamp:Date.now()}])}catch(b){ri(b)||console.error("[ModalButton] Error:",b),r(h=>[...h,{routeId:t.tabKey,text:ri(b)?ni(y,b):`❌ **${y}** error`,timestamp:Date.now()}])}},[t,e,r]),p=i.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,hf(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(y){console.error("Focus agent failed",y)}finally{o(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:x,handleRelaunch:S,handleModalButton:g,handleFocusAgent:p}}const gf=10,yf=8e3,vf=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function wf(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 Ma(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(vf.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=wf(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=>Ma(a,t,r+1));return e.length>20?[{truncatedBefore:e.length-20},...n]:n}return Object.fromEntries(Object.entries(e).slice(0,80).map(([n,a])=>[n,Ma(a,n,r+1)]))}function Vs(e,t){return Array.isArray(e)?e.slice(-t):[]}function jf(e,t=Date.now()){const r=e&&t-e.firstAt<=yf,n=r?e.count+1:1;return n>=gf?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function Wc(e){var n,a;const{activeConv:t}=e,r={version:1,createdAt:new Date(e.now??Date.now()).toISOString(),url:e.locationHref??(typeof window<"u"?window.location.href:void 0),activeConversation:{routeId:t.routeId,tabKey:t.tabKey,sessionId:t.sessionId,providerSessionId:t.providerSessionId,transport:t.transport,agentName:t.agentName,agentType:t.agentType,hostIdeType:t.hostIdeType,status:t.status,connectionState:t.connectionState,title:t.title,workspaceName:t.workspaceName,displayPrimary:t.displayPrimary,displaySecondary:t.displaySecondary,streamSource:t.streamSource,lastMessageHash:t.lastMessageHash},messageCounts:{live:((n=e.chatTailState.liveMessages)==null?void 0:n.length)??t.messages.length,activeConversation:t.messages.length,visible:e.visibleMessages.length,history:((a=e.chatTailState.historyMessages)==null?void 0:a.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:Vs(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:Vs(t.messages,10),visibleMessagesTail:Vs(e.visibleMessages,5),historyMessagesTail:Vs(e.chatTailState.historyMessages,5),actionLogsTail:Vs(e.actionLogs.filter(o=>o.routeId===t.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chatTail:{hasLiveSnapshot:!!e.chatTailState.hasLiveSnapshot,hasMoreHistory:!!e.chatTailState.hasMoreHistory,historyError:e.chatTailState.historyError||null},ui:e.ui,browser:typeof navigator<"u"?{userAgent:navigator.userAgent,language:navigator.language,online:navigator.onLine}:null};return Ma(r)}function Kc(e,t={}){const r=e&&typeof e=="object"?e:{},n=t.locatorCopyStatus??(t.locatorCopied===!1?"failed":"copied"),a=n==="copied"?"locator copied":n==="manual"?"locator shown for manual copy":"locator copy failed";return r.delivery==="daemon_file"?`Chat debug signal sent${typeof r.bundleId=="string"&&r.bundleId.trim()?` (${r.bundleId})`:""}; saved on daemon, ${a}.`:`Chat debug signal sent; ${a}.`}async function Oc(e){var t;if(typeof navigator<"u"&&((t=navigator.clipboard)!=null&&t.writeText)&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(e),"copied"}catch(r){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",r)}if(typeof document<"u"&&document.body){let r=null;try{if(r=document.createElement("textarea"),r.value=e,r.setAttribute("readonly","true"),r.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(r),r.focus(),r.select(),document.execCommand("copy"))return"copied"}catch{}finally{r==null||r.remove()}}if(typeof window<"u"&&typeof window.prompt=="function")try{return window.prompt("Copy ADHDev chat debug locator:",e),"manual"}catch{}return"failed"}function Fc(e){const t=e&&typeof e=="object"?e:{};if(t.delivery==="daemon_file"){const r=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(t.bundleId||"")}`,`savedPath: ${String(t.savedPath||"")}`,`sizeBytes: ${String(t.sizeBytes||"")}`,`createdAt: ${String(t.createdAt||"")}`];return t.summary&&typeof t.summary=="object"&&r.push("","summary:",JSON.stringify(t.summary,null,2)),Array.isArray(t.warnings)&&t.warnings.length>0&&r.push("","warnings:",...t.warnings.map(n=>`- ${String(n)}`)),r.join(`
|
|
30
|
+
`)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
|
|
31
|
+
|
|
32
|
+
\`\`\`json
|
|
33
|
+
${JSON.stringify(t.bundle,null,2)}
|
|
34
|
+
\`\`\``:`# ADHDev Chat Debug Bundle
|
|
35
|
+
|
|
36
|
+
\`\`\`json
|
|
37
|
+
${JSON.stringify(t,null,2)}
|
|
38
|
+
\`\`\``}function Bn(e,t){return`${e}:${t}`}function kf(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Gs(e,t){kf()&&console.debug(`[subscription-manager] ${e}`,t)}class Sf{constructor(){Xe(this,"active",new Map);Xe(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var u;const c=Bn(n.topic,n.key),l=this.active.get(c);let d=!0;if(l)l.handlers.add(a),l.lastUpdate&&a(l.lastUpdate);else{const f={daemonId:r,request:n,handlers:new Set([a])};this.active.set(c,f),Gs("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((u=t.sendData)==null?void 0:u.call(t,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(c,t,o.retryIntervalMs)}const m=()=>{var S;this.clearRetry(c);const f=this.active.get(c);if(!f||(f.handlers.delete(a),f.handlers.size>0))return;this.active.delete(c);const x={type:"unsubscribe",topic:n.topic,key:n.key};Gs("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(S=t.sendData)==null||S.call(t,r,x)};return m.initialSendAccepted=d,m}publish(t){const r=Bn(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,As.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),n.handlers.forEach(a=>{a(t),As.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,r,n){const a=Bn(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;Gs("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=t.sendData)==null||r.call(t,n.daemonId,n.request)}resubscribeForDaemon(t,r){var a;const n=Array.from(this.active.values()).filter(o=>o.daemonId===t);Gs("resubscribe_daemon",{daemonId:t,count:n.length,subscriptions:n.map(o=>({topic:o.request.topic,key:o.request.key}))});for(const o of n)(a=r.sendData)==null||a.call(r,o.daemonId,o.request)}scheduleRetry(t,r,n){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var l;this.retryTimers.delete(t);const o=this.active.get(t);if(!o)return;const c=((l=r.sendData)==null?void 0:l.call(r,o.daemonId,o.request))??!1;Gs("subscribe_retry",{id:t,accepted:c,topic:o.request.topic,key:o.request.key}),c||this.scheduleRetry(t,r,n)},n);this.retryTimers.set(t,a)}clearRetry(t){const r=this.retryTimers.get(t);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(t))}}const Ut=new Sf;function Nf(e,t){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===t&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,mode:n.mode,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash,completionMarker:n.completionMarker,seenCompletionMarker:n.seenCompletionMarker,settings:n.settings});for(const o of n.childSessions||[]){if(!(o!=null&&o.id))continue;const c=r.get(o.id)||{};r.set(o.id,{...c,...o})}}return r}function Cf(e){const t=[],r=new Map;for(const n of e)if(n.parentId){const a=r.get(n.parentId)||[];a.push(n),r.set(n.parentId,a)}else t.push(n);return{topLevel:t,childrenByParent:r}}function cn(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:c}=t,l=c||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:m,childrenByParent:u}=Cf(d),f=Nf(o,n),x=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,S=m.filter(y=>y.kind==="workspace"&&y.transport==="cdp-page"),g=m.filter(y=>y.kind==="agent"&&y.transport==="pty"),p=m.filter(y=>y.kind==="agent"&&y.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...x&&{machine:x,platform:x.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:S.some(y=>!!y.cdpConnected)});for(const y of S){const b=f.get(y.id),h=Zs(y,b),C=(u.get(y.id)||[]).map(N=>Zs(N,f.get(N.id)));r.push({id:`${n}:ide:${y.id}`,sessionId:y.id,providerSessionId:y.providerSessionId??(b==null?void 0:b.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,status:h.cdpConnected?"online":"detected",daemonId:n,instanceId:y.id,workspace:h.workspace,terminals:0,childSessions:C,agents:C.map(N=>({id:N.id,name:N.providerName||N.providerType,type:N.providerType,status:N.status})),activeChat:h.activeChat,chats:[],cdpConnected:h.cdpConnected,...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},...h.settings!==void 0&&{settings:h.settings},timestamp:l})}for(const y of g){const b=f.get(y.id),h=Zs(y,b);r.push({id:`${n}:cli:${y.id}`,sessionId:y.id,providerSessionId:y.providerSessionId??(b==null?void 0:b.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:y.id,cliName:h.providerName||h.providerType,mode:h.mode||(b==null?void 0:b.mode)||"terminal",workspace:h.workspace||"",activeChat:h.activeChat,...h.resume!==void 0&&{resume:h.resume},...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},...h.settings!==void 0&&{settings:h.settings},timestamp:l,_isCli:!0})}for(const y of p){const b=f.get(y.id),h=Zs(y,b);r.push({id:`${n}:acp:${y.id}`,sessionId:y.id,providerSessionId:y.providerSessionId??(b==null?void 0:b.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:y.id,cliName:h.providerName||h.providerType,mode:"chat",workspace:h.workspace||"",activeChat:h.activeChat,...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},...h.settings!==void 0&&{settings:h.settings},timestamp:l,_isAcp:!0})}return r}const Tf=15e3,Mf=15e3,If=6e4,Af=1200,ai=12,Rf=8e3,Lf=4e3,Wn=new Map,Kn=new Map,Ar=new Set,rr=new Map;function Pf(e){if(!e||typeof e!="object")return null;const t=e,r=t.status;if(r&&typeof r=="object")return r;const n=t.result;if(n&&typeof n=="object"&&"status"in n){const a=n.status;if(a&&typeof a=="object")return a}return t}function oi(e,t){const r=rr.get(e);!r||r.size===0||(rr.delete(e),r.forEach(n=>n(t)))}function _f(e,t){return new Promise(r=>{const n=rr.get(e)||new Set;rr.set(e,n);const a=c=>{clearTimeout(o),n.delete(a),n.size===0&&rr.delete(e),r(c)},o=setTimeout(()=>a(!1),t);n.add(a)})}function xr(){const{sendCommand:e,sendData:t}=gt(),{injectEntries:r,getIdes:n}=lr();return i.useCallback(async(a,o)=>{if(!a)return;const c=(o==null?void 0:o.minFreshMs)??If,l=Kn.get(a)||0;if(!(o!=null&&o.force)&&Ar.has(a)&&l>0||!(o!=null&&o.force)&&l>0&&Date.now()-l<c)return;const d=Wn.get(a);if(d)return d;const m=(async()=>{if(t&&!Ar.has(a)){const p=Ut.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},y=>{const b=n(),h=b.find(N=>N.id===a),C=cn(y.status,{daemonId:a,existingDaemon:h,existingEntries:b,timestamp:y.timestamp});C.length>0&&r(C),Kn.set(a,Date.now()),oi(a,!0)});if(p.initialSendAccepted?Ar.add(a):Ar.delete(a),!(o!=null&&o.force)&&p.initialSendAccepted&&await _f(a,Af))return}const u=await e(a,"get_status_metadata"),f=Pf(u);if(!f)return;const x=n(),S=x.find(p=>p.id===a),g=cn(f,{daemonId:a,existingDaemon:S,existingEntries:x,timestamp:f.timestamp||Date.now()});g.length>0&&r(g,{authoritativeDaemonIds:[a]}),Kn.set(a,Date.now()),oi(a,!0)})().finally(()=>{Wn.delete(a)});return Wn.set(a,m),m},[n,r,e,t])}function Df(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const Ef=60,$f=50;function Hc(e={}){return e.isCliLike?$f:Ef}function Bf(e={}){return Hc(e)}function St(e){return(typeof e=="string"?e.trim():"")||void 0}function Ht(e,t){const r=St(t);return r?`${e}:${r}`:void 0}function Yt(e,t,r){const n=Ht(t,r),a=St(r);n&&e.push(n),a&&e.push(a)}function Ns(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function Uc(e){return St(e.providerSessionId)||St(e.sessionId)||St(e.tabKey)||St(e.routeId)}function io(e){return Ns([St(e.providerSessionId),St(e.sessionId)])}function Is(e){const t=[];return Yt(t,"provider",e.providerSessionId),Yt(t,"session",e.sessionId),Yt(t,"tab",e.tabKey),Yt(t,"route",e.routeId),Ns(t)}function Wf(e){const t=[];return St(e.providerSessionId)?(Yt(t,"provider",e.providerSessionId),Ns(t)):St(e.sessionId)?(Yt(t,"session",e.sessionId),Ns(t)):St(e.tabKey)?(Yt(t,"tab",e.tabKey),Ns(t)):St(e.routeId)?(Yt(t,"route",e.routeId),Ns(t)):[]}function co(e){return Ht("provider",e.providerSessionId)||Ht("session",e.sessionId)||Ht("tab",e.tabKey)||Ht("route",e.routeId)||"unknown:"}function br(e){return io(e)[0]}function Kf(e){const t=St(e.providerSessionId),r=St(e.sessionId),n=St(e.tabKey),a=St(e.routeId),o=[Ht("provider",t),Ht("session",r),Ht("tab",n),Ht("route",a)].filter(d=>typeof d=="string"),c=Is({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=co({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:Uc({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:br({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:c}}function Ia(e,t){const r=Kf(e);return Wf(t).some(n=>r.lookupKeys.includes(n))}const gr=60,Of=1e3,lo=12e4,Ff=new Set(["generating","waiting_approval","starting","streaming","working"]),ii=new Map;function zc(e,t){return`${e}::${t}`}function Aa(e=gr){return{liveMessages:[],hasLiveSnapshot:!1,cursor:Hf([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Hf(e,t=gr){return{tailLimit:t}}function ci(e,t){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}class Uf{constructor(t){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=t.manager||Ut,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount??0),this.snapshot=Aa(Math.max(0,t.tailLimit??gr))}updateOptions(t){if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount)),t.tailLimit!==void 0){const r=Math.max(0,t.tailLimit);r!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect()))}}getSnapshot(){return this.snapshot}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=this.snapshot.hasLiveSnapshot,a=n?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),o=await t({offset:this.snapshot.historyOffset,excludeRecentCount:a}),c=Array.isArray(o.messages)?o.messages:[],l=!n&&c.length===0&&o.hasMore!==!0&&this.fallbackRecentCount>0;this.snapshot={...this.snapshot,historyMessages:[...c,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+c.length,hasMoreHistory:l?!0:o.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),t=>{this.handleUpdate(t)},{retryIntervalMs:Of}))}disconnect(){var t;(t=this.transportSubscription)==null||t.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(t=>t(this.snapshot))}handleUpdate(t){if(t.error)return;const r=Array.isArray(t.messages)?t.messages:[],n={tailLimit:this.snapshot.cursor.tailLimit};ci(this.snapshot.liveMessages)===ci(r)&&this.snapshot.cursor.tailLimit===n.tailLimit||(this.snapshot={...this.snapshot,liveMessages:r,hasLiveSnapshot:!0,cursor:n},this.emit())}}function Vc(e){const t=zc(e.daemonId,e.sessionId),r=ii.get(t);if(r)return r.updateOptions(e),r;const n=new Uf(e);return ii.set(t,n),n}function zf(e,t){return{...e,loadHistoryPage:t}}function Vf(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Gf(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Ff.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=t.now??Date.now(),a=Math.max(0,Number(t.recentActivityMs??lo)),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 qf(e=lo){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Yf(e,t={}){const r=new Set,n=[];for(const a of e){if(!Gf(a,t))continue;const o=hr(a),c=a.sessionId||"";if(!o||!c)continue;const l=zc(o,c);if(r.has(l))continue;r.add(l);const d=br(a);n.push({daemonId:o,sessionId:c,historySessionId:d||c,subscriptionKey:`daemon:${o}:session:${c}`})}return n.sort(Vf),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Xf(e,t){const{sendData:r,sendCommand:n}=gt(),a=(t==null?void 0:t.enabled)!==!1,o=hr(e),c=e.sessionId||"",l=br(e)||c,d=`daemon:${o}:session:${c}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??gr),u=i.useMemo(()=>!a||!o||!c?null:Vc({daemonId:o,sessionId:c,historySessionId:l,subscriptionKey:d,sendData:r,tailLimit:m,fallbackRecentCount:e.messages.length}),[e.messages.length,o,a,l,r,c,d,m]),[f,x]=i.useState(()=>(u==null?void 0:u.getSnapshot())||Aa(m));i.useEffect(()=>{if(!u){x(Aa(m));return}u.retain(),x(u.getSnapshot());const g=u.subscribe(p=>{x(p)});return()=>{g(),u.release()}},[u,m]);const S=i.useCallback(async()=>{!u||!o||!c||await u.loadHistoryPage(async({offset:g,excludeRecentCount:p})=>{const y=e.agentType,b=await n(o,"chat_history",{agentType:y,offset:g,limit:30,targetSessionId:c,historySessionId:l,excludeRecentCount:p}),h=b&&typeof b=="object"&&"result"in b?b.result||{}:b||{};return{messages:Array.isArray(h.messages)?h.messages:[],hasMore:h.hasMore===!0}})},[e.agentType,u,o,l,n,c]);return i.useMemo(()=>zf(f,S),[S,f])}function Jf(e,t){const{sendData:r}=gt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??gr),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??lo)),c=qf(o),[l,d]=i.useState(0);i.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(f=>f+1)},c);return()=>{clearInterval(u)}},[e.length,n,c]);const m=i.useMemo(()=>Yf(e,{recentActivityMs:o}),[e,o,l]);i.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const u=m.descriptors.map(f=>Vc({...f,sendData:r,tailLimit:a}));return u.forEach(f=>{f.retain()}),()=>{u.forEach(f=>f.release())}},[m.signature,n,r,a])}function Qf(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function li(e){const t=String(e.role||"").toLowerCase();if(t!=="user"&&t!=="assistant")return!1;const r=String(e.kind||"standard").toLowerCase();return r===""||r==="standard"}function Zf(e,t){if(e.length===0)return[];if(t.some(li))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||!li(o))continue;const c=String(o.role||"").toLowerCase();n.has(c)||(n.add(c),r.unshift(o))}return r}function ep(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,a=Math.max(0,r.length-n),o=a>0?r.slice(0,a):[],c=a>0?r.slice(-n):r,l=Zf(o,c),d=l.length>0?[...l,...c]:c;return t.length===0?d:[...t,...d]}function tp(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function sp(e){return tp(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function rp(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function np(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function ap(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Gc(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function qc(e){const t=typeof e.completionMarker=="string"?e.completionMarker.trim():"";return t||(e.lastMessageHash?e.lastMessageHash:e.lastMessageAt?String(e.lastMessageAt):e.lastUpdated?String(e.lastUpdated):"")}function op(e){return Gc(e)?!1:e.inboxBucket==="task_complete"&&qc(e).length>0}function di(e){return e.branch||"detached HEAD"}function ip(e){if(e.error)return`${di(e)} · Git error: ${e.error}`;const t=[di(e)];return e.changedFiles>0?t.push(rp(e.changedFiles,"file")+" changed"):e.dirty||t.push("clean"),e.ahead>0&&t.push(`ahead ${e.ahead}`),e.behind>0&&t.push(`behind ${e.behind}`),e.hasConflicts&&t.push("conflicts"),t.join(" · ")}function cp(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${ip(t)}`}function lp(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function dp(e,t={}){if(t.enabled===!1)return[];if(!ap(e))return[];const r=Gc(e)?"working":op(e)?"complete":null;if(!r)return[];const n=r==="complete"?qc(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${np(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:cp(r,e.git),timestamp:lp(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 up=60;function Ra({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:o,isFocusingAgent:c,actionLogs:l,userName:d,scrollToBottomRequestNonce:m,isInputActive:u=!0,isVisible:f=!0}){var ie,ye,re,me,ke,xe,ve;const x=i.useRef(new Map),S=i.useRef(void 0),g=xr(),{sendCommand:p}=gt(),{isVisible:y}=eo();pr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const b=Ct.useMemo(()=>Ks(e),[e.status,e.connectionState]),h=i.useMemo(()=>ff(e,t),[e,t]),C=i.useMemo(()=>{var te;return ro((te=h.targetEntry)==null?void 0:te.providerControls,{hostIdeType:e.hostIdeType,providerType:h.providerType})},[e.hostIdeType,h.providerType,(ie=h.targetEntry)==null?void 0:ie.providerControls]),N=Hc({isCliLike:h.isCli||h.isAcp}),v=Bf({isCliLike:h.isCli||h.isAcp}),M=Xf(e,{enabled:f&&!!e.sessionId,tailLimit:v}),[I,j]=i.useState(N),w=e.tabKey,$=M.historyMessages,P=M.hasMoreHistory,T=M.historyError,F=Qf(e,M);i.useEffect(()=>{j(N)},[N,w]);const H=Math.max(0,F.length-I),L=no(e),k=hr(e),A=sp(e),K=ao(e),_=a||K,D=!!K,[O,X]=i.useState(!1);i.useEffect(()=>{const te=h.targetEntry;k&&(!te||te.providerControls===void 0||te.controlValues===void 0)&&g(k,{minFreshMs:3e4}).catch(()=>{})},[k,h.isAcp,(ye=h.targetEntry)==null?void 0:ye.providerControls,(re=h.targetEntry)==null?void 0:re.controlValues,g]);const ge=i.useCallback(async()=>{if(!O){if(F.length>I){j(te=>Math.min(F.length,te+up));return}X(!0);try{await M.loadHistoryPage()}finally{X(!1)}}},[M,O,F.length,I]),{allMessages:ce,receivedAtMap:ee}=i.useMemo(()=>{const te=ep({historyMessages:$,liveMessages:F,visibleLiveCount:I}),he=dp(e),le=he.length>0?[...te,...he]:te,ue={};return le.forEach((oe,Q)=>{const fe=`${e.tabKey}:${tn(oe,Q)}`;let J=Df(oe)||x.current.get(fe)||0;J||(J=Date.now(),x.current.set(fe,J)),ue[tn(oe,Q)]=J}),{allMessages:le,receivedAtMap:ue}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,H,$,F,I]),z=i.useMemo(()=>l.filter(te=>te.routeId===e.tabKey).sort((te,he)=>te.timestamp-he.timestamp),[l,e.tabKey]),de=i.useCallback(async()=>{var Q,fe;if(!k)return;const te=Wc({activeConv:e,visibleMessages:ce,actionLogs:l,controls:(Q=h.targetEntry)==null?void 0:Q.providerControls,controlValues:(fe=h.targetEntry)==null?void 0:fe.controlValues,visibleBarControlCount:C.length,chatTailState:{liveMessages:M.liveMessages,hasLiveSnapshot:M.hasLiveSnapshot,hasMoreHistory:P,historyError:T,historyMessages:$},ui:{controlsVisible:y,visibleLiveCount:I,hiddenLiveCount:H,isInputActive:u,isVisible:f}}),he=await p(k,"get_chat_debug_bundle",{agentType:h.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:te}),le=on(he),ue=Fc(le),oe=await Oc(ue);oe==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),nt.showToast(Kc(le,{locatorCopyStatus:oe}),oe==="failed"?"warning":"success")},[e,l,ce,y,M.hasLiveSnapshot,M.liveMessages,h.providerType,(me=h.targetEntry)==null?void 0:me.controlValues,(ke=h.targetEntry)==null?void 0:ke.providerControls,k,P,H,$,u,f,T,p,C.length,I]),pe=i.useCallback(()=>{const te=jf(S.current);S.current=te.state,te.shouldCollect&&de().catch(he=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",he),nt.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[de]),Y=i.useMemo(()=>{if(F.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((b.isGenerating||e.status==="streaming")&&X(!1),e.status==="not_monitored"&&A)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Ls,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:o,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ps,{size:14})," Open ",L," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&A)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(pc,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:o,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ps,{size:14})," Open ",L," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!O)return!P&&$.length===0?s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"No messages yet"})]}):s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,A,o,P,$.length,c,O,F.length,L,b.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[s.jsx(em,{messages:ce,actionLogs:z,agentName:Ps(e)||L||"Agent",userName:d,isCliMode:h.isCli||h.isAcp,isWorking:b.isGenerating,contextKey:e.tabKey,receivedAtMap:ee,lastMessageHash:e.lastMessageHash,onLoadMore:ge,isLoadingMore:O,hasMoreHistory:P,hiddenLiveCount:H,loadError:T??void 0,emptyState:Y,scrollToBottomRequestNonce:m,isVisible:f}),s.jsx(rf,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:h.providerType,displayLabel:h.displayLabel,controls:(xe=h.targetEntry)==null?void 0:xe.providerControls,controlValues:(ve=h.targetEntry)==null?void 0:ve.controlValues,isActive:u,isCliTerminal:h.isCliTerminal}),!h.isCliTerminal&&s.jsx(Rc,{contextKey:e.tabKey,panelLabel:L,isSending:n,isBusy:D,statusMessage:_,onSend:r,isActive:u,showControlsToggle:C.length>0,onControlsToggle:pe})]})}let Yc=Zt;function Xc(){return Yc()}class mp{constructor(){Xe(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{var n;(n=this.listeners.get(t))==null||n.delete(r)}}emit(t,...r){var n;(n=this.listeners.get(t))==null||n.forEach(a=>a(...r))}}let Jc=new mp;class fp{sendPtyInput(t,r,n){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,r){return!1}get(t){}onScreenshot(t,r){return()=>{}}onRuntimeEvent(t,r,n){return()=>{}}requestRuntimeSnapshot(t,r,n){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let ut=new fp;function pp(e){e.dashboardWS&&(Jc=e.dashboardWS),e.connectionManager&&(ut=e.connectionManager),e.useDaemonsHook&&(Yc=e.useDaemonsHook)}const hp=.5,xp=1.25;function lt(e){return no(e)}function xs(e){return Ec(e).join(" · ")}function Qc(e){const t=Dc(e);return t||(e.title?e.title:xs(e)||"No messages yet")}function Zc(e,t){const{isReconnecting:r,isConnecting:n}=Ks(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function bp(e,t){const r=["Chat",...Ec(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function os(e){return Zc(e)||xs(e)}function gp(e){return`${lt(e)} · ${Qc(e)}`}function yp(e){const t=an(e),r=t?it(t):Ps(e);return`${lt(e)} — ${r||"Agent"}`}function vp(e){return Ps(e)||"CLI"}function el(e){return _c(e)}function tl(e){return e?`Remote · ${lt(e)||e.workspaceName||"Session"}`:"Remote"}function wp({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:c=!0,isInputActive:l=!0}){var se;Zt();const{sendPtyInput:d}=gt(),[m,u]=i.useState(!1),f=i.useRef(!1);f.current=m;const[x,S]=i.useState("Runtime terminal unavailable"),[g,p]=i.useState(!1),[y,b]=i.useState(null),[h,C]=i.useState(!1),[N,v]=i.useState(!1),[M,I]=i.useState(1),[j,w]=i.useState(!1),[$,P]=i.useState({width:0,height:0}),[T,F]=i.useState({width:0,height:0}),[H,L]=i.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[k,A]=i.useState(null),K=i.useRef(null),_=i.useRef(null),D=i.useRef(!1),O=i.useRef(!1),X=i.useRef(c),ge=i.useRef(0),ce=i.useRef(!1),ee=i.useRef(""),z=i.useRef(null),de=i.useRef(!1),pe=i.useRef(!1),Y=i.useRef(null),ie=i.useRef(null),ye=i.useRef(null),re=32*1024,me=()=>{var E,q,Z,ne;return((q=(E=K.current)==null?void 0:E.ownerDocument)==null?void 0:q.defaultView)||((ne=(Z=_.current)==null?void 0:Z.ownerDocument)==null?void 0:ne.defaultView)||window},ke=E=>{const q=me();return{ownerWindow:q,frameId:q.requestAnimationFrame(E)}},xe=()=>{const E=Y.current;if(E){try{E.ownerWindow.cancelAnimationFrame(E.frameId)}catch{}Y.current=null}},ve=()=>{const E=ie.current;if(E){try{E.ownerWindow.clearTimeout(E.timeoutId)}catch{}ie.current=null}},te=()=>{const E=ye.current;if(E){try{E.ownerWindow.clearTimeout(E.timeoutId)}catch{}ye.current=null}},he=()=>{c&&Y.current===null&&(Y.current=ke(()=>{st()}))},le=e.tabKey,ue=e.sessionId||"",oe=e.daemonId||((se=e.routeId)==null?void 0:se.split(":")[0])||e.routeId||"",Q=ao(e),fe=m?o||Q:x,J=hp,Ae=xp,Te=.05,$e=()=>{const E=T.width,q=T.height;if(!Number.isFinite($.width)||$.width<=0||!Number.isFinite($.height)||$.height<=0||!Number.isFinite(E)||E<=0||!Number.isFinite(q)||q<=0)return 1;const Z=$.width/E,ne=$.height/q;return Number(Math.min(Ae,Math.max(J,Math.min(Z,ne))).toFixed(2))},Ue=$e(),B=D.current&&M>Ue,Se=Number.isFinite(T.width)&&T.width>0?Math.max($.width,Math.round(T.width*M)):$.width,Me=Number.isFinite(T.height)&&T.height>0?Math.max($.height,Math.round(T.height*M)):$.height,De=()=>{ke(()=>{const E=_.current;E&&(E.scrollLeft=0,E.scrollTop=E.scrollHeight-E.clientHeight)})},We=()=>{var E,q;ge.current=0,ce.current=!1,ee.current="",z.current=null,de.current=!1,pe.current=!1,D.current||(O.current=!1,I(1)),Y.current!==null&&xe(),u(!1),S("Runtime terminal unavailable"),te(),ve(),b(null),A(null),w(!1),p(!1),C(!1),v(!1),(q=(E=r.current)==null?void 0:E.reset)==null||q.call(E)},He=()=>{var E,q;ge.current=0,ce.current=!1,ee.current="",z.current=null,de.current=!1,pe.current=!1,Y.current!==null&&xe(),u(!0),S(""),te(),ve(),b(null),A(null),w(!1),p(!1),C(!1),v(!1),(q=(E=r.current)==null?void 0:E.reset)==null||q.call(E)},Je=()=>{pe.current&&(pe.current=!1,ke(()=>{var E,q;(q=(E=r.current)==null?void 0:E.scrollToTop)==null||q.call(E)}))},st=()=>{if(Y.current=null,!c)return;const E=ee.current;if(!E)return;const q=E.slice(0,re);ee.current=E.slice(q.length);const Z=r.current;if(!Z){ee.current=q+ee.current,he();return}Z.write(q,()=>{if(ee.current.length>0){he();return}Je()})},mt=E=>{E&&(ee.current+=E,he())},ht=(E,q=0,Z,ne,je={})=>{var _e,Ne,Ee,Be;const Le=!!je.force;!Le&&q>0&&ge.current>=q||!Le&&q===0&&ce.current||(ge.current=q,q>0&&C(!0),u(!0),S(""),typeof Z=="number"&&typeof ne=="number"&&Z>0&&ne>0&&((Ne=(_e=r.current)==null?void 0:_e.resize)==null||Ne.call(_e,Z,ne)),ee.current="",(Be=(Ee=r.current)==null?void 0:Ee.reset)==null||Be.call(Ee),E?mt(E):Je())};i.useEffect(()=>{We()},[ue]),i.useEffect(()=>{var q;if(!ue)return;const E=((q=ut.onRuntimeEvent)==null?void 0:q.call(ut,ue,Z=>{if(!(!Z||Z.sessionId!==ue)){if(Z.type==="runtime_snapshot"){if(!c){z.current={text:Z.text||"",seq:Z.seq||0,cols:Z.cols,rows:Z.rows,force:!!Z.force};return}ht(Z.text||"",Z.seq||0,Z.cols,Z.rows,{force:!!Z.force});return}if(Z.type==="session_output"){ce.current=!0,typeof Z.seq=="number"&&(ge.current=Math.max(ge.current,Z.seq),Z.seq>0&&C(!0)),f.current||u(!0),f.current||S(""),typeof Z.data=="string"&&mt(Z.data);return}if(Z.type==="session_cleared"){if(!c){de.current=!0,ee.current="",z.current=null;return}He();return}if(Z.type==="session_io_error"){const ne=typeof Z.error=="string"&&Z.error?Z.error:typeof Z.reason=="string"&&Z.reason?Z.reason:"unknown error";u(!1),S(`Runtime input failed: ${ne}`);return}}},oe))||(()=>{});return()=>{E()}},[oe,ue,r,c]);const xt=async(E={})=>{var q;if(!oe||!ue)return{success:!1,error:"daemonId and sessionId are required"};E.preserveStatus||S(E.loadingMessage||"Loading runtime terminal...");try{const Z=await((q=ut.requestRuntimeSnapshot)==null?void 0:q.call(ut,oe,ue,{sinceSeq:E.sinceSeq,force:E.force}));return Z&&Z.success===!1?(E.preserveStatus||(u(!1),S(`Runtime terminal unavailable: ${Z.error}`)),Z):Z||{success:!0}}catch(Z){const ne=(Z==null?void 0:Z.message)||String(Z);return E.preserveStatus||(u(!1),S(`Runtime terminal unavailable: ${ne}`)),{success:!1,error:ne}}},Ce=async E=>{var Le,_e;const q=((Le=K.current)==null?void 0:Le.ownerDocument)||document,Z=q.defaultView||window,ne=(_e=Z.navigator)==null?void 0:_e.clipboard;if(ne!=null&&ne.writeText&&Z.isSecureContext)try{return await ne.writeText(E),!0}catch{}let je=null;try{return je=q.createElement("textarea"),je.value=E,je.setAttribute("readonly","true"),je.style.position="fixed",je.style.left="-9999px",je.style.top="0",q.body.appendChild(je),je.focus(),je.select(),q.execCommand("copy")}catch{return!1}finally{je==null||je.remove()}},ze=E=>{ve(),A(E);const q=me();ie.current={ownerWindow:q,timeoutId:q.setTimeout(()=>{ie.current=null,A(Z=>Z===E?null:Z)},2200)}},Qe=E=>{te(),b(E);const q=me();ye.current={ownerWindow:q,timeoutId:q.setTimeout(()=>{ye.current=null,b(Z=>Z===E?null:Z)},2200)}},Ge=async()=>{var je,Le,_e,Ne;const E=((Le=(je=r.current)==null?void 0:je.getSelection)==null?void 0:Le.call(je))||"",q=((Ne=(_e=r.current)==null?void 0:_e.getVisibleText)==null?void 0:Ne.call(_e))||"",Z=E.trimEnd()||q.trimEnd();if(!Z){ze("Nothing to copy");return}if(!await Ce(Z)){ze("Copy failed");return}ze(E.trimEnd()?"Copied selection":"Copied visible terminal")},rt=E=>{if(!m||!c)return;((d==null?void 0:d(oe,ue,E))??!1)||ze("Terminal input failed")},W=async()=>{if(g)return;p(!0),b("Loading older terminal output..."),pe.current=!0;const E=await xt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(p(!1),(E==null?void 0:E.success)===!1){pe.current=!1,b(`Older terminal output unavailable: ${E.error}`);return}v(!0),Qe("Older terminal output loaded"),ke(()=>{var q;(q=r.current)==null||q.bumpResize()})};i.useEffect(()=>{var q,Z;if(!ue)return;oe&&((q=ut.getState)==null?void 0:q.call(ut,oe))==="connected"&&xt();const E=(Z=ut.onStateChange)==null?void 0:Z.call(ut,(ne,je)=>{ne!==oe||je!=="connected"||xt()});return()=>{E==null||E()}},[oe,ue,r]),i.useEffect(()=>{t&&We()},[t,le,r]),i.useEffect(()=>{var ne,je;const E=K.current,q=(je=(ne=E==null?void 0:E.ownerDocument)==null?void 0:ne.defaultView)==null?void 0:je.ResizeObserver;if(!E||!q)return;const Z=new q(Le=>{const _e=Le[0];if(!_e)return;const{width:Ne,height:Ee}=_e.contentRect;P(Be=>{const Re=Math.round(Ne),qe=Math.round(Ee);return Be.width===Re&&Be.height===qe?Be:{width:Re,height:qe}})});return Z.observe(E),()=>Z.disconnect()},[]),i.useEffect(()=>{if(D.current)return;const E=$e();!Number.isFinite(E)||E<=0||I(q=>O.current?E<q-Te?E:q:(O.current=!0,E))},[T.height,T.width,$.height,$.width]),i.useEffect(()=>{B&&De()},[B,Me,Se]),i.useEffect(()=>{var Z;const E=X.current;if(X.current=c,!c)return;E||v(!1),de.current&&(de.current=!1,He());const q=z.current;q&&(z.current=null,ht(q.text,q.seq,q.cols,q.rows,{force:!!q.force})),oe&&ue&&((Z=ut.getState)==null?void 0:Z.call(ut,oe))==="connected"&&xt(),ee.current&&Y.current===null&&he(),ke(()=>{var ne;(ne=r.current)==null||ne.bumpResize()})},[oe,c,ue]),i.useEffect(()=>()=>{Y.current!==null&&xe(),ve(),te()},[]),i.useEffect(()=>{const E=ne=>{var Le;const je=ne.detail;je!=null&&je.sessionId&&je.sessionId!==ue||m&&((Le=r.current)==null||Le.bumpResize())},q=me(),Z=q===window?[window]:[window,q];for(const ne of Z)ne.addEventListener("adhdev:fit-cli-terminal",E);return()=>{for(const ne of Z)ne.removeEventListener("adhdev:fit-cli-terminal",E)}},[m,ue,r]);const G=m&&h&&!N&&(H.atTop||!H.canScroll)||g||!!y;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:K,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[G&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{W()},disabled:!ue||g,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:g?"Loading older...":"Load older terminal output"}),y&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:y})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[k&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:k}),s.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:()=>{Ge()},disabled:!m,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>w(E=>!E),disabled:!m,"aria-label":"Open terminal control keys","aria-expanded":j,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),j&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":"Terminal control keys",className:"absolute right-0 top-10 w-56 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>w(!1),"aria-label":"Close terminal control keys",children:"×"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt("\x1B"),children:"Esc"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt(" "),children:"Tab"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt("\r"),children:"Enter"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt("\x1B[A"),"aria-label":"Arrow up",children:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt("\x1B[D"),"aria-label":"Arrow left",children:"←"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt("\x1B[B"),"aria-label":"Arrow down",children:"↓"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt("\x1B[C"),"aria-label":"Arrow right",children:"→"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt(""),children:"Ctrl-C"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt(""),children:"Ctrl-D"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt(""),children:"Bksp"})]})]})]}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{D.current=!0,I(E=>{const q=Math.max(Ue,Number((E-.1).toFixed(2)));return q>Ue&&De(),q})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{D.current=!0,I(E=>{const q=Math.min(Ae,Number((E+.1).toFixed(2)));return q>Ue&&De(),q})},title:"Increase terminal viewport",children:"+"})]}),s.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:s.jsx("div",{style:{width:Se>0?`${Se}px`:"100%",height:Me>0?`${Me}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:T.width>0?`${T.width}px`:"100%",height:T.height>0?`${T.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:M},children:s.jsx(wc,{ref:r,readOnly:!m||!c,sizingMode:"measured",onViewportMetrics:F,onScrollMetrics:L,onInput:E=>{!m||(d==null||d(oe,ue,E))}})})})}),!m&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:x})]}),s.jsx(Rc,{contextKey:e.tabKey,panelLabel:lt(e),isSending:a,isBusy:!!Q,statusMessage:fe,onSend:async E=>Q?!1:n(E),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const jp=5e3,kp=12e3;function Sp(e){return e==="disconnected"||e==="reconnecting"}function Np({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=jp,reconnectActionDelayMs:o=kp}){const c=Sp(e),[l,d]=i.useState(()=>!c||a<=0),[m,u]=i.useState(()=>!c||o<=0),f=i.useRef(!1);i.useEffect(()=>{if(!c){d(!1);return}if(f.current=!1,a<=0){f.current=!0,d(!0);return}d(!1);const v=setTimeout(()=>{f.current=!0,d(!0)},a);return()=>clearTimeout(v)},[a,c]),i.useEffect(()=>{if(!c){u(!1);return}if(o<=0){u(!0);return}u(!1);const v=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(v)},[o,c]);const x=c?l:e==="offline"||e==="auth_failed",S=!!(n&&e!=="auth_failed"&&(!c||m)),g=i.useMemo(()=>!t||e!=="connected"?!1:a<=0||f.current,[a,t,e]),p=e==="auth_failed"?"red":e==="offline"?"orange":"accent",y={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))"},b={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},h={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},C="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",N={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[x&&s.jsx("div",{className:C,style:N,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:y[p],border:b[p],color:h[p]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&"Network offline",e==="disconnected"&&"Reconnecting",e==="reconnecting"&&"Reconnecting",e==="auth_failed"&&(r?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),S&&s.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>n==null?void 0:n(),disabled:e==="offline",children:"Reconnect now"})]})}),g&&s.jsx("div",{className:C,style:N,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function Cp({terminalBackend:e,isStandalone:t=!1,machineLabel:r,machineKey:n}){const a=i.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[o,c]=i.useState(!1);if(i.useEffect(()=>{if(!a){c(!1);return}try{c(localStorage.getItem(a)==="1")}catch{c(!1)}},[a]),!t||!e||e.backend!=="xterm"||o)return null;const l=(r==null?void 0:r.trim())||"This machine",d=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}c(!0)};return s.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[s.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[s.jsxs("span",{children:[l," is using `xterm` fallback."]}),s.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),s.jsx("button",{type:"button",onClick:d,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function uo({mode:e,onChange:t,compact:r=!1}){const n=r?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?s.jsx(Xa,{size:n}):s.jsx(zt,{size:n})})}const Bt="New session",sl="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 Tp(e){if(!e||e.isGitRepo===!1||e.reason==="not_git_repo")return null;if(e.hasConflicts)return`${e.branch||"Git"} · conflicts${e.changedFiles>0?` ${e.changedFiles}`:""}`;const t=[e.branch||"Git"];return e.changedFiles>0&&t.push(`±${e.changedFiles}`),e.ahead>0&&t.push(`↑${e.ahead}`),e.behind>0&&t.push(`↓${e.behind}`),t.length===1&&e.dirty&&t.push("dirty"),t.join(" ")}function Mp(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 Ip(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 Ds({git:e,className:t="",compact:r=!1}){const n=Tp(e),a=Mp(e);if(!n||!a)return null;const o=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return s.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${Ip(a)} ${t}`.trim(),title:o.join(" · ")||n,"data-git-tone":a,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:n})]})}function Ap({wsStatus:e,isConnected:t,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),o=a.filter(l=>l==="connected").length,c=a.filter(l=>l==="connecting"||l==="new"||l==="checking").length;return r>0&&c>0&&o===0?{tone:"limited",title:"Connected to dashboard",subtitle:"Connecting to machine..."}:t?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function ui({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function mi({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const c=gn(e.updatedAt),l=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),o()},children:"Delete"})]})]})}function Rp({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:f,onShowAllHidden:x,onResetPanelsToMain:S,inboxOpen:g,onInboxOpenChange:p,hiddenOpen:y,onHiddenOpenChange:b,onOpenNewSession:h,onOpenDashboardGuide:C,guideNudgeVisible:N=!1,actionShortcuts:v,notifications:M,notificationUnreadCount:I,onOpenNotification:j,onMarkNotificationRead:w,onMarkNotificationUnread:$,onDeleteNotification:P,onOpenGitDialog:T}){const{ides:F,p2pStates:H={}}=Zt(),L=!!e&&tt(e)&&!Ze(e),k=!!e&&Ze(e),A=l||(e?Lc(e)?"terminal":"chat":null),[K,_]=i.useState(!1),D=i.useRef(null),O=i.useRef(null),X=F.filter(re=>re.type==="adhdev-daemon"),ge=Ap({wsStatus:t,isConnected:r,daemonCount:X.length,p2pStates:H}),ce=ge.subtitle,ee=ge.tone==="connected"?"#22c55e":ge.tone==="limited"?"#eab308":"#ef4444",z=ge.tone==="connected"?"0 0 4px #22c55e80":ge.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",de=i.useMemo(()=>M.filter(re=>!re.readAt),[M]),pe=i.useMemo(()=>M.filter(re=>!!re.readAt),[M]),Y=i.useMemo(()=>de.slice(0,9),[de]),ie=I;i.useEffect(()=>{if(!g)return;const re=me=>{var ke;(ke=D.current)!=null&&ke.contains(me.target)||p(!1)};return document.addEventListener("mousedown",re),()=>document.removeEventListener("mousedown",re)},[g,p]),i.useEffect(()=>{if(!y)return;const re=me=>{var ke;(ke=O.current)!=null&&ke.contains(me.target)||b(!1)};return document.addEventListener("mousedown",re),()=>document.removeEventListener("mousedown",re)},[y,b]),i.useEffect(()=>{if(!y&&!g)return;const re=me=>{if(!me.altKey)return;const ke=me.code.match(/^Digit([1-9])$/);if(!ke)return;const xe=Number(ke[1])-1,ve=y?u[xe]:void 0,te=g?Y[xe]:void 0;if(!(!ve&&!te)){if(me.preventDefault(),me.stopPropagation(),ve){f==null||f(ve),b(!1);return}te&&(j(te),p(!1))}};return window.addEventListener("keydown",re,!0),()=>window.removeEventListener("keydown",re,!0)},[u,y,g,Y,b,p,j,f]);const ye=re=>{if(!re)return;const me=n.find(ke=>ke.tabKey===re);me&&(m==null||m(me))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(zt,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?lt(e):"Dashboard"}),s.jsx("span",{title:ge.title,"aria-label":ge.title,className:"header-title-status-dot",style:{background:ee,boxShadow:z}}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:ee,boxShadow:z}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[ce&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ce]}),h&&s.jsx("button",{type:"button",onClick:h,className:"btn btn-secondary btn-sm ml-2",title:`${Bt}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":Bt,children:s.jsx(xc,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[C&&s.jsxs("button",{type:"button",onClick:C,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:"Dashboard guide","aria-label":"Open dashboard guide",children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),N&&s.jsx("span",{children:"Guide"})]}),e&&(L||k||!Ze(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:xs(e)||lt(e),children:lt(e)}),T&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:()=>T(e.daemonId,e.workspacePath),children:s.jsx(Ds,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Ds,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(L||k)&&c&&s.jsxs(s.Fragment,{children:[L&&d&&A&&s.jsx(uo,{mode:A,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:k?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(vt,{size:14})})]}),!Ze(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(qa,{size:14})}),!L&&!Ze(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Mt,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:D,children:[s.jsxs("div",{className:`dashboard-header-hidden${K?" is-drop-target":""}`,ref:O,onDragEnter:re=>{re.dataTransfer.types.includes("text/tab-key")&&(re.preventDefault(),_(!0))},onDragOver:re=>{re.dataTransfer.types.includes("text/tab-key")&&(re.preventDefault(),re.dataTransfer.dropEffect="move",_(!0))},onDragLeave:re=>{re.currentTarget.contains(re.relatedTarget)||_(!1)},onDrop:re=>{const me=re.dataTransfer.getData("text/tab-key");re.preventDefault(),_(!1),ye(me)},children:[s.jsxs("button",{type:"button",onClick:()=>b(!y),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(Ya,{size:16}),u.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),y&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),s.jsx(ui,{value:v==null?void 0:v.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[S&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:S,children:"Reset panels"}),u.length>0&&x&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{x(),b(!1)},children:"Restore all"})]})]}),e&&m&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),s.jsx(ui,{value:v==null?void 0:v.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:lt(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(re=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{f==null||f(re),b(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:lt(re)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(re)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(re)+1]}):null,xs(re)]})]},re.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!g),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(bn,{size:16}),ie>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ie})]}),g&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[de.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),de.map(re=>s.jsx(mi,{notification:re,shortcutIndex:Y.indexOf(re)>=0?Y.indexOf(re)+1:void 0,onOpen:()=>j(re),onMarkRead:()=>w(re.id),onMarkUnread:()=>$(re.id),onDelete:()=>P(re.id)},re.id))]}),pe.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),pe.map(re=>s.jsx(mi,{notification:re,onOpen:()=>j(re),onMarkRead:()=>w(re.id),onMarkUnread:()=>$(re.id),onDelete:()=>P(re.id)},re.id))]}),M.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function wt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Lp(e,t){return String(e||"")!==String(t||"")}function Pp(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.resumableOnly;return!r&&!n&&!a&&!o?e:e.filter(c=>!(o&&!c.canResume||r&&![c.title,c.preview].map(d=>String(d||"").toLowerCase()).join(`
|
|
39
|
+
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!Cc(c.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
40
|
+
`).includes(a)))}function _p(e,t="recent"){const r=e.slice();return r.sort((n,a)=>{if(t==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const o=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(o!==0)return o}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function rl(e,t={}){return _p(Pp(e,t),t.sortMode||"recent")}function ln(e){return e?"Resume saved history":"Start fresh"}function mo(e){return e?"Resuming saved history…":"Starting fresh…"}function Dp(){return"Start fresh"}function nl(e,t=!1){return e==="cli"?ln(t):e==="ide"?"Start IDE":"Start ACP session"}function al(e,t=!1){return e==="cli"?mo(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Ep(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function $p(){return"Open saved history"}function Bp(){return"Saved History"}function fo(){return"Use saved history when you want continuity in the same provider conversation."}function Wp(){return"No saved history found yet."}function Kp(){return"Refresh saved history"}function Op(){return"Refreshing saved history…"}function is(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function cs(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 Es(e){return e==="start-fresh"?"Start fresh":"Restart"}function $s(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function po(e){return`Resume saved history with ${e}?`}function ho(){return"Review or change the target workspace before resuming saved history."}function Fp(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 xo({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:m,onClose:u,onNewChat:f,onSwitchSession:x,onRefreshHistory:S,onResumeSavedSession:g}){var P;const p=t.find(T=>T.id===e.routeId),y=(p==null?void 0:p.chats)||[],b=(P=p==null?void 0:p.activeChat)==null?void 0:P.id,h=tt(e)&&!Ze(e),[C,N]=i.useState(()=>wt()),v=l||C,M=String(d||"").trim(),I=T=>{if(m){m(T);return}N(T)},j=i.useMemo(()=>a.map(T=>{const F=String(T.workspace||"").trim();return T.canResume||F||!M?T:{...T,workspace:M,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[M,a]),w=i.useMemo(()=>rl(j,{textQuery:v.textQuery,workspaceQuery:v.workspaceQuery,modelQuery:v.modelQuery,resumableOnly:v.resumableOnly,sortMode:v.sortMode}),[j,v.modelQuery,v.resumableOnly,v.sortMode,v.textQuery,v.workspaceQuery]),$=s.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:h?Bp():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:yp(e)}),h&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:fo()})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!h&&s.jsx("button",{onClick:f,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),h?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:v.textQuery,onChange:T=>I({...v,textQuery:T.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:v.workspaceQuery,onChange:T=>I({...v,workspaceQuery:T.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:v.modelQuery,onChange:T=>I({...v,modelQuery:T.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:v.sortMode,onChange:T=>I({...v,sortMode:T.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:v.resumableOnly,onChange:T=>I({...v,resumableOnly:T.target.checked})}),"Resume-ready only"]})]}),w.map(T=>{const F=e.providerSessionId===T.providerSessionId,H=F||!T.canResume||!!c,L=T.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{H||!g||g(T)},disabled:H,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"} ${H?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${F?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:T.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Fp(T.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:T.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[T.workspace||"Workspace unknown",L?" · selected workspace":"",hs(T.summaryMetadata)?` · ${hs(T.summaryMetadata)}`:"",T.messageCount>0?` · ${T.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:F?"ACTIVE":T.canResume?L?"RESUME IN SELECTED WORKSPACE":c===T.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},T.id)})]}):y.map(T=>s.jsxs("div",{onClick:()=>{x(e.routeId,T.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===T.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${b===T.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[T.id.substring(0,12),"..."]}),b===T.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},T.id)),(h&&!o&&w.length===0||!h&&y.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Cu,{size:32})}),s.jsx("div",{className:"text-[13px]",children:h?a.length>0?"No saved history matches these filters.":Wp():"No recent chat sessions found."})]}),h&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Op()})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:S,disabled:n||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||o?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(fr,{size:13})," ",h?Kp():"Refresh History"]})})})]})]});return typeof document>"u"?$:cr.createPortal($,document.body)}const fi={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 ol({toasts:e,onDismiss:t,onClickToast:r}){return s.jsx("div",{className:"fixed right-4 z-[9999] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const a=fi[n.type]||fi.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var o;(o=n.actions)!=null&&o.length||r&&r(n)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:o=>{o.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(vt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((o,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${o.variant==="primary"||o.variant==="danger",""}`,style:o.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:o.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:l=>{l.stopPropagation(),o.onClick(),t(n.id)},children:o.label},c))})]})]},n.id)})})}const Hp=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Up(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function zp(e){return e.sessionId||e.instanceId||e.agentType}function On(e,t){return e||t}function il(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Tt(r,{fallbackId:r.id}));return t}function cl(e,t={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=t.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:t.connectionStates?t.connectionStates[r]||t.defaultConnectionState||"new":t.defaultConnectionState}}function bo(e,t={}){return Vp(e,cl(e,t))}function Vp(e,t={}){var f,x,S,g,p;const r=[],n=t.machineName,a=t.connectionState,o=Up(e),c=e.workspace||"",l=wm(e.type,{agentName:e.cliName}),d=tt(e)||Ze(e)?l:it(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(y=>{var b,h;return{sessionId:y.id,instanceId:y.id,providerSessionId:y.providerSessionId,transport:y.transport,sessionCapabilities:y.capabilities,agentType:y.providerType,agentName:y.providerName||it(y.providerType),status:y.status,title:y.title,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,messages:((b=y.activeChat)==null?void 0:b.messages)||[],activeModal:((h=y.activeChat)==null?void 0:h.activeModal)||void 0,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,surfaceHidden:y.surfaceHidden,git:y.git,settings:y.settings}}):[],u=Hp(e);if(u){const y=e.sessionId||e.instanceId,b=(f=e.settings)==null?void 0:f.meshCoordinatorFor,h=(x=e.settings)==null?void 0:x.meshNodeFor,C=b?" (Coordinator)":h?" (Mesh Node)":"",N=l+C,v=(S=e.activeChat)==null?void 0:S.activeModal,M=v&&Array.isArray(v.buttons)&&v.buttons.length>0,I=jm(e.activeChat,[{status:e.status,activeModal:(g=e.activeChat)==null?void 0:g.activeModal}],e.agents||[]),j=e.activeChat||{title:"",messages:[]};let w=j.title&&String(j.title).trim()?String(j.title).trim():"";const $=(p=e.activeChat)==null?void 0:p.id,P=e.chats;if($&&Array.isArray(P)&&P.length>0){const L=P.find(k=>k.id===$||k.id&&String(k.id)===String($));L!=null&&L.title&&String(L.title).trim()&&(w=String(L.title).trim())}const T=(tt(e)||Ze(e),e.type),F=(tt(e)||Ze(e))&&Qo(w,N,T)?"":w,H=j.messages||[];r.push({routeId:e.id,sessionId:y,providerSessionId:e.providerSessionId,nativeSessionId:y,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:tt(e)?e.mode||"terminal":"chat",agentName:N,agentType:T,status:I,title:F,messages:H,resume:e.resume,hostIdeType:!tt(e)&&!Ze(e)?e.type:void 0,workspaceName:o,workspacePath:c,git:e.git,displayPrimary:F||o||(tt(e)?e.mode==="chat"?N:`Terminal${C}`:N),displaySecondary:tt(e)&&o?N: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:M?v.buttons:void 0,modalMessage:M?v.message:void 0,streamSource:"native",tabKey:On(y,e.id),machineName:n,connectionState:a,settings:e.settings})}if(u&&(tt(e)||Ze(e)))return r;for(const y of m){const b=y.activeModal&&Array.isArray(y.activeModal.buttons)&&y.activeModal.buttons.length>0,h=km(y),C=zp(y),N=`${e.id}:${C}`,v=y.title&&String(y.title).trim()||"",M=Qo(v,y.agentName,y.agentType)?"":v,I=y.messages||[];(y.transport==="cdp-webview"||y.sessionId||y.providerSessionId||I.length>0||b||M||!["idle","panel_hidden","disconnected","not_monitored"].includes(h))&&r.push({routeId:e.id,sessionId:y.sessionId||y.instanceId,providerSessionId:y.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:y.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:y.sessionCapabilities,mode:"chat",agentName:y.agentName,agentType:y.agentType,status:h,title:M,messages:I,hostIdeType:e.type,workspaceName:o,workspacePath:c,git:y.git||e.git,displayPrimary:M||o||y.agentName||d,displaySecondary:`${d} · ${y.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,lastUpdated:y.lastUpdated||e.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,modalButtons:b?y.activeModal.buttons:void 0,modalMessage:b?y.activeModal.message:void 0,streamSource:"agent-stream",tabKey:On(y.sessionId||y.instanceId,N),machineName:n,connectionState:a,settings:y.settings})}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:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:c,git:e.git,displayPrimary:o||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:On(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings}),r}function ll(e){return String(e.type||e.id||"").trim()}function Gp(e){var t;return e.category!=="cli"||!ll(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function qp(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!Gp(a))continue;const o=ll(a);if(!o||t.has(o))continue;t.add(o);const c=String(a.displayName||a.name||o),l=a.detectedPath||((n=a.lastDetection)==null?void 0:n.path)||null;r.push({type:o,label:c,icon:a.icon,statusLabel:l?`Detected at ${l}`:"Detected on this machine",detectedPath:l})}return r}function kn(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],r=new Set,n=[];for(const a of t){const o=typeof a=="string"?a.trim():"";!o||r.has(o)||(r.add(o),n.push(o))}return n}function La(e,t){const r=new Set(t.map(n=>n.type));return kn(e).filter(n=>r.has(n))}function Yp(e){return e.map(t=>t.type)}function Xp(e,t){const r=kn(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function Jp(e,t){return kn(e).filter(r=>r!==t)}function pi(e,t,r){const n=kn(e),a=n.indexOf(t);if(a<0)return n;const o=n.filter(l=>l!==t);if(r==="top")return[t,...o];if(r==="bottom")return[...o,t];const c=r==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(c,0,t),o}function hi({direction:e}){return s.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="up"?s.jsx("polyline",{points:"18 15 12 9 6 15"}):s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function xi({value:e,availableProviders:t,onChange:r,disabled:n=!1,saveButton:a}){const[o,c]=i.useState(""),l=i.useMemo(()=>new Map(t.map(x=>[x.type,x])),[t]),d=i.useMemo(()=>La(e,t),[e,t]),m=e.length-d.length,u=t.filter(x=>!d.includes(x.type)),f=()=>{o&&(r(Xp(d,o)),c(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:d.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):d.map((x,S)=>{const g=l.get(x);return s.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border-subtle bg-bg-primary px-3 py-2 sm:flex-row sm:items-center sm:justify-between",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",S+1]}),(g==null?void 0:g.icon)&&s.jsx("span",{"aria-hidden":"true",children:g.icon}),s.jsx("span",{className:"font-mono text-[12px] text-text-primary",children:x}),s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:"available"})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:g?`${g.label} · ${g.statusLabel}`:x})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:n||S===0,title:"Move up",onClick:()=>r(pi(d,x,"up")),children:s.jsx(hi,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:n||S===d.length-1,title:"Move down",onClick:()=>r(pi(d,x,"down")),children:s.jsx(hi,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(Jp(d,x)),children:"Remove"})]})]},x)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:"Add available CLI provider"}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:o,onChange:x=>c(x.target.value),disabled:n||u.length===0,children:[s.jsx("option",{value:"",children:u.length?"Select provider…":"No additional detected CLI providers"}),u.map(x=>s.jsxs("option",{value:x.type,children:[x.label," (",x.type,")"]},x.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!o,onClick:f,children:"Add provider"}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Inventory is filtered to CLI providers detected on this machine. New launches use this order; existing running sessions may need restart.",m>0?` ${m} provider${m===1?"":"s"} from the saved policy are not detected now and will be omitted when saved.`:""]})]})}function Qp(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function dl(e,t){const r=Qp(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const ul=[{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:"🏄"}],ml=[{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:"🧩"}],fl=[{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:"🟠"}],Zp=ul,eh=ml,th=fl;function Vt(...e){return Wd(Kd(e))}function sh({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:Vt("dashboard-header",o),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function nr({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:o="max-w-6xl",contentClassName:c,children:l}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(sh,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Vt("mx-auto flex w-full flex-col gap-4",o,c),children:l})})]})}const Pa="adhdev:themechange";function rh(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function js(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function ks(e){return e==="system"?rh():e}function pl(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Ur(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Pa,{detail:{preference:e,theme:t}}))}function nh(){const e=js(),t=ks(e);pl(t),Ur(e,t)}function go(){const[e,t]=i.useState(js),[r,n]=i.useState(()=>ks(js()));i.useEffect(()=>{pl(r)},[r]),i.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=d=>{if(e==="system"){const m=d.matches?"light":"dark";n(m),Ur("system",m)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),i.useEffect(()=>{const c=d=>{const m=d.detail||{},u=m.preference,f=m.theme;t(u==="dark"||u==="light"||u==="system"?u:js()),n(f==="dark"||f==="light"?f:ks(js()))},l=d=>{if(d.key!=="theme")return;const m=js(),u=ks(m);t(m),n(u)};return window.addEventListener(Pa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(Pa,c),window.removeEventListener("storage",l)}},[]);const a=i.useCallback(c=>{const l=ks(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Ur(c,l)},[]),o=i.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",d=ks(l);n(d);try{localStorage.setItem("theme",l)}catch{}return Ur(l,d),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const bi={dark:"Dark",light:"Light",system:"System"};function ah({collapsed:e}){const{preference:t,cycleTheme:r}=go(),n=t==="dark"?s.jsx(Mu,{size:16}):t==="light"?s.jsx(Tu,{size:16}):s.jsx(Iu,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${bi[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:bi[t]})]})}function Fn(e,t){return e?typeof e=="function"?e(t):e:null}function oh({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:c,preMainContent:l,collapsedStorageKey:d="sidebar-collapsed"}){const[m,u]=i.useState(!1),[f,x]=i.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),S=()=>u(!0),g=()=>u(!1),p=()=>{x(C=>{const N=!C;try{localStorage.setItem(d,N?"1":"0")}catch{}return N})},y=i.useMemo(()=>({collapsed:f,mobileMenuOpen:m,openMobileMenu:S,closeMobileMenu:g,toggleCollapsed:p}),[f,m]),b=C=>`nav-item${C.active?" active":""} cursor-pointer ${f?"justify-center py-2.5 px-0":""}${C.className?` ${C.className}`:""}`,h=C=>s.jsxs("div",{className:b(C),id:`nav-${C.id}`,onClick:()=>{C.onSelect(),g()},title:f?C.title??(typeof C.label=="string"?C.label:void 0):C.title,children:[s.jsx("span",{className:"nav-icon",children:C.icon}),!f&&C.label]},C.id);return s.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${f?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:S,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),m&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:g,onKeyDown:C=>C.key==="Escape"&&g()}),s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${f?"justify-center gap-0":""}`,children:Fn(t,y)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:g,children:s.jsx(vt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(h)}),n.map(C=>s.jsxs("div",{className:C.className??"border-t border-border-subtle pt-2 mt-2",children:[!f&&C.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:C.title}):null,C.items.map(h)]},C.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(h),Fn(o,y),s.jsx(ah,{collapsed:f}),Fn(c,y)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function jt({title:e,icon:t,description:r,accentColor:n,className:a,children:o}){return s.jsxs("div",{className:Vt("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&s.jsxs("div",{className:"mb-4",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[t&&s.jsx("span",{className:"mr-1.5",children:t}),e]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),o]})}function dn({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:Vt("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const ih={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"},ch={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Cs({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:Vt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",ih[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:ch[e]}),s.jsx("span",{children:t})]}),r&&s.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function It({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:Vt("mb-5",n),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),r,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function Hn(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:Vt("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const lh={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"},dh={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function uh({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:Vt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",lh[e],r),children:[s.jsx("span",{className:Vt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",dh[e])}),n]})}function ss({label:e,description:t,checked:r,disabled:n,onChange:a,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o,s.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function mh({onPrefChange:e}){const[t,r]=Pm(),[n,a]=i.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);i.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const o=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(ss,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(bn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:c=>o("globalEnabled",c)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(ss,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Mt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:c=>o("browserNotifications",c)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{Ic().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(ss,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Au,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>o("completionAlert",c)}),s.jsx(ss,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ru,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>o("approvalAlert",c)}),s.jsx(ss,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ls,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:c=>o("disconnectAlert",c)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function un(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function fh(e,t){const r=un(e),n=un(t);if(!r||!n)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function hl(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function ar(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||fh(r,t)>=0)return!1;const n=un(r),a=un(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function ph(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Un(e,t){return e instanceof Error?e.message:t}function hh({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const o=e.filter(c=>c.type==="adhdev-daemon");return o.length===0?s.jsx(dn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:t||"Install ADHDev on a machine and sign in to connect it here."}):s.jsx("div",{className:"flex flex-col gap-2",children:o.map(c=>s.jsx(bh,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function gi({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:o}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return cr.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:l=>l.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,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 xh(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Zp,...eh,...th].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function bh({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var H,L;const[o,c]=i.useState("idle"),[l,d]=i.useState(""),[m,u]=i.useState(null),[f,x]=i.useState("idle"),[S,g]=i.useState(""),p=e.version||null,y=((H=e.machine)==null?void 0:H.platform)||((L=e.system)==null?void 0:L.platform)||"",b=Tt(e,{fallbackId:e.id}),h=y==="win32"?"🪟":y==="darwin"?"🍎":"🐧",C=t.filter(k=>k.daemonId===e.id&&k.transport==="cdp-page"),N=t.filter(k=>k.daemonId===e.id&&k.transport==="pty"),v=t.filter(k=>k.daemonId===e.id&&k.transport==="acp"),M=e.p2p,I=async()=>{if(r){c("upgrading"),d("Starting upgrade...");try{const k=ph(await r(e.id,"daemon_upgrade",{}));k.alreadyLatest?(c("done"),d(`Already on v${k.version||"latest"}.`)):k.upgraded||k.success?(c("done"),d(`Upgrade to v${k.version||"latest"} started. Daemon is restarting...`)):(c("error"),d(k.error||"Upgrade failed"))}catch(k){c("error"),d(Un(k,"Connection lost during upgrade"))}}},j=async()=>{if(u(null),!!n){x("loading");try{await n(e.id),x("done"),g("Machine disconnected.")}catch(k){x("error"),g(Un(k,"Failed to disconnect"))}}},w=async()=>{if(u(null),!!a){x("loading");try{await a(e.id),x("done"),g("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(k){x("error"),g(Un(k,"Failed to revoke token"))}}},$="0.9.75",P=hl(e,$),T=ar(e,$),F=C.length+N.length+v.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:h}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:b}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),p&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${P?"":"bg-bg-secondary"}`,style:P?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!P&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&P&&s.jsx("button",{onClick:I,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${$}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${T?"↑ Update now":`↑ Update${` to v${$}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(uh,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[M&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${M.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${M.state==="connecting"||M.state==="new"?"animate-pulse":""}`,style:M.state==="connecting"||M.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",M.state==="connected"?"connected":M.state==="connecting"||M.state==="new"?"connecting...":M.state||"off"]}),M.peers!==void 0&&M.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",M.peers," peer",M.peers!==1?"s":"",")"]})]}),M&&F>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),F>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[C.map(k=>{const A=xh(k.type),K=k.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:A.icon}),s.jsx("span",{children:A.name}),K!==void 0&&s.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..."})]},k.id)}),N.map(k=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:k.cliName||"CLI"})]},k.id)),v.map(k=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:k.cliName||"ACP"})]},k.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||S)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||f==="error"?"text-red-400":o==="done"||f==="done"?"text-green-400":"text-text-muted"}`,children:S||l})]}),m==="disconnect"&&s.jsx(gi,{title:"🔌 Disconnect Machine",message:`Disconnect "${b}" from ADHDev?
|
|
41
|
+
|
|
42
|
+
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
43
|
+
|
|
44
|
+
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:j,onCancel:()=>u(null)}),m==="revoke"&&s.jsx(gi,{title:"⚠️ Remove Machine",message:`Remove "${b}" from your dashboard?
|
|
45
|
+
|
|
46
|
+
This will:
|
|
47
|
+
• Immediately disconnect the machine
|
|
48
|
+
• Delete the machine registration
|
|
49
|
+
• Require restarting ADHDev on that machine
|
|
50
|
+
|
|
51
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:w,onCancel:()=>u(null)})]})}const gh=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function yh(){const{preference:e,setPreference:t}=go();return s.jsx("div",{className:"flex gap-2",children:gh.map(r=>s.jsxs("button",{onClick:()=>t(r.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx("span",{children:r.icon}),r.label]},r.id))})}function vh(e){const t=e.trim();return/^#[0-9a-fA-F]{6}$/.test(t)?t:/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:null}function wh(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function zn(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function yi(e){const{r:t,g:r,b:n}=wh(e);return .2126*zn(t)+.7152*zn(r)+.0722*zn(n)}function vi(e,t){const r=yi(e),n=yi(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function xl(e){const t=vh(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return vi(t,r)>=vi(t,n)?r:n}const _a={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},Da={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},jh=[{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"}}}],bl="adhdev-chat-theme",gl="adhdev-chat-theme-custom";function zr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(bl)||"ember"}catch{return"ember"}}function Dt(e){try{const t=localStorage.getItem(gl);if(t){const r=JSON.parse(t);return{...e==="dark"?_a:Da,...r[e]}}}catch{}return e==="dark"?_a:Da}function Rr(e,t){try{localStorage.setItem(gl,JSON.stringify({dark:e,light:t}))}catch{}}function At(e,t){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${t})`}function mn(e,t){const r=Math.min(255,parseInt(e.slice(1,3),16)+t),n=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const kh={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function or(e,t){var a;const r=(a=kh[e])==null?void 0:a[t];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",mn(r,24)),n.style.setProperty("--accent-on-primary",xl(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${mn(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 ls(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",At(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",At(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",At(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",At(e.borderSubtle,.5)),t.style.setProperty("--border-default",At(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",mn(e.accentColor,30)),t.style.setProperty("--accent-on-primary",xl(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${mn(e.accentColor,40)})`),t.style.setProperty("--border-accent",At(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",At(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${At(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${At(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function yo(){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 Sh(e){try{localStorage.setItem(bl,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ds()?"dark":"light";ls(Dt(t))}else yo(),or(e,ds()?"dark":"light")}function Nh(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=zr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ds()?"dark":"light";ls(Dt(t))}else yo(),or(e,ds()?"dark":"light")}function ds(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function kt({label:e,value:t,onChange:r}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function qs({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function Ch({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=i.useState(()=>Dt(r));i.useEffect(()=>{a(Dt(r))},[r]);const o=i.useCallback((c,l)=>{a(d=>{const m={...d,[c]:l},f=Dt(r==="dark"?"light":"dark");return r==="dark"?Rr(m,f):Rr(f,m),ls(m),t(m),m})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",s.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(qs,{title:"App Background",children:[s.jsx(kt,{label:"Background",value:n.bgPrimary,onChange:c=>o("bgPrimary",c)}),s.jsx(kt,{label:"Surface",value:n.bgSecondary,onChange:c=>o("bgSecondary",c)}),s.jsx(kt,{label:"Card",value:n.surfacePrimary,onChange:c=>o("surfacePrimary",c)})]}),s.jsxs(qs,{title:"App Text",children:[s.jsx(kt,{label:"Primary",value:n.textPrimary,onChange:c=>o("textPrimary",c)}),s.jsx(kt,{label:"Secondary",value:n.textSecondary,onChange:c=>o("textSecondary",c)}),s.jsx(kt,{label:"Muted",value:n.textMuted,onChange:c=>o("textMuted",c)})]}),s.jsxs(qs,{title:"Borders & Accent",children:[s.jsx(kt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>o("borderSubtle",c)}),s.jsx(kt,{label:"Border default",value:n.borderDefault,onChange:c=>o("borderDefault",c)}),s.jsx(kt,{label:"Accent",value:n.accentColor,onChange:c=>o("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(qs,{title:"Chat Bubbles",children:[s.jsx(kt,{label:"User bubble",value:n.userBubble,onChange:c=>o("userBubble",c)}),s.jsx(kt,{label:"User text",value:n.userText,onChange:c=>o("userText",c)}),s.jsx(kt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>o("assistantBubble",c)}),s.jsx(kt,{label:"Agent text",value:n.assistantText,onChange:c=>o("assistantText",c)})]}),s.jsxs(qs,{title:"Chat Layout",children:[s.jsx(kt,{label:"Chat BG",value:n.containerBg,onChange:c=>o("containerBg",c)}),s.jsx(kt,{label:"Send button",value:n.sendButton,onChange:c=>o("sendButton",c)}),s.jsx(kt,{label:"Input border",value:n.inputBorder,onChange:c=>o("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:c=>o("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?_a:Da,d=Dt(e?"light":"dark");e?Rr(c,d):Rr(d,c),a(c),ls(c),t(c)},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 Th(){const[e,t]=i.useState(zr),[r,n]=i.useState(!0),[a,o]=i.useState(()=>Dt("dark"));i.useEffect(()=>{n(ds());const d=new MutationObserver(()=>{const f=ds();n(f);const x=zr();x==="custom"?ls(Dt(f?"dark":"light")):or(x,f?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const f=ds();n(f);const x=zr();x==="custom"?ls(Dt(f?"dark":"light")):or(x,f?"dark":"light")};return m.addEventListener("change",u),()=>{d.disconnect(),m.removeEventListener("change",u)}},[]),i.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ls(Dt(r?"dark":"light")):(yo(),or(e,r?"dark":"light"))},[e,r]),i.useEffect(()=>{o(Dt(r?"dark":"light"))},[r]);const c=d=>{t(d),Sh(d)},l=[...jh,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(d=>{const m=e===d.id,u=r?d.preview.dark:d.preview.light,f=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>c(d.id),className:"text-left rounded-xl p-3 transition-all",style:{background:m?"var(--bg-glass-hover)":"var(--bg-glass)",border:m?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:m?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:u.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:f},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[m&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:d.id==="custom"?"🎨 Custom":d.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:d.description})]})]})]},d.id)})}),e==="custom"&&s.jsx(Ch,{dark:r,onColorsChange:d=>o(d)})]})}const vo="adhdev_mobileDashboardMode_v1",Ea="adhdev:mobile-dashboard-mode-change";function wo(){try{return localStorage.getItem(vo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Mh(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??wo())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==vo||t()};return window.addEventListener(Ea,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Ea,r),window.removeEventListener("storage",n)}}function Ih(e){try{localStorage.setItem(vo,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ea,{detail:e}))}function Ah(){const[e,t]=i.useState(!0);return i.useEffect(()=>{t(wo()==="chat")},[]),s.jsx(ss,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(zt,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{t(r),Ih(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Vn=new Map,wi=new Map;function Rh(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t,n=r.machine;return!n||typeof n!="object"?null:{machine:n,timestamp:typeof r.timestamp=="number"?r.timestamp:void 0}}function Lh(e,t,r,n){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n,platform:r.platform,machine:r}}function yl(){const{sendCommand:e}=gt(),{injectEntries:t,getIdes:r}=lr();return i.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??Mf,c=wi.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<o)return;const l=Vn.get(n);if(l)return l;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=Rh(m);if(!u)return;const f=r().find(S=>S.id===n),x=Lh(f,n,u.machine,u.timestamp||Date.now());t([x]),wi.set(n,Date.now())})().finally(()=>{Vn.delete(n)});return Vn.set(n,d),d},[r,t,e])}function Ph(e,t,r){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r.timestamp,platform:r.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...r.machine}}}function _h(e,t){const{sendData:r}=gt(),{injectEntries:n,getIdes:a}=lr(),o=Array.from(new Set(e.filter(Boolean))).join("|");i.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const c=o?o.split("|"):[];if(c.length===0)return;const l=c.map(d=>Ut.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const f=a().find(S=>S.id===d),x=Ph(f,d,u);n([x])}));return()=>{l.forEach(d=>d())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function Dh(e,t){const{sendData:r}=gt(),[n,a]=i.useState(null),[o,c]=i.useState(!1);return i.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(t!=null&&t.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const d=Ut.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},m=>{l&&(clearTimeout(l),l=null),a(m.diagnostics),c(!1)});return d.initialSendAccepted?l=setTimeout(()=>{c(!1)},Lf):c(!1),()=>{l&&clearTimeout(l),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:o,applyDiagnostics:a}}function Eh(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function vl(e){const{sendData:t}=gt(),[r,n]=i.useState({});return i.useEffect(()=>{const a=Eh(e);if(!a||!e.sessionId||!t){n({});return}const o=Ut.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),As.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return o.initialSendAccepted||n({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const wl="adhdev_hiddenTabs";function $h(){try{const e=localStorage.getItem(wl);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function vs(e){try{localStorage.setItem(wl,JSON.stringify([...e]))}catch{}}function Gn(e){return co(e)}function jo(e,t){return Is(t).some(r=>e.has(r))}function Bh(){const[e,t]=i.useState($h),r=i.useCallback(m=>{const u=Gn(m);t(f=>{const x=new Set(f);return x.has(u)?x.delete(u):x.add(u),vs(x),x})},[]),n=i.useCallback(m=>{const u=Gn(m);t(f=>{if(f.has(u))return f;const x=new Set(f);return x.add(u),vs(x),x})},[]),a=i.useCallback(m=>{const u=Gn(m);t(f=>{if(!f.has(u))return f;const x=new Set(f);return x.delete(u),vs(x),x})},[]),o=i.useCallback(()=>{t(m=>{if(m.size===0)return m;const u=new Set;return vs(u),u})},[]),c=i.useCallback((m,u)=>{t(f=>{const x=new Set(f);for(const S of u)x.add(S);return vs(x),x})},[]),l=i.useCallback((m,u)=>{t(f=>{const x=new Set(f);for(const S of u)x.delete(S);return vs(x),x})},[]),d=i.useCallback(m=>jo(e,m),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:o,hideAllForDaemon:c,showAllForDaemon:l,isHidden:d}}function jl(e){return e instanceof Error?e.message:String(e||"")}function kl(e){const t=jl(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function Sl(e){const t=jl(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Nl({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!tt(e)||Ze(e))return;const o=Os(e);if(o===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(ys(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Kt(e),mode:t})}catch(l){const d=Sl(l);c&&!d&&a(m=>{const u={...m};return o===Cl(r,c)?delete u[c]:u[c]=o,u}),kl(l)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",l instanceof Error?l.message:String(l)):console.error("Failed to switch CLI view mode:",l)}}function ji(e,t){const r=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!r||e.transport!=="pty")return e;const n=t[r];return!n||e.mode===n?e:{...e,mode:n}}function Wh(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let r=!1;const n=e.map(a=>{const o=ji(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(d=>ji(d,t)):a.childSessions,l=c!==a.childSessions;return o!==a||l?(r=!0,{...o,...l?{childSessions:c}:{}}):a});return r?n:e}function Cl(e,t){if(!t)return null;for(const r of e){if(r.sessionId===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function Kh(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,o]of Object.entries(e))Cl(t,a)===o&&(delete n[a],r=!0);return r?n:e}function Oh({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){i.useEffect(()=>{Ic()},[]);const a=i.useMemo(()=>e.map(o=>({id:o.tabKey,name:el(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return $m(a),i.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(l=>{const d=Date.now(),m={};for(const[u,f]of Object.entries(l))d-f<5e3&&(m[u]=f);return Object.keys(m).length===Object.keys(l).length?l:m})},5500);return()=>clearTimeout(c)},[t,r]),i.useEffect(()=>{const o=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const d=l.filter(m=>m.timestamp>c).slice(-100);return d.length===l.length?l:d})},6e4);return()=>clearInterval(o)},[n]),null}function ki(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function us(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],r=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,n=ki(t==null?void 0:t.receivedAt)||ki(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function $a(e,t=0){return us(e)||e.lastUpdated||t||0}function Tl(e){return us(e)||e.lastUpdated||0}function Ml(e,t,r=Tl){const n=r(t)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const o=e.displayPrimary.localeCompare(t.displayPrimary);if(o!==0)return o;const c=e.displaySecondary.localeCompare(t.displaySecondary);return c!==0?c:e.tabKey.localeCompare(t.tabKey)}function Ba(e){var r;const t=bt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function Fh(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Ba(e)&&!e.title.trim()}function Hh(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(Ba(r))-Number(Ba(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:Ml(t,r)})[0]||null}function Et(e,t){const r=e.filter(c=>c.routeId===t);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,a=r.filter(c=>c.streamSource==="agent-stream"),o=Hh(a);return n?o&&Fh(n)?o:n:o||r[0]||null}function Uh(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=r.get(n.id);if(!a){r.set(n.id,n);continue}const o=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>o||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function qn(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function zh(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function Si(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?zh(Rs(r.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((r==null?void 0:r.id)||""),String((r==null?void 0:r.index)??""),String((r==null?void 0:r.receivedAt)??(r==null?void 0:r.timestamp)??""),n].join(":")}function Vh(e){const t=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),Si(e.activeChat),...t.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastMessageAt||""),r.lastMessagePreview||"",r.lastMessageRole||"",String(r.lastUpdated||""),Si(r.activeChat)].join(":"))].join("|")}function Gh(e,t){const r=Date.now();return e.map(n=>{const a=t[n.tabKey];return a&&r-a<5e3?{...n,messages:[],title:""}:n})}function qh(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of Is({routeId:n.routeId}))r.set(o,a);for(const o of Is({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Is({tabKey:n.tabKey}))r.set(o,n)}return r}function Yh(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Xh(e){const t=Yh(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const r=String(t.role||""),n=Rs(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Jh({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=i.useMemo(()=>Uh(e),[e]),o=i.useMemo(()=>il(e),[e]),c=i.useRef([]),l=i.useRef([]),d=i.useRef([]),m=i.useRef(new Map),u=i.useRef(new Map),f=i.useMemo(()=>{const N=new Map,v=[];for(const w of a){const{connectionState:$="new",machineName:P}=cl(w,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),T=Vh(w),F=m.current.get(w.id);if(F&&F.ide===w&&F.sourceSignature===T&&F.connectionState===$&&F.machineName===P){N.set(w.id,F),v.push(...F.conversations);continue}const H=bo(w,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),L={ide:w,sourceSignature:T,connectionState:$,machineName:P,conversations:H};N.set(w.id,L),v.push(...H)}m.current=N;const M=new Map,I=w=>{const $=Xh(w),P=u.current.get(w.tabKey);if(P&&P.signature===$)return M.set(w.tabKey,P),P.timestamp;const T={signature:$,timestamp:Tl(w)||(P==null?void 0:P.timestamp)||0};return M.set(w.tabKey,T),T.timestamp},j=[...v].sort((w,$)=>Ml(w,$,I));return u.current=M,j},[a,t,o]),x=i.useMemo(()=>{const N=Gh(f,r);return qn(c.current,N)?c.current:(c.current=N,N)},[f,r]),S=i.useMemo(()=>{const N=new Map,v=Array.from(new Set(x.map(M=>M.routeId)));for(const M of v){const I=Et(x,M);I&&N.set(M,I)}return N},[x]),g=i.useMemo(()=>{const N=new Map;for(const v of x){const M=S.get(v.routeId),I=v.streamSource==="native"&&M?M:v;for(const j of Is({providerSessionId:v.providerSessionId,sessionId:v.sessionId}))N.set(j,I)}return N},[x,S]),p=i.useMemo(()=>qh(x,S),[x,S]),y=i.useCallback(N=>{if(N)return g.get(N)},[g]),b=i.useCallback(N=>{if(N)return p.get(N)},[p]),h=i.useMemo(()=>{const N=x.filter(v=>!jo(n,v));return qn(l.current,N)?l.current:(l.current=N,N)},[x,n]),C=i.useMemo(()=>{const N=h.map(v=>v.tabKey);return qn(d.current,N)?d.current:(d.current=N,N)},[h]);return{chatIdes:a,conversations:x,visibleConversations:h,visibleTabKeys:C,resolveConversationBySessionId:y,resolveConversationByTarget:b}}function Qh({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=i.useMemo(()=>{var l;return e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),o=i.useMemo(()=>{var l;return!e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),c=i.useCallback(()=>{t&&n(l=>{const d=new URLSearchParams(l);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:c}}function Zh({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){i.useEffect(()=>{nt.setIdes(e)},[e]),i.useEffect(()=>{nt.setResolveAction((a,o,c)=>{t(a,o,c).catch(()=>{})})},[t]),i.useEffect(()=>{const a=nt.onToast(o=>{r(l=>l.some(m=>m.message===o.message&&o.timestamp-m.timestamp<3e3)?l:[...l.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const c=o.duration||5e3;setTimeout(()=>r(l=>l.filter(d=>d.id!==o.id)),c)});return()=>{a()}},[r]),i.useEffect(()=>{const a=Jc.on("status_event",o=>{nt.handleRawEvent(o,"ws")});return()=>{a()}},[]),i.useEffect(()=>{var o;const a=c=>{var p;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const d=l.targetSessionId||l.targetKey||l.daemonId,m=n(d),u=(m==null?void 0:m.routeId)||l.daemonId;if(!u)return;const f=Number(l.buttonIndex),x=l.button||((p=m==null?void 0:m.modalButtons)==null?void 0:p[f])||"Approve",S=String(x).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),g=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(S);t(u,"resolve_action",{action:g?"approve":"reject",button:x,...Number.isFinite(f)&&{buttonIndex:f},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(y=>console.error("[SW Action] approval failed:",y))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,t])}const ex="adhdev_dashboardLayout_v1",tx="adhdev_dashboardDockview_v1",sx="adhdev_dashboardDockviewHiddenRestore_v1",Ys={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function ko(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function rx(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Il(e){return`${ex}:${e}`}function nx(e){const t=Il(e);return ko(t,null)}function ax(e,t){try{const r=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,n=Il(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Al(e){return`${tx}:${e}`}function ox(e){const t=Al(e);return ko(t,null)}function ix(e,t){try{const r=Al(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Rl(e){return`${sx}:${e}`}function cx(e){const t=Rl(e);return ko(t,{})}function lx(e,t){try{const r=Rl(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function dx(){return{groupAssignments:[...Ys.groupAssignments],focusedGroup:Ys.focusedGroup,groupActiveTabIds:{...Ys.groupActiveTabIds},groupTabOrders:{...Ys.groupTabOrders},groupSizes:[...Ys.groupSizes]}}function ux(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function mx(){const[e]=i.useState(()=>rx(typeof window<"u"?window.innerWidth:1280)),[t,r]=i.useState(()=>new Map),[n,a]=i.useState(0),[o,c]=i.useState({}),[l,d]=i.useState({}),[m,u]=i.useState([]),[f,x]=i.useState(()=>typeof window<"u"&&window.innerWidth<768),[S,g]=i.useState(!1),p=i.useCallback(()=>{if(S)return;const w=nx(e)??dx();r(new Map(w.groupAssignments)),a(w.focusedGroup),c(w.groupActiveTabIds),d(w.groupTabOrders),u(w.groupSizes),g(!0)},[S,e]);i.useEffect(()=>{S&&ax(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:l,groupSizes:m})},[S,e,t,n,o,l,m]),i.useEffect(()=>{const w=window.matchMedia("(max-width: 767px)"),$=P=>x(P.matches);return w.addEventListener("change",$),()=>w.removeEventListener("change",$)},[]);const y=i.useCallback(w=>{r(w)},[]),b=i.useCallback(w=>{a(w)},[]),h=i.useCallback(w=>{c(w)},[]),C=i.useCallback(w=>{d(w)},[]),N=i.useCallback(w=>{u(w)},[]),v=i.useCallback(w=>{b(w)},[b]),M=i.useCallback((w,$)=>{c(P=>(P[w]??null)===($??null)?P:{...P,[w]:$})},[]),I=i.useCallback((w,$)=>{d(P=>{const T=P[w];return ux(T,$)?P:{...P,[w]:$}})},[]),j=i.useCallback((w,$)=>{const P=$.get(w)??0;return M(P,w),v(P),P},[v,M]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:y,focusedGroup:n,updateFocusedGroup:b,focusGroup:v,groupActiveTabIds:o,updateGroupActiveTabIds:h,setGroupActiveTab:M,groupTabOrders:l,updateGroupTabOrders:C,setGroupTabOrder:I,groupSizes:m,updateGroupSizes:N,isMobile:f,hasHydratedStoredLayout:S,hydrateStoredLayout:p,focusConversationTab:j}}function fx(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=io(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function px({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:c,setSearchParams:l,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,ides:f,handleRefreshHistory:x}){const S=i.useRef(!1),g=i.useRef(!1),p=i.useRef(null),y=i.useRef(!1);i.useEffect(()=>{if(!e||S.current||t.length===0)return;if(!a){o();return}const b=r(e);b&&(c(b.tabKey,n),S.current=!0,g.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(h=>{const C=new URLSearchParams(h);return C.delete("activeTab"),C},{replace:!0}))},[e,t,r,n,a,o,c,l]),i.useEffect(()=>{if(!(g.current||a)&&t.length!==0){if(!e){o(),g.current=!0;return}if(S.current){g.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(g.current||a)&&(o(),g.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,o]),i.useEffect(()=>{if(!d){y.current=!1;return}if(!m||y.current||u)return;const b=f.find(h=>h.id===m.routeId);b&&(!b.chats||b.chats.length===0||fx(b.chats,m))&&(y.current=!0,x())},[d,m,u,f,x])}function Yn(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=io(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Ll({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[c,l]=i.useState(!1),[d,m]=i.useState(!1),u=i.useCallback(async g=>{try{await e("standalone","launch_ide",{ideType:g,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),f=i.useCallback(async(g,p)=>{try{const y=g||(t==null?void 0:t.daemonId)||"",b=await e(y,"switch_chat",{id:p,sessionId:p,...as(t)}),h=b==null?void 0:b.result;if((b==null?void 0:b.success)===!0||h==="switched"||h==="switched-by-title")return;h===!1||h==="not_found"?zs(a,"⚠️ Session tab not found — try refreshing history"):typeof h=="string"&&h.startsWith("error:")?zs(a,`⚠️ Switch error: ${h}`):zs(a,"⚠️ Session switch failed")}catch(y){console.error("Switch failed",y),zs(a,`❌ Switch failed: ${y.message||"connection error"}`)}},[t,e,a]),x=i.useCallback(async()=>{if(!(!t||c)){l(!0);try{const g=_s(t);await e(g,"new_chat",{...as(t)}),o(p=>({...p,[t.tabKey]:Date.now()}))}catch(g){console.error("New chat failed",g)}finally{l(!1)}}},[t,c,e,o]),S=i.useCallback(async()=>{var g,p;if(!(!t||d)){m(!0);try{const y=_s(t),b=async()=>e(y,"list_chats",{forceExpand:!0,...as(t)});let h=await b(),C=(h==null?void 0:h.chats)||((g=h==null?void 0:h.result)==null?void 0:g.chats);Yn(C,t)&&(await new Promise(N=>setTimeout(N,450)),h=await b(),C=(h==null?void 0:h.chats)||((p=h==null?void 0:h.result)==null?void 0:p.chats)),h!=null&&h.success&&Array.isArray(C)&&(n(t.routeId,C),Yn(C,t)&&!Yn(r,t)&&zs(a,"⚠️ History dialog did not fully open — try once more"))}catch(y){console.error("Refresh history failed",y)}finally{m(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:f,handleNewChat:x,handleRefreshHistory:S}}function hx(e,t){if(e.size!==t.size)return!1;for(const[r,n]of e)if(t.get(r)!==n)return!1;return!0}function xx(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Ni(e,t){const r=Object.keys(e),n=Object.keys(t);return r.length!==n.length?!1:r.every(a=>t[Number(a)]===e[Number(a)])}function Lr(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const o=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const d=a[l];typeof d=="number"&&d>0&&o.set(c,d)}return{assignments:o,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function Ci(e,t){const r={};for(const[n,a]of Object.entries(e)){const o=t[Number(n)];typeof o=="number"&&(r[o]=a)}return r}function bx(e,t,r){if(t.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...t].reverse().find(a=>a<e)??t[0];return r[n]??0}function gx(e,t,r){if(t.length<=1)return[];const n=t.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===t.length?n:Array(r).fill(100/r),o=a.reduce((c,l)=>c+l,0);return o>0?a.map(c=>c/o*100):Array(r).fill(100/r)}function Ti(e,t){const r={};for(const[n,a]of Object.entries(e)){const o=Number(n);r[o>=t?o+1:o]=a}return r}function Mi(e){return Array(e).fill(100/e)}function yx({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:c,isMobile:l,visibleConversations:d,visibleTabKeys:m}){const u=i.useRef(null),f=i.useMemo(()=>Lr(e,m),[e,m]),x=f.assignments,S=i.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),g=S>1,p=i.useCallback((v,M)=>{t(I=>{const j=new Map(Lr(I,m).assignments);return M===0?j.delete(v):j.set(v,M),j}),n(I=>({...I,[M]:v})),r(M)},[t,m,n,r]),y=i.useCallback(v=>{t(M=>{const I=Lr(M,m).assignments,j=new Map;for(const[w,$]of I)$!==v&&($>v?j.set(w,$-1):j.set(w,$));return j}),c(M=>{if(M.length<=1)return[];const I=[...M];I.splice(v,1);const j=I.reduce((w,$)=>w+$,0);return j>0?I.map(w=>w/j*100):[]}),r(0)},[t,m,c,r]),b=i.useCallback((v,M)=>{M.preventDefault();const I=u.current;if(!I)return;const j=M.clientX,w=I.offsetWidth,$=o.length===S?[...o]:Mi(S),P=F=>{const L=(F.clientX-j)/w*100,k=[...$];k[v]=Math.max(15,$[v]+L),k[v+1]=Math.max(15,$[v+1]-L),c(k)},T=()=>{document.removeEventListener("mousemove",P),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",P),document.addEventListener("mouseup",T)},[o,S,c]),h=i.useCallback((v,M,I)=>{if(S>=4)return;const j=I==="left"?M:M+1;t(w=>{const $=Lr(w,m).assignments,P=new Map;for(const T of d){const F=$.get(T.tabKey)??0,H=F>=j?F+1:F;H>0&&P.set(T.tabKey,H)}return j>0&&P.set(v,j),P}),c(w=>{const $=w.length===S?[...w]:Mi(S),P=$[M]??100/S,T=Math.max(15,P/2),F=Math.max(15,P/2),H=[...$];H[M]=T,H.splice(j,0,F);const L=H.reduce((k,A)=>k+A,0);return H.map(k=>k/L*100)}),n(w=>{const $=Ti(w,j);return $[j]=v,$}),a(w=>{const $=Ti(w,j);return $[j]=[v],$}),r(j)},[S,t,m,d,c,n,a,r]);i.useEffect(()=>{hx(e,x)||t(x)},[e,x,t]),i.useEffect(()=>{const{mapping:v,usedGroups:M}=f;n(I=>{const j=Ci(I,v);return Ni(I,j)?I:j}),a(I=>{const j=Ci(I,v);return Ni(I,j)?I:j}),r(I=>{const j=l?0:bx(I,M,v);return I===j?I:j}),c(I=>{const j=l?[]:gx(I,M,f.groupCount);return xx(I,j)?I:j})},[f,l,n,a,r,c]);const C=i.useMemo(()=>{const v=Array.from({length:S},()=>[]);for(const M of d){const I=x.get(M.tabKey)??0,j=Math.min(I,S-1);v[j].push(M)}return v},[d,x,S]),N=i.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:x,numGroups:S,isSplitMode:g,groupedConvs:C,moveTabToGroup:p,closeGroup:y,handleResizeStart:b,splitTabRelative:h,clearAllSplits:N}}function Xn(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="stable"||t==="latest"?"stable":t==="preview"||t==="next"?"preview":null}function vx(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="latest"||t==="stable"?"latest":t==="next"||t==="preview"?"next":null}function Pr(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function So(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=Xn(t.channel)||Xn(e.updateChannel)||Xn(e.releaseChannel)||void 0,n=vx(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=Pr(t.targetVersion)||Pr(e.serverVersion)||void 0,o=Pr(t.minVersion)||void 0,c=Pr(t.updateCommand)||(r?`adhdev update --channel ${r}`:void 0);return{...r?{channel:r}:{},...n?{npmTag:n}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...c?{updateCommand:c}:{}}}function Ss(e,t=null){return So(e).targetVersion||t}function Pl(e){return So(e).channel||null}function _l(e){const t=So(e);return{...t.channel?{channel:t.channel}:{},...t.npmTag?{npmTag:t.npmTag}:{},...t.targetVersion?{targetVersion:t.targetVersion}:{},...Object.keys(t).length>0?{updatePolicy:t}:{}}}function wx({ides:e,sendDaemonCommand:t}){const r="0.9.75",n=i.useMemo(()=>e.filter(f=>f.type!=="adhdev-daemon"?!1:hl(f,Ss(f,r))).sort((f,x)=>Number(ar(x,Ss(x,r)))-Number(ar(f,Ss(f,r)))),[r,e]),a=i.useMemo(()=>n.some(f=>ar(f,Ss(f,r))),[r,n]),o=i.useMemo(()=>n.map(f=>Ss(f,r)).find(f=>typeof f=="string"&&f.trim().length>0)||r,[r,n]),[c,l]=i.useState(!1),[d,m]=i.useState({}),u=i.useCallback(async f=>{var S,g;const x=e.find(p=>p.id===f);if(x){m(p=>({...p,[f]:"upgrading"}));try{const p=await t(f,"daemon_upgrade",_l(x));(S=p==null?void 0:p.result)!=null&&S.upgraded||(g=p==null?void 0:p.result)!=null&&g.success?m(y=>({...y,[f]:"done"})):m(y=>({...y,[f]:"error"}))}catch{m(p=>({...p,[f]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:c,setVersionBannerDismissed:l,upgradingDaemons:d,handleBannerUpgrade:u}}const Dl=80;function Vr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function jx(e){return{...e,createdAt:Vr(e.createdAt),updatedAt:Vr(e.updatedAt,e.createdAt),lastEventAt:Vr(e.lastEventAt,e.updatedAt||e.createdAt)}}function kx(e){const t=co(e);return t==="unknown:"?e.id:t}function Sx(e){return[e.type,Uc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Nx(e,t=Dl){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=kx(n),o=r.get(a);if(!o){r.set(a,n);continue}(n.updatedAt>o.updatedAt||n.updatedAt===o.updatedAt&&n.createdAt>o.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const o=a.updatedAt-n.updatedAt;return o!==0?o:a.createdAt-n.createdAt}).slice(0,Math.max(0,t))}function Cx(e,t){const r=Date.now(),n=[];for(const a of e){const o=a.sessionId?t.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden)continue;const c=yn(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const d=Vr(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),m=Sx({type:l,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(jx({id:m,dedupKey:m,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:_c(a),preview:lf(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return Nx(n)}function Tx(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function Mx(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Dl}=e,a=i.useMemo(()=>Cx(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=i.useMemo(()=>Tx(a),[a]);return{notifications:a,unreadCount:o}}function Ix({notifications:e,sendDaemonCommand:t}){const r=i.useCallback(o=>{const c=e.find(d=>d.id===o),l=Math.max(Date.now(),(c==null?void 0:c.updatedAt)||0);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_session_seen",{sessionId:c.sessionId,seenAt:l}).catch(()=>{})},[e,t]),n=i.useCallback(o=>{const c=e.find(l=>l.id===o);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]),a=i.useCallback(o=>{const c=e.find(l=>l.id===o);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"delete_notification",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}const Ax=i.createContext(null);function Rx(){return i.useContext(Ax)}function Sn(...e){const t=new Set,r=[],n=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const c=o.toLowerCase();t.has(c)||(t.add(c),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 Lx(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const r=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function Nn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=Lx(r);if(n)return n}return"C:\\"}for(const r of t){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function Px(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const r=t.includes("\\")?"\\":"/",n=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(n[0]||"")?n.length<=2?`${n[0]}\\`:n.slice(0,-1).join("\\"):n.length<=2?r:n.slice(0,-1).join(r)||r}function _x(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Cn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=_x(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,c=o.includes("\\")?"\\":"/",l=(m,u)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${u}`:m==="/"||m==="\\"?`${c}${u}`:`${m.replace(/[\\/]+$/,"")}${c}${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:l(o,m.name)})).sort((m,u)=>m.name.localeCompare(u.name)):[];return{path:o,directories:d}}function Dx(e,t){const r={meshId:t.meshId||"",workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp"};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand)\s*\}\}/g,(n,a)=>r[a]||"")}function El(e,t={}){const r=e==null?void 0:e.mcpConfig;return(r==null?void 0:r.mode)!=="manual"?null:{serverName:r.serverName||"adhdev-mesh",configFormat:r.format,configPathCommand:r.configPathCommand,requiresRestart:r.requiresRestart===!0,instructions:r.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:Dx(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function Ex(e){if(!e||typeof e!="object")return null;const t=e,r=typeof t.instructions=="string"?t.instructions:"",n=typeof t.template=="string"?t.template:"";return!r&&!n?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:r||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:n}}function Qt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Tn(e){return br(e)||e.tabKey||e.routeId||null}function $l(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(t)return t;const r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"";if(r)return r;const n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"";if(!n)return null;const a=Et(e.conversations,n)||e.conversations.find(o=>o.routeId===n);return a?Tn(a):null}function ns(e){return String(e||"").trim()}function Bl(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function fn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function $x(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Bx(e,t){const r=ns(e.providerSessionId),n=ns(e.targetSessionId),a=t.find(o=>{const c=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(ns).filter(Boolean);return!!(r&&c.includes(r)||n&&c.includes(n))});return a?Tn(a):n||r||null}function Wx(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=Bl(t.daemonId);if(n&&n!==e.machineId)return null;const a=ns(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=ns(e.resumeSessionId),c=ns(t.providerSessionId),l=ns(t.targetSessionId);if(o&&o!==c&&o!==l)return null;const d=fn(e.workspacePath);if(d){const m=fn(t.workspaceName);if(m&&!$x(m,d))return null}return Bx(t,r)}function Ii(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Kx({ides:e,conversations:t,onOpenSession:r}){const[n,a]=i.useState(null),o=i.useRef(null),c=i.useCallback(()=>{o.current=null,a(null)},[]),l=i.useCallback(d=>{o.current=d,a(d)},[]);return i.useEffect(()=>{if(!n)return;const d=fn(n.workspacePath),m=e.find(f=>{var y,b,h,C;if(!f||f.type==="adhdev-daemon"||Bl(f.daemonId||f.id)!==n.machineId||(ur(f)?"cli":Ts(f)?"acp":"ide")!==n.kind)return!1;const g=String(f.agentType||f.type||"");if(n.providerType&&g!==n.providerType)return!1;if(n.resumeSessionId)return String(f.providerSessionId||"")===n.resumeSessionId;if(d){const N=fn(f.workspace||f.runtimeWorkspaceLabel);return N?N===d:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((C=(h=(b=(y=f.activeChat)==null?void 0:y.messages)==null?void 0:b.at)==null?void 0:h.call(b,-1))==null?void 0:C.timestamp)||0)>=n.startedAt-5e3});if(!m)return;const u=$l({entrySessionId:m.sessionId,entryInstanceId:m.instanceId,entryRouteId:m.id,conversations:t});u&&(c(),r(u))},[c,t,e,r,n]),i.useEffect(()=>nt.onStatusEvent(d=>{const m=o.current;if(!m)return;const u=Wx(m,d,t);u&&(c(),r(u))}),[c,t,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:l}}function Ox({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const c=Rx(),l=i.useCallback(async(p,y)=>Cn(e,p,y),[e]),d=i.useCallback(async(p,y)=>{if(!y.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(p,"workspace_add",{path:y.trim()});return b!=null&&b.success?{ok:!0}:{ok:!1,error:(b==null?void 0:b.error)||"Could not save workspace"}}catch(b){return{ok:!1,error:b instanceof Error?b.message:"Could not save workspace"}}},[e]),m=i.useCallback(async(p,y,b)=>{var h;try{const C={ideType:y,enableCdp:!0};(h=b==null?void 0:b.workspacePath)!=null&&h.trim()&&(C.workspace=b.workspacePath.trim());const N=await e(p,"launch_ide",C);return!(N!=null&&N.success)&&(N==null?void 0:N.success)!==void 0?{ok:!1,error:(N==null?void 0:N.error)||"Could not launch IDE"}:(t({machineId:p,kind:"ide",providerType:y,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(C){return{ok:!1,error:C instanceof Error?C.message:"Could not launch IDE"}}},[e,t]),u=i.useCallback(async(p,y,b,h)=>{var N,v,M;const C=Date.now();try{const I={cliType:b};(N=h==null?void 0:h.workspacePath)!=null&&N.trim()?I.dir=h.workspacePath.trim():h!=null&&h.workspaceId&&(I.workspaceId=h.workspaceId),(v=h==null?void 0:h.resumeSessionId)!=null&&v.trim()&&(I.resumeSessionId=h.resumeSessionId.trim()),Array.isArray(h==null?void 0:h.cliArgs)&&h.cliArgs.length>0&&(I.cliArgs=h.cliArgs),(M=h==null?void 0:h.initialModel)!=null&&M.trim()&&(I.initialModel=h.initialModel.trim());const j=await e(p,"launch_cli",I),w=(j==null?void 0:j.result)||j,$=(w==null?void 0:w.sessionId)||(w==null?void 0:w.id);return j!=null&&j.success&&$?(r($),{ok:!0}):j!=null&&j.success?(t({machineId:p,kind:y,providerType:b,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:(j==null?void 0:j.error)||(w==null?void 0:w.error)||`Could not launch ${y.toUpperCase()} session`}}catch(I){return Ii(I)?(t({machineId:p,kind:y,providerType:b,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:I instanceof Error?I.message:`Could not launch ${y.toUpperCase()} session`}}},[r,e,t]),f=i.useCallback(async p=>{var y;if(c!=null&&c.listMeshes)return c.listMeshes(p);if(!p)return[];try{const b=await e(p,"list_meshes",{}),h=(b==null?void 0:b.result)??b;if((h==null?void 0:h.success)===!1)throw new Error((h==null?void 0:h.error)||"Could not load meshes");return(Array.isArray(h==null?void 0:h.meshes)?h.meshes:Array.isArray((y=h==null?void 0:h.result)==null?void 0:y.meshes)?h.result.meshes:[]).map(N=>{var v;return{id:String((N==null?void 0:N.id)||""),name:String((N==null?void 0:N.name)||(N==null?void 0:N.id)||"Untitled mesh"),repoIdentity:(N==null?void 0:N.repoIdentity)||(N==null?void 0:N.repo_identity)||null,workspace:Array.isArray(N==null?void 0:N.nodes)&&N.nodes.length>0?String(((v=N.nodes[0])==null?void 0:v.workspace)||""):null,nodesCount:Array.isArray(N==null?void 0:N.nodes)?N.nodes.length:void 0,status:(N==null?void 0:N.status)||null}}).filter(N=>N.id)}catch(b){throw console.error("List meshes failed",b),b}},[c,e]),x=i.useCallback(async(p,y,b)=>{if(!y.trim())return{ok:!1,error:"Choose a mesh first."};if(c!=null&&c.launchMeshCoordinator)return c.launchMeshCoordinator(p,y,b);const h=Date.now();try{const C={meshId:y.trim()};b.trim()&&(C.cliType=b.trim());const N=await e(p,"launch_mesh_coordinator",C),v=(N==null?void 0:N.result)??N;if((v==null?void 0:v.success)===!1||(N==null?void 0:N.success)===!1){const I=String((v==null?void 0:v.code)||(N==null?void 0:N.code)||""),j=Ex((v==null?void 0:v.meshCoordinatorSetup)||(v==null?void 0:v.manualSetup)||(N==null?void 0:N.meshCoordinatorSetup)||(N==null?void 0:N.manualSetup));return{ok:!1,error:(v==null?void 0:v.error)||(N==null?void 0:N.error)||"Could not launch mesh coordinator",code:I||void 0,manualSetup:j}}const M=(v==null?void 0:v.sessionId)||(v==null?void 0:v.id);return M?r(M):t({machineId:p,kind:"cli",providerType:(v==null?void 0:v.cliType)||b.trim()||void 0,workspacePath:(v==null?void 0:v.workspace)||null,startedAt:h}),{ok:!0}}catch(C){return Ii(C)?(t({machineId:p,kind:"cli",providerType:b.trim()||void 0,startedAt:h}),{ok:!0}):{ok:!1,error:C instanceof Error?C.message:"Could not launch mesh coordinator"}}},[c,r,e,t]),S=i.useCallback(async(p,y)=>{if(!p||!y)return[];try{const b=await e(p,"list_saved_sessions",{providerType:y,kind:"cli",limit:30}),h=(b==null?void 0:b.result)??b;return Array.isArray(h==null?void 0:h.sessions)?h.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),g=i.useCallback(async p=>{await Nl({conversation:n,mode:p,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:l,handleSaveMachineWorkspace:d,handleLaunchMachineIde:m,handleLaunchMachineProvider:u,handleListMachineMeshes:f,handleLaunchMeshCoordinator:x,handleListMachineSavedSessions:S,setActiveCliViewMode:g}}function Fx(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 Hx(e,t,r=Date.now()){return!e||!Fx(t)?null:{tabKey:e,nonce:r}}function Ux({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:c}){const[l,d]=i.useState(null),[m,u]=i.useState(null),f=i.useMemo(()=>{var y,b;if(!e){if(l){const h=t.find(C=>C.tabKey===l);if(h)return h}return r[0]}const p=n[a];if(p){const h=t.find(C=>C.tabKey===p);if(h)return h}return((y=o[a])==null?void 0:y[0])||((b=o[0])==null?void 0:b[0])},[t,l,a,n,o,e,r]),x=i.useCallback(p=>{d(p)},[]),S=i.useCallback(p=>{d(p.tabKey),c(y=>{const b=new URLSearchParams(y),h=uf(p);return h?b.set("activeTab",h):b.delete("activeTab"),b},{replace:!0})},[c]),g=i.useCallback((p,y)=>{const b=Hx(p,y);b&&u(b)},[]);return{activeConv:f,openDesktopConversation:S,requestScrollToBottom:g,scrollToBottomRequest:m,setDesktopActiveTab:x}}function zx(e){const t=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:r===e.autoReadKey?r:null}:r===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:r}:{shouldSchedule:!0,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!r,nextPendingKey:null}}function Vx(e){const t=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&t&&t!==r),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Gx({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=i.useRef(null),o=i.useRef(null),c=i.useRef(null),l=i.useRef(null),d=i.useRef(null);i.useEffect(()=>{const m=()=>{c.current&&(clearTimeout(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const u=sn(e,r),f=Vx({tabKey:e.tabKey,historySessionId:br(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:us(e),liveState:u}),x=f.autoReadKey,S=zx({autoReadKey:x,shouldMarkSeen:f.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!f.shouldMarkSeen){S.shouldCancelPending&&m(),a.current=x;return}if(!S.shouldSchedule)return;S.shouldCancelPending&&m();const g=()=>{if(document.visibilityState!=="visible"||a.current===x)return;a.current=x,o.current=null,c.current=null,l.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const y=f.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:y,completionMarker:f.completionMarker}).catch(()=>{})};if(o.current=S.nextPendingKey,document.visibilityState==="visible"){c.current=setTimeout(g,1500);const y=()=>{document.visibilityState!=="visible"&&c.current&&(clearTimeout(c.current),c.current=null)};d.current=y,document.addEventListener("visibilitychange",y);return}const p=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(g,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=p,document.addEventListener("visibilitychange",p)},[e,t,r,n]),i.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function Jn(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const r=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(r)?r:""}function qx({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:c,setClearedTabs:l,setSearchParams:d}){var A;const[m,u]=i.useState(!1),[f,x]=i.useState([]),[S,g]=i.useState(()=>wt()),[p,y]=i.useState(!1),[b,h]=i.useState(null),C=i.useRef(null),N=i.useMemo(()=>r||t||e,[e,r,t]),v=!!N&&tt(N)&&!Ze(N),M=i.useMemo(()=>{if(!N||!v)return null;const K=N.daemonId||N.routeId||"",_=Kt(N),D=Jn(N);return`${K}:${_}:${N.providerSessionId||""}:${D}`},[N,v]),I=i.useMemo(()=>!N||!v?"":Jn(N),[N,v]),{isCreatingChat:j,isRefreshingHistory:w,handleSwitchSession:$,handleNewChat:P,handleRefreshHistory:T}=Ll({sendDaemonCommand:a,activeConv:N,chats:(A=n.find(K=>K.id===(N==null?void 0:N.routeId)))==null?void 0:A.chats,updateRouteChats:o,setToasts:c,setClearedTabs:l}),F=i.useCallback(()=>{u(!0)},[]),H=i.useCallback(()=>{u(!1)},[]),L=i.useCallback(async()=>{if(!(!N||!v||p)){y(!0);try{const K=N.daemonId||N.routeId,_=Kt(N),D=Jn(N),O=await a(K,"list_saved_sessions",{agentType:_,providerType:_,kind:"cli",limit:50,...N.providerSessionId?{providerSessionId:N.providerSessionId}:{},...D?{workspace:D}:{}}),X=(O==null?void 0:O.result)??O;x(Array.isArray(X==null?void 0:X.sessions)?X.sessions:[])}catch(K){console.error("Refresh saved sessions failed",K),x([])}finally{y(!1)}}},[N,p,v,a]);i.useEffect(()=>{if(!m){C.current=null;return}if(!v){C.current=null,x([]),y(!1);return}!M||p||C.current!==M&&(C.current=M,L())},[L,m,p,v,M]);const k=i.useCallback(async K=>{if(!N||!v||!K.providerSessionId||!K.workspace)return;const _=N.daemonId||N.routeId,D=Kt(N);try{h(K.providerSessionId);const O=await a(_,"launch_cli",{cliType:D,dir:K.workspace,resumeSessionId:K.providerSessionId,initialModel:Tc(K.summaryMetadata,"model",{preferShortValue:!0})||void 0}),X=(O==null?void 0:O.result)??O,ge=typeof(X==null?void 0:X.sessionId)=="string"?X.sessionId:typeof(X==null?void 0:X.id)=="string"?X.id:"";ge&&d(ce=>{const ee=new URLSearchParams(ce);return ee.set("activeTab",ge),ee},{replace:!0}),H()}catch(O){console.error("Resume saved session failed",O)}finally{h(null)}},[H,N,v,a,d]);return{historyModalOpen:m,openHistoryModal:F,closeHistoryModal:H,historyTargetConv:N,isSavedSessionHistoryTarget:v,isHistoryCreatingChat:j,isHistoryRefreshingHistory:w,handleHistorySwitchSession:$,handleHistoryNewChat:P,handleHistoryRefresh:T,savedHistorySessions:f,savedHistoryFilters:S,setSavedHistoryFilters:g,missingWorkspaceResumePath:I,isSavedHistoryLoading:p,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:L,handleResumeSavedHistorySession:k}}function Yx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}){const[d,m]=i.useState(null),[u,f]=i.useState(null),x=i.useMemo(()=>{if(e||!n)return null;const b=l(n);return b&&!tt(b)&&!Ze(b)?b:null},[e,n,l]),S=i.useMemo(()=>{const b=d==null?void 0:d.routeId;if(!b)return null;const h=d!=null&&d.tabKey?o.find(C=>C.tabKey===d.tabKey):a?o.find(C=>C.tabKey===a):null;return(h==null?void 0:h.routeId)===b?h:Et(o,b)},[o,d,a]),g=i.useMemo(()=>{if(S)return c.find(b=>b.id===S.routeId)},[c,S]);i.useEffect(()=>{x&&(m({routeId:x.routeId,tabKey:ti(x)}),f(x),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,x]);const p=i.useCallback(b=>{b&&(m({routeId:b.routeId,tabKey:ti(b)}),f(b))},[]),y=i.useCallback(()=>{m(null),f(null)},[]);return{remoteDialogConv:S,remoteDialogIdeEntry:g,remoteDialogActiveConv:u,setRemoteDialogActiveConv:f,openRemoteDialog:p,closeRemoteDialog:y}}function Xx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:f,remoteDialogActiveConv:x,setRemoteDialogActiveConv:S,openRemoteDialog:g,closeRemoteDialog:p}=Yx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}),[y,b]=i.useState(!1),[h,C]=i.useState(null),N=i.useCallback(async I=>{const j=I||d;!j||!tt(j)&&!Ze(j)||(C(j),b(!0))},[d]),v=i.useCallback(()=>{b(!1),C(null)},[]),M=i.useCallback(async I=>{const j=h||d;if(!j||!tt(j)&&!Ze(j)){v();return}b(!1);try{const w=Kt(j),$=j.routeId||j.daemonId||"";await m($,"stop_cli",{cliType:w,targetSessionId:j.sessionId,mode:I})}catch(w){console.error("Stop CLI failed:",w)}finally{C(null)}},[d,v,h,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:f,remoteDialogActiveConv:x,setRemoteDialogActiveConv:S,openRemoteDialog:g,closeRemoteDialog:p,cliStopDialogOpen:y,cliStopTargetConv:h,requestCliStop:N,cancelCliStop:v,confirmCliStop:M}}function Wl({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var b;const c=Ws(),l=ys(e),d=o?null:Pc(e),m=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!o&&e.streamSource==="agent-stream"&&!!e.agentName,f=!o&&!u&&(e.transport==="pty"||e.transport==="acp"),x=Ps(e),S=df(e),g=(b=e.settings)==null?void 0:b.meshNodeFor;if(!m&&!u&&!f&&!d&&!g)return null;const p=i.useCallback(()=>{if(n){n();return}l&&c("/dashboard",{state:{openMachineId:l}})},[l,c,n]),y=i.useCallback(()=>{if(r){r();return}const h=Tn(e);h&&c(Qt(h))},[e,c,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[m&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:y,title:S,children:[s.jsx(Mt,{size:12}),s.jsx("span",{children:S})]}):s.jsxs("span",{className:"conversation-meta-chip",title:S,children:[s.jsx(Mt,{size:12}),s.jsx("span",{children:S})]})),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(Ls,{size:12}),s.jsx("span",{children:x})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(Ls,{size:12}),s.jsx("span",{children:x})]}),d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:p,title:d,children:[s.jsx(Xt,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(Xt,{size:12}),s.jsx("span",{children:d})]})),g&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Xt,{size:12}),s.jsx("span",{children:"Mesh Node"})]})]})}function Qn(e,t=!0){return(e??!0)&&t}const No=i.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:c,handleRelaunch:l,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u=null,handleFocusAgent:f,isFocusingAgent:x,actionLogs:S,userName:g,scrollToBottomRequestNonce:p,isInputActive:y=!0,isVisible:b=!0}){const h=n,C=!n,N=Qn(b,h),v=Qn(b,C),M=Qn(b),I=vl(t),j=I.status||I.modalMessage||I.modalButtons?{...t,...I.status?{status:I.status}:{},...I.modalMessage!==void 0?{modalMessage:I.modalMessage}:{},...I.modalButtons!==void 0?{modalButtons:I.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Sc,{activeConv:j,onModalButton:c}),s.jsx(Wl,{conversation:j,className:"chat-pane-meta-row mx-3 mt-1",meshOnly:!0}),j.transport!=="pty"&&j.transport!=="acp"&&j.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(dr,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:l,children:"Relaunch with CDP"})]})}):null,j.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:h?"visible":"hidden",pointerEvents:h?"auto":"none"},children:s.jsx(wp,{activeConv:j,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,isVisible:N,isInputActive:y&&N})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(Ra,{activeConv:j,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:f,isFocusingAgent:x,actionLogs:S,userName:g,scrollToBottomRequestNonce:p,isInputActive:y&&v,isVisible:v})})]}):s.jsx(Ra,{activeConv:j,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:f,isFocusingAgent:x,actionLogs:S,userName:g,scrollToBottomRequestNonce:p,isInputActive:y&&M,isVisible:M})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function Jx({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:d,onBack:m,onOpenNativeConversation:u,onOpenMachine:f,onOpenHistory:x,onOpenRemote:S,onStopCli:g,cliViewMode:p,onSetCliViewMode:y,handleSendChat:b,handleFocusAgent:h,handleModalButton:C,handleRelaunch:N}){const v=i.useRef(null),M=tt(e)&&!t,I=M&&p==="terminal",j=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${j} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx(Ga,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:lt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(Wl,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>f(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[M&&p&&s.jsx(uo,{mode:p,onChange:y,compact:!0}),M&&g&&s.jsx("button",{onClick:()=>{g(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(vt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),type:"button",children:s.jsx(qa,{size:14})}),!t&&!M&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",children:s.jsx(Mt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(No,{activeConv:e,clearToken:0,isCliTerminal:I,ideEntry:n,terminalRef:v,handleModalButton:C,handleRelaunch:N,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:h,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const Zn={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 Qx(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Kl(){const[e,t]=i.useState("unix"),[r,n]=i.useState("powershell"),[a,o]=i.useState(!1),c=e==="unix"?"unix":r;i.useEffect(()=>{t(Qx())},[]);const l=i.useCallback(()=>{navigator.clipboard.writeText(Zn[c].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[c]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:Zn[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Zn[c].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function Ol({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Mt},{key:"chats",label:"Chats",icon:zt}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:a,icon:o})=>{const c=e===n;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"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:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(n),type:"button","aria-pressed":c,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(o,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function _r({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function ws({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function Xs({icon:e,title:t,subtitle:r,children:n}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function Zx({conversation:e,onCancel:t,onConfirm:r}){const n=lt(e),a=xs(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"fade-in relative w-full sm:w-[min(92vw,420px)] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] border border-border-subtle bg-bg-primary shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border-subtle bg-[var(--surface-primary)] px-4 py-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base font-extrabold text-text-primary",children:"Hide this chat from the inbox?"}),s.jsx("div",{className:"mt-1 text-[13px] leading-relaxed text-text-muted",children:"This only collapses the chat locally. You can restore it from Hidden tabs."})]}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary text-text-secondary transition-colors hover:bg-surface-primary hover:text-text-primary",onClick:t,"aria-label":"Cancel hide chat",children:s.jsx(vt,{size:16})})]}),s.jsx("div",{className:"px-4 py-4",children:s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary/60 px-3.5 py-3",children:[s.jsx("div",{className:"truncate text-sm font-bold text-text-primary",children:n}),s.jsx("div",{className:"mt-1 truncate text-xs text-text-muted",children:a})]})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-border-subtle bg-bg-secondary px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))]",children:[s.jsx("button",{type:"button",className:"btn btn-secondary min-h-[40px] px-4 text-sm",onClick:t,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary min-h-[40px] px-4 text-sm",onClick:r,children:"Hide tab"})]})]})]})}function Dr({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onCollectChatDebugBundle:o}){const c=t==="needs_attention"||t==="task_complete",l=t==="working",d=t==="earlier",m=t==="task_complete",{isReconnecting:u,isConnecting:f}=Ks(e.conversation),x=lt(e.conversation),S=xs(e.conversation),g=Zc(e.conversation,{requiresAction:t==="needs_attention"}),p=c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":l?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":d?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",y=c?"bg-accent-primary shadow-glow":l?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":d?"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",b=d?"text-text-secondary":"text-text-primary",h=d?"text-text-muted":"text-text-secondary",C=d?"text-text-secondary opacity-80":"text-text-muted",N=d?"text-text-muted opacity-80":"text-text-muted",v=!l&&!m,M="text-[color:var(--status-warning)]",I=j=>{if(!o)return;j.preventDefault(),j.stopPropagation();const w=o==null?void 0:o(e.conversation);Promise.resolve(w).catch($=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",$)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${p}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[c||l?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${y}`,style:c?{color:"var(--accent-on-primary)"}:void 0,children:r(x)}),a&&s.jsxs("button",{type:"button",className:"mobile-inbox-hide-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-border-subtle bg-bg-primary/70 px-2 text-[10px] font-semibold text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:j=>{j.preventDefault(),j.stopPropagation(),a()},"aria-label":`Hide ${x}`,title:"Hide conversation",children:[s.jsx(Ya,{size:11}),s.jsx("span",{children:"Hide"})]})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:I,type:"button",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${b}`,children:x}),v&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${N}`,children:kc(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${h}`,children:[s.jsx("span",{className:"truncate",children:S}),s.jsx(Ds,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),u?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${M} animate-pulse`,children:"Reconnecting…"})]}):f?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):g==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:M,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${C}`,children:e.preview})]}),c&&!m&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),m&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),l&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]})},e.conversation.tabKey)}function Ai({size:e=32}){return s.jsx("div",{className:"flex flex-col items-center gap-2.5",children:s.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}})})}function eb({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:c,getAvatarText:l,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:f,onHideConversation:x,onOpenNewSession:S,onOpenMachine:g,onOpenSettings:p,onSectionChange:y,wsStatus:b="connected",isStandalone:h=!1,onCollectChatDebugBundle:C}){const[N,v]=i.useState(null),M=b==="disconnected"||b==="reconnecting"||b==="offline"||b==="auth_failed",I=c.length>0,j=t.length>0||r.length>0||n.length>0||a.length>0,w=e==="machines"?"Machines":"Chats",$=h?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",P=h?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",T=i.useCallback(async L=>{const k=_s(L);if(!k)return;const A=Array.isArray(L.messages)?L.messages:[],K=Wc({activeConv:L,visibleMessages:A,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:A.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),_=await m(k,"get_chat_debug_bundle",{...as(L),delivery:"daemon_file",frontendSnapshot:K}),D=on(_),O=Fc(D),X=await Oc(O);X==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),nt.showToast(Kc(D,{locatorCopyStatus:X}),X==="failed"?"warning":"success")},[d,m]),F=C||T,H=i.useCallback(()=>{N&&(x==null||x(N),v(null))},[N,x]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${$}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:w}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||r.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(bn,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:p,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(xn,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${P}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:M?s.jsx(Xs,{icon:s.jsx(Ai,{}),title:b==="offline"?"Network offline":b==="auth_failed"?"Session expired":"Reconnecting",subtitle:b==="offline"?"Waiting for network…":b==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):c.length===0?s.jsx(Xs,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:h?"Waiting for your daemon":"Connect your machines",subtitle:h?"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:!h&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Kl,{})})}):s.jsx(ws,{children:c.map((L,k)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${k>0?"border-t border-border-subtle/70":""}`,onClick:()=>g(L.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(L.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:L.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:L.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[L.unread," new"]}):L.total>0?`${L.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:L.subtitle}),L.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[L.total," chat",L.total!==1?"s":"",L.unread>0?` · ${L.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},L.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(_r,{title:"Needs attention",className:"mb-0"}),s.jsx(ws,{children:t.map((L,k)=>s.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:s.jsx(Dr,{item:L,type:"needs_attention",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>v(L.conversation):void 0,onCollectChatDebugBundle:F})},L.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(_r,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(ws,{children:r.map((L,k)=>s.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:s.jsx(Dr,{item:L,type:"task_complete",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>v(L.conversation):void 0,onCollectChatDebugBundle:F})},L.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(_r,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(ws,{children:n.map((L,k)=>s.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:s.jsx(Dr,{item:L,type:"working",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>v(L.conversation):void 0,onCollectChatDebugBundle:F})},L.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(_r,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(ws,{children:a.map((L,k)=>s.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:s.jsx(Dr,{item:L,type:"earlier",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>v(L.conversation):void 0,onCollectChatDebugBundle:F})},L.conversation.tabKey))}):j?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):M?s.jsx(Xs,{icon:s.jsx(Ai,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):I?s.jsx(Xs,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(zt,{size:20})}),title:"No conversations yet",subtitle:sl,children:S&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:S,"aria-label":Bt,title:Bt,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:Bt})]})}):s.jsx(Xs,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&o.length>0&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(ws,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[o.length," collapsed ",o.length===1?"conversation":"conversations"]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:f,children:"Restore all"})]})})})]}),e==="chats"&&S&&j&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:S,"aria-label":Bt,title:Bt,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),N&&s.jsx(Zx,{conversation:N,onCancel:()=>v(null),onConfirm:H}),s.jsx(Ol,{section:e,onSectionChange:y})]})}function tb(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 Fl(e){const t=[e.workspace||"Workspace unknown"],r=hs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=tb(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Mn({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:c="Use this folder",onClose:l,onNavigate:d,onConfirm:m}){const[u,f]=i.useState(r);i.useEffect(()=>{f(r)},[r]);const x=Px(r),S=u.trim();return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:l,"aria-label":"Close folder browser",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!x||a||d(x)},disabled:!x||a,children:[s.jsx(Ga,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:g=>f(g.target.value),onKeyDown:g=>{g.key!=="Enter"||!S||a||(g.preventDefault(),d(S))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!S||a||d(S)},disabled:!S||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):n.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:n.map(g=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(g.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(ps,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:g.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:g.path})]})]},g.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(S||r),disabled:!S&&!r||a,children:c})]})]})})}function Co({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:d=!1,showArgsInput:m,argsValue:u,onArgsChange:f,showModelInput:x,modelValue:S,onModelChange:g,historyProviderNode:p,onConfirm:y,onCancel:b}){const h=n==null?void 0:n.find(C=>C.key===a);return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:b,"aria-label":"Close launch confirmation",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:C=>o(C.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(C=>s.jsx("option",{value:C.key,children:C.label},C.key))}),(h==null?void 0:h.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h.description})]}),p,r.map(C=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:C.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:C.value})]},`${C.label}:${C.value}`)),x&&g&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:S||"",onChange:C=>g(C.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&&f&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:C=>f(C.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:b,disabled:d,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:y,disabled:d,children:[s.jsx(Ja,{size:14}),d?l:c]})]})]})})}function Ri(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ms(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,o=[];a&&o.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])o.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${Ri(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const c=(r==null?void 0:r.trim())||"",l=c?(t.workspaces||[]).find(d=>d.path===c):null;if(c&&!l&&o.push({key:`custom:${c}`,label:Ri(c),description:c,workspaceId:null,workspacePath:c}),n){const d=`saved:${n}`;if(o.some(m=>m.key===d))return{options:o,selectedKey:d}}return l?{options:o,selectedKey:`saved:${l.id}`}:c?{options:o,selectedKey:`custom:${c}`}:{options:o,selectedKey:"__home__"}}function sb(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function rb(e){return[sb(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function nb(e){return e.lastLaunchedAt?gn(e.lastLaunchedAt):""}function Hl(e){return{metaText:rb(e),updatedLabel:nb(e)}}function ea(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function ab({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var st,mt,ht,xt;const c=xr(),[l,d]=i.useState(!1),m=(((st=e.detectedIdes)==null?void 0:st.length)||0)>0,u=i.useMemo(()=>(e.workspaces||[]).map(Ce=>({id:Ce.id,path:Ce.path,label:Ce.label})),[e]),f=e.defaultWorkspaceId||null,[x,S]=i.useState(f||((mt=u[0])==null?void 0:mt.id)||""),[g,p]=i.useState(""),[y,b]=i.useState(""),[h,C]=i.useState([]),[N,v]=i.useState(!1),[M,I]=i.useState(""),[j,w]=i.useState(!1),[$,P]=i.useState(ea(m,t.length,r.length)),T=i.useRef(null),[F,H]=i.useState(null),L=i.useRef("__home__"),[k,A]=i.useState("__home__"),[K,_]=i.useState(""),[D,O]=i.useState(""),[X,ge]=i.useState(""),[ce,ee]=i.useState([]),[z,de]=i.useState(()=>wt().textQuery),[pe,Y]=i.useState(()=>wt().workspaceQuery),[ie,ye]=i.useState(()=>wt().modelQuery),[re,me]=i.useState(()=>wt().resumableOnly),[ke,xe]=i.useState(()=>wt().sortMode),[ve,te]=i.useState(!1),[he,le]=i.useState(!1),ue=i.useRef(null),oe=i.useRef(null);i.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const Q=x==="__custom__"?g.trim():((ht=u.find(Ce=>Ce.id===x))==null?void 0:ht.path)||"",fe=x==="__custom__"&&!!Q&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),J=x!=="__custom__"&&((xt=u.find(Ce=>Ce.id===x))==null?void 0:xt.path)||"",Ae=i.useMemo(()=>(e.recentLaunches||[]).map(Ce=>Ce.workspace),[e]),Te=i.useCallback(async Ce=>{v(!0),I("");try{const ze=await a(Ce);b(ze.path),p(ze.path),C(ze.directories)}catch(ze){I(ze instanceof Error?ze.message:"Could not load folder")}finally{v(!1)}},[a]),$e=i.useCallback(()=>{var ze;S("__custom__"),w(!0);const Ce=Nn(e.platform,Sn(g.trim(),J,Ae,e.defaultWorkspacePath,(ze=u.find(Qe=>Qe.id===f))==null?void 0:ze.path,u.map(Qe=>Qe.path)));Te(Ce)},[g,f,Te,Ae,J,e.platform,u]),Ue=i.useCallback(Ce=>{if(Ce!=null&&Ce.workspaceId){S(Ce.workspaceId),p("");return}if(Ce!=null&&Ce.workspacePath){S("__custom__"),p(Ce.workspacePath);return}S(""),p("")},[]),B=i.useCallback(Ce=>{if(S(Ce),Ce==="__custom__"){$e();return}p("")},[$e]),Se=i.useCallback(Ce=>{S("__custom__"),p(Ce)},[]),Me=i.useCallback((Ce,ze)=>{T.current=ze,L.current=Ce.selectedWorkspaceKey||"__home__",A(Ce.selectedWorkspaceKey||"__home__"),_(Ce.initialArgs||""),O(Ce.initialModel||""),ge(""),ee([]);const Qe=Ce.providerType?`${e.id}:${Ce.providerType}`:null;if(Lp(oe.current,Qe)){const Ge=wt();de(Ge.textQuery),Y(Ge.workspaceQuery),ye(Ge.modelQuery),me(Ge.resumableOnly),xe(Ge.sortMode)}oe.current=Qe,H(Ce),Ce.providerType&&o&&(te(!0),o(Ce.providerType).then(Ge=>ee(Ge||[])).catch(Ge=>console.warn("Failed to load saved sessions",Ge)).finally(()=>te(!1)))},[o,e.id]),De=i.useMemo(()=>rl(ce,{textQuery:z,workspaceQuery:pe,modelQuery:ie,resumableOnly:re,sortMode:ke}),[ie,re,ce,ke,z,pe]);i.useEffect(()=>{X&&(De.some(Ce=>Ce.providerSessionId===X)||ge(""))},[De,X]);const We=i.useCallback(()=>{T.current&&(le(!0),T.current().finally(()=>{T.current=null,le(!1),H(null)}))},[]),He=i.useCallback(()=>{T.current=null,H(null)},[]),Je=i.useCallback(Ce=>{L.current=Ce,A(Ce)},[]);return i.useEffect(()=>{var Ce;ue.current!==e.id&&(ue.current=e.id,S(f||((Ce=u[0])==null?void 0:Ce.id)||"__custom__"),p(""),b(""),C([]),I(""),w(!1),de(wt().textQuery),Y(wt().workspaceQuery),ye(wt().modelQuery),me(wt().resumableOnly),xe(wt().sortMode),oe.current=null,P(ea(m,t.length,r.length)))},[r.length,t.length,f,m,e.id,u]),i.useEffect(()=>{var Ce;x!=="__custom__"&&(x&&u.some(ze=>ze.id===x)||S(f||((Ce=u[0])==null?void 0:Ce.id)||"__custom__"))},[f,x,u]),i.useEffect(()=>{$==="ide"&&m||$==="cli"&&t.length>0||$==="acp"&&r.length>0||P(ea(m,t.length,r.length))},[$,r.length,t.length,m]),{showAllRecent:l,setShowAllRecent:d,hasIdeOptions:m,workspaceRows:u,defaultWorkspaceId:f,workspaceChoice:x,customWorkspacePath:g,browseCurrentPath:y,browseDirectories:h,browseBusy:N,browseError:M,browseDialogOpen:j,activeLauncherKind:$,launchConfirm:F,launchConfirmWorkspaceKeyRef:L,launchConfirmWorkspaceKey:k,launchConfirmArgs:K,launchConfirmModel:D,launchConfirmResumeId:X,launchConfirmSavedSessions:ce,launchConfirmTextFilter:z,launchConfirmWorkspaceFilter:pe,launchConfirmModelFilter:ie,launchConfirmResumableOnly:re,launchConfirmSortMode:ke,filteredLaunchConfirmSavedSessions:De,launchConfirmSessionsLoading:ve,launchConfirmBusy:he,resolvedWorkspacePath:Q,canCreateMissingWorkspace:fe,openBrowseDialog:$e,loadBrowsePath:Te,handleWorkspaceChoiceChange:B,chooseCustomWorkspacePath:Se,setCustomWorkspacePath:p,setBrowseDialogOpen:w,setActiveLauncherKind:P,openLaunchConfirm:Me,handleConfirmLaunch:We,closeLaunchConfirm:He,setWorkspaceSelectionFromOption:Ue,setLaunchConfirmWorkspaceKeyAndSync:Je,setLaunchConfirmArgs:_,setLaunchConfirmModel:O,setLaunchConfirmResumeId:ge,setLaunchConfirmTextFilter:de,setLaunchConfirmWorkspaceFilter:Y,setLaunchConfirmModelFilter:ye,setLaunchConfirmResumableOnly:me,setLaunchConfirmSortMode:xe}}function ob({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:c,machineAction:l,isStandalone:d,section:m,showBottomNav:u,onBack:f,onSectionChange:x,onOpenConversation:S,onOpenRecent:g,onOpenMachineDetails:p,onMachineUpgrade:y,onLaunchDetectedIde:b,onAddWorkspace:h,onBrowseDirectory:C,onLaunchWorkspaceProvider:N,onListSavedSessions:v}){const M=k=>k==="ide"?"IDE":k==="cli"?"CLI":"ACP",I=r.slice(0,4),j=t.slice(0,3),w=ab({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:C,onListSavedSessions:v}),$=i.useMemo(()=>I.map(k=>{const{metaText:A,updatedLabel:K}=Hl(k);return{key:`recent-launch:${k.id}`,primary:k.label,secondary:A,updatedLabel:K,onClick:()=>{const{options:_,selectedKey:D}=ms({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspacePath:k.workspace});w.openLaunchConfirm({title:k.kind==="ide"?is("restart-ide",k.label):k.providerSessionId?po(k.label):is("start-fresh",k.label),description:k.kind==="ide"?cs("restart-ide"):k.providerSessionId?ho():cs("start-fresh"),confirmLabel:k.kind==="ide"?Es("restart-ide"):k.providerSessionId?ln(!0):Es("start-fresh"),busyLabel:k.kind==="ide"?$s("restart-ide"):k.providerSessionId?mo(!0):$s("start-fresh"),workspaceOptions:_,selectedWorkspaceKey:D,details:[{label:"Mode",value:M(k.kind)},...k.providerType?[{label:"Provider",value:k.providerType}]:[]]},async()=>{const O=_.find(X=>X.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(O),await g({...k,workspace:(O==null?void 0:O.workspacePath)??null})})}}}),[w,g,I]),P=i.useMemo(()=>j.map(k=>({key:`recent-chat:${k.conversation.tabKey}`,primary:lt(k.conversation),secondary:bp(k.conversation,{timestampLabel:k.timestamp?kc(k.timestamp):null}),unread:k.unread,onClick:()=>S(k.conversation)})),[S,j]),T=w.showAllRecent?$:$.slice(0,4),F=$.length>0,H=P.length>0,L=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${L} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:f,type:"button","aria-label":"Back",children:s.jsx(Ga,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Tt(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[H&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:P.map(k=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${k.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:k.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:k.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:k.secondary})]},k.key))})]}),F&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:T.map(k=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:k.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:k.primary}),k.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:k.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:k.secondary})]},k.key))}),$.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>w.setShowAllRecent(k=>!k),children:w.showAllRecent?"Show fewer":`Show ${$.length-4} more`})})]}),(w.hasIdeOptions||n.length>0||a.length>0)&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:s.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:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),s.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),s.jsx("select",{value:w.workspaceChoice,onChange:k=>w.handleWorkspaceChoiceChange(k.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:w.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[w.workspaceRows.map(k=>s.jsxs("option",{value:k.id,children:[k.id===w.defaultWorkspaceId?"⭐ ":"",vn(k.path,k.label)||k.path]},k.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),w.workspaceChoice==="__custom__"&&s.jsxs("div",{className:"flex flex-col gap-2.5",children:[s.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(ps,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),s.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:w.resolvedWorkspacePath||w.browseCurrentPath||"No folder selected yet."})]})]})}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.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:w.openBrowseDialog,children:"Select workspace…"}),s.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:()=>{w.resolvedWorkspacePath&&h(w.resolvedWorkspacePath)},disabled:!w.resolvedWorkspacePath||w.browseBusy,children:"Save as workspace"})]})]}),w.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[w.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.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:()=>w.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.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:()=>w.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.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:()=>w.setActiveLauncherKind("acp"),children:"ACP"})]}),w.activeLauncherKind&&s.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[s.jsx("div",{className:"text-xs font-bold text-text-secondary",children:w.activeLauncherKind==="ide"?"Choose an IDE":w.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:w.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(k=>s.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:A,selectedKey:K}=ms({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspaceId:w.workspaceChoice!=="__custom__"?w.workspaceChoice:null,currentWorkspacePath:w.resolvedWorkspacePath});w.openLaunchConfirm({title:`Launch ${k.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:A,selectedWorkspaceKey:K,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:k.name}]},async()=>{const _=A.find(D=>D.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(_),b(k.type,{workspacePath:(_==null?void 0:_.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:k.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath||"Use selected workspace"})]},k.type)):(w.activeLauncherKind==="cli"?n:a).map(k=>s.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 A=w.activeLauncherKind==="cli"?"cli":"acp",{options:K,selectedKey:_}=ms({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspaceId:w.workspaceChoice!=="__custom__"?w.workspaceChoice:null,currentWorkspacePath:w.resolvedWorkspacePath});w.openLaunchConfirm({title:`Launch ${k.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${A.toUpperCase()}`,workspaceOptions:K,selectedWorkspaceKey:_,details:[{label:"Mode",value:A.toUpperCase()},{label:"Provider",value:k.displayName}],showArgsInput:!0,showModelInput:A==="acp",initialArgs:"",initialModel:"",providerType:k.type},async()=>{const D=K.find(O=>O.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(D),N(A,k.type,{workspaceId:(D==null?void 0:D.workspaceId)??null,workspacePath:(D==null?void 0:D.workspacePath)??null,args:w.launchConfirmArgs,model:w.launchConfirmModel,resumeSessionId:w.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[k.icon?`${k.icon} `:"",k.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath||"Use selected workspace"})]},k.type))})]}),l.message&&s.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,w.canCreateMissingWorkspace&&s.jsx("div",{className:"mt-2",children:s.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:()=>h(w.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:y,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:p,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),w.browseDialogOpen&&s.jsx(Mn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:w.browseCurrentPath,directories:w.browseDirectories,busy:w.browseBusy,error:w.browseError,confirmLabel:"Use this folder",onClose:()=>w.setBrowseDialogOpen(!1),onNavigate:k=>{w.loadBrowsePath(k)},onConfirm:k=>{w.chooseCustomWorkspacePath(k),w.setBrowseDialogOpen(!1)}}),w.launchConfirm&&s.jsx(Co,{title:w.launchConfirm.title,description:w.launchConfirm.description,details:w.launchConfirm.details,workspaceOptions:w.launchConfirm.workspaceOptions,selectedWorkspaceKey:w.launchConfirmWorkspaceKey,onWorkspaceChange:w.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:w.launchConfirm.providerType?ln(!!w.launchConfirmResumeId):w.launchConfirm.confirmLabel,busyLabel:w.launchConfirm.providerType?void 0:w.launchConfirm.busyLabel,busy:w.launchConfirmBusy,showArgsInput:w.launchConfirm.showArgsInput,argsValue:w.launchConfirmArgs,onArgsChange:w.setLaunchConfirmArgs,showModelInput:w.launchConfirm.showModelInput,modelValue:w.launchConfirmModel,onModelChange:w.setLaunchConfirmModel,historyProviderNode:w.launchConfirm.providerType&&(w.launchConfirmSessionsLoading||w.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),w.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:fo()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:w.launchConfirmTextFilter,onChange:k=>w.setLaunchConfirmTextFilter(k.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:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:w.launchConfirmWorkspaceFilter,onChange:k=>w.setLaunchConfirmWorkspaceFilter(k.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:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:w.launchConfirmModelFilter,onChange:k=>w.setLaunchConfirmModelFilter(k.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:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),s.jsxs("select",{value:w.launchConfirmSortMode,onChange:k=>w.setLaunchConfirmSortMode(k.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:w.launchConfirmResumableOnly,onChange:k=>w.setLaunchConfirmResumableOnly(k.target.checked),disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:w.launchConfirmResumeId,onChange:k=>w.setLaunchConfirmResumeId(k.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Dp()}),w.filteredLaunchConfirmSavedSessions.map(k=>s.jsxs("option",{value:k.providerSessionId,disabled:!k.canResume,children:[k.title||k.providerSessionId," ",k.canResume?"":"(workspace missing)"]},k.providerSessionId))]}),!w.launchConfirmSessionsLoading&&w.launchConfirmSavedSessions.length>0&&w.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),w.launchConfirmResumeId&&(()=>{const k=w.filteredLaunchConfirmSavedSessions.find(K=>K.providerSessionId===w.launchConfirmResumeId);if(!k)return null;const A=Fl(k);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:A.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:A.providerSessionId}),s.jsx("div",{className:"mt-1",children:A.metaLine}),A.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:A.updatedLabel}),A.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:A.preview})]})})()]}),onConfirm:w.handleConfirmLaunch,onCancel:w.closeLaunchConfirm}),u&&s.jsx(Ol,{section:m,onSectionChange:x})]})}function Gr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function ib(e,t=[]){const r=new Map(e.map(a=>[a.conversation.tabKey,a])),n=t.map(a=>r.get(a)).filter(a=>!!a);return n.length===e.length?n:Gr(e)}function cb(e){var r;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":"Offline"}function lb(e,t){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:hs(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,d,m,u;const a=ur(n)?"cli":Ts(n)?"acp":"ide",o=hs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(ur(n)?n.cliName||n.type:Ts(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ts(n)?o||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((u=(m=(d=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:d.at)==null?void 0:m.call(d,-1))==null?void 0:u.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function db(e,t){const r=new Map;for(const n of t){const a=ys(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((f,x)=>x.timestamp-f.timestamp)[0]||null,c=(o==null?void 0:o.conversation)||null,l=Ca(n),d=a.filter(f=>f.unread||f.requiresAction).length,m=cb(n),u=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:Tt(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:c,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:l,preview:c?gp(c):"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,c=a.latestTimestamp||a.fallbackActivityAt||0;return c!==o?c-o:n.label.localeCompare(a.label)})}function ub(e){return e==="chat"}function Er(e,t){var r;if(!(typeof window>"u"))try{if(!(!!((r=import.meta.env)!=null&&r.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function mb({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:x,onRequestedMobileSectionConsumed:S,setSelectedTabKey:g,setScreen:p,setSelectedMachineId:y,setSection:b,setMachineBackTarget:h,resetMachineAction:C}){const N=i.useRef(null),v=i.useCallback(M=>{if(!(M!=null&&M.sessionId))return;const I=sn(M,c),j=Math.max(Date.now(),us(M),I.lastUpdated||0);Er("mark_read:start",{tabKey:M.tabKey,sessionId:M.sessionId,displayPrimary:lt(M),inboxBucket:I.inboxBucket,unread:I.unread,lastSeenAt:I.lastSeenAt,lastUpdated:I.lastUpdated,activityAt:us(M),readAt:j}),l(ys(M)||M.routeId,"mark_session_seen",{sessionId:M.sessionId,providerSessionId:M.providerSessionId,seenAt:j,completionMarker:I.completionMarker}).then(w=>{Er("mark_read:result",{tabKey:M.tabKey,sessionId:M.sessionId,result:w})}).catch(w=>{Er("mark_read:error",{tabKey:M.tabKey,sessionId:M.sessionId,error:w instanceof Error?w.message:String(w)})})},[c,l]);return i.useEffect(()=>{var I;if(!n){ub(o)&&p("inbox"),g(((I=e[0])==null?void 0:I.tabKey)||null),N.current=null;return}if(o!=="chat"){N.current=null;return}const M=`${n.tabKey}:${n.sessionId||""}`;N.current!==M&&(N.current=M,v(n))},[e,v,o,n,p,g]),i.useEffect(()=>{if(!d)return;const M=e.find(I=>I.tabKey===d);M&&(g(M.tabKey),p("chat"),m==null||m())},[e,m,d,p,g]),i.useEffect(()=>{if(!u)return;const M=t.find(I=>I.id===u);M&&(y(M.id),C(),b("machines"),h("inbox"),p("machine"),f==null||f())},[t,f,u,C,h,p,b,y]),i.useEffect(()=>{x&&(b(x),p("inbox"),S==null||S())},[S,x,p,b]),i.useEffect(()=>{const M=r.filter(I=>I.inboxBucket==="task_complete"||I.unread);M.length!==0&&Er("inbox_state",{screen:o,selectedTabKey:a,items:M.map(I=>{const j=sn(I.conversation,c);return{liveState:j,tabKey:I.conversation.tabKey,sessionId:I.conversation.sessionId,displayPrimary:lt(I.conversation),serverBucket:j.inboxBucket,computedBucket:I.inboxBucket,serverUnread:j.unread,computedUnread:I.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:us(I.conversation)}})})},[r,c,o,a]),{markConversationRead:v}}function fb(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Li(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function pb(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function hb({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,o]=i.useState("idle"),[c,l]=i.useState(""),[d,m]=i.useState(null),u=i.useCallback(()=>{o("idle"),l(""),m(null)},[]),f=i.useCallback(async(h,C,N)=>{var v;try{o("loading"),l(`Launching ${C}…`);const M={ideType:C,enableCdp:!0};(v=N==null?void 0:N.workspacePath)!=null&&v.trim()&&(M.workspace=N.workspacePath.trim()),await e(h,"launch_ide",M),o("done"),l(`${C} launch requested`)}catch(M){o("error"),l(M instanceof Error?M.message:"Launch IDE failed"),console.error("Launch IDE failed",M)}},[e]),x=i.useCallback(async(h,C,N)=>{if(C.trim())try{o("loading"),l(N!=null&&N.createIfMissing?"Creating folder…":"Saving workspace…");const v=await e(h,"workspace_add",{path:C.trim(),createIfMissing:(N==null?void 0:N.createIfMissing)===!0});if(v!=null&&v.success){o("done"),l(N!=null&&N.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}o("error"),l((v==null?void 0:v.error)||"Could not save workspace")}catch(v){o("error"),l(v instanceof Error?v.message:"Could not save workspace")}},[e]),S=i.useCallback(async h=>{var C,N,v,M,I,j;try{o("loading"),l("Starting daemon upgrade…");const w=await e(h,"daemon_upgrade",{});if((C=w==null?void 0:w.result)!=null&&C.alreadyLatest){o("done"),l(`Already on v${((N=w==null?void 0:w.result)==null?void 0:N.version)||"latest"}.`);return}if((v=w==null?void 0:w.result)!=null&&v.upgraded||(M=w==null?void 0:w.result)!=null&&M.success){o("done"),l(`Upgrade to v${((I=w==null?void 0:w.result)==null?void 0:I.version)||"latest"} started. Daemon is restarting…`);return}o("error"),l(((j=w==null?void 0:w.result)==null?void 0:j.error)||"Upgrade failed")}catch(w){o("error"),l(w instanceof Error?w.message:"Upgrade failed")}},[e]),g=i.useCallback(async(h,C,N,v)=>{var j,w,$;const M=Date.now(),I={machineId:h,kind:C,providerType:N,workspaceId:(v==null?void 0:v.workspaceId)||null,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:M};try{o("loading"),l(`Launching ${N}…`),m(I);const P={cliType:N};(j=v==null?void 0:v.workspacePath)!=null&&j.trim()?P.dir=v.workspacePath.trim():v!=null&&v.workspaceId&&(P.workspaceId=v.workspaceId),v!=null&&v.resumeSessionId&&(P.resumeSessionId=v.resumeSessionId),(w=v==null?void 0:v.args)!=null&&w.trim()&&(P.cliArgs=v.args.trim().split(/\s+/).filter(Boolean)),($=v==null?void 0:v.model)!=null&&$.trim()&&(P.initialModel=v.model.trim());const T=await e(h,"launch_cli",P),F=(T==null?void 0:T.result)||T,H=(F==null?void 0:F.sessionId)||(F==null?void 0:F.id);if(T!=null&&T.success&&H){m(null),o("done"),l(`${N} launched`),t(Qt(H));return}if(T!=null&&T.success){o("loading"),l(`${N} launch requested — waiting for session…`);return}m(null),o("error"),l((T==null?void 0:T.error)||(F==null?void 0:F.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(P){if(pb(P)){o("loading"),l(`${N} launch requested — waiting for session…`);return}m(null),o("error"),l(P instanceof Error?P.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),p=i.useCallback(async(h,C)=>{try{const N=await e(h,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),v=(N==null?void 0:N.result)??N;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(N){return console.error("Failed to list saved sessions on mobile:",N),[]}},[e]),y=i.useCallback(async(h,C)=>Cn(e,h,C),[e]);i.useEffect(()=>{if(!d)return;const h=Li(d.workspacePath),C=r.find(v=>{var P,T,F,H;if(!v||v.type==="adhdev-daemon"||fb(v.daemonId||v.id)!==d.machineId||(v.transport==="acp"?"acp":v.transport==="pty"?"cli":null)!==d.kind||String(v.agentType||v.type||"")!==d.providerType)return!1;const w=String(v.providerSessionId||"");if(d.resumeSessionId&&w)return w===d.resumeSessionId;if(h){const L=Li(v.workspace||v.runtimeWorkspaceLabel);return L?L===h:!1}return Number(v.lastUpdated||v._lastUpdate||v.timestamp||((H=(F=(T=(P=v.activeChat)==null?void 0:P.messages)==null?void 0:T.at)==null?void 0:F.call(T,-1))==null?void 0:H.timestamp)||0)>=d.startedAt-5e3});if(!C)return;const N=$l({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:n});N&&(m(null),o("done"),l(`${d.providerType} launched`),t(Qt(N)))},[n,r,t,d]),i.useEffect(()=>{if(!d)return;const h=window.setTimeout(()=>{m(C=>!C||C.startedAt!==d.startedAt?C:(o("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[d]);const b=i.useCallback(async(h,C)=>{if(C.kind==="ide"&&C.providerType){await f(h,C.providerType,{workspacePath:C.workspace||null});return}(C.kind==="cli"||C.kind==="acp")&&C.providerType&&await g(h,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[f,g]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:f,handleAddWorkspace:x,handleMachineUpgrade:S,handleLaunchWorkspaceProvider:g,handleListSavedSessions:p,handleBrowseDirectory:y,handleOpenRecent:b}}function xb({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:c,setSelectedMachineId:l,setSection:d,setMachineBackTarget:m}){const u=i.useCallback(b=>{o(b.tabKey),c("chat"),n(b)},[n,c,o]),f=i.useCallback(b=>{const h=e.find(C=>C.routeId===b.routeId&&C.streamSource==="native");h&&(o(h.tabKey),c("chat"),n(h))},[e,n,c,o]),x=i.useCallback(()=>{n(t),c("inbox")},[n,t,c]),S=i.useCallback((b,h="inbox")=>{l(b),a(),d("machines"),m(h),c("machine")},[a,m,c,d,l]),g=i.useCallback(b=>{const h=ys(b);h&&S(h,"chat")},[S]),p=i.useCallback(()=>{a(),c(r)},[r,a,c]),y=i.useCallback(b=>{d(b),c("inbox")},[c,d]);return{openConversation:u,openNativeConversation:f,backFromConversation:x,openMachine:S,openConversationMachine:g,backFromMachine:p,changeMachineSection:y}}function bs(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function bb(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function gb({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:x,onRequestedMobileSectionConsumed:S,onOpenHistory:g,onOpenRemote:p,onStopCli:y,wsStatus:b,isConnected:h,onShowAllHiddenConversations:C,onHideConversation:N,onOpenNewSession:v,liveSessionInboxState:M,setCliViewModeOverrides:I}){const[j,w]=i.useState(()=>{var J;return((J=e[0])==null?void 0:J.tabKey)||null}),[$,P]=i.useState(()=>e[0]?"chat":"inbox"),[T,F]=i.useState("chats"),[H,L]=i.useState(null),[k,A]=i.useState("inbox"),K=i.useRef([]),_=Ws(),D="0.9.75",O=i.useMemo(()=>e.find(J=>J.tabKey===j)||e[0]||null,[e,j]),X=i.useMemo(()=>O?r.find(J=>J.id===O.routeId):void 0,[r,O]),ge=i.useMemo(()=>!O||Ze(O)||!tt(O)?null:Os(O),[O]),ce=i.useMemo(()=>r.filter(J=>J.type==="adhdev-daemon").sort(to),[r]),ee=i.useMemo(()=>ce.find(J=>J.id===H)||null,[ce,H]),z=jn({sendDaemonCommand:a,activeConv:O||void 0,setActionLogs:o,isStandalone:c}),de=hb({sendDaemonCommand:a,navigate:_,ides:r,conversations:e}),pe=i.useMemo(()=>e.map(J=>{const Ae=$==="chat"&&(O==null?void 0:O.tabKey)===J.tabKey,Te=yn(J,M,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ae}),$e=us(J),Ue=Qc(J);return{conversation:J,timestamp:$e,preview:Ue,unread:Te.unread,requiresAction:Te.requiresAction,isWorking:Te.isWorking,inboxBucket:Te.inboxBucket}}),[e,M,$,O]),{markConversationRead:Y}=mb({conversations:e,machineEntries:ce,items:pe,selectedConversation:O,selectedTabKey:j,screen:$,liveSessionInboxState:M,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:x,onRequestedMobileSectionConsumed:S,setSelectedTabKey:w,setScreen:P,setSelectedMachineId:L,setSection:F,setMachineBackTarget:A,resetMachineAction:de.resetMachineAction}),ie=xb({conversations:e,selectedConversation:O,machineBackTarget:k,markConversationRead:Y,resetMachineAction:de.resetMachineAction,setSelectedTabKey:w,setScreen:P,setSelectedMachineId:L,setSection:F,setMachineBackTarget:A}),ye=i.useMemo(()=>Gr(pe.filter(J=>J.requiresAction)),[pe]),re=i.useMemo(()=>Gr(pe.filter(J=>J.unread&&!J.requiresAction)),[pe]),me=i.useMemo(()=>ib(pe.filter(J=>!J.unread&&!J.requiresAction&&J.isWorking),K.current),[pe]);i.useEffect(()=>{K.current=me.map(J=>J.conversation.tabKey)},[me]);const ke=i.useMemo(()=>Gr(pe.filter(J=>!J.unread&&!J.requiresAction&&!J.isWorking)),[pe]),xe=i.useMemo(()=>ee?pe.filter(J=>ys(J.conversation)===ee.id):[],[pe,ee]),ve=i.useMemo(()=>lb(ee,r),[r,ee]),te=(ee==null?void 0:ee.version)||null,he=!!ee&&!!te&&!0&&te!==D,le=i.useMemo(()=>(ee==null?void 0:ee.availableProviders)||[],[ee]),ue=i.useMemo(()=>le.filter(J=>bs(J,"cli")).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[le]),oe=i.useMemo(()=>le.filter(J=>bs(J,"acp")).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[le]),Q=i.useMemo(()=>db(ce,pe),[pe,ce]),fe=i.useCallback(async J=>{ee&&await de.handleOpenRecent(ee.id,J)},[de,ee]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:$==="chat"&&O?s.jsx(Jx,{selectedConversation:O,isAcp:Ze(O),isStandalone:c,selectedIdeEntry:X,actionLogs:n,userName:l,isSendingChat:z.isSendingChat,sendFeedbackMessage:z.sendFeedbackMessage,isFocusingAgent:z.isFocusingAgent,handleModalButton:z.handleModalButton,handleRelaunch:z.handleRelaunch,onBack:ie.backFromConversation,onOpenNativeConversation:ie.openNativeConversation,onOpenMachine:ie.openConversationMachine,onOpenHistory:g,onOpenRemote:p,onStopCli:y,cliViewMode:ge,onSetCliViewMode:async J=>{await Nl({conversation:O,mode:J,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:I})},handleSendChat:z.handleSendChat,handleFocusAgent:z.handleFocusAgent}):$==="machine"&&ee?s.jsx(ob,{selectedMachineEntry:ee,selectedMachineConversations:xe,selectedMachineRecentLaunches:ve,cliProviders:ue,acpProviders:oe,selectedMachineNeedsUpgrade:he,appVersion:D,machineAction:de.machineAction,isStandalone:c,section:T,showBottomNav:k==="inbox",onBack:ie.backFromMachine,onSectionChange:ie.changeMachineSection,onOpenConversation:ie.openConversation,onOpenRecent:fe,onOpenMachineDetails:()=>_(`/machines/${ee.id}`),onMachineUpgrade:()=>de.handleMachineUpgrade(ee.id),onLaunchDetectedIde:(J,Ae)=>de.handleLaunchDetectedIde(ee.id,J,Ae),onAddWorkspace:(J,Ae)=>de.handleAddWorkspace(ee.id,J,Ae),onBrowseDirectory:J=>de.handleBrowseDirectory(ee.id,J),onLaunchWorkspaceProvider:(J,Ae,Te)=>de.handleLaunchWorkspaceProvider(ee.id,J,Ae,Te),onListSavedSessions:J=>de.handleListSavedSessions(ee.id,J)}):s.jsx(eb,{section:T,attentionItems:ye,unreadItems:re,workingItems:me,completedItems:ke,hiddenConversations:t,machineCards:Q,getAvatarText:bb,actionLogs:n,sendDaemonCommand:a,onOpenConversation:ie.openConversation,onShowAllHidden:C,onHideConversation:N,onOpenNewSession:v,onOpenMachine:ie.openMachine,onOpenSettings:()=>_("/settings"),onSectionChange:F,wsStatus:b,isConnected:h,isStandalone:c})})}function ta(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function yb({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const c=i.useRef(0),[l,d]=i.useState(!1),[m,u]=i.useState(null),f=i.useCallback(()=>{c.current=0,d(!1),u(null)},[]);i.useEffect(()=>(window.addEventListener("dragend",f),window.addEventListener("drop",f),()=>{window.removeEventListener("dragend",f),window.removeEventListener("drop",f)}),[f]);const x=i.useCallback(y=>{y.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,d(!0))},[]),S=i.useCallback(y=>{if(!y.dataTransfer.types.includes("text/tab-key"))return;if(y.preventDefault(),!ta(t,r)){u("merge");return}const b=y.currentTarget.getBoundingClientRect(),h=y.clientX-b.left,C=b.width/3;h<C?u("split-left"):h>C*2?u("split-right"):u("merge")},[t,r]),g=i.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,d(!1),u(null))},[]),p=i.useCallback(y=>{c.current=0,d(!1);const b=y.dataTransfer.getData("text/tab-key"),h=b?e.some(N=>N.tabKey===b):!1,C=m;if(u(null),o(),!!b){if(y.preventDefault(),C==="split-left"&&ta(t,r)){r==null||r(b,"split-left");return}if(C==="split-right"&&ta(t,r)){r==null||r(b,"split-right");return}if(h){a(b);return}n==null||n(b)}},[e,m,t,r,n,a,o]);return{dragOver:l,dropAction:m,resetDragState:f,handleDragEnter:x,handleDragOver:S,handleDragLeave:g,handleDrop:p}}function vb(e,t){const r=new Set(t.map(o=>o.tabKey)),n=e.filter(o=>r.has(o)),a=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...n,...a]}function wb({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,c]=i.useState(t??null),[l,d]=i.useState(r??[]),[m,u]=i.useState(null),f=i.useRef(null),x=i.useRef(null),S=i.useRef(n),g=i.useRef(a);i.useEffect(()=>{S.current=n},[n]),i.useEffect(()=>{g.current=a},[a]),i.useEffect(()=>{t&&t!==o&&c(t)},[t,o]),i.useEffect(()=>{d(I=>{const j=vb(I,e);return j.length===I.length&&j.every((w,$)=>w===I[$])?I:j})},[e]);const p=i.useMemo(()=>{const I=m??l;if(I.length===0)return e;const j=new Map(I.map((w,$)=>[w,$]));return[...e].sort((w,$)=>{const P=j.get(w.tabKey)??999,T=j.get($.tabKey)??999;return P-T})},[e,m,l]);i.useEffect(()=>{var j,w;if(p.length===0){o!==null&&(c(null),(j=S.current)==null||j.call(S,null));return}if(o&&p.some($=>$.tabKey===o))return;const I=p[0].tabKey;I!==o&&(c(I),(w=S.current)==null||w.call(S,I))},[p,o]);const y=i.useMemo(()=>p.find(I=>I.tabKey===o),[p,o]),b=i.useCallback(I=>{var j;c(I),(j=S.current)==null||j.call(S,I)},[]),h=i.useCallback((I,j,w)=>{d($=>{var H;const P=$.filter(L=>L!==I),T=P.indexOf(j);if(T<0)return $;const F=w==="left"?T:T+1;return P.splice(F,0,I),(H=g.current)==null||H.call(g,P),P}),u(null)},[]),C=i.useCallback((I,j,w)=>{const P=(l.length>0?l:e.map(H=>H.tabKey)).filter(H=>H!==I),T=P.indexOf(j);if(T<0)return;const F=w==="left"?T:T+1;P.splice(F,0,I),f.current=P,u(P)},[l,e]),N=i.useCallback(()=>{var j;const I=f.current;I&&(d(I),(j=g.current)==null||j.call(g,I))},[]),v=i.useCallback(()=>{f.current=null,u(null)},[]),M=i.useCallback(I=>{d(j=>{var $;const w=j.filter(P=>P!==I);return w.push(I),($=g.current)==null||$.call(g,w),w})},[]);return{activeTabId:o,activeConv:y,sortedConversations:p,previewOrderRef:f,draggingTabRef:x,selectTab:b,handleTabReorder:h,updatePreviewOrder:C,commitPreviewOrder:N,clearPreviewOrder:v,moveTabToEnd:M,setDraggingTabKey:I=>{x.current=I}}}function jb({dropAction:e,canSplit:t}){return s.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),s.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function To({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:o}){if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!r&&!n,l=n&&!!o,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?sl: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&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),l&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Bt,"aria-label":Bt,children:[s.jsx(xc,{size:14}),s.jsx("span",{children:Bt})]})}),c&&s.jsx(Kl,{}),c&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const Ul="adhdev-tab-shortcuts";function zl(){try{return JSON.parse(localStorage.getItem(Ul)||"{}")}catch{return{}}}function Vl({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,c]=i.useState(()=>zl()),[l,d]=i.useState(null),m=i.useCallback(f=>{const x=[];return f.metaKey&&x.push(a?"⌘":"Meta"),f.ctrlKey&&x.push("Ctrl"),f.altKey&&x.push(a?"⌥":"Alt"),f.shiftKey&&x.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(x.push(f.key.length===1?f.key.toUpperCase():f.key),x.join("+"))},[a]),u=i.useCallback(f=>{c(f);try{localStorage.setItem(Ul,JSON.stringify(f))}catch{}},[]);return i.useEffect(()=>{if(!e||!l)return;const f=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){d(null);return}const S=m(x);if(!S)return;const g={...o};for(const[p,y]of Object.entries(g))y===S&&delete g[p];g[l]=S,u(g),d(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[e,l,o,u,m]),i.useEffect(()=>{if(!e)return;const f=x=>{if(!(!x.ctrlKey&&!x.metaKey&&!x.altKey)){for(const[S,g]of Object.entries(o))if(t.includes(S)&&m(x)===g){x.preventDefault(),r(),n(S);return}}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,o,t,r,n,m]),{isMac:a,tabShortcuts:o,shortcutListening:l,setShortcutListening:d,saveShortcuts:u}}const sa=e=>{e.preventDefault()},kb=i.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:c,draggingTabRef:l,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:f,onReorderTab:x,onCommitPreviewOrder:S,onClearPreviewOrder:g,onDragStateReset:p,onDragTabKeyChange:y,onReceiveTab:b,onOpenContextMenu:h,longPressTimer:C,isGroupActive:N}){const v=Ks(t),M=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",I=v.isReconnecting,j=i.useCallback(A=>{l.current=t.tabKey,y(t.tabKey),A.dataTransfer.setData("text/tab-key",t.tabKey),A.dataTransfer.effectAllowed="move"},[t.tabKey,l,y]),w=i.useCallback(()=>{l.current=null,y(null),S(),g(),p()},[l,y,S,g,p]),$=i.useCallback(A=>{const K=l.current;if(!(!K||K===t.tabKey)&&A.dataTransfer.types.includes("text/tab-key")){A.preventDefault(),A.stopPropagation();const _=A.currentTarget.getBoundingClientRect(),D=A.clientX<_.left+_.width/2?"left":"right";f(K,t.tabKey,D)}},[t.tabKey,l,f]),P=i.useCallback(A=>{A.preventDefault(),A.stopPropagation();const K=A.dataTransfer.getData("text/tab-key");if(K&&K!==t.tabKey){const _=A.currentTarget.getBoundingClientRect(),D=A.clientX<_.left+_.width/2?"left":"right";c.includes(K)?x(K,t.tabKey,D):b&&b(K)}g()},[t.tabKey,c,x,b,g]),T=i.useCallback(A=>{A.stopPropagation(),d(),m(t.tabKey),u(t)},[t,u,d,m]),F=i.useCallback(A=>{A.preventDefault(),h(A.clientX,A.clientY,t.tabKey)},[t.tabKey,h]),H=i.useCallback(A=>{const K=A.touches[0];C.current=setTimeout(()=>{h(K.clientX,K.clientY,t.tabKey)},600)},[t.tabKey,C,h]),L=i.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),k=["adhdev-dockview-tab",M,r&&"is-active",N&&"is-group-active",I&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:k,draggable:!0,onDragStart:j,onDragEnd:w,onDragOver:$,onDrop:P,onClick:T,onContextMenu:F,onTouchStart:H,onTouchEnd:L,onTouchMove:L,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:v.isGenerating?s.jsx("div",{className:"tab-spinner"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):I?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:lt(t),children:lt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[I?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:os(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[os(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:os(t)}),s.jsx(Ds,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),o&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${o}`,children:o})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function Sb({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:x,onDragTabKeyChange:S,onReceiveTab:g,onHideTab:p,isGroupActive:y,allowTabShortcuts:b=!0}){const[h,C]=i.useState(null),N=i.useRef(null),v=i.useRef(null),M=i.useMemo(()=>e.map(F=>F.tabKey),[e]);pr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:I,tabShortcuts:j,shortcutListening:w,setShortcutListening:$,saveShortcuts:P}=Vl({enabled:b,sortedTabKeys:e.map(F=>F.tabKey),onFocus:o,onSelectTab:c});i.useEffect(()=>{if(!h)return;const F=H=>{const L=document.querySelector("[data-pane-context-menu]");L&&L.contains(H.target)||C(null)};return window.addEventListener("mousedown",F,!0),()=>window.removeEventListener("mousedown",F,!0)},[h]),i.useEffect(()=>{const F=v.current;if(!F)return;const H=L=>{Math.abs(L.deltaY)<=Math.abs(L.deltaX)||(L.preventDefault(),F.scrollLeft+=L.deltaY)};return F.addEventListener("wheel",H,{passive:!1}),()=>F.removeEventListener("wheel",H)},[]);const T=i.useCallback((F,H,L)=>{C({x:F,y:H,tabKey:L})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:v,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(F=>s.jsx(kb,{conv:F,isActive:t===F.tabKey,isDraggedTab:a.current===F.tabKey,isTaskCompleteUnread:n.has(F.tabKey),shortcut:b?j[F.tabKey]:void 0,conversationKeys:M,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:x,onDragTabKeyChange:S,onReceiveTab:g,onOpenContextMenu:T,longPressTimer:N,isGroupActive:y},F.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),h&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:h.x,top:h.y},children:[b&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:sa,onClick:F=>{F.stopPropagation(),$(h.tabKey),C(null)},children:["⌨ ",j[h.tabKey]?`Change shortcut (${j[h.tabKey]})`:"Set shortcut"]}),j[h.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:sa,onClick:()=>{const F={...j};delete F[h.tabKey],P(F),C(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[b&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:sa,onClick:()=>{p(h.tabKey),C(null)},children:"🚫 Hide from Dashboard"})]})]}),b&&w&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>$(null),children:s.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:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",I?"⌘+1":"Ctrl+1",", ",I?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Nb({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,userName:d,groupIndex:m,onFocus:u,isSplitMode:f,numGroups:x,onMoveTab:S,onReceiveTab:g,style:p,onActiveTabChange:y,initialActiveTabId:b,initialTabOrder:h,onTabOrderChange:C,onHideTab:N,isFocused:v,allowTabShortcuts:M=!0,onOpenNewSession:I,liveSessionInboxState:j}){const{sendCommand:w}=gt(),$=i.useRef(null),{activeTabId:P,activeConv:T,sortedConversations:F,draggingTabRef:H,selectTab:L,handleTabReorder:k,updatePreviewOrder:A,commitPreviewOrder:K,clearPreviewOrder:_,moveTabToEnd:D,setDraggingTabKey:O}=wb({conversations:e,initialActiveTabId:b,initialTabOrder:h,onActiveTabChange:y,onTabOrderChange:C}),X=jn({sendDaemonCommand:a,activeConv:T,setActionLogs:o,isStandalone:c}),{dragOver:ge,dropAction:ce,resetDragState:ee,handleDragEnter:z,handleDragOver:de,handleDragLeave:pe,handleDrop:Y}=yb({conversations:e,numGroups:x,onMoveTab:S,onReceiveTab:g,onOwnTabDrop:D,onClearPreviewOrder:_}),ie=T&&!Ze(T)&&Os(T)==="terminal",ye=i.useMemo(()=>T?t.find(xe=>xe.id===T.routeId):void 0,[t,T]),re=i.useMemo(()=>T?n.filter(xe=>xe.routeId===T.tabKey):[],[n,T]),me=i.useMemo(()=>new Set(F.filter(xe=>um(xe,j,{isOpenConversation:xe.tabKey===P})).map(xe=>xe.tabKey)),[P,j,F]);pr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:P,dragOver:ge});const ke=i.useCallback(xe=>{xe.streamSource==="agent-stream"&&xe.agentType&&w(xe.routeId,Bc(),{agentType:xe.agentType,...xe.sessionId&&{targetSessionId:xe.sessionId}}).catch(()=>{})},[w]);return s.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:[s.jsx(Sb,{conversations:F,activeTabId:P,groupIndex:m,numGroups:x,unreadTabKeys:me,draggingTabRef:H,onFocus:u,onSelectTab:L,onConversationActivated:ke,onPreviewReorder:A,onReorderTab:k,onCommitPreviewOrder:K,onClearPreviewOrder:_,onDragStateReset:ee,onDragTabKeyChange:O,onMoveTab:S,onReceiveTab:g,onHideTab:N,isGroupActive:v??!1,allowTabShortcuts:M}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:z,onDragOver:de,onDragLeave:pe,onDrop:Y,children:[ge&&s.jsx(jb,{dropAction:ce,canSplit:!!(x<4&&S)}),T?s.jsx(No,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!ie,ideEntry:ye,terminalRef:$,handleModalButton:X.handleModalButton,handleRelaunch:X.handleRelaunch,handleSendChat:X.handleSendChat,isSendingChat:X.isSendingChat,sendFeedbackMessage:X.sendFeedbackMessage,handleFocusAgent:X.handleFocusAgent,isFocusingAgent:X.isFocusingAgent,actionLogs:re,userName:d,isInputActive:!f||!!v}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(To,{conversationsCount:e.length,isSplitMode:f,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:I})})]})]})}function Cb({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:f,userName:x,focusedGroup:S,focusGroup:g,moveTabToGroup:p,splitTabRelative:y,closeGroup:b,handleResizeStart:h,groupActiveTabIds:C,setGroupActiveTab:N,groupTabOrders:v,setGroupTabOrder:M,toggleHiddenTab:I,onOpenNewSession:j,allowTabShortcuts:w=!0,liveSessionInboxState:$}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((P,T)=>{const F=t&&n.length===r?`${n[T]}%`:void 0;return s.jsxs(Ct.Fragment,{children:[t&&T>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:H=>h(T-1,H),onDoubleClick:()=>b(T),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(Nb,{style:t?{flexBasis:F??`${100/r}%`,flexGrow:F?0:1,flexShrink:F?0:1}:void 0,conversations:P,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:f,userName:x,groupIndex:T,isFocused:t&&S===T,onFocus:()=>g(T),isSplitMode:t,numGroups:r,onMoveTab:(H,L)=>{L==="left"&&T>0?p(H,T-1):L==="right"&&T<r-1?p(H,T+1):L==="split-left"&&r<4?y(H,T,"left"):L==="split-right"&&r<4&&y(H,T,"right")},onReceiveTab:H=>p(H,T),onActiveTabChange:H=>N(T,H),initialActiveTabId:C[T],initialTabOrder:v[T],onTabOrderChange:H=>M(T,H),onHideTab:I,onOpenNewSession:j,allowTabShortcuts:w,liveSessionInboxState:$})]},T)})})}function Gl({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=i.useState(null),[c,l]=i.useState(null);i.useEffect(()=>e?ut.onScreenshot("ide-page",(u,f)=>{if(u!==e)return;const x=new FileReader;x.onload=()=>o(x.result),x.readAsDataURL(f)}):void 0,[e]),i.useEffect(()=>{r!=="connected"&&o(null)},[r]),i.useEffect(()=>{var u;return e?((u=ut.onStatus)==null?void 0:u.call(ut,(f,x)=>{f===e&&x!=null&&x.screenshotUsage&&l(x.screenshotUsage)}))||(()=>{}):void 0},[e]),i.useEffect(()=>{o(null)},[e,t]),i.useEffect(()=>{const m=e?ut.get(e):null;if(!(!m||r!=="connected"))return n!=="chat"&&t?m.startScreenshots(t):m.stopScreenshots(t),()=>{m.stopScreenshots(t)}},[n,r,t,e]);const d=i.useCallback(async(m,u)=>{const f=e?ut.get(e):null;return!f||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):f.sendInput(m,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:d}}const ql="adhdev-dashboard-action-shortcuts",Tb=1200,Mb=[["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 Ib(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function at(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function Yl(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 Wa(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function pn(e){const t=Object.fromEntries(Yl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(ql)||"{}"),n={...t,...r};for(const[a,o]of Mb)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function Xl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Ab({enabled:e=!0,onTrigger:t}){const r=Ib(),[n,a]=i.useState(()=>pn(r)),[o,c]=i.useState(null),[l,d]=i.useState([]),m=i.useRef({parts:[],timer:null}),u=i.useCallback(p=>{const y=[];return p.metaKey&&y.push(r?"⌘":"Meta"),p.ctrlKey&&y.push("Ctrl"),p.altKey&&y.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&y.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(y.push(Xl(p.key)),y.join("+"))},[r]),f=i.useCallback(p=>{a(p);try{localStorage.setItem(ql,JSON.stringify(p))}catch{}},[]);i.useEffect(()=>{const p=pn(r),y=Object.entries(n),b=Object.entries(p);y.length===b.length&&y.every(([h,C])=>p[h]===C)||f(p)},[n,r,f]);const x=i.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),S=i.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},Tb))},[]);i.useEffect(()=>{if(!o)return;const p=y=>{if(y.preventDefault(),y.stopPropagation(),y.key==="Escape"){c(null),d([]);return}const b=u(y);if(!b)return;const C=!(y.metaKey||y.ctrlKey||y.altKey)&&/^[A-Z0-9]$/.test(b);if(l.length===0&&C){d([b]);return}const v=[...l,b].slice(0,2).join(" "),M={...n};for(const[I,j]of Object.entries(M))j===v&&delete M[I];M[o]=v,f(M),c(null),d([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,u,f,o,l]),i.useEffect(()=>{if(!e||o)return;const p=y=>{if(y.defaultPrevented)return;const b=u(y);if(!b)return;const h=y.metaKey||y.ctrlKey||y.altKey;if(Wa(y.target))return;const C=m.current.parts,N=h?[b]:[...C.slice(-1),b].slice(-2),v=N.join(" "),M=N[N.length-1],I=Object.entries(n).filter(([,T])=>!!T),j=I.find(([,T])=>T===v);if(j){y.preventDefault(),x(),t(j[0]);return}if(I.some(([,T])=>T.startsWith(`${v} `))){y.preventDefault(),m.current.parts=N,S();return}const $=I.find(([,T])=>T===M);if($){y.preventDefault(),x(),t($[0]);return}if(I.some(([,T])=>T.startsWith(`${M} `))){y.preventDefault(),m.current.parts=[M],S();return}x()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,S,e,u,t,x,o]),i.useEffect(()=>()=>x(),[x]);const g=i.useMemo(()=>Yl(r),[r]);return{isMac:r,actionDefinitions:g,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:d,saveShortcuts:f}}function Rb({isTabInPopout:e,isTabFloating:t,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(t&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):t?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:r?`Change shortcut (${r})`:"Set shortcut",shortcut:n.setActiveTabShortcut}),r&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:n.hideCurrentTab,tone:"muted"}),a}function Jl(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Pi({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!Jl(n):!0}function Lb({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:Jl(r)}const Ql=1e3,Pb=4;function _i(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Di(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function _b({detachDelayMs:e=Ql,stillnessThresholdPx:t=Pb,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,c=null,l=null,d=null,m=null,u=!1;const f=()=>{m!=null&&(a(m),m=null)},x=()=>{f(),l=null},S=()=>{f(),o=null,c=null,l=null,d=null,u=!1},g=()=>{!o||!l||!d||u||m!=null||(m=n(()=>{m=null,!(!o||!l||!d||u)&&_i(d,c)&&(Di(l,d,t)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},p=b=>{if(!(!o||u)){if(!_i(b,c)){d={clientX:b.clientX,clientY:b.clientY},x();return}(!l||Di(l,b,t))&&(f(),l={clientX:b.clientX,clientY:b.clientY}),d={clientX:b.clientX,clientY:b.clientY},g()}},y=b=>{!o||u||(b&&(d={clientX:b.clientX,clientY:b.clientY}),x())};return{startDrag:b=>{f(),o=b.panelId,c=b.selfPanelBounds??null,l=null,d={clientX:b.clientX,clientY:b.clientY},u=!1},markSelfPanel:p,markNonSelfPanel:y,markNoDropTarget:y,markDockTarget:y,endDrag:S,isDragging:()=>o!=null,hasDetached:()=>u,dispose:S}}function Db(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function $r(e){return e.isActive}function Ei(e){return e.isVisible}const Zl=i.createContext(null);function In(){const e=i.useContext(Zl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function qr(e){return lt(e)||e.tabKey}function Eb(e){return`remote:${e}`}function Pt(e){return e.startsWith("remote:")}function $i(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function $b(e){e.preventDefault()}function ra(e){var n;const t=e==null?void 0:e.defaultView;if(!t)return;const r=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),r(e==null?void 0:e.body),r(e==null?void 0:e.documentElement),(n=t.requestAnimationFrame)==null||n.call(t,()=>{try{t.focus(),r(e==null?void 0:e.body)}catch{}})}catch{}}function na(e,t){e.classList.remove(ya.className,va.className),e.classList.add(t==="light"?ya.className:va.className)}function Bi(e){return e?Array.from(new Set(e.groups.map(t=>{var r,n;return(n=(r=t.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(t=>!!t&&t!==window))):[]}function Bb(e){const[,t]=i.useState(0);i.useEffect(()=>{const r=()=>t(a=>a+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const a of n)a.dispose()}},[e.api,e.containerApi])}function Wb(e,t,r){var c;const n=[t];let a;for(const l of n){let d;for(const m of l){const u=e.addPanel({id:m.tabKey,component:"conversation",title:qr(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??((c=t[0])==null?void 0:c.tabKey)??null}function Wi(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])Pt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of t){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==qr(n)&&a.api.setTitle(qr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:qr(n),params:{kind:"conversation",tabKey:n.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 Ki(e,t,r){var d,m;const n=r?Eb(r):null;for(const u of[...e.panels])Pt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Et(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),c=tl(a);if(o){o.title!==c&&o.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((m=e.panels.find(u=>!Pt(u.id)))==null?void 0:m.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function Kb({params:e,api:t}){var S;const r=In(),n=i.useRef(null),[a,o]=i.useState(()=>$r(t)),[c,l]=i.useState(()=>Ei(t)),d=r.conversationsByTabKey.get(e.tabKey),m=jn({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});i.useEffect(()=>{o($r(t)),l(Ei(t));const g=[t.onDidActiveChange(p=>o(p.isActive)),t.onDidActiveGroupChange(p=>{if(!$r(t)&&!p.isActive){o(!1);return}o($r(t))}),t.onDidVisibilityChange(p=>l(p.isVisible))];return()=>{for(const p of g)p.dispose()}},[t]);const u=i.useMemo(()=>d?r.ides.find(g=>g.id===d.routeId):void 0,[r.ides,d]),f=i.useMemo(()=>d?r.actionLogs.filter(g=>g.routeId===d.tabKey):[],[r.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(To,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const x=!Ze(d)&&Os(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(No,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:x,ideEntry:u,terminalRef:n,handleModalButton:m.handleModalButton,handleRelaunch:m.handleRelaunch,handleSendChat:m.handleSendChat,isSendingChat:m.isSendingChat,handleFocusAgent:m.handleFocusAgent,isFocusingAgent:m.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((S=r.scrollToBottomRequest)==null?void 0:S.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:c})})}function Ob({params:e}){var d;const t=In(),r=i.useMemo(()=>Et([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=i.useMemo(()=>t.ides.find(m=>m.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((d=r==null?void 0:r.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:c,handleRemoteAction:l}=Gl({doId:a,targetSessionId:r?$c(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(jc,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:o,screenshotUsage:c,transportType:r.transport,onAction:l})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function Fb(){const e=In();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(To,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Hb(e){var S,g;Bb(e);const t=In(),r=i.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=Et([...t.conversationsByTabKey.values()],e.params.routeId),y=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,b=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${y?" is-active":""}${b?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:p!=null&&p.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:p.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const n=t.conversationsByTabKey.get(e.params.tabKey);if(!n)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((g=e.api.group.activePanel)==null?void 0:g.id)===e.api.id,o=e.api.isGroupActive,c=yn(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,d=c.isConnecting,m=c.isGenerating,u=c.isWaiting,f=c.unread,x=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${o?" is-group-active":""}${l?" is-reconnecting":""}`,title:lt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var y;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((y=p.target)==null?void 0:y.ownerDocument)??document})},children:[f&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:m?s.jsx("div",{className:"tab-spinner"}):u?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):d?s.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:lt(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:os(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:os(n)}):s.jsx("span",{children:os(n)})})]}),x&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:x,children:x})]})}function Ub({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:d,userName:m,toggleHiddenTab:u,actionShortcuts:f,registerActionHandlers:x,onActiveTabChange:S,onOpenNewSession:g,onRequestScrollToBottom:p,requestedActiveTabKey:y,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:h,scrollToBottomRequest:C,liveSessionInboxState:N,layoutProfile:v}){var Qe,Ge,rt;const{theme:M}=go(),{sendCommand:I}=gt(),j=i.useRef(null),w=i.useRef(null),$=i.useRef(null),P=i.useRef(!1),T=i.useRef(!1),F=i.useRef(!1),H=i.useRef(null),L=i.useRef([]),[k,A]=i.useState(null),[K,_]=i.useState(0),D=i.useRef(typeof window>"u"?{}:cx(v)),O=i.useMemo(()=>new Map(e.map(W=>[W.tabKey,W])),[e]),X=i.useMemo(()=>{const W=j.current;return W?W.groups.some(U=>{try{const G=U.model.location.type;return G!=="floating"&&G!=="popout"?!1:U.panels.some(se=>O.has(se.id))}catch{return!1}}):!1},[O,K,e]),ge=i.useCallback(()=>{var W;(W=j.current)==null||W.focus()},[]),ce=i.useCallback((W,U)=>{p==null||p(W,U)},[p]),ee=i.useCallback(W=>{const U=document,G=W.document;for(const ne of U.querySelectorAll('link[rel="stylesheet"]')){const je=G.createElement("link");je.rel="stylesheet",je.href=ne.href,ne.crossOrigin&&(je.crossOrigin=ne.crossOrigin),G.head.appendChild(je)}for(const ne of U.querySelectorAll("style")){const je=G.createElement("style");je.textContent=ne.textContent,G.head.appendChild(je)}const se=[];for(const ne of U.styleSheets)try{for(const je of ne.cssRules)je instanceof CSSStyleRule&&(je.selectorText===":root"||je.selectorText==="html")&&se.push(je.cssText)}catch{}if(se.length>0){const ne=G.createElement("style");ne.textContent=se.join(`
|
|
52
|
+
`),G.head.appendChild(ne)}const E=U.documentElement.getAttribute("data-theme");E&&G.documentElement.setAttribute("data-theme",E),G.documentElement.style.colorScheme=E==="light"?"light":"dark",G.body.className=U.body.className;const q=U.documentElement.getAttribute("style");q&&G.documentElement.setAttribute("style",q);const Z=G.getElementById("dv-popout-window");Z instanceof HTMLElement&&(Z.classList.add("adhdev-dockview"),na(Z,M))},[M]),z=i.useCallback(()=>{var U;const W=j.current;if(W)for(const G of W.groups)try{const se=(U=G.element)==null?void 0:U.ownerDocument;if(!se||se===document)continue;const E=se.getElementById("dv-popout-window");E instanceof HTMLElement&&(E.classList.add("adhdev-dockview"),na(E,M));const q=document.documentElement.getAttribute("data-theme");q&&se.documentElement.setAttribute("data-theme",q),se.documentElement.style.colorScheme=q==="light"?"light":"dark",se.body.className=document.body.className;const Z=document.documentElement.getAttribute("style");Z?se.documentElement.setAttribute("style",Z):se.documentElement.removeAttribute("style")}catch{}},[M]),de=i.useCallback(W=>{const U=j.current;if(!U)return;const G=U.getPanel(W);G&&U.addPopoutGroup(G,{popoutUrl:"/popout.html",onDidOpen:({window:se})=>{ee(se),ve();const E=O.get(W);se.document.title=E?`${lt(E)} — ADHDev`:"ADHDev — Popout"}})},[O,ee]),pe=i.useCallback(W=>{const U=j.current,G=U==null?void 0:U.getPanel(W);if(!U||!G)return;const se=U.groups.filter(E=>{var q;try{return((q=E.element)==null?void 0:q.ownerDocument)===document}catch{return!0}});se.length>0?G.api.moveTo({group:se[0],position:"center"}):G.api.moveTo({position:"center"}),G.api.setActive()},[]),Y=i.useCallback(W=>{var se;const U=j.current;if(!U)return!1;const G=U.getPanel(W);if(!G)return!1;try{return((se=G.group.element)==null?void 0:se.ownerDocument)!==document}catch{return!1}},[]),ie=i.useCallback(W=>{Y(W)&&pe(W),u(W)},[Y,pe,u]),ye=i.useCallback(W=>{const U=j.current,G=U==null?void 0:U.getPanel(W);!U||!G||U.addFloatingGroup(G,{width:600,height:500})},[]),re=i.useCallback(W=>{var G;const U=(G=j.current)==null?void 0:G.getPanel(W);if(!U)return!1;try{return U.group.model.location.type==="floating"}catch{return!1}},[]),me=i.useCallback(()=>{var U,G;const W=(G=(U=j.current)==null?void 0:U.activePanel)==null?void 0:G.id;return!W||Pt(W)?null:O.has(W)?W:null},[O]),ke=i.useCallback(W=>{const U=j.current,G=U==null?void 0:U.getPanel(W);if(!U||!G)return;const se=U.groups.filter(E=>{try{return E.model.location.type==="grid"}catch{return!0}});se.length>0?G.api.moveTo({group:se[0],position:"center"}):G.api.moveTo({position:"center"}),G.api.setActive()},[]),xe=i.useCallback(()=>{var q;const W=j.current;if(!W)return;const G=W.groups.filter(Z=>{var ne;try{return((ne=Z.element)==null?void 0:ne.ownerDocument)===document&&Z.model.location.type==="grid"}catch{return!1}})[0]||null,se=[...W.panels];for(const Z of se){const ne=(q=Z.group.element)==null?void 0:q.ownerDocument,je=Z.group.model.location.type;ne===document&&je==="grid"||(G&&G.id!==Z.group.id?Z.api.moveTo({group:G,position:"center"}):Z.api.moveTo({position:"center"}))}const E=W.activePanel;E&&(E.group.model.openPanel(E),E.api.setActive()),ra(document)},[]),ve=i.useCallback(()=>{var U,G;const W=j.current;if(W)for(const se of W.groups){const E=(U=se.element)==null?void 0:U.ownerDocument;if(!E||E===document)continue;const q=E.getElementById("dv-popout-window");if(!(q instanceof HTMLElement))continue;let Z=null,ne=E.title||"ADHDev",je="Popout workspace";const Le=se.activePanel;if(Le)if(Z=Le.id,Pt(Le.id)){const Re=((G=Le.params)==null?void 0:G.routeId)||Le.id.slice(7),qe=Et([...O.values()],Re);ne=tl(qe),je=qe!=null&&qe.machineName?`Remote view · ${qe.machineName}`:"Remote view"}else{const Re=O.get(Le.id);ne=Re?lt(Re):Le.title||Le.id,je=Re?os(Re):"Dockview panel"}E.title=`${ne} — ADHDev`;const _e=Array.from(E.querySelectorAll("#adhdev-popout-header"));for(const Re of _e)Re.remove();const Ne=E.createElement("div");Ne.id="adhdev-popout-header",E.body.appendChild(Ne),Ne.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(";")),Ne.innerHTML=`
|
|
53
|
+
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
54
|
+
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
55
|
+
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${$i(ne)}</div>
|
|
56
|
+
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${$i(je)}</div>
|
|
57
|
+
</div>
|
|
58
|
+
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
59
|
+
<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>
|
|
60
|
+
<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>
|
|
61
|
+
</div>
|
|
62
|
+
`,q.style.top="52px",q.style.height="calc(100% - 52px)";const Ee=Ne.querySelector("[data-adhdev-popout-focus]");Ee&&(Ee.onclick=()=>{window.focus()});const Be=Ne.querySelector("[data-adhdev-popout-dock]");Be&&(Be.disabled=!Z,Be.style.opacity=Z?"1":"0.5",Be.style.cursor=Z?"pointer":"default",Be.onclick=()=>{var Re;Z&&pe(Z),(Re=E.defaultView)==null||Re.focus()})}},[O,pe]),te=i.useCallback(W=>{var se;const U=j.current,G=U==null?void 0:U.getPanel(W);if(!(!U||!G)){G.group.model.openPanel(G),G.api.setActive(),ce(W,"dockview-shortcut");try{const E=G.group.model.location;E.type==="popout"?E.getWindow().focus():ra((se=G.group.element)==null?void 0:se.ownerDocument)}catch{}}},[ce]),he=i.useCallback(W=>{const U=j.current,G=U==null?void 0:U.activePanel,se=(U==null?void 0:U.activeGroup)||(G==null?void 0:G.group);if(!U||!G||!se)return;const E=se.panels||[];if(E.length<=1)return;const q=E.findIndex(je=>je.id===G.id);if(q<0)return;const Z=(q+W+E.length)%E.length,ne=E[Z];ne&&(ne.group.model.openPanel(ne),ne.api.setActive(),Pt(ne.id)||ce(ne.id,"dockview-shortcut"))},[ce]),le=i.useCallback(W=>{var Ee;const U=j.current,G=(U==null?void 0:U.activeGroup)||((Ee=U==null?void 0:U.activePanel)==null?void 0:Ee.group);if(!U||!G)return;const se=U.groups||[],E=se.find(Be=>Be.id===G.id);if(!E)return;const q=E.element.getBoundingClientRect(),Z=q.left+q.width/2,ne=q.top+q.height/2,je=(Be,Re,qe,et)=>Math.max(0,Math.min(Re,et)-Math.max(Be,qe)),Le=Be=>{const Re=Be.element.getBoundingClientRect(),qe=Re.left+Re.width/2,et=Re.top+Re.height/2;let ct=0,ft=0,dt=0,yt=!1;if(W==="left"?(yt=qe<Z,ct=Math.max(0,q.left-Re.right),ft=Math.abs(et-ne),dt=je(q.top,q.bottom,Re.top,Re.bottom)):W==="right"?(yt=qe>Z,ct=Math.max(0,Re.left-q.right),ft=Math.abs(et-ne),dt=je(q.top,q.bottom,Re.top,Re.bottom)):W==="above"?(yt=et<ne,ct=Math.max(0,q.top-Re.bottom),ft=Math.abs(qe-Z),dt=je(q.left,q.right,Re.left,Re.right)):(yt=et>ne,ct=Math.max(0,Re.top-q.bottom),ft=Math.abs(qe-Z),dt=je(q.left,q.right,Re.left,Re.right)),!yt)return Number.POSITIVE_INFINITY;const Ve=dt>0?0:120;return ct*3+ft+Ve};let _e=null,Ne=Number.POSITIVE_INFINITY;for(const Be of se){if(Be.id===E.id)continue;const Re=Le(Be);Number.isFinite(Re)&&(Re>=Ne||(Ne=Re,_e=Be))}return _e||void 0},[]),ue=i.useCallback(W=>{var se;const U=le(W);if(!U)return;const G=U.activePanel||U.panels[0];G&&(U.model.openPanel(G),G.api.setActive(),Pt(G.id)||ce(G.id,"dockview-focus"),ra((se=U.element)==null?void 0:se.ownerDocument))},[le,ce]),oe=i.useCallback((W,U)=>{const G=j.current,se=G==null?void 0:G.activePanel,E=(G==null?void 0:G.activeGroup)||(se==null?void 0:se.group);if(!G||!se||!E)return;let q=le(W);!q&&(U!=null&&U.createGroupIfMissing)&&(q=G.addGroup({referenceGroup:E,direction:W})),q&&(se.api.moveTo({group:q,position:"center"}),se.group.model.openPanel(se),se.api.setActive(),Pt(se.id)||ce(se.id,U!=null&&U.createGroupIfMissing?"dockview-split":"dockview-move"))},[le,ce]),{isMac:Q,tabShortcuts:fe,shortcutListening:J,setShortcutListening:Ae,saveShortcuts:Te}=Vl({sortedTabKeys:e.map(W=>W.tabKey),onFocus:ge,onSelectTab:te}),$e=i.useCallback(()=>{var G;const W=j.current;if(!W)return;const U=W.activePanel;if(U){if(Pt(U.id)){const se=((G=U.params)==null?void 0:G.routeId)||U.id.slice(7),E=Et(e,se);E!=null&&E.tabKey&&Ae(E.tabKey);return}O.has(U.id)&&Ae(U.id)}},[O,te,Ae,e]),Ue=i.useCallback(W=>{const U=[];return W.metaKey&&U.push(Q?"⌘":"Meta"),W.ctrlKey&&U.push("Ctrl"),W.altKey&&U.push(Q?"⌥":"Alt"),W.shiftKey&&W.key.length!==1&&U.push(Q?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(W.key)?null:(U.push(Xl(W.key)),U.join("+"))},[Q]),B=i.useCallback(W=>{var U,G;switch(W){case"splitActiveTabRight":oe("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":oe("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const se=me();se&&ye(se);return}case"popoutActiveTab":{const se=me();se&&de(se);return}case"dockActiveTab":{const se=me();if(!se)return;Y(se)?pe(se):re(se)&&ke(se);return}case"focusLeftPane":ue("left");return;case"focusRightPane":ue("right");return;case"focusUpPane":ue("above");return;case"focusDownPane":ue("below");return;case"moveActiveTabToLeftPane":oe("left");return;case"moveActiveTabToRightPane":oe("right");return;case"moveActiveTabToUpPane":oe("above");return;case"moveActiveTabToDownPane":oe("below");return;case"selectPreviousGroupTab":he(-1);return;case"selectNextGroupTab":he(1);return;case"setActiveTabShortcut":$e();return;case"hideCurrentTab":{const se=(G=(U=j.current)==null?void 0:U.activePanel)==null?void 0:G.id;se&&!Pt(se)&&ie(se);return}default:return}},[he,ke,ue,ye,me,ie,re,Y,pe,oe,de,$e]);i.useEffect(()=>{if(!k)return;const W=k.sourceDocument,U=W.defaultView??window,G=se=>{const E=W.querySelector("[data-dockview-tab-context-menu]");E&&E.contains(se.target)||A(null)};return U.addEventListener("mousedown",G,!0),U!==window&&window.addEventListener("mousedown",()=>A(null),!0),()=>{U.removeEventListener("mousedown",G,!0),U!==window&&window.removeEventListener("mousedown",()=>A(null),!0)}},[k]);const Se=i.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:O,hasDetachedConversationPanels:X,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:g,liveSessionInboxState:N,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:ie,userName:m,scrollToBottomRequest:C,tabShortcuts:fe,openTabContextMenu:({x:W,y:U,tabKey:G,sourceDocument:se})=>A({x:W,y:U,tabKey:G,sourceDocument:se??document}),popoutTab:de,moveTabBackToMain:pe,isTabInPopout:Y,floatTab:ye,isTabFloating:re}),[n,t,O,X,r,c,l,g,N,a,o,ie,m,C,fe,de,pe,Y,ye,re]),Me=k?Rb({isTabInPopout:Y(k.tabKey),isTabFloating:re(k.tabKey),tabShortcut:fe[k.tabKey],actionShortcuts:f}):[],De=i.useCallback(W=>{var se;const U=j.current;if((((se=U==null?void 0:U.activePanel)==null?void 0:se.id)??null)===W.id){W.group.model.openPanel(W);return}W.group.model.openPanel(W),W.api.setActive()},[]),We=i.useCallback((W,U="requested-tab")=>{if(!W)return!1;const G=j.current;if(!G)return!1;const se=G.getPanel(W);return se?(De(se),ce(W,U),h==null||h(),!0):!1},[De,h,ce]),He=i.useCallback(()=>{if(F.current)return!1;const W=We(H.current,"stored-layout-restore");return W&&(F.current=!0),W},[We]),Je=i.useCallback(()=>{var U;const W=j.current;W&&ix(v,{activeTabId:((U=W.activePanel)==null?void 0:U.id)??null,layout:W.toJSON()})},[v]),st=i.useCallback(()=>{lx(v,D.current)},[v]),mt=i.useCallback(W=>{var se,E,q,Z;const U=j.current;if(!U)return{kind:"grid"};const G=U.toJSON();for(const ne of G.floatingGroups||[])if((E=(se=ne.data)==null?void 0:se.views)!=null&&E.includes(W)&&ne.position)return{kind:"floating",position:ne.position};for(const ne of G.popoutGroups||[])if((Z=(q=ne.data)==null?void 0:q.views)!=null&&Z.includes(W))return{kind:"popout",position:ne.position,popoutUrl:ne.url};return{kind:"grid"}},[]),ht=i.useCallback(W=>{const U=j.current;if(!U)return;const G=U.getPanel(W),se=D.current[W];if(!G||!se||se.kind==="grid")return;if(G.group.model.location.type===se.kind){delete D.current[W],st();return}if(se.kind==="floating"){U.addFloatingGroup(G,{x:se.position.left??24,y:se.position.top??24,width:se.position.width,height:se.position.height}),delete D.current[W],st();return}delete D.current[W],st()},[st]);i.useEffect(()=>(x==null||x({setShortcutForActiveTab:$e,restoreHiddenTabToSavedLocation:ht,activateConversationTab:te,resetAllPanelsToMain:xe,activatePreviousTabInGroup:()=>he(-1),activateNextTabInGroup:()=>he(1),floatActiveTab:()=>{const W=me();W&&ye(W)},popoutActiveTab:()=>{const W=me();W&&de(W)},dockActiveTab:()=>{const W=me();W&&(Y(W)?pe(W):re(W)&&ke(W))},splitActiveTabRight:()=>oe("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>oe("below",{createGroupIfMissing:!0}),focusLeftPane:()=>ue("left"),focusRightPane:()=>ue("right"),focusUpPane:()=>ue("above"),focusDownPane:()=>ue("below"),moveActiveTabToLeftPane:()=>oe("left"),moveActiveTabToRightPane:()=>oe("right"),moveActiveTabToUpPane:()=>oe("above"),moveActiveTabToDownPane:()=>oe("below")}),()=>x==null?void 0:x(null)),[he,ke,ye,ue,me,re,Y,oe,pe,de,x,xe,ht,te,$e]),i.useEffect(()=>()=>{var W;(W=$.current)==null||W.call($),$.current=null},[]);const xt=i.useCallback(W=>{var G,se;j.current=W.api,(G=$.current)==null||G.call($),$.current=null;const U=ox(v);if(H.current=(U==null?void 0:U.activeTabId)??null,U!=null&&U.layout&&W.api.fromJSON(U.layout,{reuseExistingPanels:!1}),T.current=Pi({hasStoredLayout:!!(U!=null&&U.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),T.current||(Wi(W.api,e),Ki(W.api,e,b)),W.api.totalPanels===0&&e.length>0){const E=Wb(W.api,e,y);if(E){const q=W.api.getPanel(E);q&&De(q)}}else!T.current&&!We(y)&&He();if(P.current=!0,W.api.onDidActivePanelChange(E=>{var Z;if(H.current=(E==null?void 0:E.id)??null,F.current=!0,ve(),E&&Pt(E.id)){const ne=((Z=E.params)==null?void 0:Z.routeId)||E.id.slice(7),je=Et(e,ne);S((je==null?void 0:je.tabKey)??null),Je();return}if(S((E==null?void 0:E.id)??null),Je(),!E)return;const q=O.get(E.id);(q==null?void 0:q.streamSource)==="agent-stream"&&q.agentType&&I(q.routeId,Bc(),{agentType:q.agentType,...q.sessionId&&{targetSessionId:q.sessionId}}).catch(()=>{})}),W.api.onDidLayoutChange(()=>{Je(),ve(),_(E=>E+1)}),Db()){const E=Ne=>({clientX:Ne.clientX,clientY:Ne.clientY}),q=Ne=>{const Ee=Ne==null?void 0:Ne.getBoundingClientRect();return Ee?{left:Ee.left,right:Ee.right,top:Ee.top,bottom:Ee.bottom}:null},Z=Ne=>{var Be;const Ee=(Be=w.current)==null?void 0:Be.getBoundingClientRect();return Ee?Ne.clientX<Ee.left||Ne.clientX>Ee.right||Ne.clientY<Ee.top||Ne.clientY>Ee.bottom:!1},ne=_b({detachDelayMs:Ql,onDetach:({panelId:Ne,clientX:Ee,clientY:Be})=>{var dt,yt;const Re=W.api.getPanel(Ne);if(!Re)return;try{if(Re.group.model.location.type!=="grid")return}catch{return}const qe=(dt=w.current)==null?void 0:dt.getBoundingClientRect(),et=(yt=Re.group.element)==null?void 0:yt.getBoundingClientRect(),ct=Math.round(Math.min(Math.max((et==null?void 0:et.width)??600,360),720)),ft=Math.round(Math.min(Math.max((et==null?void 0:et.height)??500,260),640));W.api.addFloatingGroup(Re,{x:qe?Math.max(0,Ee-qe.left-32):void 0,y:qe?Math.max(0,Be-qe.top-18):void 0,width:ct,height:ft}),Re.api.setActive(),Je(),ve(),_(Ve=>Ve+1)}}),je=[W.api.onWillDragPanel(Ne=>{if(!(Ne.nativeEvent.defaultPrevented||Ne.nativeEvent.shiftKey)){try{if(Ne.panel.group.model.location.type!=="grid")return}catch{return}ne.startDrag({panelId:Ne.panel.id,selfPanelBounds:q(Ne.panel.group.element),...E(Ne.nativeEvent)})}}),W.api.onWillShowOverlay(Ne=>{if(ne.hasDetached()){Ne.preventDefault();return}ne.markDockTarget(E(Ne.nativeEvent))}),W.api.onWillDrop(Ne=>{if(ne.hasDetached()){Ne.preventDefault(),ne.endDrag();return}ne.markDockTarget(E(Ne.nativeEvent))}),W.api.onDidDrop(()=>ne.endDrag()),W.api.onUnhandledDragOverEvent(Ne=>{ne.isDragging()&&ne.markSelfPanel(E(Ne.nativeEvent))})],Le=Ne=>{if(!ne.isDragging())return;const Ee=E(Ne);Z(Ee)&&ne.markNonSelfPanel(Ee)},_e=()=>ne.endDrag();window.addEventListener("dragover",Le,!0),window.addEventListener("drop",_e,!0),window.addEventListener("dragend",_e,!0),$.current=()=>{ne.dispose();for(const Ne of je)Ne.dispose();window.removeEventListener("dragover",Le,!0),window.removeEventListener("drop",_e,!0),window.removeEventListener("dragend",_e,!0)}}W.api.onDidAddGroup(E=>{requestAnimationFrame(()=>{var q,Z;try{const ne=(q=E.element)==null?void 0:q.ownerDocument;if(!ne||ne===document)return;(Z=ne.getElementById("dv-popout-window"))==null||Z.classList.add("adhdev-dockview");const je=document.documentElement.getAttribute("data-theme");je&&ne.documentElement.setAttribute("data-theme",je),ne.body.className=document.body.className;const Le=document.documentElement.getAttribute("style");Le&&ne.documentElement.setAttribute("style",Le)}catch{}ve(),_(ne=>ne+1)})}),S(((se=W.api.activePanel)==null?void 0:se.id)??null)},[De,We,O,r,d,v,S,Je,y,b,I,ve,e]);i.useLayoutEffect(()=>{const W=j.current;if(!W||!P.current||T.current&&Pi({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;T.current&&(T.current=!1);const U=L.current,G=new Set(U),se=e.map(_e=>_e.tabKey),E=new Set(se),q=Lb({previousVisibleConversationCount:U.length,visibleConversationCount:e.length,ides:r});let Z=!1;for(const _e of U)E.has(_e)||q||(D.current[_e]=mt(_e),Z=!0);Z&&st(),q||(Wi(W,e),Ki(W,e,b));const ne=se.filter(_e=>!G.has(_e));let je=!1;for(const _e of ne){const Ne=W.getPanel(_e),Ee=D.current[_e];if(!Ne||!Ee||Ee.kind==="grid")continue;if(Ne.group.model.location.type===Ee.kind){delete D.current[_e],je=!0;continue}if(Ee.kind==="floating"){W.addFloatingGroup(Ne,{x:Ee.position.left??24,y:Ee.position.top??24,width:Ee.position.width,height:Ee.position.height}),delete D.current[_e],je=!0;continue}}if(je&&st(),L.current=se,y&&We(y))return;!W.activePanel&&W.panels[0]&&De(W.panels[0]),!!(W.activePanel&&W.getPanel(W.activePanel.id))||He()},[De,We,He,r,d,st,mt,y,b,e]),i.useEffect(()=>{P.current&&We(y)},[We,y]),i.useEffect(()=>{const W=G=>{const se=G.target;if(!se)return;const E=se.querySelector("[data-tab-key]")||se.closest("[data-tab-key]");if(E){const q=E.getAttribute("data-tab-key");if(q&&G.dataTransfer){const Z=se.closest(".dv-tab")||E.closest(".dv-tab")||E;G.dataTransfer.effectAllowed="move",G.dataTransfer.setData("text/tab-key",q),Z instanceof HTMLElement&&G.dataTransfer.setDragImage(Z,Math.max(12,Math.round(Z.clientWidth/2)),Math.max(10,Math.round(Z.clientHeight/2)))}}};window.addEventListener("dragstart",W);const U=Bi(j.current);for(const G of U)G.addEventListener("dragstart",W);return()=>{window.removeEventListener("dragstart",W);for(const G of U)G.removeEventListener("dragstart",W)}},[K]),i.useEffect(()=>{var U;const W=(U=w.current)==null?void 0:U.querySelector(".adhdev-dockview");W instanceof HTMLElement&&na(W,M),z(),ve()},[ve,z,M]),i.useEffect(()=>{ve()},[ve]),i.useEffect(()=>{const W=U=>{if(U.defaultPrevented||J)return;const G=Ue(U);if(!G)return;const se=U.metaKey||U.ctrlKey||U.altKey;Wa(U.target)&&!se||pn(Q).setActiveTabShortcut!==G||(U.preventDefault(),U.stopPropagation(),$e())};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[Ue,Q,J,$e]),i.useEffect(()=>{const W=w.current;if(!W)return;const U=G=>{var ne,je;if(!G.isTrusted)return;const se=(je=(ne=G.target)==null?void 0:ne.closest)==null?void 0:je.call(ne,".dv-scrollable");if(!se)return;G.preventDefault(),G.stopPropagation();const E=Math.abs(G.deltaX),q=Math.abs(G.deltaY),Z=E>q?G.deltaX:G.deltaY;se.dispatchEvent(new WheelEvent("wheel",{deltaY:Z,deltaMode:G.deltaMode,bubbles:!1,cancelable:!0}))};return W.addEventListener("wheel",U,{passive:!1,capture:!0}),()=>W.removeEventListener("wheel",U,{capture:!0})},[]),i.useEffect(()=>{const W=Bi(j.current);if(W.length===0)return;const U=W.map(G=>{let se=[],E=null;const q=()=>{E!=null&&G.clearTimeout(E),E=null,se=[]},Z=()=>{E!=null&&G.clearTimeout(E),E=G.setTimeout(()=>{E=null,se=[]},1200)},ne=Le=>{if(!Le.ctrlKey&&!Le.metaKey&&!Le.altKey)return;const _e=Ue(Le);if(!_e)return;const Ne=zl();for(const[Ee,Be]of Object.entries(Ne))if(e.some(Re=>Re.tabKey===Ee)&&Be===_e){Le.preventDefault(),te(Ee);return}},je=Le=>{if(Le.defaultPrevented||J)return;const _e=Ue(Le);if(!_e)return;const Ne=Le.metaKey||Le.ctrlKey||Le.altKey;if(Wa(Le.target))return;const Ee=pn(Q),Be=Object.entries(Ee).filter(([Ve,we])=>!!we&&(Ve==="splitActiveTabRight"||Ve==="splitActiveTabDown"||Ve==="floatActiveTab"||Ve==="popoutActiveTab"||Ve==="dockActiveTab"||Ve==="focusLeftPane"||Ve==="focusRightPane"||Ve==="focusUpPane"||Ve==="focusDownPane"||Ve==="moveActiveTabToLeftPane"||Ve==="moveActiveTabToRightPane"||Ve==="moveActiveTabToUpPane"||Ve==="moveActiveTabToDownPane"||Ve==="selectPreviousGroupTab"||Ve==="selectNextGroupTab"||Ve==="setActiveTabShortcut"||Ve==="hideCurrentTab")),Re=Ne?[_e]:[...se.slice(-1),_e].slice(-2),qe=Re.join(" "),et=Re[Re.length-1],ct=Be.find(([,Ve])=>Ve===qe);if(ct){Le.preventDefault(),q(),B(ct[0]);return}if(Be.some(([,Ve])=>Ve.startsWith(`${qe} `))){Le.preventDefault(),se=Re,Z();return}const dt=Be.find(([,Ve])=>Ve===et);if(dt){Le.preventDefault(),q(),B(dt[0]);return}if(Be.some(([,Ve])=>Ve.startsWith(`${et} `))){Le.preventDefault(),se=[et],Z();return}q()};return G.addEventListener("keydown",ne),G.addEventListener("keydown",je),()=>{q(),G.removeEventListener("keydown",ne),G.removeEventListener("keydown",je)}});return()=>{for(const G of U)G()}},[Ue,Q,K,te,J,B,e]);const Ce=M==="light"?ya:va,ze=((rt=(Ge=(Qe=j.current)==null?void 0:Qe.activePanel)==null?void 0:Ge.group.element)==null?void 0:rt.ownerDocument)??document;return s.jsxs(Zl.Provider,{value:Se,children:[s.jsx("div",{ref:w,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(Od,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:Kb,remote:Ob},defaultTabComponent:Hb,watermarkComponent:Fb,onReady:xt,singleTabMode:"default",tabAnimation:"smooth",theme:Ce,popoutUrl:"/popout.html"})}),k&&cr.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:k.x,top:k.y},children:Me.map(W=>{if(W.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},W.id);let U=s.jsx(Eu,{size:13,className:"shrink-0 opacity-70"}),G=()=>{};switch(W.id){case"dockInWindow":case"dockBackToGrid":U=s.jsx(Bu,{size:13,className:"shrink-0 opacity-70"}),G=()=>{ke(k.tabKey),A(null)};break;case"moveBackToMain":U=s.jsx(Du,{size:13,className:"shrink-0 opacity-70"}),G=()=>{pe(k.tabKey),A(null)};break;case"floatAsPanel":U=s.jsx($u,{size:13,className:"shrink-0 opacity-70"}),G=()=>{ye(k.tabKey),A(null)};break;case"openInNewWindow":U=s.jsx(_u,{size:13,className:"shrink-0 opacity-70"}),G=()=>{de(k.tabKey),A(null)};break;case"setShortcut":G=se=>{se.stopPropagation(),Ae(k.tabKey),A(null)};break;case"removeShortcut":U=s.jsx(vt,{size:13,className:"shrink-0 opacity-70"}),G=()=>{const se={...fe};delete se[k.tabKey],Te(se),A(null)};break;case"hideTab":U=s.jsx(Ya,{size:13,className:"shrink-0 opacity-70"}),G=()=>{ie(k.tabKey),A(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${W.tone==="muted"?"text-text-muted":""}`,onMouseDown:$b,onClick:G,children:[U,s.jsx("span",{className:"flex-1 min-w-0",children:W.label}),W.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:W.shortcut}):null]},W.id)})}),k.sourceDocument.body),J&&cr.createPortal(s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>Ae(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:W=>W.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",Q?"⌘+1":"Ctrl+1",", ",Q?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),ze.body)]})}const ed="adhdev-recent-launch-args-v1",zb=8;function td(e){return String(e||"").trim().replace(/\s+/g," ")}function Mo(e,t){return`${e.trim()}::${t.trim()}`}function Io(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(ed)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function sd(e){if(!(typeof window>"u"))try{window.localStorage.setItem(ed,JSON.stringify(e))}catch{}}function Ka(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=Io().byKey[Mo(r,n)])==null?void 0:o.items)||[]}function rd(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=td(r);if(!n||!a||!o)return;const c=Io(),l=Mo(n,a),d=((u=c.byKey[l])==null?void 0:u.items)||[],m=[o,...d.filter(f=>f!==o)].slice(0,zb);c.byKey[l]={items:m},sd(c)}function Vb(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=td(r);if(!n||!a||!o)return;const c=Io(),l=Mo(n,a),m=(((u=c.byKey[l])==null?void 0:u.items)||[]).filter(f=>f!==o);m.length>0?c.byKey[l]={items:m}:delete c.byKey[l],sd(c)}function nd(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Yr({title:e,description:t,action:r,children:n,className:a="",contentClassName:o=""}){return s.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),t&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:t})]}),r?s.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?s.jsx("div",{className:t||r?`mt-3 ${o}`.trim():o,children:n}):null]})}function Gb({savedSessionsLoading:e,savedSessionsLoaded:t,savedSessionsCount:r=0}){return e?"Refreshing saved history…":t?r>0?`${r} saved ${r===1?"history":"histories"} loaded. Open saved history to choose one.`:"No saved history found yet. New Hermes CLI conversations will appear here after ADHDev captures provider history.":"Start fresh, or open saved history when you want continuity."}function ad({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:c,onOpenHistory:l,onClearSelection:d}){const m=o?Fl(o):null,u=Gb({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Yr,{title:"Saved history",description:fo(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:c,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:l,children:$p()})]}),children:[m?s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),s.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:m.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:m.providerSessionId}),s.jsx("div",{className:"mt-1",children:m.metaLine}),m.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:m.updatedLabel}),m.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:m.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:d,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:u}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function od({setup:e,providerName:t,className:r=""}){return e?s.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${r}`,children:[s.jsxs("div",{className:"font-semibold",children:["Manual MCP setup required",t?` for ${t}`:""]}),e.instructions&&s.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-text-muted",children:[e.serverName&&s.jsxs("span",{children:["Server: ",s.jsx("code",{children:e.serverName})]}),e.configFormat&&s.jsxs("span",{children:["Format: ",s.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&s.jsxs("span",{children:["Config path: ",s.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&s.jsx("span",{children:"Start a fresh CLI session after editing config."})]}),e.template&&s.jsx("pre",{className:"mt-3 max-h-72 overflow-auto rounded-lg border border-border-subtle bg-bg-primary p-3 text-xs font-mono leading-relaxed text-text-primary select-all whitespace-pre-wrap",children:e.template})]}):null}function qb({workspaceMode:e,activeKind:t,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:o,onSelect:c}){return e==="mesh"?null:s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:r},{id:"ide",label:"IDE",enabled:n},{id:"acp",label:"ACP",enabled:a}].map(l=>s.jsx("button",{type:"button",className:`btn btn-sm ${t===l.id?"btn-primary":"btn-secondary"}`,onClick:()=>c(l.id),disabled:!l.enabled||o,children:l.label},l.id))})]})}function aa(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>bs(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>bs(a,"acp"))?"acp":null}function Br(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Yb({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:c,onListMeshes:l,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Ve,we;const u=xr(),f=i.useMemo(()=>[...e].sort(to),[e]),[x,S]=i.useState(((Ve=f[0])==null?void 0:Ve.id)||""),g=i.useMemo(()=>f.find(V=>V.id===x)||f[0],[x,f]),p=i.useMemo(()=>((g==null?void 0:g.workspaces)||[]).map(V=>({id:V.id,path:V.path,label:V.label})),[g]),y=(g==null?void 0:g.defaultWorkspaceId)||null,[b,h]=i.useState("workspace"),[C,N]=i.useState(""),[v,M]=i.useState(""),[I,j]=i.useState([]),[w,$]=i.useState(""),[P,T]=i.useState(!1),[F,H]=i.useState(null),[L,k]=i.useState(""),[A,K]=i.useState(aa(f[0])),[_,D]=i.useState(""),[O,X]=i.useState(""),[ge,ce]=i.useState([]),[ee,z]=i.useState(""),[de,pe]=i.useState([]),[Y,ie]=i.useState(!1),[ye,re]=i.useState(!1),[me,ke]=i.useState(""),[xe,ve]=i.useState(!1),[te,he]=i.useState(()=>wt()),[le,ue]=i.useState(null),[oe,Q]=i.useState(!1),[fe,J]=i.useState(""),[Ae,Te]=i.useState(null),[$e,Ue]=i.useState(!1),[B,Se]=i.useState(""),[Me,De]=i.useState([]),[We,He]=i.useState(!1),[Je,st]=i.useState(""),[mt,ht]=i.useState(!1),xt=i.useRef(null),Ce=i.useRef(0);i.useEffect(()=>{var V;!x&&((V=f[0])!=null&&V.id)&&S(f[0].id)},[x,f]),i.useEffect(()=>{!g||!(!g.workspaces||!g.availableProviders||!g.detectedIdes||!g.recentLaunches)||u(g.id,{minFreshMs:3e4}).catch(()=>{})},[u,g]);const ze=i.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(V=>bs(V,"cli")),[g]),Qe=i.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(V=>bs(V,"acp")),[g]),Ge=i.useMemo(()=>((g==null?void 0:g.detectedIdes)||[]).map(V=>({id:V.type,label:V.name||V.type,meta:V.running?"Detected locally":"Available to open"})),[g]),rt=i.useMemo(()=>A==="cli"?ze.map(V=>({id:V.type,label:V.displayName||V.type,meta:"CLI provider"})):A==="acp"?Qe.map(V=>({id:V.type,label:V.displayName||V.type,meta:"ACP provider"})):Ge,[Qe,A,ze,Ge]),W=i.useMemo(()=>I.find(V=>V.id===w)||null,[I,w]),U=i.useMemo(()=>ze.find(V=>V.type===_)||null,[ze,_]),G=i.useMemo(()=>El(U==null?void 0:U.meshCoordinator,{meshId:(W==null?void 0:W.id)||"",workspace:(W==null?void 0:W.workspace)||""}),[U,W]),se=Ae||G,E=i.useCallback(async V=>{T(!0),k("");try{const Ie=await l(V);j(Ie),$(R=>{var ae;return Ie.some(be=>be.id===R)?R:((ae=Ie[0])==null?void 0:ae.id)||""}),H(V)}catch(Ie){j([]),$(""),H(V),k(Ie instanceof Error?Ie.message:"Could not load meshes")}finally{T(!1)}},[l]);i.useEffect(()=>{var Ie;if(!g)return;if(xt.current!==g.id){xt.current=g.id,h("workspace"),N(y||((Ie=p[0])==null?void 0:Ie.id)||"__home__"),M(""),j([]),$(""),H(null),k(""),K(aa(g)),D(""),X(""),z(""),pe([]),re(!1),ke(""),he(wt()),J(""),Te(null);return}N(R=>{var ae;return R==="__custom__"||R==="__home__"||p.some(be=>be.id===R)?R:y||((ae=p[0])==null?void 0:ae.id)||"__home__"}),K(R=>R==="ide"&&Ge.length>0||R==="cli"&&ze.length>0||R==="acp"&&Qe.length>0?R:aa(g))},[Qe.length,ze.length,y,Ge.length,g,p]),i.useEffect(()=>{!g||b!=="mesh"||F===g.id||P||E(g.id)},[E,F,P,g,b]),i.useEffect(()=>{b==="mesh"&&A!=="cli"&&ze.length>0&&K("cli")},[A,ze.length,b]),i.useEffect(()=>{var V;A&&(rt.some(Ie=>Ie.id===_)||D(((V=rt[0])==null?void 0:V.id)||""))},[A,rt,_]),i.useEffect(()=>{Te(null)},[g==null?void 0:g.id,w,_,b]);const q=i.useCallback(async(V,Ie)=>{const R=Ce.current+1;return Ce.current=R,ie(!0),ke(""),m(V,Ie).then(ae=>{Ce.current===R&&pe(ae)}).catch(ae=>{Ce.current===R&&(pe([]),ke(ae instanceof Error?ae.message:"Could not load saved sessions"))}).finally(()=>{Ce.current===R&&(ie(!1),re(!0))})},[m]),Z=i.useCallback((V,Ie)=>{ce(Ka(V,Ie))},[]);i.useEffect(()=>{Ce.current+=1,z(""),he(wt()),!g||!_||A==="ide"?ce([]):Z(g.id,_),re(!1),pe([]),ke(""),ie(!1)},[A,Z,q,g,_]),i.useEffect(()=>{if(!ee)return;const V=de.find(Ie=>Ie.providerSessionId===ee);V!=null&&V.canResume||z("")},[de,ee]);const ne=C==="__custom__"?v.trim():C==="__home__"?"":((we=p.find(V=>V.id===C))==null?void 0:we.path)||"",je=i.useMemo(()=>g?t.filter(V=>V.id!==g.id&&V.daemonId===g.id).map(V=>V.workspace):[],[t,g]),Le=i.useMemo(()=>((g==null?void 0:g.recentLaunches)||[]).map(V=>V.workspace),[g]),_e=i.useCallback(V=>{const Ie=String(V.workspace||"").trim();if(!Ie)return;const R=p.find(ae=>Br(ae.path)===Br(Ie));if(R){N(R.id),M("");return}N("__custom__"),M(Ie)},[p]),Ne=i.useCallback(V=>{const Ie=String(V.workspace||"").trim();if(!Ie)return{workspaceId:null,workspacePath:null};const R=p.find(ae=>Br(ae.path)===Br(Ie));return R?{workspaceId:R.id,workspacePath:null}:{workspaceId:null,workspacePath:Ie}},[p]),Ee=i.useMemo(()=>de.find(V=>V.providerSessionId===ee)||null,[de,ee]),Be=i.useMemo(()=>{var Ie;if(A!=="cli"||!g||!_)return null;const V=((Ie=ze.find(R=>R.type===_))==null?void 0:Ie.displayName)||_;return{routeId:g.id,daemonId:g.id,providerSessionId:ee||void 0,transport:"pty",mode:"chat",agentName:V,agentType:_,status:"idle",title:V,messages:[],ideType:_,workspaceName:ne,workspacePath:ne,displayPrimary:V,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${g.id}:${_}`,machineName:Tt(g,{fallbackId:g.id})}},[A,ze,ne,g,ee,_]),Re=i.useCallback(()=>{var Ie;if(!g)return;N("__custom__"),Ue(!0),st("");const V=Nn(g.platform,Sn(v.trim(),ne,je,Le,g.defaultWorkspacePath,(Ie=p.find(R=>R.id===y))==null?void 0:Ie.path,p.map(R=>R.path)));He(!0),n(g.id,V).then(R=>{Se(R.path),M(R.path),De(R.directories)}).catch(R=>{st(R instanceof Error?R.message:"Could not load folder")}).finally(()=>He(!1))},[v,y,Le,je,n,ne,g,p]),qe=i.useCallback(V=>{g&&(He(!0),st(""),n(g.id,V).then(Ie=>{Se(Ie.path),M(Ie.path),De(Ie.directories)}).catch(Ie=>{st(Ie instanceof Error?Ie.message:"Could not load folder")}).finally(()=>He(!1)))},[n,g]),et=i.useCallback(async()=>{if(!g||!ne)return;ht(!0),J("");const V=await a(g.id,ne);if(ht(!1),!V.ok){J(V.error||"Could not save workspace");return}J("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,ne,g]),ct=i.useCallback(async()=>{if(!g)return;if(b==="mesh"){if(!w||!_)return;Q(!0),J(""),Te(null);const R=await d(g.id,w,_);if(Q(!1),!R.ok){if(R.code==="mesh_coordinator_manual_mcp_setup_required"&&R.manualSetup){Te(R.manualSetup),J("Manual MCP setup required before this provider can act as mesh coordinator.");return}J(R.error||"Could not start mesh coordinator");return}r();return}if(!A||!_)return;Q(!0),J("");const V=O.trim()?O.trim().split(/\s+/).filter(Boolean):[],Ie=A==="ide"?await o(g.id,_,{workspacePath:ne||null}):await c(g.id,A,_,{workspaceId:C!=="__home__"&&C!=="__custom__"?C:null,workspacePath:C==="__custom__"&&ne||null,resumeSessionId:A==="cli"&&ee?ee:null,cliArgs:V});if(Q(!1),!Ie.ok){J(Ie.error||"Could not start session");return}A!=="ide"&&O.trim()&&(rd(g.id,_,O),Z(g.id,_)),r()},[A,O,Z,r,o,d,c,ne,g,w,ee,_,C,b]),ft=b==="mesh"?"Start mesh coordinator":A?nl(A,A==="cli"&&!!ee):"Start",dt=b==="mesh"?"Starting coordinator…":A?al(A,A==="cli"&&!!ee):"Starting…",yt=f.length>5;return g?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[s.jsx(Yr,{title:"Machine",children:yt?s.jsx("select",{"aria-label":"Machine",value:g.id,onChange:V=>S(V.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:oe,children:f.map(V=>s.jsx("option",{value:V.id,children:Tt(V,{fallbackId:V.id})},V.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:f.map(V=>{const Ie=Tt(V,{fallbackId:V.id}),R=g.id===V.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${Ie}`,"aria-pressed":R,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${R?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/60 text-text-secondary hover:bg-bg-secondary hover:text-text-primary"}`,onClick:()=>S(V.id),disabled:oe,title:Ie,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${V.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:Ie})]},V.id)})})}),s.jsxs(Yr,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:b==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Re,disabled:oe,children:"Browse…"}):void 0,children:[s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":"Launch target type",children:[{id:"workspace",label:"Workspace",desc:"Normal session"},{id:"mesh",label:"Mesh",desc:"Coordinator session"}].map(V=>s.jsxs("button",{type:"button",role:"radio","aria-checked":b===V.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${b===V.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{h(V.id),J(""),V.id==="mesh"&&g&&F!==g.id&&!P&&E(g.id)},disabled:oe,children:[s.jsx("div",{className:"text-sm font-semibold",children:V.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:V.desc})]},V.id))}),b==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:C,onChange:V=>{const Ie=V.target.value;N(Ie),Ie==="__custom__"?Re():J("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:oe,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),p.map(V=>s.jsxs("option",{value:V.id,children:[V.id===y?"⭐ ":"",vn(V.path,V.label)||V.path]},V.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:C==="__home__"?"Launch without a workspace.":ne||"Select a workspace folder."}),C==="__custom__"&&ne&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Re,disabled:oe,children:[s.jsx(ps,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:et,disabled:oe||mt,children:mt?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[P&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!P&&L&&s.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:L}),!P&&!L&&I.length===0&&s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker."}),I.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:I.map(V=>s.jsxs("button",{type:"button",role:"radio","aria-checked":w===V.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${w===V.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(V.id),disabled:oe,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:V.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[V.repoIdentity||"Repo mesh",typeof V.nodesCount=="number"?` · ${V.nodesCount} node${V.nodesCount===1?"":"s"}`:""]}),V.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",V.workspace]})]},V.id))}),W&&s.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),s.jsx(qb,{workspaceMode:b,activeKind:A,cliEnabled:ze.length>0,ideEnabled:Ge.length>0,acpEnabled:Qe.length>0,busy:oe,onSelect:K}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:A==="ide"?"Choose IDE":A==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[rt.map(V=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${_===V.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>D(V.id),disabled:oe,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:V.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:V.meta})]},V.id)),rt.length===0&&s.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),b==="mesh"&&se&&s.jsx(od,{setup:se,providerName:(U==null?void 0:U.displayName)||(U==null?void 0:U.name)||_}),b!=="mesh"&&A!=="ide"&&s.jsxs(Yr,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:O,onChange:V=>X(V.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:oe}),ge.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:ge.map(V=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>X(V),disabled:oe,title:V,children:V},V))})]}),b!=="mesh"&&A==="cli"&&s.jsx(ad,{busy:oe,savedSessionsLoading:Y,savedSessionsError:me,selectedSession:Ee,onRefresh:()=>{!g||!_||q(g.id,_)},onOpenHistory:()=>{!g||!_||(ve(!0),nd({hasLoadedInitialResults:ye,isLoading:Y})&&q(g.id,_))},onClearSelection:()=>z("")}),fe&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${fe.includes("saved")||fe.includes("requested")||fe.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:fe})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:r,disabled:oe,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:ct,disabled:oe||(b==="mesh"?!w||!_||A!=="cli"||P:!A||!_||C==="__custom__"&&!ne),children:[s.jsx(Ja,{size:14}),oe?dt:ft]})]})]})}),$e&&s.jsx(Mn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:B,directories:Me,busy:We,error:Je,onClose:()=>Ue(!1),onNavigate:qe,onConfirm:V=>{M(V),Se(V),N("__custom__"),Ue(!1)}}),xe&&Be&&s.jsx(xo,{activeConv:Be,ides:[],isCreatingChat:!1,isRefreshingHistory:Y,savedSessions:de,isSavedSessionsLoading:Y,isResumingSavedSessionId:le,savedHistoryFilters:te,missingWorkspaceResumePath:ne||null,onSavedHistoryFiltersChange:he,onClose:()=>ve(!1),onNewChat:()=>{z(""),ve(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!g||!_||q(g.id,_)},onResumeSavedSession:V=>{if(!g||!_||le||!V.canResume)return;const Ie=Ne(V);z(V.providerSessionId),_e(V),ue(V.providerSessionId),ve(!1),Q(!0),J(""),c(g.id,"cli",_,{workspaceId:Ie.workspaceId,workspacePath:Ie.workspacePath,resumeSessionId:V.providerSessionId}).then(R=>{if(!R.ok){J(R.error||"Could not resume session");return}r()}).finally(()=>{Q(!1),ue(R=>R===V.providerSessionId?null:R)})}})]}):null}function Xb(e,t){const{sendCommand:r}=gt(),[n,a]=i.useState(null),[o,c]=i.useState(!1);i.useEffect(()=>{if(!e||!t){a(null);return}c(!0),r(e,"git_remote_url",{workspace:t}).then(d=>{const m=(d==null?void 0:d.result)??d;a(typeof(m==null?void 0:m.remoteUrl)=="string"?m.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>c(!1))},[e,t,r]);const l=Jb(n);return{remoteUrl:n,githubUrl:l,loading:o}}function Jb(e){if(!e)return null;const t=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(t)return`https://github.com/${t[1]}`;const r=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return r?`https://github.com/${r[1]}`:null}const id=5e3;function Qb(e){return`git:${e}`}function Zb({workspace:e,includeDiffSummary:t=!1,intervalMs:r=id}){return{type:"subscribe",topic:"workspace.git",key:Qb(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function Ao(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function gs(e,t){if(e instanceof Error)return e.message;if(e&&typeof e=="object"){const r=e;if(typeof r.error=="string"&&r.error.trim())return r.error;if(typeof r.message=="string"&&r.message.trim())return r.message}return t}function eg(e){const t=Ao(e);return(t==null?void 0:t.success)===!1?{status:null,error:gs(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:gs(t,"Git status response did not include status")}}function tg(e){const t=Ao(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:gs(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:gs(t,"Git diff summary response did not include diffSummary")}}function oa(e){return e===void 0||typeof e=="boolean"}function sg(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&oa(t.binary)&&oa(t.truncated)&&oa(t.staged)}function rg(e){const t=Ao(e);return(t==null?void 0:t.success)===!1?{diff:null,error:gs(t,"Git file diff request failed")}:sg(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:gs(t,"Git file diff response did not include a valid diff object")}}function ng({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=id}){const{sendCommand:o,sendData:c}=gt(),l=typeof t=="string"?t.trim():"",d=!!(r&&e&&l),[m,u]=i.useState(null),[f,x]=i.useState(null),[S,g]=i.useState(!1),[p,y]=i.useState(null),b=i.useCallback(async()=>{if(!(!d||!e||!l)){g(!0),y(null);try{const C=eg(await o(e,"git_status",{workspace:l}));if(C.error){u(null),x(null),y(C.error);return}if(u(C.status),!n){x(null);return}const N=tg(await o(e,"git_diff_summary",{workspace:l}));if(N.error){x(null),y(N.error);return}x(N.diffSummary)}catch(C){y(gs(C,"Git status request failed"))}finally{g(!1)}}},[d,e,n,o,l]),h=i.useMemo(()=>l?Zb({workspace:l,includeDiffSummary:n,intervalMs:a}):null,[n,a,l]);return i.useEffect(()=>{if(!d||!e||!l||!h){u(null),x(null),g(!1),y(null);return}const C=c?Ut.subscribe({sendData:c},e,h,N=>{var v,M;N.workspace===l&&(u(N.status),x(N.diffSummary??null),y(((v=N.status)==null?void 0:v.error)||((M=N.diffSummary)==null?void 0:M.error)||null),g(!1))},{retryIntervalMs:1e3}):null;return b(),()=>{C==null||C()}},[d,e,b,h,c,l]),{status:m,diffSummary:f,loading:S,error:p,refresh:b}}const ag={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},og={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 Oi(e){return e.split("/").pop()??e}function ig(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function cg({files:e,truncated:t,onFileClick:r,selectedPath:n,className:a=""}){return e.length===0?s.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:"No changed files."}):s.jsxs("div",{className:`flex flex-col ${a}`,children:[s.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(o=>{const c=n===o.path,l=ag[o.status]??"?",d=og[o.status]??"text-zinc-400",m=ig(o.path),u=Oi(o.path),f=o.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${c?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(o),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:o.status,children:l}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&s.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),s.jsx("span",{className:"text-text-primary",children:u}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",Oi(o.oldPath)]}),f]}),!o.binary&&(o.insertions>0||o.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",o.insertions]}),o.insertions>0&&o.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),o.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",o.deletions]})]}),o.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${o.path}-${o.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function lg(e,t){let r="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?r="bg-emerald-500/10 text-emerald-300":e.startsWith("-")&&!e.startsWith("---")?r="bg-red-500/10 text-red-300":e.startsWith("@@")?r="text-sky-400":(e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ "))&&(r="text-text-secondary"),s.jsx("div",{className:`px-3 ${r}`,children:s.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},t)}function dg({diff:e,binary:t,truncated:r,loading:n,error:a,className:o=""}){const c=i.useRef(null);if(i.useEffect(()=>{c.current&&(c.current.scrollTop=0)},[e]),n)return s.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${o}`,children:"Loading diff…"});if(a)return s.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${o}`,children:a});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"No diff available."});const l=e.split(`
|
|
63
|
+
`);return s.jsxs("div",{ref:c,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:l.map((d,m)=>lg(d,m))}),r&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary border-t border-border/30",children:["Diff truncated — run ",s.jsx("code",{className:"font-mono",children:"git diff"})," locally for full output."]})]})}function ug(e,t){const r=[`Branch: ${e||"unknown"}`];r.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const n={};for(const a of t.files)n[a.status]||(n[a.status]=[]),n[a.status].push(a.path);for(const[a,o]of Object.entries(n))r.push(`${a}: ${o.slice(0,5).join(", ")}${o.length>5?` (+${o.length-5} more)`:""}`);return r.join(`
|
|
64
|
+
`)}function cd({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=gt(),{status:a,diffSummary:o,loading:c,error:l,refresh:d}=ng({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=i.useState(null),[f,x]=i.useState(null),[S,g]=i.useState(""),[p,y]=i.useState(!1),[b,h]=i.useState(!1),[C,N]=i.useState(null),[v,M]=i.useState(null),{githubUrl:I}=Xb(e,t),j=i.useCallback(async H=>{if(!((m==null?void 0:m.path)===H.path&&!m.loading)){u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const L=await n(e,"git_diff_file",{workspace:t,path:H.path,staged:H.staged}),k=rg(L);if(k.error||!k.diff){u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!1,error:k.error??"Failed to load diff"});return}u({path:H.path,diff:k.diff.diff,binary:k.diff.binary??!1,truncated:k.diff.truncated??!1,loading:!1,error:null})}catch(L){const k=L instanceof Error?L.message:"Failed to load diff";u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!1,error:k})}}},[e,n,m,t]),w=i.useCallback(H=>{g(""),y(!1),N(null),M(null),x(H)},[]),$=i.useCallback(()=>{x(null),N(null),h(!1)},[]),P=i.useCallback(async()=>{var H,L,k;if(f){h(!0),N(null);try{let A;f==="checkpoint"?A=await n(e,"git_checkpoint",{workspace:t,message:S,includeUntracked:p}):f==="stash"?A=await n(e,"git_stash_push",{workspace:t,message:S,includeUntracked:p}):f==="stash_pop"?A=await n(e,"git_stash_pop",{workspace:t}):f==="checkout_files"&&m&&(A=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const K=(A==null?void 0:A.result)??A;if((K==null?void 0:K.success)===!1||K!=null&&K.error){N((K==null?void 0:K.error)??"Action failed"),h(!1);return}f==="checkpoint"?M(`Checkpoint created: ${((L=(H=K==null?void 0:K.checkpoint)==null?void 0:H.commit)==null?void 0:L.slice(0,7))??"done"}`):f==="stash"?M(`Stashed as ${((k=K==null?void 0:K.stash)==null?void 0:k.stashRef)??"stash@{0}"}`):f==="stash_pop"?M("Stash restored"):(M("File reverted"),u(null)),x(null),await d()}catch(A){N(A instanceof Error?A.message:"Action failed")}finally{h(!1)}}},[f,n,e,t,S,p,m,d]),T=!!(a!=null&&a.hasConflicts),F=a?a.staged+a.modified+a.untracked+a.deleted+a.renamed:null;return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:H=>{H.target===H.currentTarget&&r()},children:s.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),I&&s.jsx("a",{href:`${I}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-sky-400 underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:d,disabled:c,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),s.jsx("button",{onClick:r,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(vt,{className:"h-4 w-4"})})]}),a&&s.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[a.headCommit&&s.jsxs("span",{title:a.headMessage??void 0,children:[s.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&s.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&s.jsxs("span",{className:"text-orange-400",children:["↑",a.ahead," ahead"]}),a.behind>0&&s.jsxs("span",{className:"text-orange-400",children:["↓",a.behind," behind"]}),a.staged>0&&s.jsxs("span",{className:"text-emerald-400",children:[a.staged," staged"]}),a.modified>0&&s.jsxs("span",{children:[a.modified," modified"]}),a.untracked>0&&s.jsxs("span",{children:[a.untracked," untracked"]}),a.deleted>0&&s.jsxs("span",{className:"text-red-400",children:[a.deleted," deleted"]}),a.stashCount>0&&s.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&s.jsx("span",{className:"font-bold text-red-400",children:"conflicts"}),F===0&&!a.error&&s.jsx("span",{className:"text-emerald-500",children:"clean"}),o&&o.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[o.files.length," file",o.files.length!==1?"s":"",o.totalInsertions>0&&s.jsxs("span",{className:"text-emerald-500",children:[" +",o.totalInsertions]}),o.totalDeletions>0&&s.jsxs("span",{className:"text-red-400",children:[" -",o.totalDeletions]})]})]}),l&&s.jsx("div",{className:"shrink-0 border-b border-border/50 bg-red-500/10 px-4 py-2 text-xs text-red-400",children:l}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[c&&!o&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),o&&s.jsx(cg,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:j}),!c&&!o&&!l&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:m?s.jsx(dg,{diff:m.diff,binary:m.binary,truncated:m.truncated,loading:m.loading,error:m.error,className:"h-full"}):s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),v&&s.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-emerald-500/10 px-4 py-2 text-xs text-emerald-400 flex items-center justify-between",children:[s.jsx("span",{children:v}),s.jsx("button",{onClick:()=>M(null),className:"ml-2 text-emerald-400 hover:text-text-primary",children:"×"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[s.jsx("button",{onClick:()=>w("checkpoint"),disabled:T,title:T?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),s.jsx("button",{onClick:()=>w("stash"),disabled:T,title:T?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),s.jsx("button",{onClick:()=>w("stash_pop"),disabled:T||!(a!=null&&a.stashCount),title:T?"Resolve conflicts before restoring a stash":a!=null&&a.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),s.jsx("button",{onClick:()=>w("checkout_files"),disabled:!m,title:m?`Revert changes to ${m.path}`:"Select a file to revert",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkout selected"}),o&&o.files.length>0&&s.jsx("button",{onClick:()=>{const H=ug((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(H),M("Copied to clipboard"),setTimeout(()=>M(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),f&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[f==="checkpoint"&&"Create checkpoint commit",f==="stash"&&"Stash changes",f==="stash_pop"&&"Restore latest stash?",f==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(f==="checkpoint"||f==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:S,onChange:H=>g(H.target.value),maxLength:200,placeholder:"Message (required)",className:"rounded border border-border bg-surface-alt px-2 py-1 text-xs text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-border",autoFocus:!0}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:p,onChange:H=>y(H.target.checked)}),"Include untracked files"]})]}),C&&s.jsx("p",{className:"text-xs text-red-400",children:C}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:$,disabled:b,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),s.jsx("button",{onClick:P,disabled:b||(f==="checkpoint"||f==="stash")&&!S.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:b?"Working…":"Confirm"})]})]})})]})})}function mg({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=i.useState(!1),[o,c]=i.useState(!1),[l,d]=i.useState(!1),[m,u]=i.useState(!1),[f,x]=i.useState(!1),[S,g]=i.useState("quickstart"),[p,y]=i.useState("workspace"),b=i.useMemo(()=>!t&&!e,[t,e]),h=i.useCallback(j=>{a(j),j&&c(!1)},[]),C=i.useCallback(j=>{c(j),j&&a(!1)},[]),N=i.useCallback(()=>{g(r===0?"quickstart":"shortcuts"),y("workspace"),d(!0),a(!1),c(!1)},[r]),v=i.useCallback(()=>{d(!1)},[]),M=i.useCallback(()=>{u(!0)},[]),I=i.useCallback(()=>{u(!1)},[]);return i.useEffect(()=>{if(!b){x(!1);return}x(!0);const j=window.setTimeout(()=>{x(!1)},1e4);return()=>window.clearTimeout(j)},[b]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:l,newSessionOpen:m,guideNudgeVisible:f,guideTab:S,shortcutSection:p,isDesktopDashboard:b,setGuideTab:g,setShortcutSection:y,handleInboxOpenChange:h,handleHiddenOpenChange:C,handleOpenShortcutHelp:N,closeShortcutHelp:v,openNewSession:M,closeNewSession:I}}function fg(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 pg(e){return e instanceof Error?e.message:String(e||"")}function hg(e){const t=pg(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function xg({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:c,onStopCli:l,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:f,ides:x,actionLogs:S,sendDaemonCommand:g,setActionLogs:p,setCliViewModeOverrides:y,isStandalone:b,initialDataLoaded:h,userName:C,requestedMobileTabKey:N,onRequestedMobileTabConsumed:v,requestedMachineId:M,onRequestedMachineConsumed:I,requestedMobileSection:j,onRequestedMobileSectionConsumed:w,containerRef:$,isSplitMode:P,numGroups:T,groupSizes:F,groupedConvs:H,clearedTabs:L,focusedGroup:k,focusGroup:A,moveTabToGroup:K,splitTabRelative:_,closeGroup:D,handleResizeStart:O,groupActiveTabIds:X,setGroupActiveTab:ge,groupTabOrders:ce,setGroupTabOrder:ee,toggleHiddenTab:z,visibleConversations:de,requestedDesktopTabKey:pe,onRequestedDesktopTabConsumed:Y,onDesktopActiveTabChange:ie,onRequestScrollToBottom:ye,onHideConversation:re,onShowHiddenConversation:me,onShowAllHiddenConversations:ke,scrollToBottomRequest:xe,machineEntries:ve,layoutProfile:te,onBrowseMachineDirectory:he,onSaveMachineWorkspace:le,onLaunchMachineIde:ue,onLaunchMachineProvider:oe,onListMachineMeshes:Q,onLaunchMeshCoordinator:fe,onListMachineSavedSessions:J,notifications:Ae,notificationUnreadCount:Te,liveSessionInboxState:$e,onMarkNotificationRead:Ue,onMarkNotificationUnread:B,onDeleteNotification:Se}){const Me=Ct.useRef(null),{inboxOpen:De,hiddenOpen:We,shortcutHelpOpen:He,newSessionOpen:Je,guideNudgeVisible:st,guideTab:mt,shortcutSection:ht,isDesktopDashboard:xt,setGuideTab:Ce,setShortcutSection:ze,handleInboxOpenChange:Qe,handleHiddenOpenChange:Ge,handleOpenShortcutHelp:rt,closeShortcutHelp:W,openNewSession:U,closeNewSession:G}=mg({isMobile:t,showMobileChatMode:e,visibleConversationCount:de.length}),[se,E]=Ct.useState(null),q=Ct.useCallback((we,V)=>{E({daemonId:we,workspace:V})},[]),Z=Ct.useCallback(we=>{var V;cr.flushSync(()=>{me(we)}),(V=Me.current)==null||V.restoreHiddenTabToSavedLocation(we.tabKey)},[me]),ne=Ct.useCallback(we=>{var Ie;const V=u.find(R=>Ia(R,we))||f.find(R=>Ia(R,we));V&&(f.some(R=>R.tabKey===V.tabKey)&&Z(V),ie(V.tabKey),(Ie=Me.current)==null||Ie.activateConversationTab(V.tabKey),ye(V.tabKey,"notification-open")),Ue(we.id),Qe(!1)},[Z,f,u,ie,Ue,ye]),je=Ct.useCallback(()=>{var V;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((V=Me.current)==null||V.resetAllPanelsToMain(),Ge(!1))},[Ge]),Le=Ct.useCallback(async we=>{var be;if(!r)return;const V=(be=r.modalButtons)==null?void 0:be[we];if(!V)return;const Ie=_s(r);if(!Ie)return;const R=V.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),ae=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(R);try{await g(Ie,"resolve_action",{button:V,action:ae?"approve":"reject",buttonIndex:we,...as(r)})}catch(Ke){hg(Ke)||console.error("[Shortcut approval] Failed:",Ke)}},[r,g]),{isMac:_e,actionDefinitions:Ne,actionShortcuts:Ee,shortcutListening:Be,shortcutListeningDraft:Re,setShortcutListening:qe,setShortcutListeningDraft:et,saveShortcuts:ct}=Ab({enabled:xt&&!He,onTrigger:we=>{var V,Ie,R,ae,be,Ke,Pe,Oe,ot,Nt,pt,Gt,yr,vr,wr,jr;if(we==="openShortcutHelp"){rt();return}if(we==="openNewSession"){U();return}if(we==="hideCurrentTab"){r&&re(r);return}if(we==="toggleHiddenTabs"){Ge(!We);return}if(we==="openHistoryForActiveTab"){r&&!Ze(r)&&o(r);return}if(we==="openRemoteForActiveTab"){r&&!tt(r)&&!Ze(r)&&c(r);return}if(we==="splitActiveTabRight"){(V=Me.current)==null||V.splitActiveTabRight();return}if(we==="splitActiveTabDown"){(Ie=Me.current)==null||Ie.splitActiveTabDown();return}if(we==="floatActiveTab"){(R=Me.current)==null||R.floatActiveTab();return}if(we==="popoutActiveTab"){(ae=Me.current)==null||ae.popoutActiveTab();return}if(we==="dockActiveTab"){(be=Me.current)==null||be.dockActiveTab();return}if(we==="focusLeftPane"){(Ke=Me.current)==null||Ke.focusLeftPane();return}if(we==="focusRightPane"){(Pe=Me.current)==null||Pe.focusRightPane();return}if(we==="focusUpPane"){(Oe=Me.current)==null||Oe.focusUpPane();return}if(we==="focusDownPane"){(ot=Me.current)==null||ot.focusDownPane();return}if(we==="moveActiveTabToLeftPane"){(Nt=Me.current)==null||Nt.moveActiveTabToLeftPane();return}if(we==="moveActiveTabToRightPane"){(pt=Me.current)==null||pt.moveActiveTabToRightPane();return}if(we==="moveActiveTabToUpPane"){(Gt=Me.current)==null||Gt.moveActiveTabToUpPane();return}if(we==="moveActiveTabToDownPane"){(yr=Me.current)==null||yr.moveActiveTabToDownPane();return}if(we==="triggerPrimaryApprovalAction"){Le(0);return}if(we==="triggerSecondaryApprovalAction"){Le(1);return}if(we==="triggerTertiaryApprovalAction"){Le(2);return}if(we==="setActiveTabShortcut"){(vr=Me.current)==null||vr.setShortcutForActiveTab();return}if(we==="selectPreviousGroupTab"){(wr=Me.current)==null||wr.activatePreviousTabInGroup();return}if(we==="selectNextGroupTab"){(jr=Me.current)==null||jr.activateNextTabInGroup();return}!r||!tt(r)||Ze(r)||we==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),ft=Ct.useCallback(()=>{W(),qe(null),et([])},[W,qe,et]),dt=Ct.useMemo(()=>ht==="all"?Ne:Ne.filter(we=>fg(we)===ht),[Ne,ht]),yt=Ct.useCallback(()=>{const we=Object.fromEntries(Ne.map(V=>[V.id,""]));ct(we)},[Ne,ct]),Ve=Ct.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const we=Object.fromEntries(Ne.map(V=>[V.id,V.defaultShortcut]));ct(we)},[Ne,ct]);return Ct.useEffect(()=>{const we=V=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?V.metaKey&&V.key.toLowerCase()==="w":V.ctrlKey&&V.key.toLowerCase()==="w")&&(V.preventDefault(),r&&re&&re(r))};return window.addEventListener("keydown",we),()=>window.removeEventListener("keydown",we)},[r,re]),Ct.useEffect(()=>{if(!He||Be)return;const we=V=>{V.key==="Escape"&&(V.preventDefault(),ft())};return window.addEventListener("keydown",we,!0),()=>window.removeEventListener("keydown",we,!0)},[ft,He,Be]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(Rp,{activeConv:r,wsStatus:n,isConnected:a,conversations:de,hiddenConversations:f,onOpenHistory:o,onHideConversation:re,onShowConversation:Z,onShowAllHidden:ke,onResetPanelsToMain:je,notifications:Ae,notificationUnreadCount:Te,onOpenNotification:ne,onMarkNotificationRead:Ue,onMarkNotificationUnread:B,onDeleteNotification:Se,inboxOpen:De,onInboxOpenChange:Qe,hiddenOpen:We,onHiddenOpenChange:Ge,onOpenNewSession:t?void 0:U,onOpenDashboardGuide:rt,guideNudgeVisible:st,actionShortcuts:Ee,onOpenRemote:()=>{!r||tt(r)||Ze(r)||c(r)},onStopCli:l,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:q}),e?s.jsx(gb,{conversations:u,hiddenConversations:f,ides:x,actionLogs:S,sendDaemonCommand:g,setActionLogs:p,setCliViewModeOverrides:y,isStandalone:b,userName:C,requestedActiveTabKey:N,onRequestedActiveTabConsumed:v,requestedMachineId:M,onRequestedMachineConsumed:I,requestedMobileSection:j,onRequestedMobileSectionConsumed:w,onOpenHistory:o,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowAllHiddenConversations:ke,onHideConversation:re,onOpenNewSession:U,liveSessionInboxState:$e}):t?s.jsx(Cb,{containerRef:$,isSplitMode:P,numGroups:T,groupSizes:F,groupedConvs:H,clearedTabs:L,ides:x,actionLogs:S,sendDaemonCommand:g,setActionLogs:p,isStandalone:b,hasRegisteredMachines:ve.length>0,userName:C,focusedGroup:k,focusGroup:A,moveTabToGroup:K,splitTabRelative:_,closeGroup:D,handleResizeStart:O,groupActiveTabIds:X,setGroupActiveTab:ge,groupTabOrders:ce,setGroupTabOrder:ee,toggleHiddenTab:z,onOpenNewSession:U,allowTabShortcuts:!1,liveSessionInboxState:$e}):s.jsx(Ub,{visibleConversations:de,clearedTabs:L,ides:x,actionLogs:S,sendDaemonCommand:g,setActionLogs:p,isStandalone:b,hasRegisteredMachines:ve.length>0,initialDataLoaded:h,userName:C,toggleHiddenTab:z,actionShortcuts:Ee,registerActionHandlers:we=>{Me.current=we},onActiveTabChange:ie,requestedActiveTabKey:pe,onRequestedActiveTabConsumed:Y,onRequestScrollToBottom:ye,scrollToBottomRequest:xe,onOpenNewSession:U,liveSessionInboxState:$e,layoutProfile:te}),Je&&s.jsx(Yb,{machines:ve,ides:x,onClose:G,onBrowseDirectory:he,onSaveWorkspace:le,onLaunchIde:ue,onLaunchProvider:oe,onListMeshes:Q,onLaunchMeshCoordinator:fe,onListSavedSessions:J}),se&&s.jsx(cd,{daemonId:se.daemonId,workspace:se.workspace,onClose:()=>E(null)}),He&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:ft,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",onClick:we=>we.stopPropagation(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:ft,"aria-label":"Close dashboard guide",children:s.jsx(vt,{size:14})})]}),s.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(we=>s.jsx("button",{type:"button",className:`btn btn-sm ${mt===we.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ce(we.id),children:we.label},we.id))}),mt==="overview"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",_e?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),mt==="quickstart"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),mt==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(we=>s.jsx("button",{type:"button",className:`btn btn-sm ${ht===we.id?"btn-primary":"btn-secondary"}`,onClick:()=>ze(we.id),children:we.label},we.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:yt,children:"Disable all"}),s.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:Ve,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:dt.map(we=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Be===we.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:we.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:we.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:we.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:Be===we.id?Re.length>0?`${Re.join(" ")} ...`:"Listening...":Ee[we.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{qe(we.id),et([])},children:Be===we.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const V={...Ee};V[we.id]="",ct(V)},children:"Disable"})]})]})},we.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",_e?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",", or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs."]})]})]})})]})}const ia=[{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 bg({onClose:e}){const[t,r]=i.useState(0),n=ia[t],a=t===ia.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:o=>{o.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(vt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:ia.map((o,c)=>s.jsx("div",{style:{width:c===t?24:8,height:8,borderRadius:4,background:c===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx("span",{children:n.icon})," ",n.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&s.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>a?e():r(o=>o+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
|
|
65
|
+
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
66
|
+
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
67
|
+
`})]})}function gg({hasExtensions:e,ideName:t,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?s.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[s.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${r==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a("native"),children:t}),n.map(o=>{const c=r===o.tabKey,l=o.status==="waiting_approval",d=o.status==="generating";return s.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${c?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(o.tabKey),children:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),o.title,l&&s.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},o.tabKey)})]}):null}function yg({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,c]=i.useState(()=>a||"native"),l=i.useMemo(()=>il(t),[t]),d=i.useMemo(()=>e?bo(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),m=i.useMemo(()=>d.find(p=>p.streamSource==="native"),[d]),u=i.useMemo(()=>d.filter(p=>p.streamSource==="agent-stream"),[d]),f=i.useMemo(()=>e?Et(d,e.id):null,[d,e]);i.useEffect(()=>{a&&c(a)},[a]),i.useEffect(()=>{if(a||!f)return;const p=f.streamSource==="native"?"native":f.tabKey;!p||o===p||o==="native"&&c(p)},[o,f,a]),i.useEffect(()=>{var p;o!=="native"&&(u.some(y=>y.tabKey===o)||c(((p=u[0])==null?void 0:p.tabKey)||"native"))},[o,u]),i.useEffect(()=>{o==="native"&&(m||u[0]&&c(u[0].tabKey))},[o,m,u]);const x=i.useMemo(()=>o==="native"&&m?m:u.find(p=>p.tabKey===o)||f||m||u[0],[o,m,f,u]),S=i.useMemo(()=>u.map(p=>({tabKey:p.tabKey,title:el(p)||n,status:p.status})),[u,n]),g=i.useCallback(p=>{if(p)return d.find(y=>Ia(y,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[d]);return{activeChatTab:o,setActiveChatTab:c,activeConv:x,conversations:d,extensionTabs:S,hasExtensions:S.length>0,resolveConversationByTarget:g}}function vg({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:c,isStandalone:l,userName:d,onOpenHistory:m,onConversationChange:u,onClose:f}){const[x,S]=i.useState("split"),[g,p]=i.useState(()=>Jt(e)?"native":e.tabKey),y=i.useRef(null),b=i.useMemo(()=>t||r.find(A=>A.id===e.routeId),[e.routeId,t,r]),h=i.useMemo(()=>it((b==null?void 0:b.type)||""),[b==null?void 0:b.type]),{conversations:C,extensionTabs:N,hasExtensions:v}=yg({ideData:b,allIdes:r,connectionStates:n,ideName:h||"IDE",preferredTabKey:Jt(e)?void 0:e.tabKey}),M=i.useMemo(()=>b?Et(C,b.id):null,[b,C]);i.useEffect(()=>{const A=y.current,K={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(y.current=K,!(A&&A.routeId===K.routeId&&A.tabKey===K.tabKey&&A.streamSource===K.streamSource)){if(Jt(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),i.useEffect(()=>{if(g==="native"){if(C.some(A=>A.streamSource==="native"))return;(M==null?void 0:M.streamSource)==="agent-stream"&&p(M.tabKey);return}if(!C.some(A=>A.tabKey===g)){if((M==null?void 0:M.streamSource)==="agent-stream"){p(M.tabKey);return}p("native")}},[C,g,M]);const I=i.useMemo(()=>g==="native"?C.find(A=>A.streamSource==="native")||e:C.find(A=>A.tabKey===g)||e,[e,C,g]),j=vl(I),w=i.useMemo(()=>j.status||j.modalMessage||j.modalButtons?{...I,...j.status?{status:j.status}:{},...j.modalMessage!==void 0?{modalMessage:j.modalMessage}:{},...j.modalButtons!==void 0?{modalButtons:j.modalButtons}:{}}:I,[I,j]),$=hr(w),P=jn({sendDaemonCommand:o,activeConv:w,setActionLogs:c,isStandalone:l}),{connScreenshot:T,screenshotUsage:F,handleRemoteAction:H}=Gl({doId:$,targetSessionId:$c(w),connState:w.connectionState||"new",viewMode:x}),L=i.useMemo(()=>a.filter(A=>A.routeId===w.tabKey),[a,w.tabKey]);i.useEffect(()=>{u==null||u(w)},[w,u]),i.useEffect(()=>{const A=K=>{K.key==="Escape"&&f()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[f]);const k=i.useCallback(A=>{A.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:f,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:k,children:[s.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[s.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Mt,{size:16})}),s.jsx("span",{className:"truncate",children:no(I)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:f,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(A=>{const K=x===A;return s.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:()=>S(A),title:A==="split"?"Split view":"Remote only",children:A==="split"?s.jsx(ju,{size:15}):s.jsx(Mt,{size:15})},A)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>m(I),title:"Chat History",children:[s.jsx(qa,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:f,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${x==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[x!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${x==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(gg,{hasExtensions:v,ideName:h||"IDE",activeChatTab:g,extensionTabs:N,onSelectTab:p}),s.jsx(Sc,{activeConv:w,onModalButton:P.handleModalButton}),s.jsx(Ra,{activeConv:w,ideEntry:b,showMetaChips:!1,handleSendChat:P.handleSendChat,isSendingChat:P.isSendingChat,sendFeedbackMessage:P.sendFeedbackMessage,handleFocusAgent:P.handleFocusAgent,isFocusingAgent:P.isFocusingAgent,actionLogs:L,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${x==="split"?"order-1 md:order-2":""}`,children:s.jsx(jc,{addLog:()=>{},connState:w.connectionState||"new",connScreenshot:T,screenshotUsage:F,transportType:w.transport,onAction:H})})]})]})})}function wg({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=vp(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[s.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",o,"?"]}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:t?"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.":"This provider does not support graceful stop. Force Stop will end the runtime immediately."})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&s.jsx("button",{onClick:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),s.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:"Force Stop"}),s.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function jg({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(Np,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(xo,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,missingWorkspaceResumePath:e.missingWorkspaceResumePath,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),t.conversation&&s.jsx(vg,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose}),r.open&&r.targetConv&&(tt(r.targetConv)||Ze(r.targetConv))&&s.jsx(wg,{activeConv:r.targetConv,canSaveAndStop:tt(r.targetConv)&&!Ze(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(ol,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),o.open&&s.jsx(bg,{onClose:o.onClose})]})}function kg({daemons:e,targetVersion:t,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:o}){return e.length===0?null:s.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:r?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:r?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[s.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:s.jsx(fr,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[r?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(c=>{const l=Tt(c,{fallbackId:c.id}),d=n[c.id],m=c.version||c.daemonVersion||"unknown",u=c.versionUpdateRequired===!0,x=Pl(c)==="preview"?"Update to preview":u?"Update now":"Upgrade";return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:l}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),u&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),d==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:u?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):d==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(c.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:u?"var(--status-danger)":"var(--status-warning)",background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:x})]},c.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:s.jsx(vt,{size:16})})]})}function Sg(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function Ng(e){const t=e.machine;return typeof(t==null?void 0:t.cpus)!="number"||typeof(t==null?void 0:t.totalMem)!="number"||typeof(t==null?void 0:t.arch)!="string"||typeof(t==null?void 0:t.release)!="string"}function Cg(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>Ng(t)).map(t=>t.id)}}function Tg(){var $o,Bo,Wo,Ko;const{sendCommand:e}=gt(),t=xr(),r=yl(),n=za(),a=Ws(),[o,c]=Fd(),l=o.get("activeTab"),d=(($o=n.state)==null?void 0:$o.openRemoteForTabKey)||null,m=((Bo=n.state)==null?void 0:Bo.openMachineId)||null,u=((Wo=n.state)==null?void 0:Wo.mobileSection)||null,f=Xc(),x=f.ides||[],S=f.initialLoaded??!0,{updateRouteChats:g,setToasts:p}=f,[y,b]=i.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),h=f.toasts||[],C=f.wsStatus||"connected",N=f.isConnected??!0,v=f.connectionStates||{},M=f.showReconnected||!1,{layoutProfile:I,groupAssignments:j,updateGroupAssignments:w,focusedGroup:$,updateFocusedGroup:P,focusGroup:T,groupActiveTabIds:F,updateGroupActiveTabIds:H,setGroupActiveTab:L,groupTabOrders:k,updateGroupTabOrders:A,setGroupTabOrder:K,groupSizes:_,updateGroupSizes:D,isMobile:O,hasHydratedStoredLayout:X,hydrateStoredLayout:ge,focusConversationTab:ce}=mx(),[ee,z]=i.useState(()=>wo());i.useEffect(()=>Mh(z),[]);const de=i.useMemo(()=>Sg({isMobile:O,mobileViewMode:ee}),[O,ee]),[pe,Y]=i.useState([]),[ie,ye]=i.useState({}),[re,me]=i.useState({});pr("Dashboard",{ideCount:x.length,toastCount:h.length,focusedGroup:$,groupCount:Object.keys(j).length,actionLogCount:pe.length});const ke=i.useMemo(()=>x.filter(Ye=>Ye.type==="adhdev-daemon").sort(to),[x]),xe=ke[0],ve=!!xe;i.useEffect(()=>{const{metadataDaemonIds:Ye,runtimeDaemonIds:Lt}=Cg(ke);for(const Fs of Ye)t(Fs,{minFreshMs:3e4}).catch(()=>{});for(const Fs of Lt)r(Fs,{minFreshMs:3e4}).catch(()=>{})},[t,r,ke]);const te=(xe==null?void 0:xe.terminalBackend)||null,he=xe?Tt(xe,{fallbackId:xe.id}):null,le=(xe==null?void 0:xe.id)||null,ue=i.useMemo(()=>Wh(x,ie),[x,ie]),{hiddenTabs:oe,hideTarget:Q,toggleTarget:fe,showTarget:J,showAllTabs:Ae}=Bh(),{conversations:Te,visibleConversations:$e,visibleTabKeys:Ue,resolveConversationBySessionId:B,resolveConversationByTarget:Se}=Jh({ides:ue,connectionStates:v,clearedTabs:re,hiddenTabs:oe}),Me=i.useMemo(()=>new Map(Te.map(Ye=>[Ye.tabKey,Ye])),[Te]);Jf($e,de),i.useEffect(()=>{Object.keys(ie).length!==0&&ye(Ye=>Kh(Ye,x))},[x,ie]);const De=i.useMemo(()=>dm(x),[x]),{notifications:We,unreadCount:He}=Mx({conversations:Te,liveSessionInboxState:De}),{handleMarkDashboardNotificationRead:Je,handleMarkDashboardNotificationUnread:st,handleDeleteDashboardNotification:mt}=Ix({notifications:We,sendDaemonCommand:e}),{containerRef:ht,normalizedGroupAssignments:xt,numGroups:Ce,isSplitMode:ze,groupedConvs:Qe,moveTabToGroup:Ge,closeGroup:rt,handleResizeStart:W,splitTabRelative:U}=yx({groupAssignments:j,updateGroupAssignments:w,updateFocusedGroup:P,updateGroupActiveTabIds:H,updateGroupTabOrders:A,groupSizes:_,updateGroupSizes:D,isMobile:O,visibleConversations:$e,visibleTabKeys:Ue}),{activeConv:G,openDesktopConversation:se,requestScrollToBottom:E,scrollToBottomRequest:q,setDesktopActiveTab:Z}=Ux({isMobile:O,conversations:Te,visibleConversations:$e,groupActiveTabIds:F,focusedGroup:$,groupedConvs:Qe,setSearchParams:c});Gx({activeConv:G,isMobile:O,liveSessionInboxState:De,sendDaemonCommand:e});const{requestedDesktopTabKey:ne,requestedMobileTabKey:je,consumeRequestedActiveTab:Le}=Qh({isMobile:O,urlActiveTab:l,resolveConversationBySessionId:B,setSearchParams:c}),{remoteDialogConv:_e,remoteDialogIdeEntry:Ne,remoteDialogActiveConv:Ee,setRemoteDialogActiveConv:Be,openRemoteDialog:Re,closeRemoteDialog:qe,cliStopDialogOpen:et,cliStopTargetConv:ct,requestCliStop:ft,cancelCliStop:dt,confirmCliStop:yt}=Xx({isMobile:O,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:ne,conversations:Te,ides:x,resolveConversationByTarget:Se,activeConv:G,sendDaemonCommand:e}),{historyModalOpen:Ve,openHistoryModal:we,closeHistoryModal:V,historyTargetConv:Ie,isSavedSessionHistoryTarget:R,isHistoryCreatingChat:ae,isHistoryRefreshingHistory:be,handleHistorySwitchSession:Ke,handleHistoryNewChat:Pe,handleHistoryRefresh:Oe,savedHistorySessions:ot,savedHistoryFilters:Nt,setSavedHistoryFilters:pt,missingWorkspaceResumePath:Gt,isSavedHistoryLoading:yr,resumingSavedHistorySessionId:vr,handleRefreshSavedHistory:wr,handleResumeSavedHistorySession:jr}=qx({activeConv:G,remoteDialogConv:_e,remoteDialogActiveConv:Ee,ides:x,sendDaemonCommand:e,updateRouteChats:g,setToasts:p,setClearedTabs:me,setSearchParams:c}),fd=i.useMemo(()=>$e,[$e]),kr=O&&ee==="chat",pd=i.useMemo(()=>Te.filter(Ye=>jo(oe,Ye)),[Te,oe]),_o=i.useCallback(Ye=>{const Lt=new URLSearchParams(o);Lt.set("activeTab",Ye),c(Lt,{replace:!0})},[o,c]),{trackPendingLaunch:hd}=Kx({ides:x,conversations:Te,onOpenSession:_o}),{handleBrowseMachineDirectory:xd,handleSaveMachineWorkspace:bd,handleLaunchMachineIde:gd,handleLaunchMachineProvider:yd,handleListMachineMeshes:vd,handleLaunchMeshCoordinator:wd,handleListMachineSavedSessions:jd,setActiveCliViewMode:kd}=Ox({sendDaemonCommand:e,trackPendingLaunch:hd,onOpenSession:_o,activeConv:G,ides:x,setCliViewModeOverrides:ye});Oh({visibleConversations:$e,clearedTabs:re,setClearedTabs:me,setActionLogs:Y}),Zh({ides:x,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Se});const{isRefreshingHistory:Sd,handleRefreshHistory:Nd}=Ll({sendDaemonCommand:e,activeConv:G,chats:(Ko=x.find(Ye=>Ye.id===(G==null?void 0:G.routeId)))==null?void 0:Ko.chats,updateRouteChats:g,setToasts:p,setClearedTabs:me});px({urlActiveTab:O&&!kr?l:null,conversations:Te,resolveConversationBySessionId:B,normalizedGroupAssignments:xt,hasHydratedStoredLayout:O&&!kr?X:!0,hydrateStoredLayout:O&&!kr?ge:()=>{},focusConversationTab:ce,setSearchParams:c,historyModalOpen:Ve,activeConv:G,isRefreshingHistory:Sd,ides:x,handleRefreshHistory:Nd});const Cd=i.useMemo(()=>!G||!tt(G)||Ze(G)?null:Os(G),[G]),{versionMismatchDaemons:Td,hasRequiredVersionDaemons:Do,targetVersion:Md,versionBannerDismissed:Id,setVersionBannerDismissed:Ad,upgradingDaemons:Rd,handleBannerUpgrade:Ld}=wx({ides:x,sendDaemonCommand:e}),Eo=i.useCallback(Ye=>{J(Ye),se(Ye)},[se,J]),Pd=i.useCallback(Ye=>{Q(Ye)},[Q]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[s.jsx(Cp,{terminalBackend:te,isStandalone:ve,machineLabel:he,machineKey:le}),(!Id||Do)&&s.jsx(kg,{daemons:Td,targetVersion:Md,required:Do,upgradingDaemons:Rd,onUpgrade:Ld,onDismiss:()=>Ad(!0)}),s.jsx(xg,{showMobileChatMode:kr,isMobile:O,activeConv:G,wsStatus:C,isConnected:N,onOpenHistory:Ye=>{Ye&&Be(Ye),we()},onOpenRemote:Re,onStopCli:ft,activeCliViewMode:Cd,onSetActiveCliViewMode:kd,mobileChatConversations:fd,ides:x,actionLogs:pe,sendDaemonCommand:e,setActionLogs:Y,setCliViewModeOverrides:ye,isStandalone:ve,initialDataLoaded:S,userName:f.userName,requestedMobileTabKey:je,onRequestedMobileTabConsumed:Le,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:ht,isSplitMode:ze,numGroups:Ce,groupSizes:_,groupedConvs:Qe,clearedTabs:re,focusedGroup:$,focusGroup:T,moveTabToGroup:Ge,splitTabRelative:U,closeGroup:rt,handleResizeStart:W,groupActiveTabIds:F,setGroupActiveTab:L,groupTabOrders:k,setGroupTabOrder:K,toggleHiddenTab:Ye=>fe(Me.get(Ye)||{tabKey:Ye}),visibleConversations:$e,hiddenConversations:pd,requestedDesktopTabKey:ne,onRequestedDesktopTabConsumed:Le,onDesktopActiveTabChange:Z,onRequestScrollToBottom:E,onHideConversation:Pd,onShowHiddenConversation:Eo,onShowAllHiddenConversations:Ae,scrollToBottomRequest:q,machineEntries:ke,layoutProfile:I,onBrowseMachineDirectory:xd,onSaveMachineWorkspace:bd,onLaunchMachineIde:gd,onLaunchMachineProvider:yd,onListMachineMeshes:vd,onLaunchMeshCoordinator:wd,onListMachineSavedSessions:jd,notifications:We,notificationUnreadCount:He,liveSessionInboxState:De,onMarkNotificationRead:Je,onMarkNotificationUnread:st,onDeleteNotification:mt}),s.jsx("style",{children:`
|
|
68
|
+
body { overflow: hidden; overscroll-behavior: none; }
|
|
69
|
+
`}),s.jsx(jg,{historyModal:{open:Ve,targetConv:Ie,ides:x,isCreatingChat:ae,isRefreshingHistory:R?!1:be,savedSessions:ot,savedHistoryFilters:Nt,missingWorkspaceResumePath:Gt||null,onSavedHistoryFiltersChange:pt,isSavedSessionsLoading:yr,isResumingSavedSessionId:vr,onClose:V,onNewChat:Pe,onSwitchSession:Ke,onRefreshHistory:R?wr:Oe,onResumeSavedSession:jr},remoteDialog:{conversation:_e,ideEntry:Ne,ides:x,connectionStates:v,actionLogs:pe,sendDaemonCommand:e,setActionLogs:Y,isStandalone:ve,userName:f.userName,onOpenHistory:Ye=>{Ye&&Be(Ye),we()},onConversationChange:Be,onClose:qe},cliStopDialog:{open:et,targetConv:ct,onCancel:dt,onStopNow:async()=>{await yt("hard")},onSaveAndStop:async()=>{await yt("save")}},connectionBanner:{wsStatus:C,showReconnected:M,loginUrl:f.connectionLoginUrl,onReconnect:f.retryServerConnection},toastOverlay:{toasts:h,onDismiss:Ye=>p(Lt=>Lt.filter(Fs=>Fs.id!==Ye)),onClick:Ye=>{if(Ye.targetKey){const Lt=Se(Ye.targetKey);Lt&&(ce(Lt.tabKey,xt),Eo(Lt),E(Lt.tabKey,"toast-open"))}}},onboarding:{open:y,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}b(!1)}}})]})}function Mg({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[o,c]=i.useState([]),[l,d]=i.useState(null),[m,u]=i.useState(null),[f,x]=i.useState(!1),[S,g]=i.useState(null),[p,y]=i.useState(!1),[b,h]=i.useState(""),C=i.useRef(null),N=i.useCallback(_=>{C.current=_},[]),v=i.useCallback((_,D,O=!1)=>{c(X=>[...X.slice(-100),{timestamp:Date.now(),level:_,message:D}]),setTimeout(()=>{var X;return(X=a.current)==null?void 0:X.scrollIntoView({behavior:"smooth"})},100),O&&nt.showToast(D,_==="error"||_==="warn"?"warning":"success")},[a]),M=i.useCallback(_=>{const D=_ instanceof Error?_.message:String(_||"");return D.includes("P2P command timeout")||D.includes("P2P not connected")||D.includes("P2P not available")},[]),I=i.useCallback(async(_,D)=>{var O;if(!e||l)return!1;d(_),v("info",`Launching ${it(_)}${D!=null&&D.workspace?` in ${D.workspace}`:""}...`);try{const X={ideType:_,enableCdp:!0};(O=D==null?void 0:D.workspace)!=null&&O.trim()?X.workspace=D.workspace.trim():D!=null&&D.useDefaultWorkspace&&(X.useDefaultWorkspace=!0);const ge=await r(e,"launch_ide",X);return v(ge!=null&&ge.success?"info":"error",ge!=null&&ge.success?`${it(_)} launched`:`Failed: ${ge==null?void 0:ge.error}`,!0),!!(ge!=null&&ge.success)}catch(X){return v("error",`Launch error: ${X.message}`,!0),!1}finally{d(null)}},[e,l,v,r]),j=i.useCallback(async _=>{if(!e)return{success:!1};const{cliType:D,dir:O,workspaceId:X,useDefaultWorkspace:ge,useHome:ce,argsStr:ee,model:z,resumeSessionId:de}=_;if(!D)return v("warn","Select a CLI or ACP provider first",!0),{success:!1};const pe=ee?ee.split(/\s+/).filter(Boolean):void 0,Y=(O==null?void 0:O.trim())||(X?"(saved id)":ge?"(default workspace)":ce?"(home)":"");v("info",`Launching ${D}${Y?` in ${Y}`:""}${z?` (model: ${z})`:""}...`),u(D);try{const ie={cliType:D,cliArgs:pe,initialModel:z||void 0};O!=null&&O.trim()?ie.dir=O.trim():X?ie.workspaceId=X:ge?ie.useDefaultWorkspace=!0:ce&&(ie.useHome=!0),de&&(ie.resumeSessionId=de);const ye=await r(e,"launch_cli",ie),re=(ye==null?void 0:ye.result)||ye;return ye!=null&&ye.success?(v("info",`${D} launched`,!0),(re==null?void 0:re.launchSource)==="home"?v("info","📂 Running in home directory (explicit choice)"):(re==null?void 0:re.launchSource)==="defaultWorkspace"&&v("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:re==null?void 0:re.sessionId}):(v("error",`Failed: ${(ye==null?void 0:ye.error)||(re==null?void 0:re.error)}`,!0),(ye==null?void 0:ye.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&g({cliType:D,argsStr:ee,model:z}),{success:!1,sessionId:re==null?void 0:re.sessionId})}catch(ie){return M(ie)?(v("warn",`${D} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(v("error",`Launch error: ${ie.message}`,!0),{success:!1})}finally{u(null)}},[e,v,M,r]),w=i.useCallback(async(_,D,O,X)=>e?_?D.trim()?j({cliType:_,dir:D,argsStr:O,model:X}):(g({cliType:_,argsStr:O,model:X}),{success:!1}):(v("warn","Select a provider",!0),{success:!1}):{success:!1},[e,v,j]),$=i.useCallback(async(_,D,O)=>{if(e&&window.confirm(`Stop ${_}?
|
|
70
|
+
This will terminate the process.`))try{const X=await r(e,"stop_cli",{cliType:_,dir:D,targetSessionId:O});X!=null&&X.success?v("info",`${_} stopped`,!0):v("error",`Stop failed: ${(X==null?void 0:X.error)||"Unknown error"}`,!0)}catch(X){v("error",`Stop failed: ${X.message}`,!0)}},[e,v,r]),P=i.useCallback(async _=>{try{await r(_.daemonId,"restart_ide",{ideType:_.type}),v("info",`${it(_.type)} restart initiated`,!0)}catch(D){v("error",`Restart failed: ${D.message}`,!0)}},[v,r]),T=i.useCallback(async _=>{if(window.confirm(`Stop ${it(_.type)}?
|
|
71
|
+
This will disconnect CDP and optionally kill the process.`))try{const D=await r(_.daemonId,"stop_ide",{ideType:_.type,killProcess:!0});D!=null&&D.success?v("info",`${it(_.type)} stopped`,!0):v("error",`Stop failed: ${(D==null?void 0:D.error)||"Unknown error"}`,!0)}catch(D){v("error",`Stop failed: ${D.message}`,!0)}},[v,r]),F=i.useCallback(async()=>{if(e)try{const _=await r(e,"detect_ides",{});v("info",`Found ${((_==null?void 0:_.result)||[]).length} IDE(s)`,!0)}catch(_){v("error",`Detection failed: ${_.message}`,!0)}},[e,v,r]),H=i.useCallback(async _=>{if(!e||!_.trim())return!1;x(!0);try{const D=await r(e,"workspace_add",{path:_.trim()});return D!=null&&D.success?(v("info",`Workspace added: ${_.trim()}`),!0):(v("error",(D==null?void 0:D.error)||"workspace_add failed"),!1)}catch(D){return v("error",D.message),!1}finally{x(!1)}},[e,v,r]),L=i.useCallback(async _=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){x(!0);try{const D=await r(e,"workspace_remove",{id:_});D!=null&&D.success?v("info","Workspace removed",!0):v("error",(D==null?void 0:D.error)||"workspace_remove failed",!0)}catch(D){v("error",D.message,!0)}finally{x(!1)}}},[e,v,r]),k=i.useCallback(async _=>{var D;if(e){x(!0);try{const O=await r(e,"workspace_set_default",_===null?{clear:!0}:{id:_});if(O!=null&&O.success){v("info",_?"Default workspace updated":"Default workspace cleared",!0);const X=typeof O.defaultWorkspacePath=="string"?O.defaultWorkspacePath:"";X&&((D=C.current)==null||D.call(C,X))}else v("error",(O==null?void 0:O.error)||"workspace_set_default failed",!0)}catch(O){v("error",O.message,!0)}finally{x(!1)}}},[e,v,r]),A=i.useCallback(async _=>{var O;if(!e||!_.trim())return;const D=_.trim();x(!0);try{const X=await r(e,"workspace_set_default",{path:D});X!=null&&X.success?(v("info","Default workspace set from history"),(O=C.current)==null||O.call(C,D)):v("error",(X==null?void 0:X.error)||"Could not set default (path missing on disk?)")}catch(X){v("error",X.message)}finally{x(!1)}},[e,v,r]),K=i.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:b}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:b})}catch(_){v("warn",`Live nickname updated, but account sync failed: ${_.message}`)}v("info",`Nickname set to "${b||"(cleared)"}"`),y(!1)}catch(_){v("error",`Failed: ${_.message}`)}},[e,b,t,v,n,r]);return{logs:o,launchingIde:l,launchingAgentType:m,workspaceBusy:f,launchPick:S,setLaunchPick:g,editingNickname:p,setEditingNickname:y,nicknameInput:b,setNicknameInput:h,addLog:v,handleLaunchIde:I,runLaunchCliCore:j,handleLaunchCli:w,handleStopCli:$,handleRestartIde:P,handleStopIde:T,handleDetectIdes:F,handleWorkspaceAdd:H,handleWorkspaceRemove:L,handleWorkspaceSetDefault:k,handleWorkspaceResumePath:A,handleSaveNickname:K,setOnDefaultWorkspaceChanged:N}}function Ig({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:c}){var P;const{workspaceBusy:l,handleWorkspaceAdd:d,handleWorkspaceRemove:m,handleWorkspaceSetDefault:u}=o,[f,x]=i.useState(!1),[S,g]=i.useState(""),[p,y]=i.useState([]),[b,h]=i.useState(!1),[C,N]=i.useState(""),v=i.useCallback(async T=>{h(!0),N("");try{const F=await Cn(c,e,T);g(F.path),y(F.directories)}catch(F){N(F instanceof Error?F.message:"Could not load folder")}finally{h(!1)}},[e,c]),M=i.useCallback(()=>{x(!0);const T=[...r.map(H=>H.workspace),...n.map(H=>H.workspace),...a.map(H=>H.workspace)],F=Nn(t.platform,Sn(T,t.defaultWorkspacePath,(t.workspaces||[]).map(H=>H.path)));v(F)},[a,n,r,v,t.defaultWorkspacePath,t.platform,t.workspaces]),I=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,j=t.availableMem??t.freeMem??t.totalMem,w=I&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-j)/t.totalMem*100))):0,$=((P=t.loadavg)==null?void 0:P[0])||0;return s.jsxs("div",{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[s.jsx(Tr,{icon:s.jsx(hc,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?xm(t.uptime):"Waiting…"}),s.jsx(Tr,{icon:s.jsx(Mt,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(Tr,{icon:s.jsx(Xa,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(Tr,{icon:s.jsx(Su,{size:16}),label:"ACPs",value:`${a.length}`})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),s.jsxs("div",{className:"flex gap-6",children:[s.jsx(Yo,{value:I?Math.min(Math.round($/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:I?`${$.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(Yo,{value:w,max:100,label:"Memory",color:"#3b82f6",detail:I?`${En(t.totalMem-j)} / ${En(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${En(t.totalMem)} total`})]})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[s.jsx(ps,{size:14})," Workspaces"]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[s.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),s.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:l,value:t.defaultWorkspaceId||"",onChange:T=>void u(T.target.value===""?null:T.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(T=>s.jsx("option",{value:T.id,children:T.label||T.path},T.id))]}),t.defaultWorkspacePath&&s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:t.defaultWorkspacePath,children:t.defaultWorkspacePath})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded transition-colors text-xs",disabled:l,onClick:M,children:"Select workspace…"}),s.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(t.workspaces||[]).length>0&&s.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(t.workspaces||[]).map(T=>s.jsxs("li",{className:"flex items-start gap-2 text-[11px] text-text-muted rounded-lg border border-border-subtle bg-bg-primary px-2.5 py-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[T.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:vn(T.path,T.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:T.path,children:T.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void m(T.id),children:"Remove"})]},T.id))})]}),f&&s.jsx(Mn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:S,directories:p,busy:b,error:C,confirmLabel:"Add workspace",onClose:()=>x(!1),onNavigate:T=>{v(T)},onConfirm:T=>{(async()=>{if(!T)return;await d(T)&&x(!1)})()}})]})}function Ag(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t;return!r.settings||typeof r.settings!="object"?null:{settings:r.settings,values:r.values&&typeof r.values=="object"?r.values:{}}}function Rg(e,t,r){const n=[];for(const[a,o]of Object.entries(e.settings)){const c=r!=null&&r.filterSchema?r.filterSchema(o):o;if(c.length===0)continue;const l=t.find(d=>d.type===a);n.push({type:a,displayName:(l==null?void 0:l.displayName)||a,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:c,values:e.values[a]||{}})}return n}function ca(e){if(!e||typeof e!="object")return!1;const t=e;return(t.sourceMode==="normal"||t.sourceMode==="no-upstream")&&typeof t.disableUpstream=="boolean"&&(t.explicitProviderDir===null||typeof t.explicitProviderDir=="string")&&typeof t.userDir=="string"&&typeof t.upstreamDir=="string"&&Array.isArray(t.providerRoots)}function Fi(e){if(!e||typeof e!="object")return null;if(ca(e))return e;const t=e,r=t.result;return ca(r)?r:ca(t.sourceConfig)?t.sourceConfig:null}function Lg(e){const t=e.trim();return t||null}const Hi=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Pg=[{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 _g({machineId:e,provider:t,sendDaemonCommand:r,onClose:n}){const[a,o]=i.useState("config"),[c,l]=i.useState("codex-cli"),[d,m]=i.useState([]),[u,f]=i.useState(""),[x,S]=i.useState([]),[g,p]=i.useState(""),y=i.useRef(null),b=i.useRef(null),h=j=>{m(w=>w.includes(j)?w.filter($=>$!==j):[...w,j])},C=()=>m([...Hi]),N=()=>m([]);i.useEffect(()=>{var j;(j=y.current)==null||j.scrollIntoView({behavior:"smooth"})},[x]),i.useEffect(()=>()=>{b.current&&clearInterval(b.current)},[]);const v=i.useCallback(()=>{b.current&&clearInterval(b.current),b.current=setInterval(async()=>{try{const j=await r(e,"provider_auto_fix_status",{providerType:t.type});(j==null?void 0:j.running)===!1&&a==="running"&&(o("done"),S(w=>[...w,`
|
|
72
|
+
✅ Auto-fix completed!`]),b.current&&clearInterval(b.current))}catch{}},3e3)},[e,t.type,r,a]),M=async()=>{if(d.length!==0){o("running"),S(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${d.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),p("");try{const j=await r(e,"provider_auto_fix",{providerType:t.type,functions:d,agent:c,...u?{comment:u}:{}});j!=null&&j.success&&(j!=null&&j.started||j!=null&&j.running)?(S(w=>[...w,"✅ Agent started. Monitoring progress..."]),v()):(o("error"),p((j==null?void 0:j.error)||"Failed to start auto-fix"))}catch(j){o("error"),p((j==null?void 0:j.message)||"Connection failed")}}},I=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:t.type}),S(j=>[...j,`
|
|
73
|
+
⚠️ Auto-fix cancelled.`]),o("done"),b.current&&clearInterval(b.current)}catch{}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:j=>j.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:t.icon||"🔧"}),s.jsxs("div",{children:[s.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",t.displayName]}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),s.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),s.jsx("div",{className:"flex gap-2",children:Pg.map(j=>s.jsxs("button",{onClick:()=>l(j.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===j.value?j.color+"66":"var(--border-subtle)",background:c===j.value?j.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===j.value?j.color:"var(--text-primary)"},children:j.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:j.desc})]},j.value))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:C,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),s.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),s.jsx("button",{onClick:N,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Hi.map(j=>s.jsxs("button",{onClick:()=>h(j),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(j)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(j)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(j)?"#a78bfa":"var(--text-secondary)"},children:[d.includes(j)?"☑ ":"☐ ",j]},j))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",s.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),s.jsx("textarea",{value:u,onChange:j=>f(j.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[x.map((j,w)=>s.jsx("div",{className:j.startsWith("✅")?"text-green-400":"",style:j.startsWith("❌")||j.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:j},w)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:y})]}),g&&s.jsx("div",{className:"mt-2 px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:g})]})]}),s.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[s.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&d.length>0&&`${d.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),s.jsxs("div",{className:"flex gap-2",children:[a==="config"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:M,disabled:d.length===0,className:"machine-btn",style:{background:d.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:d.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:d.length>0?"#a78bfa":void 0,opacity:d.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&s.jsx("button",{onClick:I,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{o("config"),S([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Dg({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var v;const o=t.filter(M=>M.category==="ide"),[c,l]=i.useState(((v=o[0])==null?void 0:v.type)||""),[d,m]=i.useState(""),[u,f]=i.useState(""),[x,S]=i.useState(!1),[g,p]=i.useState(""),[y,b]=i.useState(!1),h=M=>{const I=M.toLowerCase().replace(/[^a-z0-9-]/g,"");m(I),(!u||u===C(d))&&f(C(I))},C=M=>M.split("-").map(I=>I.charAt(0).toUpperCase()+I.slice(1)).join(" "),N=async()=>{if(!(!d||!u||!c)){S(!0),p("");try{const M=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:c});M!=null&&M.success||M!=null&&M.created?(b(!0),a==null||a(d)):p((M==null?void 0:M.error)||"Failed to create provider")}catch(M){p((M==null?void 0:M.message)||"Connection failed")}S(!1)}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:M=>M.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:y?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:d})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:o.map(M=>s.jsxs("button",{onClick:()=>l(M.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===M.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===M.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:M.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===M.type?"#a78bfa":"var(--text-secondary)"},children:M.displayName})]},M.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:d,onChange:M=>h(M.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",d||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:u,onChange:M=>f(M.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),g&&s.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:g})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:y?s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:N,disabled:!d||!u||x,className:"machine-btn",style:{background:d&&u?"rgba(34,197,94,0.12)":void 0,borderColor:d&&u?"rgba(34,197,94,0.3)":void 0,color:d&&u?"#86efac":void 0,opacity:!d||!u||x?.4:1},children:x?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Ui(e){return e==="cli"||e==="acp"}function Eg(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 $g(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 zi(e){if(!e)return"No result yet";const t=e.stage||"check",r=e.ok?"OK":"Failed",n=e.message||e.path||e.command||"";return n?`${t}: ${r} — ${n}`:`${t}: ${r}`}function Bg({machineId:e,providers:t,sendDaemonCommand:r}){var H;const[n,a]=i.useState([]),[o,c]=i.useState(!1),[l,d]=i.useState(null),[m,u]=i.useState("all"),[f,x]=i.useState(null),[S,g]=i.useState(!1),[p,y]=i.useState(null),[b,h]=i.useState("normal"),[C,N]=i.useState(""),[v,M]=i.useState(!1),I=i.useCallback(async()=>{if(e)try{const L=await r(e,"get_provider_source_config",{}),k=Fi(L);k&&(y(k),h(k.sourceMode),N(k.explicitProviderDir||""))}catch{}},[e,r]),j=i.useCallback(async()=>{if(e){c(!0);try{const L=await r(e,"get_provider_settings",{}),k=Ag(L);if(k){const A=Rg(k,t,{filterSchema:K=>K.filter(_=>_.key!=="enabled")});A.sort((K,_)=>K.category.localeCompare(_.category)||K.displayName.localeCompare(_.displayName)),a(A)}}catch{}c(!1)}},[e,t,r]);i.useEffect(()=>{n.length===0&&j(),p||I()},[]);const w=async(L,k,A)=>{d(`${L}.${k}`),a(K=>K.map(_=>_.type===L?{..._,values:{..._.values,[k]:A}}:_));try{const K=await r(e,"set_provider_setting",{providerType:L,key:k,value:A});K!=null&&K.success||j()}catch{j()}d(null)},$=async(L,k)=>{await w(L,"enabled",k),await j()},P=async L=>{d(`${L}.detect`);try{await r(e,"detect_provider",{providerType:L})}finally{await j(),d(null)}},T=async L=>{await w(L,"executablePath",""),await w(L,"executableArgs",""),await j()},F=async()=>{M(!0);try{const L=await r(e,"set_provider_source_config",{providerSourceMode:b,providerDir:Lg(C)}),k=Fi(L);k?(y(k),h(k.sourceMode),N(k.explicitProviderDir||"")):await I(),await j()}catch{await I()}M(!1)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex justify-between items-center mb-4",children:[s.jsxs("div",{className:"flex gap-1 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(L=>s.jsx("button",{onClick:()=>u(L),className:`machine-btn text-[10px] px-2 py-0.5 ${m===L?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:L.toUpperCase()},L))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>g(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),s.jsx("button",{onClick:j,disabled:o,className:"machine-btn",children:o?"⏳ Loading...":"↻ Refresh"})]})]}),s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Running CLI sessions refresh provider scripts/config; process binary changes still apply on next launch."})]}),s.jsx("button",{onClick:I,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),s.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),s.jsxs("select",{value:b,onChange:L=>h(L.target.value),className:"machine-input text-[11px]",children:[s.jsx("option",{value:"normal",children:"normal"}),s.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),s.jsx("input",{type:"text",value:C,onChange:L=>N(L.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void F(),disabled:v,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:v?"Applying…":"Apply + Reload"})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(p==null?void 0:p.userDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(p==null?void 0:p.upstreamDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((H=p==null?void 0:p.providerRoots)==null?void 0:H.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(L=>L.category===m).length>1&&(()=>{const L=n.filter(_=>_.category===m),k=new Map;for(const _ of L)for(const D of _.schema){if(D.type!=="boolean")continue;const O=k.get(D.key),X=!!(_.values[D.key]??D.default);O?(O.onCount+=X?1:0,O.total+=1):k.set(D.key,{label:D.label||D.key,onCount:X?1:0,total:1})}const A=[...k.entries()].filter(([,_])=>_.total===L.length);if(A.length===0)return null;const K=async(_,D)=>{for(const O of L)await w(O.type,_,D)};return s.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[s.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",m.toUpperCase()," providers (",L.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:A.map(([_,D])=>{const O=D.onCount===D.total,X=D.onCount===0;return s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:"text-text-secondary font-medium",children:D.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",D.onCount,"/",D.total,")"]}),s.jsx("button",{onClick:()=>void K(_,!0),disabled:O,className:`machine-btn text-[9px] px-1.5 py-px ${O?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void K(_,!1),disabled:X,className:`machine-btn text-[9px] px-1.5 py-px ${X?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},_)})})]})})(),o&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):s.jsx("div",{className:"flex flex-col gap-2",children:n.filter(L=>m==="all"||L.category===m).map(L=>s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[s.jsx("span",{className:"text-lg",children:L.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:L.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:L.category==="acp"?"rgba(139,92,246,0.08)":L.category==="cli"?"rgba(59,130,246,0.08)":L.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:L.category==="acp"?"#a78bfa":L.category==="cli"?"#60a5fa":L.category==="ide"?"#86efac":"var(--status-warning)"},children:L.category}),Ui(L.category)&&(()=>{const k=t.find(_=>_.type===L.type),A=(k==null?void 0:k.enabled)===!0||L.values.enabled===!0,K=(k==null?void 0:k.machineStatus)||(A?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${$g(K)}`,children:Eg(K)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void $(L.type,!A),disabled:l===`${L.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${A?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:A?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void P(L.type),disabled:!A||l===`${L.type}.detect`,title:A?"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 ${A?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void T(L.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),L.category==="ide"&&s.jsx("button",{onClick:()=>x(t.find(k=>k.type===L.type)||{type:L.type,name:L.displayName,displayName:L.displayName,icon:L.icon,category:L.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"})]}),Ui(L.category)&&(()=>{const k=t.find(A=>A.type===L.type);return s.jsxs("div",{className:"mb-2.5 grid gap-1 rounded-lg border border-white/[0.06] bg-bg-primary/40 px-3 py-2 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Detection:"})," ",zi(k==null?void 0:k.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",zi(k==null?void 0:k.lastVerification)]}),s.jsx("div",{className:"text-[9px] text-text-muted",children:"Supported catalog entry only becomes launchable after Enable + Detect succeeds. Custom executable path/args below are machine-local overrides."})]})})(),s.jsx("div",{className:"flex flex-col gap-2",children:L.schema.map(k=>s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[k.label||k.key,l===`${L.type}.${k.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),k.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:k.description})]}),s.jsx("div",{className:"shrink-0",children:k.type==="boolean"?s.jsx("button",{onClick:()=>w(L.type,k.key,!(L.values[k.key]??k.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:L.values[k.key]??k.default?"#8b5cf6":"var(--border-subtle)"},children:s.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:L.values[k.key]??k.default?21:3}})}):k.type==="number"?s.jsx("input",{type:"number",value:Number(L.values[k.key]??k.default??0)||0,min:k.min,max:k.max,onChange:A=>{const K=parseInt(A.target.value)||0;k.min!==void 0&&K<k.min||k.max!==void 0&&K>k.max||w(L.type,k.key,K)},className:"machine-input w-20 text-center text-[11px]"}):k.type==="select"&&k.options?s.jsx("select",{value:String(L.values[k.key]??k.default??""),onChange:A=>w(L.type,k.key,A.target.value),className:"machine-input text-[11px]",children:k.options.map(A=>s.jsx("option",{value:A,children:A},A))}):s.jsx("input",{type:"text",value:String(L.values[k.key]??k.default??""),onBlur:A=>w(L.type,k.key,A.target.value),className:"machine-input w-[120px] text-[11px]"})})]},k.key))})]},L.type))}),f&&s.jsx(_g,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>x(null)}),S&&s.jsx(Dg,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>g(!1),onCreated:()=>{g(!1),j()}})]})}const Wg=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Kg({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function Og(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function Fg(e){return e.trim().toLowerCase()}function An(e,t){const r=Fg(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function Ro(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Bs(e,t=220){const r=Ro(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function Hg(e){const t=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(t))return{kind:t.length>0?"structured":"empty",entries:t.map(r=>{const n=r;return{timestamp:Number(n.ts)||0,level:n.level||"info",message:`[${String(n.category||"daemon")}] ${String(n.message||"")}`.trim()}}),rawText:""};if(typeof t=="string"){const r=t.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function Ug(e,t){return e.filter(r=>An([r.level,r.message],t))}function Vi(e){return`${e.timestamp}:${e.level}:${e.message}`}function zg(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const c of e.entries)n.set(Vi(c),c);for(const c of t.entries)n.set(Vi(c),c);const a=Array.from(n.values()).sort((c,l)=>c.timestamp-l.timestamp).slice(-r),o=a.reduce((c,l)=>Math.max(c,Number(l.timestamp||0)),e.lastTs);return{entries:a,kind:"structured",rawText:"",lastTs:o}}return t.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:t.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function Vg(e,t,r=120){if(t.length===0)return e;const n=new Map;for(const a of e)n.set(a.id,a);for(const a of t)n.set(a.id,a);return Array.from(n.values()).sort((a,o)=>a.ts-o.ts).slice(-r)}function Gg(e,t){return e.split(`
|
|
74
|
+
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>An([r],t))}function qg(e,t){return e.filter(r=>An([r.level,r.category,r.stage,r.interactionId,Ro(r.payload)],t))}function Yg(e,t){return e.filter(r=>An([r.kind,r.topic,r.interactionId,Ro(r.payload)],t))}function Gi(e){return e==="warn"||e==="error"}function Xg({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){return{all:e.length+t.length+r.length+n.length,info:e.filter(a=>a.level!=="debug").length+r.filter(a=>a.level!=="debug").length+n.length,issues:e.filter(a=>Gi(a.level)).length+r.filter(a=>Gi(a.level)).length}}function Jg({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(o=>`${new Date(o.timestamp).toISOString()} ${o.level.toUpperCase()} ${o.message}`)].join(`
|
|
75
|
+
`)):t.length>0&&a.push(["[daemon logs]",...t].join(`
|
|
76
|
+
`)),r.length>0&&a.push(["[trace]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${Bs(o.payload,500)}`.trim())].join(`
|
|
77
|
+
`)),n.length>0&&a.push(["[browser events]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${Bs(o.payload,500)}`.trim())].join(`
|
|
78
|
+
`)),a.join(`
|
|
79
|
+
|
|
80
|
+
`)}function Qg({machineId:e,sendDaemonCommand:t}){const[r,n]=i.useState([]),[a,o]=i.useState("empty"),[c,l]=i.useState(""),[d,m]=i.useState([]),[u,f]=i.useState([]),[x,S]=i.useState(null),[g,p]=i.useState(!0),[y,b]=i.useState("info"),[h,C]=i.useState("all"),[N,v]=i.useState(!0),[M,I]=i.useState(!0),[j,w]=i.useState(""),[$,P]=i.useState(""),[T,F]=i.useState(0),H=i.useRef(0),L=i.useRef(0),k=i.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),A=i.useRef([]),K=i.useCallback(()=>{const ee={entries:[],kind:"empty",rawText:"",lastTs:0};k.current=ee,H.current=0,n([]),l(""),o("empty"),v(!0)},[]),_=i.useCallback(()=>{A.current=[],L.current=0,m([]),I(!0)},[]),D=i.useCallback(ee=>{ee!==y&&(K(),b(ee))},[y,K]),O=i.useCallback(ee=>{C(z=>z===ee?z:ee)},[]),X=i.useCallback(()=>{K(),_(),f([]),S(null),w(""),P(""),As.clear()},[K,_]),ge=i.useCallback(()=>{F(ee=>ee+1)},[]),ce=i.useCallback(async()=>{if(!e)return;const ee=H.current,z=L.current,[de,pe]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:y,since:ee}),t(e,"get_debug_trace",Kg({count:120,since:z,category:h}))]);if(de.status==="fulfilled"){const Y=de.value,ie=(Y==null?void 0:Y.result)||Y,ye=Hg(ie),re=zg(k.current,ye,300);k.current=re,H.current=re.lastTs,v(!1),w((Y==null?void 0:Y.success)===!1?String((Y==null?void 0:Y.error)||"Could not load daemon logs"):""),o(re.kind),l(re.rawText),n(re.entries)}else v(!1),w(de.reason instanceof Error?de.reason.message:"Could not load daemon logs");if(pe.status==="fulfilled"){const Y=pe.value,ie=(Y==null?void 0:Y.result)||Y;if((Y==null?void 0:Y.success)===!1)P(String((Y==null?void 0:Y.error)||"Could not load daemon trace"));else if(Array.isArray(ie==null?void 0:ie.trace)){const ye=ie.trace,re=Vg(A.current,ye,120),me=ye.reduce((ke,xe)=>Math.max(ke,Number(xe.ts||0)),z);A.current=re,me>z&&(L.current=me),P(""),m(re)}else P("");I(!1)}else I(!1),P(pe.reason instanceof Error?pe.reason.message:"Could not load daemon trace");f(As.list({limit:120})),S(Date.now())},[y,e,t,h]);return i.useEffect(()=>{_()},[_,h]),i.useEffect(()=>{if(!e||(ce(),!g))return;const ee=setInterval(()=>{ce()},3e3);return()=>clearInterval(ee)},[g,ce,e,T]),{daemonLogs:r,daemonLogKind:a,daemonRawText:c,debugTrace:d,webEvents:u,lastUpdatedAt:x,autoRefresh:g,logLevel:y,traceCategory:h,daemonLoading:N,traceLoading:M,daemonFetchError:j,traceFetchError:$,setAutoRefresh:p,setLogLevel:D,setTraceCategory:O,refresh:ge,clear:X}}function Zg({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:c,traceCount:l,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":o>0||c>0?"ok":"empty",detail:r||(a==="text"?`${c} raw file-fallback line(s)`:`${o} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:n?"error":t?"loading":l>0?"ok":"empty",detail:n||`${l} 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 qi(e){return e==="warn"||e==="error"}function ey(e){const t=e.toLowerCase();return/\[(err|error)\]/i.test(e)||t.includes(" error ")||t.includes(" failed")?"error":/\[(wrn|warn|warning)\]/i.test(e)||t.includes(" warning ")||t.includes(" timeout")?"warn":/\[(dbg|debug)\]/i.test(e)?"debug":"info"}function ty(e,t){const r=e.match(/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\b/);if(r){const n=Date.parse(r[0]);if(Number.isFinite(n))return n}return Number.MAX_SAFE_INTEGER-1e5+t}function Yi(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function sy(e){const t=Bs(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function ry(e){const t=Bs(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function ny({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.forEach((o,c)=>{a.push({id:`daemon-log-${o.timestamp}-${c}`,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:ry(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:sy(o),category:o.category,stage:o.stage,interactionId:o.interactionId,payload:o.payload})}),t.forEach((o,c)=>{a.push({id:`raw-file-${c}`,source:"raw_file",ts:ty(o,c),severity:ey(o),message:o,raw:o})}),a.sort((o,c)=>o.ts!==c.ts?o.ts-c.ts:Yi(o.source)-Yi(c.source))}function ay(e){return`${e.source}:${e.severity}:${e.message}`}function oy(e){const t=e.filter(n=>qi(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!qi(n.severity))continue;const a=ay(n),o=r.get(a);o?(o.count+=1,o.firstTs=Math.min(o.firstTs,n.ts),o.lastTs=Math.max(o.lastTs,n.ts)):r.set(a,{key:a,source:n.source,severity:n.severity,message:n.message,count:1,firstTs:n.ts,lastTs:n.ts})}return{totalCount:e.length,issueCount:t.length,latestIssue:t[0]||null,repeatedPatterns:Array.from(r.values()).filter(n=>n.count>1).sort((n,a)=>a.count!==n.count?a.count-n.count:a.lastTs-n.lastTs).slice(0,5)}}function iy(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Xi(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${iy(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function cy({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
|
|
81
|
+
`)),a.push(["[source status]",...r.map(c=>`${c.label}: ${c.status} - ${c.detail}`)].join(`
|
|
82
|
+
`)),t.latestIssue&&a.push(["[latest issue]",Xi(t.latestIssue)].join(`
|
|
83
|
+
`)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(c=>`${c.count}x ${c.severity.toUpperCase()} ${c.source} ${c.message}`)].join(`
|
|
84
|
+
`));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(Xi):["No diagnostic events captured."]].join(`
|
|
85
|
+
`)),a.join(`
|
|
86
|
+
|
|
87
|
+
`)}function ly(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function dy(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function uy({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:c,searchQuery:l,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:f}){const x=Og(n,o),S=Ug(e,l),g=Gg(t,l),p=qg(x,l),y=Yg(a,l),b=ly(S,c),h=c==="all"?g:[],C=dy(p,c),N=c==="issues"?[]:y,v=Xg({daemonLogs:S,daemonRawLines:g,trace:p,webEvents:y}),M=ny({daemonLogs:b,daemonRawLines:h,trace:C,webEvents:N}),I=oy(M),j=Zg({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:f,daemonLogKind:r,daemonLogsCount:S.length,daemonRawLineCount:g.length,traceCount:p.length,webEventCount:y.length});return{filteredDaemonLogs:S,filteredDaemonRawLines:g,filteredTraceEntries:p,filteredWebEvents:y,visibleDaemonLogs:b,visibleDaemonRawLines:h,visibleTraceEntries:C,visibleWebEvents:N,quickFilterCounts:v,diagnosticEvents:M,diagnosticsSummary:I,sourceStates:j}}function my(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function ld(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Oa(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 la(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 Lo(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function fy({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Oa(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:ld(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:Lo(e.source)}),e.category&&e.stage&&s.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&s.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&s.jsxs("span",{children:["ix=",e.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function py({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:c,onCopyVisible:l,onToggleAutoRefresh:d,onRefresh:m,onClear:u}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(f=>s.jsx("button",{type:"button",onClick:()=>a(f.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===f.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:f.label},f.id))}),s.jsx("input",{value:r,onChange:f=>o(f.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:l,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:d,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function hy({logLevel:e,traceCategory:t,onLogLevelChange:r,onTraceCategoryChange:n}){return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-3",children:s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(a=>s.jsxs("button",{onClick:()=>r(a),className:`machine-btn text-[10px] px-2 py-0.5 ${e===a?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",a.toUpperCase(),"+"]},a))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:Wg.map(a=>s.jsx("button",{onClick:()=>n(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function xy({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:c,traceFetchError:l}){var u,f;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((f=e.latestIssue)==null?void 0:f.severity)==="warn"?"warning":"good",m=c||l?"danger":o?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${la(e.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:n.trim()?`Filtered by “${n.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${la(d)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[Lo(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:ld(e.latestIssue.ts)})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${la(m)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:c||l?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",my(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(x=>s.jsxs("div",{children:[x.label,": ",x.status]},x.id))})]})]})}function by({patterns:e}){return e.length===0?null:s.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(t=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[s.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[t.count,"× ",t.severity.toUpperCase()," · ",Lo(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function gy({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:c,visibleWebEvents:l,quickFilter:d,searchQuery:m}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,timeline:!u.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(u=>s.jsx(fy,{event:u},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,daemon:!u.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&o.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:d==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((u,f)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${f}`)),e.daemonLogKind!=="text"&&a.map((u,f)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Oa(u.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:u.level==="error"?"ERR":u.level==="warn"?"WRN":u.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:u.message})]},`log-${f}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,trace:!u.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&c.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&c.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&c.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No trace entries match the current search.":e.traceCategory==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),c.map(u=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Oa(u.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.level.toUpperCase()}),s.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Bs(u.payload,360)||"No payload"})]},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,web:!u.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[l.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[l.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),l.map(u=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.kind}),u.topic&&s.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Bs(u.payload,360)||"No payload"})]},u.id))]})]})]})}function yy({machineId:e,sendDaemonCommand:t}){const r=Qg({machineId:e,sendDaemonCommand:t}),[n,a]=i.useState("info"),[o,c]=i.useState(""),[l,d]=i.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=i.useRef(null),u=i.useRef(!1),f=i.useMemo(()=>uy({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&&f.diagnosticEvents.length>0){const g=u.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:g}),u.current=!0},50)}},[f.diagnosticEvents.length,r.autoRefresh]);const x=i.useCallback(async()=>{var p;const g=Jg({daemonLogs:f.visibleDaemonLogs,daemonRawLines:f.visibleDaemonRawLines,trace:f.visibleTraceEntries,webEvents:f.visibleWebEvents});if(!g.trim()){nt.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(g)),nt.showToast("Copied visible logs to clipboard.","success")}catch(y){nt.showToast(y instanceof Error?y.message:"Could not copy visible logs","warning")}},[f.visibleDaemonLogs,f.visibleDaemonRawLines,f.visibleTraceEntries,f.visibleWebEvents]),S=i.useCallback(async()=>{var p;const g=cy({events:f.diagnosticEvents,summary:f.diagnosticsSummary,sources:f.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(g)),nt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(y){nt.showToast(y instanceof Error?y.message:"Could not copy diagnostic bundle","warning")}},[f.diagnosticEvents,f.diagnosticsSummary,f.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(py,{quickFilter:n,quickFilterCounts:f.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:c,onCopyDiagnostics:()=>{S()},onCopyVisible:()=>{x()},onToggleAutoRefresh:()=>r.setAutoRefresh(g=>!g),onRefresh:r.refresh,onClear:r.clear}),s.jsx(hy,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(xy,{diagnosticsSummary:f.diagnosticsSummary,diagnosticEventsCount:f.diagnosticEvents.length,sourceStates:f.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(by,{patterns:f.diagnosticsSummary.repeatedPatterns}),s.jsx(gy,{streams:r,sectionsOpen:l,setSectionsOpen:d,diagnosticEvents:f.diagnosticEvents,visibleDaemonLogs:f.visibleDaemonLogs,visibleDaemonRawLines:f.visibleDaemonRawLines,visibleTraceEntries:f.visibleTraceEntries,visibleWebEvents:f.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:m})]})}function vy(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 dd(e){const t=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return t?t==="auto_resumed"?"restored after restart":t==="resume_failed"?"restore failed":t==="host_restart_interrupted"?"host restart interrupted":t==="orphan_snapshot"?"snapshot recovered":t.replace(/_/g," "):null}function wy(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const c=String((o==null?void 0:o.lifecycle)||"").trim(),l=dd((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(c)?t.push(o):(c==="stopped"||c==="failed")&&(d||l)?r.push(o):n.push(o)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function jy(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function da(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 ua(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function ma(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Ji(e){if(!e)return"unknown";const t=Date.now()-e,r=Math.max(0,Math.round(t/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const a=Math.round(n/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function ky(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Sy(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 Ny(e){var r;const t=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const a=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!a)continue;const o=`${n.providerType}::${n.workspace}::${a}`;t.set(o,(t.get(o)||0)+1)}return Array.from(t.values()).filter(n=>n>1).length}function Cy({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=i.useState(""),[o,c]=i.useState(null),[l,d]=i.useState(!1),m=Dh(e,{enabled:!!e,includeSessions:!0,limit:ai,intervalMs:Rf}),u=m.diagnostics,f=m.loading,x=m.applyDiagnostics,S=i.useMemo(()=>vy({diagnostics:u,loading:f,refreshing:l,error:n}),[u,f,l,n]),g=i.useMemo(()=>new Map(t.map(P=>[P.sessionId||P.id,P])),[t]),p=i.useCallback(async()=>{if(e){d(!0);try{const P=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:ai}),T=ua(P);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Could not load hosted runtime diagnostics");x(T.diagnostics||T.result||null),a("")}catch(P){const T=P instanceof Error?P.message:"Could not load hosted runtime diagnostics";a(T)}finally{d(!1)}}},[x,e,r]);i.useEffect(()=>{!e||u||f||l||p()},[u,f,e,p,l]);const y=i.useCallback(async(P,T)=>{const F=`${P}:${T.sessionId}`;if(!(P==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
|
|
88
|
+
This will terminate the hosted runtime.`))){c(F);try{const H=await r(e,P,{sessionId:T.sessionId}),L=ua(H);if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Session host action failed");const k=P==="session_host_resume_session"?"resumed":P==="session_host_restart_session"?"restarted":"stopped";nt.showToast(`Session host ${k}: ${T.displayName}`,"success"),await p()}catch(H){const L=H instanceof Error?H.message:"Session host action failed";nt.showToast(L,"warning"),a(L)}finally{c(H=>H===F?null:H)}}},[e,p,r]),b=i.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
89
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const T=await r(e,"session_host_prune_duplicate_sessions",{}),F=ua(T);if(!(F!=null&&F.success))throw new Error((F==null?void 0:F.error)||"Duplicate prune failed");const H=F.result||{},L=Array.isArray(H.prunedSessionIds)?H.prunedSessionIds.length:0,k=typeof H.duplicateGroupCount=="number"?H.duplicateGroupCount:0;nt.showToast(`Pruned ${L} duplicate runtime(s) across ${k} group(s)`,"success"),await p()}catch(T){const F=T instanceof Error?T.message:"Duplicate prune failed";nt.showToast(F,"warning"),a(F)}finally{c(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,p,r]),h=i.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((P,T)=>(T.lastActivityAt||0)-(P.lastActivityAt||0)),[u==null?void 0:u.sessions]),C=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)||[]}:wy(h),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,h]),N=C.liveRuntimes,v=C.recoverySnapshots,M=C.inactiveRecords,I=i.useMemo(()=>Ny(N),[N]),j=i.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),w=i.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(P=>P.level==="warn"||P.level==="error")||null,[u==null?void 0:u.recentLogs]),$=(P,T)=>{var O;const F=o===`session_host_resume_session:${P.sessionId}`,H=o===`session_host_restart_session:${P.sessionId}`,L=o===`session_host_stop_session:${P.sessionId}`,k=dd(P.meta),A=g.get(P.sessionId),K=P.attachedClients.length===1?"1 client":`${P.attachedClients.length} clients`,_=T==="recovery"?"Recover":"Resume",D=jy(T);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:P.displayName||(A==null?void 0:A.cliName)||P.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Sy(P.lifecycle)}`,children:P.lifecycle}),k&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:k})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:P.workspaceLabel||(A==null?void 0:A.runtimeWorkspaceLabel)||P.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:P.runtimeKey}),P.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",P.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((O=P.writeOwner)==null?void 0:O.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:ky(P.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(uc,{size:11})," ",K]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Ji(P.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",D]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[T==="recovery"&&(P.lifecycle==="interrupted"||P.lifecycle==="failed"||P.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{y("session_host_resume_session",P)},children:F?`${_}ing…`:_}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{y("session_host_restart_session",P)},children:H?"Restarting…":"Restart"}),T==="live"&&(P.lifecycle==="running"||P.lifecycle==="starting"||P.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{y("session_host_stop_session",P)},children:L?"Stopping…":"Stop"})]})]})},P.sessionId)};return s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(Xt,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Ep()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[I>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{b()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${I})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${S.toneClass}`,children:S.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:f||l,children:[s.jsx(fr,{size:13}),f||l?"Refreshing…":"Refresh"]})]})]}),n&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(dr,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:v.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Ji(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:ma(u.hostStartedAt)})]})]}),w&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(dr,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:w.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[ma(w.timestamp),w.sessionId?` · ${w.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Xa,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:da("live")}),N.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:N.map(P=>$(P,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Xt,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:da("recovery")}),v.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:v.map(P=>$(P,"recovery"))})]}),M.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:da("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:M.map(P=>$(P,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),j.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:j.map(P=>{var F;const T=h.find(H=>H.sessionId===P.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(T==null?void 0:T.displayName)||((F=g.get(P.sessionId))==null?void 0:F.cliName)||P.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[P.action,P.lifecycle?` · ${P.lifecycle}`:"",P.detail?` · ${P.detail}`:"",P.error?` · ${P.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${P.success===!1?"text-red-300":"text-text-secondary"}`,children:ma(P.timestamp)})]},`${P.sessionId}:${P.timestamp}:${P.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Ty({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(o=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{a(null),n({cliType:t.cliType,workspaceId:o.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:o.label||o.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:o.path})]},o.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function fa({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function pa({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function My({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:c}){const l=n.slice(0,6),d=r.slice(0,4),m="0.9.75",u=Pl(e),f=Ss(e,m),x=ar(e,f),S=u==="preview"?"Update to preview":"Update daemon";return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[l.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(fa,{icon:s.jsx(zt,{size:13}),children:"Current Chats"}),s.jsx(pa,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(g=>{const p=$a(g);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(g),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:lt(g)}),p>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:gn(p)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:xs(g)})]},g.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(fa,{icon:s.jsx(hc,{size:13}),children:"Recent Launches"}),s.jsx(pa,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(g=>{const{metaText:p,updatedLabel:y}=Hl(g);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>o(g),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:g.label}),y&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:y})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:p})]},g.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(fa,{icon:s.jsx(dr,{size:13}),children:"Daemon Update"}),s.jsx(pa,{className:"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:x?"Daemon update required":"Version mismatch detected"}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[x?"This machine is on an incompatible daemon version. Update it before starting more sessions.":u==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",f&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",f,u?` (${u})`:""]})]}),s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[s.jsx(fr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:S})]})]})})]})]})}function Iy(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function Ay({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:o,onCustomPathChange:c,onOpenBrowseDialog:l}){return s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:t,onChange:d=>{const m=d.target.value;if(o(m),m==="__custom__"&&a){l();return}m!=="__custom__"&&c("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(e.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(d=>s.jsxs("option",{value:d.id,children:[d.id===e.defaultWorkspaceId?"⭐ ":"",vn(d.path,d.label)]},d.id)),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),t==="__custom__"&&(a?s.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:l,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:d=>c(d.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:t==="__custom__"?r?s.jsx("span",{className:"font-mono truncate block",title:r,children:r}):a?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":r?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:t===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const Ry={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 Wr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ha({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:c,sendDaemonCommand:l,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const f=Ws(),{handleLaunchIde:x,handleStopCli:S,handleRestartIde:g,handleStopIde:p,handleDetectIdes:y,launchingIde:b,launchingAgentType:h,addLog:C}=c,[N,v]=i.useState(null),M=i.useCallback(R=>{R&&f(Qt(R))},[f]),I=Ry[e],j=e==="ide",w=e==="acp",$=i.useMemo(()=>n.filter(R=>bs(R,e)),[e,n]),P=i.useMemo(()=>new Map($.map(R=>[R.type,R.displayName||R.type])),[$]),[T,F]=i.useState(""),[H,L]=i.useState(""),[k,A]=i.useState([]),[K,_]=i.useState(""),[D,O]=i.useState(""),[X,ge]=i.useState([]),[ce,ee]=i.useState(!1),[z,de]=i.useState(!1),[pe,Y]=i.useState(""),[ie,ye]=i.useState(!1),[re,me]=i.useState(()=>wt()),[ke,xe]=i.useState(null),[ve,te]=i.useState(m?"__custom__":d||t.defaultWorkspaceId||""),[he,le]=i.useState(m||""),[ue,oe]=i.useState([]),[Q,fe]=i.useState(!1),[J,Ae]=i.useState(""),[Te,$e]=i.useState([]),[Ue,B]=i.useState(!1),[Se,Me]=i.useState(""),De=i.useRef(null),[We,He]=i.useState(null),Je=i.useRef("__home__"),[st,mt]=i.useState("__home__"),[ht,xt]=i.useState(!1),Ce=i.useRef(0),ze=ue.filter(R=>!a.some(ae=>ae.type===R&&bt(ae.status)!=="stopped")),Qe=i.useRef({});i.useEffect(()=>{t.defaultWorkspaceId&&!ve&&te(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),i.useEffect(()=>{if(m){te("__custom__"),le(m);return}d&&(te(d),le(""))},[d,m]),i.useEffect(()=>{j||T&&($.some(R=>R.type===T)||(F(""),O("")))},[$,j,T]);const Ge=(()=>{if(ve==="__custom__")return he.trim();if(!ve)return"";const R=(t.workspaces||[]).find(ae=>ae.id===ve);return(R==null?void 0:R.path)||""})(),rt=i.useCallback(R=>{const ae=Qe.current[R];ae&&(clearTimeout(ae),delete Qe.current[R]),oe(be=>be.includes(R)?be.filter(Ke=>Ke!==R):be)},[]),W=i.useRef(new Set),U=i.useCallback(async R=>{if(l){B(!0),Me("");try{const ae=await Cn(l,r,R);Ae(ae.path),le(ae.path),$e(ae.directories)}catch(ae){Me(ae instanceof Error?ae.message:"Could not load folder")}finally{B(!1)}}},[r,l]),G=i.useCallback(()=>{if(!l)return;te("__custom__"),fe(!0);const R=a.map(be=>be.workspace),ae=Nn(t.platform,Sn(he.trim(),Ge,m,R,t.defaultWorkspacePath,(t.workspaces||[]).map(be=>be.path)));U(ae)},[he,m,U,t.defaultWorkspacePath,t.platform,t.workspaces,a,Ge,l]),se=i.useCallback(R=>{const ae=String(R.workspace||"").trim();if(!ae)return;const be=(t.workspaces||[]).find(Ke=>Wr(Ke.path)===Wr(ae));if(be){te(be.id),le("");return}te("__custom__"),le(ae)},[t.workspaces]),E=i.useCallback(R=>{const ae=String(R.workspace||"").trim();if(!ae)return{workspaceId:null,workspacePath:"",useHome:!0};const be=(t.workspaces||[]).find(Ke=>Wr(Ke.path)===Wr(ae));return be?{workspaceId:be.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ae,useHome:!1}},[t.workspaces]),q=i.useCallback(async R=>{if(!l||!R||e!=="cli"){ge([]),ee(!1),de(!1),Y("");return}const ae=Ce.current+1;Ce.current=ae,ee(!0),Y("");try{const be=await l(r,"list_saved_sessions",{providerType:R,kind:"cli",limit:30});if(Ce.current!==ae)return;const Ke=(be==null?void 0:be.result)??be;ge(Array.isArray(Ke==null?void 0:Ke.sessions)?Ke.sessions:[])}catch(be){if(Ce.current!==ae)return;ge([]),Y(be instanceof Error?be.message:"Could not load saved sessions")}finally{Ce.current===ae&&(ee(!1),de(!0))}},[e,r,l]),Z=i.useMemo(()=>{if(e!=="cli"||!T)return null;const R=P.get(T)||T;return{routeId:r,daemonId:r,providerSessionId:D||void 0,transport:"pty",mode:"chat",agentName:R,agentType:T,status:"idle",title:R,messages:[],ideType:T,workspaceName:Ge,workspacePath:Ge,displayPrimary:R,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${T}`}},[e,r,P,Ge,D,T]),ne=i.useCallback(R=>{if(e==="ide"||!R){A([]);return}A(Ka(r,R))},[e,r]),je=i.useCallback((R,ae)=>{e==="ide"||!R||(Vb(r,R,ae),A(Ka(r,R)))},[e,r]);i.useEffect(()=>{Ce.current+=1,O(""),ne(T),de(!1),ge([]),Y(""),ee(!1)},[e,ne,q,T]);const Le=i.useMemo(()=>X.find(R=>R.providerSessionId===D)||null,[X,D]);i.useEffect(()=>{if(!D)return;const R=X.find(ae=>ae.providerSessionId===D);R!=null&&R.canResume||O("")},[X,D]);const _e=i.useCallback((R,ae)=>{De.current=ae,Je.current=R.selectedWorkspaceKey||"__home__",mt(R.selectedWorkspaceKey||"__home__"),He(R)},[]),Ne=i.useCallback(()=>{De.current&&(xt(!0),De.current().finally(()=>{De.current=null,xt(!1),He(null)}))},[]),Ee=i.useCallback(R=>{if(!R)return;oe(be=>be.includes(R)?be:[...be,R]);const ae=Qe.current[R];ae&&clearTimeout(ae),Qe.current[R]=setTimeout(()=>{oe(be=>be.includes(R)?be.filter(Ke=>Ke!==R):be),delete Qe.current[R]},2e4)},[]);i.useEffect(()=>{for(const ae of a)bt(ae.status)!=="stopped"&&(ue.includes(ae.type)&&!W.current.has(ae.type)&&(W.current.add(ae.type),C("info",`${P.get(ae.type)||ae.type} launched`,!0)),rt(ae.type));const R=new Set(a.filter(ae=>bt(ae.status)!=="stopped").map(ae=>ae.type));W.current.forEach(ae=>{!ue.includes(ae)&&!R.has(ae)&&W.current.delete(ae)})},[C,rt,a,ue,P]),i.useEffect(()=>()=>{Object.values(Qe.current).forEach(clearTimeout),Qe.current={}},[]);const[Be,Re]=i.useState({}),[qe,et]=i.useState(null);i.useEffect(()=>{if(!j||!r||!l)return;(async()=>{try{const ae=await l(r,"get_ide_extensions",{}),be=(ae==null?void 0:ae.result)||ae;be!=null&&be.success&&(be!=null&&be.ideExtensions)&&Re(be.ideExtensions)}catch{}})()},[j,r,l]);const ct=R=>j?it(R.type):e==="cli"?R.cliName:R.acpName,ft=j?t.detectedIdes||[]:[],dt=i.useCallback(async R=>{const ae=(R==null?void 0:R.type)||T,be=(R==null?void 0:R.workspacePath)??Ge;if(j){await x(ae,be?{workspace:be}:void 0)&&Ee(ae);return}const Ke=await c.runLaunchCliCore({cliType:ae,dir:R!=null&&R.workspaceId?void 0:be||void 0,workspaceId:(R==null?void 0:R.workspaceId)||void 0,useHome:(R==null?void 0:R.useHome)||!(R!=null&&R.workspaceId)&&!be,argsStr:(R==null?void 0:R.argsStr)??(H||void 0),model:(R==null?void 0:R.model)??(w&&K||void 0),resumeSessionId:(R==null?void 0:R.resumeSessionId)||!w&&e==="cli"&&ae===T&&D||void 0});if(Ke.success||Ke.pending){const Pe=(R==null?void 0:R.argsStr)??H;!j&&(Pe!=null&&Pe.trim())&&(rd(r,ae,Pe),ne(ae)),Ee(ae),Ke.success&&Ke.sessionId&&M(Ke.sessionId)}},[c,x,w,j,H,K,ne,Ee,r,M,Ge,D,T]),yt=nl(j?"ide":w?"acp":"cli",!j&&!w&&!!D),Ve=al(j?"ide":w?"acp":"cli",!j&&!w&&!!D),we=()=>{var Pe;const R=j?it(T):P.get(T)||T,ae=!j&&!w&&!!D,{options:be,selectedKey:Ke}=ms({machine:t,currentWorkspaceId:ve&&ve!=="__custom__"?ve:null,currentWorkspacePath:Ge});_e({title:ae?po(R):is("start-fresh",R),description:ae?ho():cs("start-fresh"),confirmLabel:yt,busyLabel:Ve,workspaceOptions:be,selectedWorkspaceKey:Ke,details:[{label:"Mode",value:I.label},{label:"Provider",value:R},...!j&&e==="cli"&&D?[{label:"Resume",value:((Pe=X.find(Oe=>Oe.providerSessionId===D))==null?void 0:Pe.title)||D}]:[],...!j&&H.trim()?[{label:"Arguments",value:H.trim()}]:[],...w&&K.trim()?[{label:"Model",value:K.trim()}]:[]]},async()=>{const Oe=be.find(ot=>ot.key===Je.current);Oe!=null&&Oe.workspaceId?(te(Oe.workspaceId),le("")):Oe!=null&&Oe.workspacePath?(te("__custom__"),le(Oe.workspacePath)):(te(""),le("")),await dt({workspaceId:(Oe==null?void 0:Oe.workspaceId)??null,workspacePath:(Oe==null?void 0:Oe.workspacePath)??"",useHome:!(Oe!=null&&Oe.workspaceId)&&!(Oe!=null&&Oe.workspacePath)})})},V=R=>{j?p(R):S(R.type,R.workspace,R.id)},Ie=i.useCallback(async(R,ae,be=!1)=>{if(R.mode===ae){be&&R.sessionId&&M(R.sessionId);return}if(!l||!R.sessionId){be&&R.sessionId&&M(R.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:R.sessionId,cliType:R.type,mode:ae}),be&&M(R.sessionId)}catch(Ke){const Pe=Sl(Ke);kl(Ke)?console.warn(Pe?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Ke instanceof Error?Ke.message:String(Ke)):console.error("Failed to switch CLI view mode:",Ke)}},[r,M,l]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${I.accent} relative overflow-hidden`,children:[s.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",I.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:j?ft.length>0?ft.map(R=>{const ae=a.find(ot=>(ot.type||"").toLowerCase()===(R.type||"").toLowerCase()&&bt(ot.status)!=="stopped"),be=R.running||!!ae,Ke=!!ae&&ae.cdpConnected,Pe=ue.includes(R.type||R.id||""),Oe=T===(R.type||"");return s.jsxs("button",{onClick:()=>{if(Ke&&ae){const ot=ae.sessionId;ot?f(Qt(ot),{state:{openRemoteForTabKey:ot}}):f("/dashboard",{state:{openRemoteForTabKey:ae.id}});return}Pe||F(ot=>ot===(R.type||"")?"":R.type||"")},disabled:!!b||Pe,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Ke?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Oe?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:b&&b!==R.type?.4:1},children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:o(R.type)}),be&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Ke?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:R.name||it(R.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Ke?"text-green-400":Pe?"text-orange-400":Oe?"text-accent-primary":"text-text-muted"}`,children:Ke?"Open Session":Pe?"Starting...":Oe?"Configure":"Select"})]})]},R.type)}):s.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",s.jsxs("button",{onClick:y,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[s.jsx(vu,{size:14})," Scan System"]})]}):$.length>0?$.map(R=>{const ae=T===R.type,be=ue.includes(R.type),Pe=!!a.find(Oe=>Oe.type===R.type&&bt(Oe.status)!=="stopped");return s.jsxs("button",{onClick:()=>F(Oe=>Oe===R.type?"":R.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ae?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:R.icon}),Pe&&s.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:R.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${be?"text-orange-400":ae?"text-accent-primary":"text-text-muted"}`,children:be?"Starting...":ae?"Configure":"Select"})]})]},R.type)}):s.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),T&&(j?ft.find(R=>R.type===T):$.find(R=>R.type===T))&&s.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:j?it(T):P.get(T)||T})]}),s.jsx(Ay,{machine:t,selectedWorkspace:ve,resolvedWorkspacePath:Ge,customPath:he,canBrowse:!!l,onWorkspaceChange:te,onCustomPathChange:le,onOpenBrowseDialog:G}),!j&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&s.jsx(ad,{busy:!!h||!!b||ue.includes(T),savedSessionsLoading:ce,savedSessionsError:pe,savedSessionsLoaded:z,savedSessionsCount:X.length,selectedSession:Le,onRefresh:()=>void q(T),onOpenHistory:()=>{T&&(ye(!0),nd({hasLoadedInitialResults:z,isLoading:ce})&&q(T))},onClearSelection:()=>O("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[w&&s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),s.jsx("input",{type:"text",placeholder:"Leave empty for default",value:K,onChange:R=>_(R.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),s.jsx("input",{type:"text",placeholder:"Optional flags...",value:H,onChange:R=>L(R.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"}),k.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:k.map(R=>s.jsxs("div",{className:"inline-flex max-w-full items-stretch overflow-hidden rounded-md border border-[#ffffff1a] bg-bg-tertiary text-xs text-text-secondary transition-colors hover:border-accent-primary/40 hover:text-text-primary",title:R,children:[s.jsx("button",{type:"button",className:"min-w-0 max-w-[220px] truncate px-2.5 py-1.5 text-left",onClick:()=>L(R),children:R}),s.jsx("button",{type:"button",className:"flex items-center justify-center border-l border-[#ffffff1a] px-1.5 text-text-muted transition-colors hover:bg-status-error/10 hover:text-status-error focus:outline-none focus:ring-1 focus:ring-status-error/50",onClick:()=>je(T,R),"aria-label":`Remove startup arguments: ${R}`,title:"Remove startup arguments",children:s.jsx(vt,{size:12})})]},R))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:we,disabled:!!h||!!b||ue.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:h===T||b===T?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+ue.filter(R=>!a.some(ae=>ae.type===R&&bt(ae.status)!=="stopped")).length,")"]}),a.length===0&&ze.length===0?s.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",I.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[ze.map(R=>s.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:o(R)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:j?it(R):P.get(R)||R}),s.jsx("div",{className:"text-[11px] text-text-muted",children:h===R?"Launching process...":"Waiting for process and session to register..."})]})]}),s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${R}`)),a.map(R=>{const ae=j?R:null,be=!j&&!w?R:null,Ke=bt(R.status);return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:o(R.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[ct(R),(ae==null?void 0:ae.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",ae.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex min-w-0 flex-wrap items-center gap-2",children:[s.jsx("span",{className:"truncate",children:R.workspace||"—"}),u&&R.git&&R.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:Pe=>{Pe.stopPropagation(),u(R.daemonId??r,R.workspace)},children:s.jsx(Ds,{git:R.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Ds,{git:R.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(be==null?void 0:be.mode)&&s.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)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[be.runtimeKey&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),s.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",be.runtimeKey]}),s.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Pe;(Pe=navigator.clipboard)==null||Pe.writeText(`adhdev attach ${be.runtimeKey}`),v(be.runtimeKey||null),window.setTimeout(()=>{v(Oe=>Oe===be.runtimeKey?null:Oe)},1200)},children:N===be.runtimeKey?"Copied":"Copy"})]}),be.runtimeWriteOwner&&s.jsx("span",{style:{color:be.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:be.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Iy(be.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Ke==="stopped"?"bg-red-500/[0.08] text-red-500":Ke==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Ke}),j&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Pe=R.sessionId;if(Pe){f(Qt(Pe),{state:{openRemoteForTabKey:Pe}});return}f("/dashboard",{state:{openRemoteForTabKey:R.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:s.jsx(Mt,{size:13})}),s.jsx("button",{onClick:()=>{const Pe=R.workspace||"",{options:Oe,selectedKey:ot}=ms({machine:t,currentWorkspacePath:Pe});_e({title:is("restart-ide",it(R.type)),description:cs("restart-ide"),confirmLabel:Es("restart-ide"),busyLabel:$s("restart-ide"),workspaceOptions:Oe,selectedWorkspaceKey:ot,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:it(R.type)}]},async()=>{const Nt=Oe.find(Gt=>Gt.key===Je.current),pt=(Nt==null?void 0:Nt.workspacePath)??"";if(pt&&pt!==Pe){await dt({type:R.type,workspacePath:pt});return}await g(R)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:s.jsx(fr,{size:14})})]}),w&&s.jsx("button",{onClick:()=>{const Pe=R.sessionId;Pe&&M(Pe)},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:!R.sessionId,children:s.jsx(zt,{size:14})}),be&&Ke!=="stopped"&&s.jsxs(s.Fragment,{children:[be.mode&&s.jsx(uo,{mode:be.mode,onChange:Pe=>void Ie(be,Pe,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Pe=R.sessionId;Pe&&M(Pe)},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:!R.sessionId,children:be.mode==="chat"?s.jsx(zt,{size:14}):s.jsx(Mt,{size:13})})]}),Ke==="stopped"?s.jsx("button",{onClick:()=>{const Pe=R.workspace||"",Oe=j?it(R.type):ct(R),{options:ot,selectedKey:Nt}=ms({machine:t,currentWorkspacePath:Pe});_e({title:is("restart-stopped",Oe),description:cs("restart-stopped"),confirmLabel:Es("restart-stopped"),busyLabel:$s("restart-stopped"),workspaceOptions:ot,selectedWorkspaceKey:Nt,details:[{label:"Mode",value:I.label},{label:"Provider",value:Oe}]},async()=>{const pt=ot.find(Gt=>Gt.key===Je.current);await dt({type:R.type,workspaceId:(pt==null?void 0:pt.workspaceId)??null,workspacePath:(pt==null?void 0:pt.workspacePath)??"",useHome:!(pt!=null&&pt.workspaceId)&&!(pt!=null&&pt.workspacePath)})})},disabled:ue.includes(R.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:ue.includes(R.type)?"⏳":s.jsx(Ja,{size:14})}):s.jsx("button",{onClick:()=>V(R),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:s.jsx(vt,{size:14})})]})]}),ae&&ae.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ae.aiAgents.map(Pe=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${rn(Pe.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Pe.name," · ",bt(Pe.status)]},Pe.id))}),ae&&(Be[ae.type]||[]).length>0&&l&&s.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[s.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:(Be[ae.type]||[]).map(Pe=>s.jsxs("button",{disabled:qe===`${ae.type}.${Pe.type}`,onClick:async()=>{const Oe=`${ae.type}.${Pe.type}`;et(Oe);try{await l(r,"set_ide_extension",{ideType:ae.type,extensionType:Pe.type,enabled:!Pe.enabled}),Re(ot=>({...ot,[ae.type]:(ot[ae.type]||[]).map(Nt=>Nt.type===Pe.type?{...Nt,enabled:!Nt.enabled}:Nt)}))}catch(ot){console.error("Extension toggle failed:",ot)}finally{et(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${Pe.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Pe.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Pe.name,s.jsx("span",{className:"text-[9px] font-normal",children:Pe.enabled?"ON":"OFF"})]},Pe.type))})]})]},R.id)})]}),Q&&l&&s.jsx(Mn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:J,directories:Te,busy:Ue,error:Se,confirmLabel:"Use this folder",onClose:()=>fe(!1),onNavigate:R=>{U(R)},onConfirm:R=>{le(R),te("__custom__"),fe(!1)}}),We&&s.jsx(Co,{title:We.title,description:We.description,details:We.details,workspaceOptions:We.workspaceOptions,selectedWorkspaceKey:st,onWorkspaceChange:R=>{Je.current=R,mt(R)},confirmLabel:We.confirmLabel,busyLabel:We.busyLabel,busy:ht,onConfirm:Ne,onCancel:()=>{De.current=null,He(null)}}),ie&&Z&&s.jsx(xo,{activeConv:Z,ides:[],isCreatingChat:!1,isRefreshingHistory:ce,savedSessions:X,isSavedSessionsLoading:ce,isResumingSavedSessionId:ke,savedHistoryFilters:re,missingWorkspaceResumePath:Ge||null,onSavedHistoryFiltersChange:me,onClose:()=>ye(!1),onNewChat:()=>{O(""),ye(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{q(T)},onResumeSavedSession:R=>{if(!R.canResume||ke)return;const ae=E(R);O(R.providerSessionId),se(R),xe(R.providerSessionId),ye(!1),dt({type:R.providerType,workspaceId:ae.workspaceId,workspacePath:ae.workspacePath,useHome:ae.useHome,resumeSessionId:R.providerSessionId}).finally(()=>{xe(be=>be===R.providerSessionId?null:be)})}})]})}const Qi=[{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 Ly({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:c,getIcon:l,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:f,onOpenGitDialog:x}){var y;const[S,g]=i.useState(d);i.useEffect(()=>{g(d)},[d]);const p=i.useMemo(()=>({ide:n.length,cli:a.length,acp:o.length}),[n.length,a.length,o.length]);return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[s.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:Qi.map(b=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${S===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>g(b.id),children:[s.jsx("span",{children:b.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${S===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:p[b.id]})]},b.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(y=Qi.find(b=>b.id===S))==null?void 0:y.helper})]}),S==="ide"&&s.jsx(ha,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),S==="cli"&&s.jsx(ha,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),S==="acp"&&s.jsx(ha,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:o,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x})]})}function Py({onNicknameSynced:e}={}){var le,ue,oe,Q,fe,J,Ae,Te,$e,Ue;const{id:t}=Hd(),r=Ws(),n=za(),{sendCommand:a}=gt(),o=xr(),c=yl(),l=Xc(),d=l.ides||[],m=l.initialLoaded??!0,u=d.find(B=>B.id===t&&B.type==="adhdev-daemon"),f=d.some(B=>B.type==="adhdev-daemon"),x=t?(le=l.connectionRetryStatuses)==null?void 0:le[t]:void 0,S=!!(x!=null&&x.blocked),[g,p]=i.useState("workspace"),[y,b]=i.useState(null),h=i.useCallback((B,Se)=>{b({daemonId:B,workspace:Se})},[]),[C,N]=i.useState("ide"),v=i.useRef(null),[M,I]=i.useState(null),j=i.useRef("__home__"),[w,$]=i.useState("__home__"),[P,T]=i.useState(!1),F=i.useRef(null);i.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||o(t,{minFreshMs:3e4}).catch(()=>{})},[o,u,t]),i.useEffect(()=>{if(!t||!u||g!=="overview")return;const 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")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[g,c,u,t]),_h(t&&g==="overview"?[t]:[],{enabled:g==="overview",intervalMs:Tf});const H=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},L=Mg({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:F});i.useEffect(()=>nt.onToast(Se=>{l.setToasts(De=>{if(De.some(Je=>Je.message===Se.message&&Se.timestamp-Je.timestamp<3e3))return De;const He={id:Se.id,message:Se.message,type:Se.type,timestamp:Se.timestamp,targetKey:Se.targetKey,actions:Se.actions};return[...De.slice(-4),He]});const Me=Se.duration||5e3;setTimeout(()=>l.setToasts(De=>De.filter(We=>We.id!==Se.id)),Me)}),[l]);const k=(u==null?void 0:u.availableProviders)||[],A={};for(const B of k)A[B.type]=B.icon;const K=B=>A[B]||"",_=u?{id:u.id,hostname:Nc(u,{fallbackId:u.id}),platform:((ue=u.machine)==null?void 0:ue.platform)||"unknown",arch:((oe=u.machine)==null?void 0:oe.arch)||"",cpus:((Q=u.machine)==null?void 0:Q.cpus)||0,totalMem:((fe=u.machine)==null?void 0:fe.totalMem)||0,freeMem:(J=u.machine)==null?void 0:J.freeMem,availableMem:(Ae=u.machine)==null?void 0:Ae.availableMem,loadavg:(Te=u.machine)==null?void 0:Te.loadavg,uptime:($e=u.machine)==null?void 0:$e.uptime,release:((Ue=u.machine)==null?void 0:Ue.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,D=d.filter(B=>B.daemonId===t&&B.type!=="adhdev-daemon").filter(B=>!ur(B)&&!Ts(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:Sm(B.aiAgents||(B.agents||[]).map(Se=>({id:Se.name,name:Se.name,status:Se.status,version:Se.version}))),activeChat:B.activeChat||null,chats:B.chats||[],childSessions:B.childSessions||[],cdpConnected:B.cdpConnected||!1,daemonId:t})),O=d.filter(B=>B.daemonId===t&&ur(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:t})),X=d.filter(B=>B.daemonId===t&&Ts(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:t})),ge=u?Tt(u,{fallbackId:t}):"",ce="workspace",ee=n.state,z=ee==null?void 0:ee.initialMachineTab,de=ee==null?void 0:ee.initialWorkspaceCategory,pe=ee==null?void 0:ee.initialWorkspaceId,Y=ee==null?void 0:ee.initialWorkspacePath,ie=z==="ides"||z==="clis"||z==="acps"?"workspace":z||ce,ye=z==="ides"?"ide":z==="clis"?"cli":z==="acps"?"acp":de,re=[...D.map(B=>{var Se,Me,De,We,He;return{id:`ide:${B.type}:${B.workspace||""}`,label:((Se=B.activeChat)==null?void 0:Se.title)||B.type,kind:"ide",providerType:B.type,subtitle:B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:((He=(We=(De=(Me=B.activeChat)==null?void 0:Me.messages)==null?void 0:De.at)==null?void 0:We.call(De,-1))==null?void 0:He.timestamp)||0}}),...O.map(B=>{var Se,Me,De,We,He;return{id:`cli:${B.type}:${B.workspace||""}`,label:((Se=B.activeChat)==null?void 0:Se.title)||B.cliName,kind:"cli",providerType:B.type,providerSessionId:B.providerSessionId,subtitle:B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:((He=(We=(De=(Me=B.activeChat)==null?void 0:Me.messages)==null?void 0:De.at)==null?void 0:We.call(De,-1))==null?void 0:He.timestamp)||0}}),...X.map(B=>{var Se,Me,De,We,He;return{id:`acp:${B.type}:${B.workspace||""}`,label:((Se=B.activeChat)==null?void 0:Se.title)||B.acpName,kind:"acp",providerType:B.type,providerSessionId:B.providerSessionId,subtitle:hs(B.summaryMetadata)||B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:((He=(We=(De=(Me=B.activeChat)==null?void 0:Me.messages)==null?void 0:De.at)==null?void 0:We.call(De,-1))==null?void 0:He.timestamp)||0}})].sort((B,Se)=>(Se.lastLaunchedAt||0)-(B.lastLaunchedAt||0)),me=((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:hs(B.summaryMetadata)||B.workspace||void 0,workspace:B.workspace,summaryMetadata:B.summaryMetadata,lastLaunchedAt:B.lastLaunchedAt})):re,ke=i.useMemo(()=>{var Se;const B=((Se=l.connectionStates)==null?void 0:Se[t||""])||void 0;return d.filter(Me=>Me.daemonId===t&&Me.type!=="adhdev-daemon").flatMap(Me=>bo(Me,{connectionStates:t&&B?{[t]:B}:void 0,defaultConnectionState:B})).filter(Me=>!(Me.transport==="pty"&&Me.mode==="terminal")).sort((Me,De)=>$a(De)-$a(Me))},[d,l.connectionStates,t]),xe=i.useCallback(B=>{const Se=Tn(B);Se&&r(Qt(Se))},[r]),ve=i.useCallback(()=>{v.current&&(T(!0),v.current().finally(()=>{v.current=null,T(!1),I(null)}))},[]),te=i.useCallback(B=>{if(!_)return;const{options:Se,selectedKey:Me}=ms({machine:_,currentWorkspacePath:B.workspace}),De=async()=>{N(B.kind),p("workspace")};v.current=async()=>{const We=Se.find(st=>st.key===j.current),He=(We==null?void 0:We.workspacePath)??null,Je=(We==null?void 0:We.workspaceId)??null;if(B.kind==="ide"&&B.providerType){await L.handleLaunchIde(B.providerType,He?{workspace:He}:void 0);return}if((B.kind==="cli"||B.kind==="acp")&&B.providerType){await L.runLaunchCliCore({cliType:B.providerType,dir:Je?void 0:He||"",workspaceId:Je||void 0,model:B.kind==="acp"&&Tc(B.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:B.providerSessionId});return}await De()},j.current=Me,$(Me),I({title:B.kind==="ide"?is("restart-ide",B.label):B.providerSessionId?po(B.label):is("start-fresh",B.label),description:B.kind==="ide"?cs("restart-ide"):B.providerSessionId?ho():cs("start-fresh"),confirmLabel:B.kind==="ide"?Es("restart-ide"):B.providerSessionId?ln(!0):Es("start-fresh"),busyLabel:B.kind==="ide"?$s("restart-ide"):B.providerSessionId?mo(!0):$s("start-fresh"),workspaceOptions:Se,details:[{label:"Mode",value:B.kind.toUpperCase()},...B.providerType?[{label:"Provider",value:B.providerType}]:[]]})},[L,_]);if(i.useEffect(()=>{p(ie)},[ce,ie,t]),i.useEffect(()=>{ye&&N(ye)},[ye,t]),!_)return m?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:H,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const he=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Mt,{size:14})," Workspace"]}),count:D.length+O.length+X.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xn,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(wu,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(gu,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:H,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[L.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:L.nicknameInput,onChange:B=>L.setNicknameInput(B.target.value),onKeyDown:B=>{B.key==="Enter"&&L.handleSaveNickname(),B.key==="Escape"&&L.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:L.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>L.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{L.setEditingNickname(!0),L.setNicknameInput(_.machineNickname||"")},title:"Click to set nickname",children:ge}),S?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),l.retryConnection&&t&&s.jsx("button",{onClick:()=>l.retryConnection(t),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:"Reconnect"})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[_.platform," · ",_.arch]}),s.jsxs("span",{children:[_.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),_.p2p.available&&s.jsxs("span",{children:["P2P ",_.p2p.state==="connected"?"connected":_.p2p.state]}),_.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:_.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:he.map(B=>s.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 ${g===B.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[B.label,B.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${g===B.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:B.count})]},B.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[g==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(My,{machineEntry:u,providers:k,recentLaunches:me,currentConversations:ke,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",_l(u))}catch{}},onOpenRecent:te,onOpenConversation:xe}),s.jsx(Ly,{machine:_,machineId:t,providers:k,ideSessions:D,cliSessions:O,acpSessions:X,actions:L,getIcon:K,initialCategory:C,initialWorkspaceId:pe,initialWorkspacePath:Y,sendDaemonCommand:a,onOpenGitDialog:h})]}),g==="providers"&&s.jsx(Bg,{machineId:t,providers:k,sendDaemonCommand:a}),g==="overview"&&s.jsx(Ig,{machineId:t,machine:_,ideSessions:D,cliSessions:O,acpSessions:X,actions:L,sendDaemonCommand:a}),g==="session-host"&&s.jsx(Cy,{machineId:t,cliSessions:O,sendDaemonCommand:a}),g==="logs"&&s.jsx(yy,{machineId:t,sendDaemonCommand:a})]})})}),L.launchPick&&_&&s.jsx(Ty,{machine:_,launchPick:L.launchPick,actions:L}),M&&s.jsx(Co,{title:M.title,description:M.description,details:M.details,workspaceOptions:M.workspaceOptions,selectedWorkspaceKey:w,onWorkspaceChange:B=>{j.current=B,$(B)},confirmLabel:M.confirmLabel,busyLabel:M.busyLabel,busy:P,onConfirm:ve,onCancel:()=>{v.current=null,I(null)}}),y&&s.jsx(cd,{daemonId:y.daemonId,workspace:y.workspace,onClose:()=>b(null)}),s.jsx(ol,{toasts:l.toasts||[],onDismiss:B=>l.setToasts(Se=>Se.filter(Me=>Me.id!==B)),onClickToast:B=>{B.targetKey&&r(Qt(B.targetKey))}}),s.jsx("style",{children:`
|
|
90
|
+
@keyframes toast-in {
|
|
91
|
+
from { opacity: 0; transform: translateX(40px); }
|
|
92
|
+
to { opacity: 1; transform: translateX(0); }
|
|
93
|
+
}
|
|
94
|
+
`})]})}const Kr=[{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."}],_y={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function Xr(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function Dy(e){const t=Xr(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"launch not ready unless an explicit provider is selected"}}function xa(e){return{..._y,...(e==null?void 0:e.policy)||{}}}function Ey({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const o=a.id.toLowerCase(),c=a.name.toLowerCase();return o==="hermes-cli"||o.includes("hermes")||c.includes("hermes")}),n=El(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(jt,{title:"Hermes MCP Config",description:"Hermes does not auto-import repo-local .mcp.json. Add this YAML under mcp_servers in Hermes config, then start a fresh Hermes session.",children:s.jsx(od,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function $y(){var ee;const{sendCommand:e}=gt(),{ides:t}=Zt(),r=t.find(z=>z.daemonMode||z.type==="adhdev-daemon"),n=(r==null?void 0:r.id)||"",a=[];let o=[];if(r){const z=r.availableProviders||[];o=qp(z);for(const de of z)de.category==="cli"&&a.push({id:de.type||de.id,name:de.displayName||de.name||de.type,meshCoordinator:de.meshCoordinator})}const[c,l]=i.useState([]),[d,m]=i.useState(null),[u,f]=i.useState(!0),[x,S]=i.useState(null),[g,p]=i.useState(!1),[y,b]=i.useState(null),[h,C]=i.useState({}),[N,v]=i.useState(!1),[M,I]=i.useState(""),[j,w]=i.useState(""),[$,P]=i.useState(!1),[T,F]=i.useState(""),[H,L]=i.useState([]),k=c.find(z=>z.id===d)||null;i.useEffect(()=>{C(Object.fromEntries(((k==null?void 0:k.nodes)||[]).map(z=>[z.id,Xr(z)])))},[k]),i.useEffect(()=>{const z=Yp(o);$&&H.length===0&&z.length>0&&L(z)},[$,o,H.length]);const A=i.useCallback(async()=>{if(n){f(!0);try{const z=await e(n,"list_meshes");z!=null&&z.success?(l(z.meshes||[]),S(null)):S((z==null?void 0:z.error)||"Failed to load meshes")}catch(z){S((z==null?void 0:z.message)||"Failed to load meshes")}finally{f(!1)}}},[n,e]);i.useEffect(()=>{A()},[A]);async function K(){var z;if(!(!n||!M.trim()))try{const de=await e(n,"create_mesh",{name:M.trim(),repoIdentity:j.trim()||void 0});de!=null&&de.success?(v(!1),I(""),w(""),await A(),m(((z=de.mesh)==null?void 0:z.id)||null)):S((de==null?void 0:de.error)||"Create failed")}catch(de){S((de==null?void 0:de.message)||"Create failed")}}async function _(z){if(!(!n||!confirm("Delete this mesh?")))try{await e(n,"delete_mesh",{meshId:z}),m(null),await A()}catch(de){S((de==null?void 0:de.message)||"Delete failed")}}async function D(){if(!(!n||!d||!T.trim()))try{const z=await e(n,"add_mesh_node",{meshId:d,workspace:T.trim(),providerPriority:La(H,o)});z!=null&&z.success?(P(!1),F(""),L([]),await A()):S((z==null?void 0:z.error)||"Add node failed")}catch(z){S((z==null?void 0:z.message)||"Add node failed")}}async function O(z){var Y;if(!n||!d)return;const de=xa(k),pe=((Y=Kr.find(ie=>ie.value===de.sessionCleanupOnNodeRemove))==null?void 0:Y.label)||"Preserve history and runtimes";if(confirm(`Remove this node?
|
|
95
|
+
|
|
96
|
+
Node removal cleanup policy: ${pe}`))try{await e(n,"remove_mesh_node",{meshId:d,nodeId:z}),await A()}catch(ie){S((ie==null?void 0:ie.message)||"Remove node failed")}}async function X(z){if(!n||!d)return;const de={...xa(k),...z};try{p(!0),S(null);const pe=await e(n,"update_mesh",{meshId:d,policy:de});if((pe==null?void 0:pe.success)===!1){S(pe.error||"Policy update failed");return}await A()}catch(pe){S((pe==null?void 0:pe.message)||"Policy update failed")}finally{p(!1)}}async function ge(z){if(!n||!d)return;const de=La(h[z.id]||Xr(z),o),pe={...z.policy||{}};delete pe.provider_priority,de.length?pe.providerPriority=de:delete pe.providerPriority;try{b(z.id),S(null);const Y=await e(n,"update_mesh_node",{meshId:d,nodeId:z.id,policy:pe});if((Y==null?void 0:Y.success)===!1){S(Y.error||"Node policy update failed");return}await A()}catch(Y){S((Y==null?void 0:Y.message)||"Node policy update failed")}finally{b(null)}}if(!n)return s.jsx(nr,{icon:s.jsx(Sr,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})});if(!k)return s.jsxs(nr,{icon:s.jsx(Sr,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>v(!0),children:"+ Create Mesh"}),children:[x&&s.jsx(Cs,{variant:"error",className:"mb-4",children:x}),N&&s.jsx(jt,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(It,{label:"Name",children:s.jsx(Hn,{value:M,onChange:z=>I(z.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(It,{label:"Repo Identity (optional)",children:s.jsx(Hn,{value:j,onChange:z=>w(z.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:K,disabled:!M.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(!1),children:"Cancel"})]})]})}),u?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):c.length===0?s.jsx(dn,{icon:s.jsx(Sr,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:c.map(z=>s.jsxs("button",{className:"text-left w-full p-4 rounded-xl border border-border-subtle bg-bg-panel hover:border-accent-primary/40 transition-colors",onClick:()=>m(z.id),children:[s.jsx("div",{className:"font-semibold text-sm",children:z.name}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:z.repoIdentity||"No repo identity"}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[z.nodes.length," node(s)"]})]},z.id))})]});const ce=xa(k);return s.jsxs(nr,{icon:s.jsx(Sr,{}),title:k.name,subtitle:k.repoIdentity||"Repo Mesh",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(null),children:"← Back"}),s.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>_(k.id),children:"Delete"})]}),children:[x&&s.jsx(Cs,{variant:"error",className:"mb-4",children:x}),s.jsxs(jt,{title:"Policy",description:"Coordinator safety defaults and node-removal session cleanup behavior for this local mesh.",children:[s.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[s.jsx(It,{label:"Checkpoint before task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce.requirePreTaskCheckpoint?"yes":"no",onChange:z=>X({requirePreTaskCheckpoint:z.target.value==="yes"}),disabled:g,children:[s.jsx("option",{value:"no",children:"No"}),s.jsx("option",{value:"yes",children:"Yes"})]})}),s.jsx(It,{label:"Checkpoint after task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce.requirePostTaskCheckpoint?"yes":"no",onChange:z=>X({requirePostTaskCheckpoint:z.target.value==="yes"}),disabled:g,children:[s.jsx("option",{value:"yes",children:"Yes"}),s.jsx("option",{value:"no",children:"No"})]})}),s.jsx(It,{label:"Push approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce.requireApprovalForPush?"required":"not_required",onChange:z=>X({requireApprovalForPush:z.target.value==="required"}),disabled:g,children:[s.jsx("option",{value:"required",children:"Require approval before push"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(It,{label:"Destructive git approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce.requireApprovalForDestructiveGit?"required":"not_required",onChange:z=>X({requireApprovalForDestructiveGit:z.target.value==="required"}),disabled:g,children:[s.jsx("option",{value:"required",children:"Require approval"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(It,{label:"Dirty workspace behavior",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce.dirtyWorkspaceBehavior||"warn",onChange:z=>X({dirtyWorkspaceBehavior:z.target.value}),disabled:g,children:[s.jsx("option",{value:"warn",children:"Warn and continue"}),s.jsx("option",{value:"block",children:"Block task"}),s.jsx("option",{value:"checkpoint_then_continue",children:"Checkpoint then continue"})]})}),s.jsx(It,{label:"Max parallel tasks",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:String(ce.maxParallelTasks??2),onChange:z=>X({maxParallelTasks:Number(z.target.value)}),disabled:g,children:[1,2,3,4,5,6,7,8].map(z=>s.jsx("option",{value:z,children:z},z))})})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(It,{label:"Node removal session cleanup",hint:"Separate transcript cleanup from runtime/process cleanup. Preserve is safest when completed work may need review.",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce.sessionCleanupOnNodeRemove||"preserve",onChange:z=>X({sessionCleanupOnNodeRemove:z.target.value}),disabled:g,children:Kr.map(z=>s.jsx("option",{value:z.value,children:z.label},z.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((ee=Kr.find(z=>z.value===ce.sessionCleanupOnNodeRemove))==null?void 0:ee.description)||Kr[0].description})]}),g&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),s.jsxs(jt,{title:"Nodes",description:"Workspaces participating in this mesh.",children:[s.jsx("div",{className:"flex justify-end mb-3",children:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>P(!0),children:"+ Add Node"})}),$&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:"Add Node"}),s.jsx("button",{onClick:()=>P(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(vt,{size:16})})]}),s.jsx(It,{label:"Workspace Path",children:s.jsx(Hn,{value:T,onChange:z=>F(z.target.value),placeholder:"/Users/dev/projects/myapp",autoFocus:!0})}),s.jsx(It,{label:"Provider Priority",hint:"Order used when launching without an explicit provider. Empty means fail closed unless a provider is selected explicitly.",children:s.jsx(xi,{value:H,availableProviders:o,onChange:L})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:D,disabled:!T.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>P(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),k.nodes.length===0?s.jsx(dn,{icon:s.jsx(ps,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:k.nodes.map(z=>{const de=Xr(z),pe=Dy(z);return s.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium",children:z.workspace.split("/").pop()}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:z.workspace}),s.jsx("div",{className:"mt-3 max-w-2xl",children:s.jsxs(It,{label:"Provider priority",hint:"Used when launches omit an explicit provider. Empty keeps fail-closed behavior until a provider is selected manually.",children:[s.jsx(xi,{value:h[z.id]??de,availableProviders:o,onChange:Y=>C(ie=>({...ie,[z.id]:Y})),disabled:y===z.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>void ge(z),disabled:y===z.id,children:y===z.id?"Saving...":"Save policy"})}),s.jsxs("div",{className:"mt-2 text-[12px]",children:[s.jsx("span",{className:"text-text-muted",children:"Effective provider priority: "}),s.jsx("span",{className:pe.configured?"text-text-primary font-mono":"text-amber-400",children:pe.label}),pe.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",pe.launchBlockedMessage,")"]})]})]})})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:()=>O(z.id),children:s.jsx(vt,{size:14})})]},z.id)})})]}),s.jsx(Ey,{meshId:k.id,availableCliAgents:a})]})}function Po(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function By(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=Po();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function $t(e,t){return await fetch(By(e),{credentials:"same-origin",...t})}function ud(){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 Wy{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(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r)}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}sendData(t,r){return!1}sendPtyInput(t,r,n){return!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,o,c){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:o,rows:c})}emitSessionOutput(t,r,n){!t||typeof r!="string"||!r||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(t,r){const n=this.runtimeListeners.get(t)||new Set;return n.add(r),this.runtimeListeners.set(t,n),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,r,n){if(!r)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`,window.location.origin);typeof(n==null?void 0:n.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(n.sinceSeq));const o=await $t(`${a.pathname}${a.search}`);if(!o.ok){let l=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(l=d.error)}catch{}return{success:!1,error:l}}const c=await o.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof c.seq=="number"?c.seq:0,text:typeof c.text=="string"?c.text:"",truncated:!!c.truncated,cols:typeof c.cols=="number"?c.cols:void 0,rows:typeof c.rows=="number"?c.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Ot=new Wy;function Ky(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Po();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Or=Ky(),Zi=3e3,Oy=3e4;let _t=null,Fy=0;const hn=new Map;let ts=null,ir=null;function ec(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Js(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function Hy(e){return e==="connected"?"connected":e}async function Jr(e,t,r){const n=dl(e,r||{}),a=_t;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++Fy}_${Date.now()}`;return new Promise((c,l)=>{const d=setTimeout(()=>{hn.delete(o),l(new Error(`WS command timeout: ${t}`))},3e4);hn.set(o,{resolve:m=>{clearTimeout(d),c(m)},reject:m=>{clearTimeout(d),l(m)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Fa(e,t){const r=_t;if(!r||r.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(t)),!0}catch{return!1}}function Uy(e,t,r){const n=_t;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=dl(e,{sessionId:t,targetSessionId:t,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}class zy{constructor(t){Xe(this,"daemonId");Xe(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(_t==null?void 0:_t.readyState)===WebSocket.OPEN}get connectionState(){return(_t==null?void 0:_t.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Jr(this.daemonId,t,r)}async sendInput(t,r){return Jr(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,ts&&(clearInterval(ts),ts=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Jr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(o=>o.blob());Ot.emitScreenshot(this.daemonId,a)}}catch{}};r(),ts=setInterval(r,2e3)}stopScreenshots(t){ts&&(clearInterval(ts),ts=null)}}let Rt=null;function Vy(e){return(!Rt||Rt.daemonId!==e)&&(Rt=new zy(e)),Rt}function Gy({children:e}){const t=i.useRef(lr()),r=lr();t.current=r;const{setUserName:n}=Zt(),a=i.useRef(n);a.current=n;const o=i.useRef(null),c=i.useRef(null),[,l]=i.useState("disconnected"),d=i.useCallback((p,y)=>{l(p),ir==null||ir(p,y)},[]),m=i.useRef(null),u=i.useRef(),f=i.useRef(Zi),x=i.useRef(!0),S=i.useRef(!1),g=i.useRef("initial_connect");return i.useEffect(()=>{x.current=!0,S.current=!1;function p(){var h,C;if(!x.current||((h=m.current)==null?void 0:h.readyState)===WebSocket.OPEN||((C=m.current)==null?void 0:C.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Or}...`),Js("connect_attempt",{url:Or,reason:g.current,delayMs:f.current});let b;try{b=new WebSocket(Or)}catch(N){console.error("[Standalone WS] Failed to create WebSocket:",N),y();return}m.current=b,b.onopen=()=>{if(!x.current){b.close();return}d("connected"),f.current=Zi,Js("open",{url:Or,reason:g.current}),Ut.resubscribeAll({sendData:Fa}),console.log("[Standalone WS] Connected")},_t=b,b.onmessage=N=>{var v,M;try{const I=JSON.parse(N.data);if((I.type==="command_result"||I.type==="error")&&I.requestId){const j=hn.get(I.requestId);j&&(hn.delete(I.requestId),I.type==="error"?j.reject(new Error(((v=I.data)==null?void 0:v.message)||"Command failed")):j.resolve(I.data));return}if(I.type==="session_output"){const j=I.sessionId||I.cliId||I.cliType;j&&Ot.emitSessionOutput(j,typeof I.data=="string"?I.data:"",typeof I.seq=="number"?I.seq:void 0);return}if(I.type==="runtime_snapshot"){Ot.emitRuntimeSnapshot(I.sessionId,typeof I.text=="string"?I.text:"",typeof I.seq=="number"?I.seq:0,!!I.truncated,typeof I.cols=="number"?I.cols:void 0,typeof I.rows=="number"?I.rows:void 0);return}if(I.type==="topic_update"){const j=I.update;j&&Ut.publish(j);return}if(I.type==="status"||I.type==="initial_state"){const j=I.data;if(!j)return;const{injectEntries:w,markLoaded:$,getIdes:P}=t.current,T=j.instanceId||"standalone",F=P().find(k=>k.id===T),H=Vy(T);Ot.register(T,H),Ot.setState(T,"connected"),d("connected",T),Ot.emitStatus(T,j);const L=cn(j,{daemonId:T,existingDaemon:F,existingEntries:P()});ec("ws_status",{type:I.type,daemonId:T,sessions:(j.sessions||[]).map(k=>({id:k.id,parentId:k.parentId,providerType:k.providerType,kind:k.kind,transport:k.transport,unread:k.unread,inboxBucket:k.inboxBucket,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,title:k.title})),recentLaunches:(j.recentLaunches||[]).map(k=>({id:k.id,providerType:k.providerType,kind:k.kind,workspace:k.workspace,lastLaunchedAt:k.lastLaunchedAt}))}),ec("entries",{daemonId:T,entries:L.filter(k=>k.type!=="adhdev-daemon").map(k=>({id:k.id,type:k.type,unread:k.unread,inboxBucket:k.inboxBucket,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,sessionId:k.sessionId}))}),L.length>0&&w(L,{authoritativeDaemonIds:[T]}),$(),c.current!==T&&((M=o.current)==null||M.call(o),c.current=T,o.current=Ut.subscribe({sendData:Fa},T,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${T}`,params:{includeSessions:!0}},k=>{if(k.topic!=="daemon.metadata")return;const A=t.current.getIdes(),K=A.find(D=>D.id===T),_=cn(k.status,{daemonId:T,existingDaemon:K,existingEntries:A,timestamp:k.timestamp});_.length>0&&t.current.injectEntries(_,{authoritativeDaemonIds:[T]}),k.userName&&a.current&&a.current(k.userName)}))}}catch(I){console.error("[Standalone WS] Parse error:",I)}},b.onclose=N=>{x.current&&(Rt==null||Rt.stopScreenshots(),Rt&&Ot.setState(Rt.daemonId,"disconnected"),d("disconnected"),m.current=null,g.current=`close:${N.code}${N.wasClean?":clean":":unclean"}`,Js("close",{code:N.code,reason:N.reason||"",wasClean:N.wasClean}),y())},b.onerror=N=>{S.current||!x.current||(g.current="error",Js("error",{message:N instanceof Event?"event":String(N),readyState:b.readyState}),console.warn("[Standalone WS] Error, will reconnect:",N))}}function y(){if(!x.current)return;clearTimeout(u.current);const b=f.current;console.log(`[Standalone WS] Reconnecting in ${b}ms...`),Js("schedule_reconnect",{reason:g.current,delayMs:b}),u.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,Oy),p()},b)}return p(),()=>{var b;x.current=!1,S.current=!0,(b=o.current)==null||b.call(o),o.current=null,c.current=null,clearTimeout(u.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,_t=null),Rt&&(Rt.stopScreenshots(),Ot.unregister(Rt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function qy({children:e}){const[t,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(ir=(c,l)=>{r(c),l&&a(l)},()=>{ir=null}),[]);const o=i.useMemo(()=>{const c=t==="connected",l=Hy(t),d={};return n&&(d[n]=l),d.standalone=l,{wsStatus:t,isConnected:c,connectionStates:d}},[t,n]);return s.jsx(iu,{connectionOverrides:o,children:s.jsx(Gy,{children:e})})}const md="adhdev_standalone_font_preferences",fs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Rn=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],mr=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],Yy=new Set(Rn.map(e=>e.id)),Xy=new Set(mr.map(e=>e.id));function Wt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Qr("chat",t.chat),code:Qr("code",t.code),terminal:Qr("terminal",t.terminal)}}function Qr(e,t){const r=fs[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",o=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?Yy:Xy).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Zr(e,t){var a;const r=Qr(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?Rn:mr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function Jy(e){const t=Wt(e),r=Zr("chat",t.chat),n=Zr("code",t.code),a=Zr("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function rs(e,t=document.documentElement){const r=Wt(e),n=Jy(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function Ha(e){const t=Wt(e);try{localStorage.setItem(md,JSON.stringify(t))}catch{}return t}function Qy(){try{const e=localStorage.getItem(md);if(e)return Wt(JSON.parse(e))}catch{}return fs}function Zy(){return rs(Qy())}function Qs(e,t){var n;const r=e==="chat"?Rn:mr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const ev=[{id:"dashboard",path:"/dashboard",icon:s.jsx(dc,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(Xt,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(Ls,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(xn,{}),label:"Settings"}];function tv({children:e}){const t=Ws(),r=za(),n=i.useMemo(()=>ev.map(o=>({...o,active:r.pathname.startsWith(o.path),onSelect:()=>t(o.path)})),[r.pathname,t]),a=i.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Docs"}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(mc,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(fc,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(oh,{brand:({collapsed:o})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!o&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:o})=>o?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.75"]}),footerActions:({collapsed:o,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:o?"Expand sidebar":"Collapse sidebar",children:[s.jsx("span",{className:"nav-icon text-base",children:o?"›":"‹"}),!o&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const sv=[{icon:s.jsx(Xt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(zt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(pc,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Mt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Ls,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(mc,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],rv=[{icon:s.jsx(ku,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(dc,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(bn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(bu,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(uc,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(yu,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],nv=[{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 s.jsxs(nr,{icon:s.jsx(fc,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.9.75"]}),children:[s.jsx(jt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),s.jsx(jt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:sv.map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(jt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:ul.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:fl.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:ml.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(jt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:rv.map(e=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(jt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),s.jsx("tbody",{children:nv.map((e,t)=>s.jsxs("tr",{className:t%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),s.jsx(dn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:"Cloud is optional, not required",description:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(Pu,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function ba(e,t,r){return{...e,[t]:r}}function ga({surface:e,title:t,description:r,value:n,options:a,onChange:o}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:c=>{const l=c.target.value;o(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),n.preset==="custom"&&s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:c=>o({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:Zr(e,n)})]})]})]})}function ov({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:c,onResetToSaved:l,onResetToDefaults:d}){const m=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&s.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&s.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(ga,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Rn,onChange:u=>o(ba(e,"chat",u))}),s.jsx(ga,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:mr,onChange:u=>o(ba(e,"code",u))}),s.jsx(ga,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:mr,onChange:u=>o(ba(e,"terminal",u))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",Qs("chat",e.chat.preset)," · Code: ",Qs("code",e.code.preset)," · Terminal: ",Qs("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Qs("chat",fs.chat.preset)," / ",Qs("code",fs.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:c,disabled:r||!m,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),s.jsx("button",{type:"button",onClick:l,disabled:r||!m,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),s.jsx("button",{type:"button",onClick:d,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function iv(){const{ides:e}=Zt(),t=e.find(Y=>Y.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=gt(),{userName:a}=Zt(),[o,c]=i.useState(a||""),[l,d]=i.useState(null),[m,u]=i.useState(null),[f,x]=i.useState(fs),[S,g]=i.useState(!1),[p,y]=i.useState(""),[b,h]=i.useState(""),[C,N]=i.useState("127.0.0.1"),[v,M]=i.useState(""),[I,j]=i.useState(""),[w,$]=i.useState(""),[P,T]=i.useState(""),[F,H]=i.useState(""),[L,k]=i.useState(!1),A=async()=>{const ie=await(await $t("/auth/session")).json();d(ie)},K=async()=>{const ie=await(await $t("/api/v1/standalone/preferences")).json();u(ie),N(ie.standaloneBindHost);const ye=Wt(ie.standaloneFontPreferences);x(ye),rs(ye),Ha(ye)};i.useEffect(()=>{a!==void 0&&c(a)},[a]),i.useEffect(()=>{Promise.all([A(),K()]).catch(Y=>{T(Y instanceof Error?Y.message:String(Y))})},[]),i.useEffect(()=>{rs(f)},[f]);const _=Y=>{const ie=Y.target.value.trim();t!=null&&t.id&&ie!==a&&n(t.id,"set_user_name",{userName:ie}).catch(console.error)},[D,O]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),X=Y=>{O(Y);try{localStorage.setItem("adhdev_sound",Y?"1":"0")}catch{}},ge=async()=>{y(""),h(""),g(!0);try{const Y=Wt(f),ie=await $t("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:Y})}),ye=await ie.json();if(!ie.ok)throw new Error((ye==null?void 0:ye.error)||"Failed to save standalone font preferences");const re=Wt(ye.standaloneFontPreferences);u(ye),x(re),rs(re),Ha(re),h("Standalone chat fonts saved for this self-hosted dashboard.")}catch(Y){y(Y instanceof Error?Y.message:String(Y))}finally{g(!1)}},ce=()=>{const Y=Wt(m==null?void 0:m.standaloneFontPreferences);y(""),h(""),x(Y),rs(Y)},ee=()=>{y(""),h(""),x(fs),rs(fs)},z=async()=>{T(""),H(""),k(!0);try{const Y=await $t("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),ie=await Y.json();if(!Y.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to save standalone network preference");u(ie),N(ie.standaloneBindHost),H(ie.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(Y){T(Y instanceof Error?Y.message:String(Y))}finally{k(!1)}},de=async()=>{if(T(""),H(""),I.trim().length<4){T("Password must be at least 4 characters.");return}if(I!==w){T("New password and confirmation do not match.");return}k(!0);try{const Y=await $t("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:I})}),ie=await Y.json();if(!Y.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to save password");d(ie),await K(),M(""),j(""),$(""),H(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),ud()}catch(Y){T(Y instanceof Error?Y.message:String(Y))}finally{k(!1)}},pe=async()=>{T(""),H(""),k(!0);try{const Y=await $t("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),ie=await Y.json();if(!Y.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to clear password");d(ie),await K(),M(""),j(""),$(""),H("Standalone password disabled.")}catch(Y){T(Y instanceof Error?Y.message:String(Y))}finally{k(!1)}};return s.jsxs(nr,{icon:s.jsx(xn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Cs,{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."}),(l==null?void 0:l.publicHostWarning)&&s.jsx(Cs,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),s.jsx(jt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:"Version"}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.75"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(jt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="127.0.0.1",onChange:()=>N("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="0.0.0.0",onChange:()=>N("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:()=>{z()},disabled:L,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:L?"Saving…":"Save default network mode"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(jt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.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."}),P&&s.jsx(Cs,{variant:"error",children:P}),F&&s.jsx(Cs,{variant:"success",children:F}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:v,onChange:Y=>M(Y.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:I,onChange:Y=>j(Y.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:w,onChange:Y=>$(Y.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{de()},disabled:L,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:L?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{pe()},disabled:L,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),s.jsx(jt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(Y=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${Y.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:Y.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:Y.type})]},Y.type))})}),s.jsx(jt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(hh,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(jt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(yh,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI."}),s.jsx(Th,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),s.jsx(ov,{value:f,savedValue:Wt(m==null?void 0:m.standaloneFontPreferences),saving:S,error:p,notice:b,onChange:x,onSave:()=>{ge()},onResetToSaved:ce,onResetToDefaults:ee})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),s.jsx(Ah,{})]})]})}),s.jsx(jt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(mh,{}),s.jsx(ss,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Lu,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:D,onChange:X})]})}),s.jsx(jt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(xu,{size:16,className:"text-text-secondary"})," Display Name"]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:o,onChange:Y=>c(Y.target.value),onBlur:_,onKeyDown:Y=>{Y.key==="Enter"&&Y.currentTarget.blur()}})]})})})]})}nh();Nh();Zy();const cv=cc({baseUrl:"",getToken:Po});function lv({children:e}){const[t,r]=i.useState(null),[n,a]=i.useState(!0),[o,c]=i.useState(""),[l,d]=i.useState(""),[m,u]=i.useState(!1),f=async()=>{a(!0),d("");try{const g=await(await $t("/auth/session")).json();r(g)}catch(S){d(S instanceof Error?S.message:String(S))}finally{a(!1)}};i.useEffect(()=>{f()},[]),i.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let S=!1;return(async()=>{try{const g=await $t("/api/v1/standalone/preferences");if(!g.ok)return;const p=await g.json();if(S)return;const y=Wt(p.standaloneFontPreferences);rs(y),Ha(y)}catch{}})(),()=>{S=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const x=async S=>{S.preventDefault(),u(!0),d("");try{const g=await $t("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),p=await g.json();if(!g.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),ud()}catch(g){d(g instanceof Error?g.message:String(g))}finally{u(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:x,children:[s.jsx("input",{type:"password",value:o,onChange:S=>c(S.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled:m||!o,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:m?"Signing in…":"Unlock dashboard"})]}):s.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),l&&s.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:l})]})}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function tc(){const{ides:e,initialLoaded:t}=Zt();if(!t)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?s.jsx(wa,{to:`/machines/${r.id}`,replace:!0}):s.jsx(wa,{to:"/dashboard",replace:!0})}function dv(){const e=i.useMemo(()=>({sendCommand:Jr,sendData:Fa,sendPtyInput:Uy}),[]);return s.jsx(Ud,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(du,{client:cv,children:s.jsx(lv,{children:s.jsx(qy,{children:s.jsx(mu,{value:e,children:s.jsx(tv,{children:s.jsxs(zd,{children:[s.jsx(qt,{path:"/dashboard",element:s.jsx(Tg,{})}),s.jsx(qt,{path:"/machine",element:s.jsx(tc,{})}),s.jsx(qt,{path:"/machines/:id",element:s.jsx(Py,{})}),s.jsx(qt,{path:"/machines",element:s.jsx(tc,{})}),s.jsx(qt,{path:"/about",element:s.jsx(av,{})}),s.jsx(qt,{path:"/settings",element:s.jsx(iv,{})}),s.jsx(qt,{path:"/mesh",element:s.jsx($y,{})}),s.jsx(qt,{path:"*",element:s.jsx(wa,{to:"/dashboard",replace:!0})})]})})})})})})})}pp({connectionManager:Ot});Vd(document.getElementById("root")).render(s.jsx(dv,{}));
|