@adhdev/daemon-standalone 0.9.76-rc.42 → 0.9.76-rc.44
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/dist/index.js +441 -454
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/index-o5f7l2vL.js +96 -0
- package/public/assets/index-w5h5sWwt.css +1 -0
- package/public/index.html +2 -2
- package/vendor/mcp-server/index.js +156 -177
- package/vendor/mcp-server/index.js.map +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 Ad=Object.defineProperty;var Rd=(e,t,r)=>t in e?Ad(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Xe=(e,t,r)=>Rd(e,typeof t!="symbol"?t+"":t,r);import{r as o,j as s,M as Wa,a as Ld,b as Pd,c as _d,R as Ct,d as lr,t as Dd,e as Ed,u as Os,D as $d,f as ba,g as ga,h as Fa,i as Bd,k as Od,B as Kd,l as Wd,m as qt,N as ya,n as Fd}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 i of a)if(i.type==="childList")for(const c of i.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).observe(document,{childList:!0,subtree:!0});function r(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(a){if(a.ep)return;a.ep=!0;const i=r(a);fetch(a.href,i)}})();function Hd(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(i=>!n.interactionId||i.interactionId===n.interactionId).filter(i=>!n.topic||i.topic===n.topic).filter(i=>!n.kind||i.kind===n.kind).slice(-a).map(i=>({...i,payload:i.payload?{...i.payload}:{}}))},clear(){r.splice(0,r.length)}}}const As=Hd();function Bo(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 Ud(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function zd(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Zi(e,t){if(!e)return t??null;if(!t)return e??null;const r=zd(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 er(e,t){const r=Ud(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:Zi(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 ec(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 i=e.find(c=>c.id===a.id);return i?er(a,i):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(t.map(i=>i.id));for(const i of e)a.has(i.id)||n.push(i)}return n}function Oo(e){return!!e&&typeof e=="object"&&"text"in e}function Ha(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(i=>typeof i=="string"?i:Oo(i)?String(i.text||""):"").join(r):Oo(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Rs(e){return Ha(e,{normalizeWhitespace:!0})}const tc=o.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}),sc=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Ko(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 rc(e,t,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=t.version??r.version??e.version,i=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),i&&(n.serverVersion=i),d&&(n.versionUpdateReason=d),a&&i&&a===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||c&&a&&i&&a!==i)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function Vd(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 Rn(e){if(!e||typeof e!="object")return"";const t=e,r=Vd(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 Gd(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=Rn(n);for(let i=0;i<a.length;i+=1)r^=a.charCodeAt(i),r=Math.imul(r,16777619)>>>0}return{count:e.length,hash:r.toString(16).padStart(8,"0"),first:Rn(e[0]),last:Rn(e[e.length-1])}}function va(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function wa(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(va(e)&&va(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)wa(e[l],t[l],r);return}const n=e,a=t,i=new Set([...Object.keys(n),...Object.keys(a)]);for(const c of i)c!=="messages"&&wa(n[c],a[c],r)}function sr(e,t){return Array.isArray(e)?e.map(r=>sr(r,t)):!e||typeof e!="object"?e:va(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Gd(a,t):sr(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,sr(n,t)]))}function qd(e,t){try{const r=new WeakSet;return wa(e,t,r),JSON.stringify(sr(e,r))===JSON.stringify(sr(t,r))}catch{return!1}}function ja(e,t,r){return qd(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function nc(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Yd(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Wo(e,t,r,n){var l;const a=(l=t.chats)!=null&&l.length?t.chats:e.chats,i=ec(e.childSessions,t.childSessions,{preserveMissing:n}),c=Zi(t.activeChat,e.activeChat);return rc(e,t,{...e,...t,chats:a,childSessions:i,activeChat:c,_lastUpdate:r})}function Xd(e,t,r){var a,i;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=ec(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((i=e.chats)!=null&&i.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"])Yd(n,t,c);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function Jd(e,t,r,n){const a=Xd(e,t,n),i=Object.keys(a).length>0?rc(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return ja(e,i,r)}function Qd(e){const t=new Set(e.map(i=>i.id)),r=new Set,n=new Set,a=new Set;for(const i of e){const c=nc(i);c&&r.add(c),c&&i.type!=="adhdev-daemon"&&n.add(c),c&&i.type==="adhdev-daemon"&&i._sessionListAuthoritative&&a.add(c)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function Zd(e,t,r,n,a,i){return!a.has(t)||!i.has(t)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function eu(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function tu(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 i=new Map;for(const x of t)i.set(x.id,x);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:m}=Qd(e);for(const x of e){const N=i.get(x.id);if(!N){i.set(x.id,{...x,_lastUpdate:n});continue}const y=Ko(x),p=Ko(N),g=nc(x),b=!a.has(g);if(y>p){const S=Wo(N,x,n,b);i.set(x.id,ja(N,S,n));continue}if(y<p){i.set(x.id,Jd(N,x,n,b));continue}const h=x.timestamp||n,C=N._lastUpdate||N.timestamp||0;if(h>=C){const S=Wo(N,x,n,b);i.set(x.id,ja(N,S,n));continue}(u=x.chats)!=null&&u.length&&!((f=N.chats)!=null&&f.length)&&i.set(x.id,{...N,chats:x.chats})}for(const[x,N]of i){const y=N.daemonId||x.split(":")[0];if(!l.has(y))continue;if(a.has(y)&&m.has(y)&&!c.has(x)){i.delete(x);continue}const p=n-(N._lastUpdate||N.timestamp||0);Zd(N,y,p,c,a,d)&&i.delete(x)}for(const[x,N]of i){const y=N.daemonId||x.split(":")[0];if(eu(N,y,l,d,i))continue;n-(N._lastUpdate||N.timestamp||0)>3e5&&N.status!=="online"&&i.delete(x)}return Array.from(i.values())}function su(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 ru({children:e,connectionOverrides:t}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[d,m]=o.useState(void 0),u=o.useRef(r);o.useEffect(()=>{u.current=r},[r]);const f=o.useCallback((b,h)=>{n(C=>{let S=!1;const v=C.map(M=>M.id!==b||M.chats===h?M:(S=!0,{...M,chats:h}));return S?v:C})},[]),x=o.useCallback((b,h)=>{n(C=>{const S=C.length===0?b:tu(b,C,h),v=!su(C,S);return v&&As.record({kind:"dashboard.entries_applied",payload:{incoming:Bo(b),next:Bo(S)}}),v?S:C})},[]),N=o.useCallback(()=>i(!0),[]),y=o.useMemo(()=>({injectEntries:x,markLoaded:N,getIdes:()=>u.current}),[x,N]),p=t,g=o.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(sc.Provider,{value:y,children:s.jsx(tc.Provider,{value:g,children:e})})}function Zt(){return o.useContext(tc)}function dr(){return o.useContext(sc)}function ac(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${t}${l.startsWith("/")?"":"/"}${l}`}function i(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,N=setTimeout(()=>x.abort(),15e3);try{const y=await fetch(f,{...d,headers:m,signal:x.signal});if(y.status===401)throw n==null||n(),new Error("Unauthorized");if(!y.ok){const p=await y.json().catch(()=>({error:y.statusText}));throw new Error(p.error||`API Error: ${y.status}`)}return y.json()}finally{clearTimeout(N)}}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=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const nu=ac({baseUrl:"http://localhost:3847"}),au=o.createContext(nu);function ou({client:e,children:t}){return s.jsx(au.Provider,{value:e,children:t})}const iu={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},oc=o.createContext(iu);function cu({value:e,children:t}){return s.jsx(oc.Provider,{value:e,children:t})}function gt(){return o.useContext(oc)}function lu(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 du(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function uu(e){return e?lu([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),du(e.content)]):""}const Fe={size:18};function ic({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 Ua({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 cc({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 mu({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 fu({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 lc({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 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:"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 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("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 hu({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 za({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 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("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 pr({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 ur({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 Nr({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 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:"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 Va({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 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("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}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("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 Ga({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 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("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function qa({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 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("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 yu({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 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("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 wu({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 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:"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 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("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 Su({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 Nu({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 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("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 Tu({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 Mu({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 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("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 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("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 Ru({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 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("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 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("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 _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:"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 pc=[Ld,{singleTilde:!1}],hc=[pc,Pd,_d],Du=[pc],Ya=200,Eu=80,Fo=650,Hs=new Map;function en(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function $u(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}:${uu(n)}`}function Bu(e,t,r,n){return e||!t?!1:en(r,n)}function Ou({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=Eu,bottomThresholdPx:a=Ya}){const i=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:i>n,showBottom:Math.max(0,c-i-l)>a}}function Ku(e){return Ou({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function tr(e,t=Ya){return!!e&&e.fromBottom>=t}function Wu(e,t){return en(e,t)?!tr(e):!0}function Fu({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function Hu({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function Ln(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function xc(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Uu(e,t,r){return Number(e.receivedAt||r[tn(e,t)]||0)||0}function zu(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 bc(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Vu(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function Cr(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 Pn(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 Ho(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):bc(e)?s.jsx(Wa,{remarkPlugins:hc,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function Tr({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:Ho(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=Pn(r);return a?s.jsx("img",{src:a,alt:Cr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=Pn(r);return a?s.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=Pn(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:Cr(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||Cr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=Cr(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}),Ho(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=Ha(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 Gu=o.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(Wa,{remarkPlugins:Du,children:t.text}),s.jsx("span",{className:"action-time",children:xc(t.timestamp)})]})},(e,t)=>e.log===t.log),qu=o.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:i,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=Vu(t.content)?t.content:null,x=!!(f!=null&&f.some(B=>B.type!=="text")),N=Ha(t.content,{joiner:`
|
|
4
|
+
`});if(u==="thought"){const B=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(wu,{size:13}),s.jsx("span",{children:B})]}),s.jsx("div",{className:"chat-msg-body",children:N})]})}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(Tr,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:N})]});if(u==="terminal"){const B=(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:B}),s.jsx("span",{children:P})]}),x&&f?s.jsx("div",{className:"chat-msg-body",children:s.jsx(Tr,{parts:f,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:N})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:x&&f?s.jsx(Tr,{parts:f,renderAsPreformatted:!1}):N.slice(0,100)});const y=t.meta,g=(typeof(y==null?void 0:y.renderMode)=="string"?y.renderMode.trim():"")==="preformatted",b=N,h=!1,C=b,S=g,v=!S&&bc(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:xc(r)})]}),(b||x)&&s.jsx("div",{className:"chat-markdown",children:x&&f?s.jsx(Tr,{parts:f,renderAsPreformatted:S}):S?s.jsx("pre",{className:"chat-preformatted",children:C}):v?s.jsx(Wa,{remarkPlugins:hc,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),Yu=o.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:d={},lastMessageHash:m,emptyState:u,onLoadMore:f,isLoadingMore:x,hasMoreHistory:N,hiddenLiveCount:y=0,loadError:p,scrollToBottomRequestNonce:g,isVisible:b=!0},h){const C=o.useRef(null),S=o.useRef(null),v=o.useRef(null),M=o.useRef(0),I=o.useRef(""),j=o.useRef(""),w=o.useRef(!1),B=o.useRef(null),P=o.useRef(!1),T=o.useRef(null),H=o.useRef(!1),[z,R]=o.useState(new Set),[k,A]=o.useState({showTop:!1,showBottom:!1}),F=o.useRef(!1),_=o.useRef(!1),E=o.useRef(b),K=o.useRef(b),Y=o.useRef(null);K.current=b;const be=()=>{const Q=C.current;return Q?Q.scrollHeight-Q.scrollTop-Q.clientHeight<Ya:!0},ce=o.useCallback(()=>{const Q=C.current,me=Q?Ku(Q):{showTop:!1,showBottom:!1};A(J=>J.showTop===me.showTop&&J.showBottom===me.showBottom?J:me)},[]),D=o.useCallback((Q="auto")=>{var J;const me=C.current;me&&(me.scrollTo({top:me.scrollHeight,behavior:Q}),(J=me.ownerDocument.defaultView)==null||J.requestAnimationFrame(()=>ce()))},[ce]),ie=o.useCallback((Q="auto")=>{var J;const me=C.current;me&&(me.scrollTo({top:0,behavior:Q}),(J=me.ownerDocument.defaultView)==null||J.requestAnimationFrame(()=>ce()))},[ce]),fe=o.useCallback(()=>{var Te;const Q=C.current,me=(Te=window.getSelection)==null?void 0:Te.call(window);if(!Q||!me||me.rangeCount===0||me.isCollapsed){H.current=!1;return}const J=me.anchorNode,Ae=me.focusNode;H.current=!!(J&&Ae&&Q.contains(J)&&Q.contains(Ae))},[]),xe=o.useMemo(()=>t.filter(zu),[t]),X=xe.length===t.length?m:void 0,le=$u(xe,X),ye=o.useCallback(()=>{const Q=C.current;if(!Q||!l||!K.current)return;const me={top:Q.scrollTop,fromBottom:Math.max(0,Q.scrollHeight-Q.scrollTop-Q.clientHeight),messageFingerprint:le};Y.current={contextKey:l,snapshot:me},Hs.set(l,me)},[l,le]),se=o.useCallback((Q="auto")=>{B.current!=null&&cancelAnimationFrame(B.current),B.current=requestAnimationFrame(()=>{B.current=null,D(Q)})},[D]),ue=o.useCallback(()=>{F.current=!1,P.current=!0,_.current=!0,T.current!=null&&window.clearTimeout(T.current),T.current=window.setTimeout(()=>{P.current=!1,T.current=null},Fo)},[]);o.useEffect(()=>{const Q=!w.current,me=j.current!==l;if(j.current=l,Q||me){w.current=!0;const Ae=l?Hs.get(l):null,Te=!!Ae&&en(Ae,le);F.current=Te?tr(Ae):!1,P.current=Wu(Ae,le),H.current||(Te?requestAnimationFrame(()=>{const $e=C.current;$e&&(Ln($e,Ae),F.current=tr(Ae),ce(),_.current=!0)}):se("auto")),M.current=xe.length,I.current=le;return}xe.length>M.current;const J=le!==I.current;Fu({hasSelection:H.current,userScrolledUp:F.current,hasChatContentChanged:J})&&se("auto"),M.current=xe.length,I.current=le},[le,l,xe.length,se,ce]),o.useEffect(()=>{g&&(ue(),H.current||se("auto"))},[ue,se,g]),o.useEffect(()=>{const Q=E.current;Q&&!b&&ye(),K.current=b,E.current=b;const me=l?Hs.get(l):null;if(Bu(Q,b,me,le)){if(!me)return;F.current=tr(me),P.current=!1,H.current||requestAnimationFrame(()=>{const J=C.current;J&&(Ln(J,me),ce())});return}},[b,l,le,ue,ye,se,ce]),o.useEffect(()=>()=>{const Q=Y.current;Q&&Hs.set(Q.contextKey,Q.snapshot),B.current!=null&&cancelAnimationFrame(B.current),T.current!=null&&window.clearTimeout(T.current)},[]),o.useEffect(()=>{const Q=S.current,me=C.current;if(!Q||!me)return;const J=()=>{T.current!=null&&window.clearTimeout(T.current),T.current=window.setTimeout(()=>{P.current=!1,T.current=null},Fo)},Ae=new ResizeObserver(()=>{ce();const Te=P.current;Hu({hasSelection:H.current,userScrolledUp:F.current,contextAutoScrollActive:Te})&&(se("auto"),Te&&J())});return Ae.observe(Q),me!==Q&&Ae.observe(me),()=>{Ae.disconnect(),T.current!=null&&(window.clearTimeout(T.current),T.current=null)}},[se,l,ce]),o.useImperativeHandle(h,()=>({scrollToBottom:(Q="smooth")=>{D(Q)}}),[D]),o.useEffect(()=>{const Q=C.current;if(!Q)return;let me;const J=()=>{ye(),clearTimeout(me),me=setTimeout(()=>{F.current=!be(),ce()},50)};return Q.addEventListener("scroll",J,{passive:!0}),()=>{Q.removeEventListener("scroll",J),clearTimeout(me)}},[ye,ce]),o.useEffect(()=>(document.addEventListener("selectionchange",fe),()=>document.removeEventListener("selectionchange",fe)),[fe]);const ke=o.useRef(0),he=o.useRef(!1);o.useEffect(()=>{const Q=C.current;if(!Q||!he.current||ke.current===0)return;const me=Q.scrollHeight-ke.current;me>0&&(Q.scrollTop=me),ce(),ye(),ke.current=0,he.current=!1},[xe.length,ye,ce]),o.useEffect(()=>{if(_.current||!l)return;const Q=Hs.get(l),me=C.current;if(!(!Q||!me)){if(!en(Q,le)){D("auto"),_.current=!0;return}Ln(me,Q),F.current=tr(Q),ce(),_.current=!0}},[l,le,xe.length,D,ce]);const ve=()=>{const Q=C.current;Q&&(ke.current=Q.scrollHeight),he.current=!0,f==null||f()},ee=()=>{F.current=!0,ie("smooth"),ye()},pe=()=>{ue(),D("smooth"),ye()},oe=o.useMemo(()=>{const Q=xe.map((Te,$e)=>({type:"message",data:Te,index:$e,ts:Uu(Te,$e,d)}));if(!r||r.length===0)return Q;const me=[...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<me.length&&Te.ts>0&&me[Ae].ts<Te.ts;)J.push(me[Ae++]);J.push(Te)}for(;Ae<me.length;)J.push(me[Ae++]);return J},[xe,r,d]),de=y>0||!!N,ae=y>0?`↑ Show ${Math.min(y,80)} earlier messages${y>80?` (${y} 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:S,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..."}),de&&!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&&y===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:ae})}),oe.length===0&&!de&&(u||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),oe.map(Q=>{if(Q.type==="action"){const O=Q.data;return s.jsx(Gu,{log:O},`action-${Q.index}`)}const me=Q.data,J=Q.index,Ae=tn(me,J),Te=me.receivedAt||d[Ae],$e=`${l}-${Ae}`,Ue=z.has($e);return s.jsx(qu,{message:me,receivedAt:Te,agentName:n,userName:a,isCliMode:i,isTextExpanded:Ue,onToggleTextExpanded:()=>R(O=>{const Se=new Set(O);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:ee,"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:pe,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Xu=o.memo(Yu,(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),Ju="modulepreload",Qu=function(e){return"/"+e},Uo={},Zu=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=Qu(d),d in Uo)return;Uo[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":Ju,m||(f.as="script"),f.crossOrigin="",f.href=d,l&&f.setAttribute("nonce",l),document.head.appendChild(f),m)return new Promise((x,N)=>{f.addEventListener("load",x),f.addEventListener("error",()=>N(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(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"&&i(l.reason);return t().catch(i)})};let zo=!1;const gc=o.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:i="measured"},c)=>{const l=o.useRef(null),[d,m]=o.useState(null),u=o.useRef([]),f=o.useRef(!1),x=o.useRef(!1),N=o.useRef(!1),y=o.useRef(!1),p=()=>{const g=l.current;if(g){f.current&&(g.clear(),f.current=!1);for(const b of u.current)g.write(b.data,b.onProcessed);u.current=[],x.current&&(g.fit(),x.current=!1),N.current&&(g.bumpResize(),N.current=!1),y.current&&(g.scrollToTop(),y.current=!1)}};return o.useImperativeHandle(c,()=>({write:(g,b)=>{l.current?l.current.write(g,b):u.current.push({data:g,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:(g,b)=>{l.current&&typeof l.current.resize=="function"&&l.current.resize(g,b)},fit:()=>{l.current?l.current.fit():x.current=!0},bumpResize:()=>{l.current?l.current.bumpResize():N.current=!0},scrollToTop:()=>{l.current?l.current.scrollToTop():y.current=!0},getSelection:()=>{var g,b;return((b=(g=l.current)==null?void 0:g.getSelection)==null?void 0:b.call(g))||""},getVisibleText:()=>{var g,b;return((b=(g=l.current)==null?void 0:g.getVisibleText)==null?void 0:b.call(g))||""}}),[]),o.useEffect(()=>{d&&p()},[d]),o.useEffect(()=>{let g=!1;return Zu(()=>import("./terminal-BeBmUW3m.js"),__vite__mapDeps([0,1,2])).then(b=>{zo||(zo=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),g||m(()=>b.GhosttyTerminalView)}).catch(b=>{console.error("[CliTerminal] failed to load terminal renderer",b)}),()=>{g=!0}},[]),d?s.jsx(d,{ref:l,onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:i,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"}})});gc.displayName="CliTerminal";function Mr({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 Vo({value:e,max:t,label:r,color:n="#8b5cf6",detail:a,compact:i=!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 i?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 em({cursorPos:e,viewportRef:t,imgRef:r}){var h;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(h=t.current)==null?void 0:h.getBoundingClientRect();if(!i)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,N;d>m?(u=a.width,f=a.width/d,x=0,N=(a.height-f)/2):(f=a.height,u=a.height*d,x=(a.width-u)/2,N=0);const y=a.left-i.left+x+u*e.nx,p=a.top-i.top+N+f*e.ny,g=Math.max(8,Math.min(i.width-8,y)),b=Math.max(8,Math.min(i.height-8,p));return s.jsxs("div",{style:{position:"absolute",left:g-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 tm({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:d,isConnActive:m,zoom:u,isMobile:f,mobileFillZoom:x,onZoomOut:N,onZoomReset:y,onZoomIn:p,transportType:g,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),i(!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:()=>{i(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),"%"]}),g==="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"}),g==="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(),N()},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(),y()},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 sm({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 rm(){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 Go(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 hr(e,t){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!rm())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,Go(l)]))}),r.current=t;return}const i=Object.keys({...a,...t}).filter(c=>!Object.is(a[c],t[c]));i.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:i,snapshot:Object.fromEntries(i.map(c=>[c,Go(t[c])]))}),r.current=t})}function nm({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:d,setPanX:m,setPanY:u,setZoom:f,lastWheelTimeRef:x,onAction:N,setLastActionStatus:y,spawnRippleFromNormalized:p,clampPan:g,isMobile:b,mobileFillZoom:h}){const[C,S]=o.useState(null),v=o.useRef(null),M=o.useRef(null),I=o.useRef(null),j=o.useRef(!1),w=o.useRef(null),B=o.useRef(0),P=o.useRef(null),T=o.useRef(1),H=o.useRef({x:0,y:0}),z=o.useRef(!1),R=o.useRef(n),k=o.useRef(N),A=30,F=550,_=18,E=60,K=400,Y=12,be=()=>{if(v.current)return;const ie={nx:.5,ny:.5};v.current=ie,S(ie)};return o.useEffect(()=>{R.current=n,n==="mouse"&&be()},[n]),o.useEffect(()=>{k.current=N},[N]),o.useEffect(()=>{const ie=e.current;if(!ie)return;const fe=ue=>{if(!r.current)return null;const ke=r.current.getBoundingClientRect();return!ke.width||!ke.height?null:{nx:Math.max(0,Math.min(1,(ue.clientX-ke.left)/ke.width)),ny:Math.max(0,Math.min(1,(ue.clientY-ke.top)/ke.height))}},xe=(ue,ke)=>{if(!r.current)return{dnx:0,dny:0};const he=r.current,ve=he.getBoundingClientRect(),ee=he.naturalWidth||ve.width,pe=he.naturalHeight||ve.height,oe=ee/pe,de=ve.width/ve.height;let ae,Q;return oe>de?(ae=ve.width,Q=ve.width/oe):(Q=ve.height,ae=ve.height*oe),{dnx:ue/ae,dny:ke/Q}},X=(ue,ke,he)=>{if(he<=1.05)return;const ve=-(ue-.5)*100,ee=-(ke-.5)*100,pe=g(ve,ee,he);(Math.abs(pe.x-l.current)>.1||Math.abs(pe.y-d.current)>.1)&&(m(pe.x),u(pe.y),l.current=pe.x,d.current=pe.y)},le=ue=>{const ke=t.current;if(ke&&ue.target instanceof Node&&ke.contains(ue.target))ue.preventDefault();else return;if(ue.touches.length===1){const he=ue.touches[0];M.current={x:he.clientX,y:he.clientY,time:Date.now()},I.current={x:he.clientX,y:he.clientY},z.current||(j.current=!1),w.current=setTimeout(()=>{if(!j.current&&!z.current)if(j.current=!0,R.current==="mouse"){const ve=v.current||{nx:.5,ny:.5};y("Right Click"),p(ve.nx,ve.ny,"right"),k.current("input_click",{...ve,button:"right"}).catch(()=>{})}else{const ve=fe(he);ve&&(y("Right Click"),p(ve.nx,ve.ny,"right"),k.current("input_click",{...ve,button:"right"}).catch(()=>{}))}},500);return}if(ue.touches.length===2){w.current&&clearTimeout(w.current),j.current=!0,z.current=!0;const he=ue.touches[1].clientX-ue.touches[0].clientX,ve=ue.touches[1].clientY-ue.touches[0].clientY;P.current=Math.sqrt(he*he+ve*ve),T.current=c.current,H.current={x:(ue.touches[0].clientX+ue.touches[1].clientX)/2,y:(ue.touches[0].clientY+ue.touches[1].clientY)/2}}},ye=ue=>{const ke=t.current;if(ke&&ue.target instanceof Node&&ke.contains(ue.target)&&ue.preventDefault(),ue.touches.length===1&&I.current){const he=ue.touches[0],ve=he.clientX-I.current.x,ee=he.clientY-I.current.y;if(!j.current&&M.current){const pe=he.clientX-M.current.x,oe=he.clientY-M.current.y;Math.sqrt(pe*pe+oe*oe)>8&&(j.current=!0,w.current&&clearTimeout(w.current))}if(j.current)if(R.current==="mouse"){const pe=xe(ve,ee),oe=v.current||{nx:.5,ny:.5},de=Math.max(0,Math.min(1,oe.nx+pe.dnx)),ae=Math.max(0,Math.min(1,oe.ny+pe.dny));v.current={nx:de,ny:ae},S({nx:de,ny:ae}),y(`Cursor: ${Math.round(de*100)}%, ${Math.round(ae*100)}%`),X(de,ae,c.current);const Q=Date.now();Q-x.current>=30&&(x.current=Q,k.current("input_mouseMoved",{nx:de,ny:ae}).catch(()=>{}))}else if(c.current>1){const pe=t.current;if(pe){const oe=pe.clientWidth,de=pe.clientHeight,ae=l.current+ve/oe*100,Q=d.current+ee/de*100,me=g(ae,Q,c.current);m(me.x),u(me.y),l.current=me.x,d.current=me.y}}else{const pe=fe(he);if(pe){const oe=Date.now();oe-x.current>=40&&(x.current=oe,y("Scroll"),k.current("input_wheel",{nx:pe.nx,ny:pe.ny,deltaX:Math.round(-ve*2.5),deltaY:Math.round(-ee*2.5)}).catch(()=>{}))}}I.current={x:he.clientX,y:he.clientY};return}if(ue.touches.length===2&&P.current!==null){const he=ue.touches[1].clientX-ue.touches[0].clientX,ve=ue.touches[1].clientY-ue.touches[0].clientY,pe=Math.sqrt(he*he+ve*ve)/P.current,oe=(ue.touches[0].clientX+ue.touches[1].clientX)/2,de=(ue.touches[0].clientY+ue.touches[1].clientY)/2,ae=oe-H.current.x,Q=de-H.current.y,me=Math.abs(pe-1)>.03;if(R.current==="mouse"){if(me){const J=Math.max(i,Math.min(5,T.current*pe));f(J),c.current=J}else if(Math.abs(ae)>2||Math.abs(Q)>2){const J=v.current||{nx:.5,ny:.5},Ae=Date.now();Ae-x.current>=30&&(x.current=Ae,y("Scroll"),k.current("input_wheel",{nx:J.nx,ny:J.ny,deltaX:Math.round(-ae*3),deltaY:Math.round(-Q*3)}).catch(()=>{}))}}else{const J=Math.max(i,Math.min(5,T.current*pe));f(J),c.current=J;const Ae=t.current;if(Ae&&J>1){const Te=Ae.clientWidth,$e=Ae.clientHeight,Ue=l.current+ae/Te*100,O=d.current+Q/$e*100,Se=g(Ue,O,J);m(Se.x),u(Se.y),l.current=Se.x,d.current=Se.y}}H.current={x:oe,y:de}}},se=ue=>{var ke;if(w.current&&clearTimeout(w.current),P.current=null,ue.touches.length===1&&z.current){const he=ue.touches[0];M.current={x:he.clientX,y:he.clientY,time:Date.now()},I.current={x:he.clientX,y:he.clientY},j.current=!0;return}if(ue.touches.length===0){if(z.current){z.current=!1,j.current=!1;return}if(ue.changedTouches.length===1){const he=ue.changedTouches[0],ve=Date.now(),ee=ve-(((ke=M.current)==null?void 0:ke.time)||0),pe=M.current?he.clientX-M.current.x:0,oe=M.current?he.clientY-M.current.y:0,de=Math.sqrt(pe*pe+oe*oe);if(R.current==="mouse"){if(ee<A||ee>F||de>_){j.current=!1;return}const ae=v.current||fe(he);ae&&(y(`Click: ${Math.round(ae.nx*100)}%, ${Math.round(ae.ny*100)}%`),p(ae.nx,ae.ny,"left"),k.current("input_click",{...ae}).catch(()=>{}))}else{if(j.current){j.current=!1;return}if(ee<E||ee>K||de>Y){j.current=!1;return}const ae=fe(he);if(!ae)return;ve-B.current<300?(y("Double tap"),p(ae.nx,ae.ny,"double"),k.current("input_click",{...ae,clickCount:2}).catch(()=>{}),B.current=0):(y(`Tap: ${Math.round(ae.nx*100)}%, ${Math.round(ae.ny*100)}%`),p(ae.nx,ae.ny,"left"),k.current("input_click",{...ae}).catch(()=>{}),B.current=ve)}}j.current=!1}};return ie.addEventListener("touchstart",le,{passive:!1}),ie.addEventListener("touchmove",ye,{passive:!1}),ie.addEventListener("touchend",se,{passive:!1}),()=>{ie.removeEventListener("touchstart",le),ie.removeEventListener("touchmove",ye),ie.removeEventListener("touchend",se),w.current&&clearTimeout(w.current)}},[e,t,r,i,c,l,d,m,u,f,x,y,p,g]),{cursorPos:C,cursorPosRef:v,handleToggleInputMode:()=>{a(ie=>{const fe=ie==="touch"?"mouse":"touch";return fe==="mouse"&&be(),fe})},handleZoomReset:()=>{const ie=b?h:1;f(ie),c.current=ie,m(0),u(0),l.current=0,d.current=0}}}function yc({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),d=o.useRef(null),[m,u]=o.useState(null),[f,x]=o.useState(""),[,N]=o.useState(!1),[y,p]=o.useState([]),g=o.useRef(0),[b,h]=o.useState(!1),[C,S]=o.useState(!1),v=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[M,I]=o.useState(v?"mouse":"touch"),[j,w]=o.useState(1),B=o.useRef(!1),[P,T]=o.useState(1),[H,z]=o.useState(0),[R,k]=o.useState(0);hr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:M,zoom:P,panX:H,panY:R,isMenuOpen:b,isImeOpen:C});const A=o.useRef(0),F=o.useRef(P),_=o.useRef(H),E=o.useRef(R);o.useEffect(()=>{F.current=P},[P]),o.useEffect(()=>{_.current=H},[H]),o.useEffect(()=>{E.current=R},[R]),o.useEffect(()=>{var ee;(ee=c.current)==null||ee.focus()},[]);const K=r==="connected",Y=n,be=K?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ce=K?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!v||B.current||!Y)return;const ee=d.current,pe=l.current;if(!ee||!pe)return;const oe=()=>{const de=pe.clientWidth,ae=pe.clientHeight,Q=ee.naturalWidth,me=ee.naturalHeight;if(!Q||!me||!de||!ae)return;const J=Math.min(de/Q,ae/me),Te=Math.max(de/Q,ae/me)/J;Te>1.01&&(w(Te),T(Te),F.current=Te),B.current=!0};ee.complete&&ee.naturalWidth?oe():ee.addEventListener("load",oe,{once:!0})},[Y,v]);const D=.5;o.useEffect(()=>{P<=D&&(z(0),k(0))},[P,D]);const ie=(ee,pe,oe)=>{if(oe<=D)return{x:0,y:0};const de=(oe-1)/(2*oe)*100,ae=(oe-1)/(2*oe)*100;return{x:Math.max(-de,Math.min(de,ee)),y:Math.max(-ae,Math.min(ae,pe))}},fe=(ee,pe)=>{if(!d.current)return null;const oe=d.current.getBoundingClientRect();return!oe.width||!oe.height?null:{nx:Math.max(0,Math.min(1,(ee-oe.left)/oe.width)),ny:Math.max(0,Math.min(1,(pe-oe.top)/oe.height))}},xe=(ee,pe,oe)=>{const de=l.current;if(!de)return;const ae=de.getBoundingClientRect(),Q=++g.current;p(me=>[...me,{id:Q,x:ee-ae.left,y:pe-ae.top,type:oe}]),setTimeout(()=>p(me=>me.filter(J=>J.id!==Q)),600)},X=(ee,pe,oe)=>{const de=d.current,ae=l.current;if(!de||!ae)return;const Q=de.getBoundingClientRect(),me=ae.getBoundingClientRect(),J=de.naturalWidth||Q.width,Ae=de.naturalHeight||Q.height,Te=J/Ae,$e=Q.width/Q.height;let Ue,O,Se,Me;Te>$e?(Ue=Q.width,O=Q.width/Te,Se=0,Me=(Q.height-O)/2):(O=Q.height,Ue=Q.height*Te,Se=(Q.width-Ue)/2,Me=0);const De=Q.left-me.left+Se+Ue*ee,Oe=Q.top-me.top+Me+O*pe,He=++g.current;p(Je=>[...Je,{id:He,x:De,y:Oe,type:oe}]),setTimeout(()=>p(Je=>Je.filter(st=>st.id!==He)),600)},le=async ee=>{var oe;const pe=fe(ee.clientX,ee.clientY);if(pe){u(`Click: ${Math.round(pe.nx*100)}%, ${Math.round(pe.ny*100)}%`),xe(ee.clientX,ee.clientY,"left"),(oe=c.current)==null||oe.focus();try{const de=await e("input_click",{nx:pe.nx,ny:pe.ny});de!=null&&de.success||t(`❌ Click failed: ${de==null?void 0:de.error}`)}catch(de){t(`❌ Click error: ${de.message||de}`)}}},ye=async(ee,pe,oe,de=0)=>{try{await e("input_key",{type:oe?"char":"keyDown",key:ee,code:pe,text:oe?ee:void 0,unmodifiedText:oe?ee:void 0,modifiers:de})}catch(ae){t(`❌ Key error: ${ae.message||ae}`)}},se=async ee=>{if(ee.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ee.key)&&ee.preventDefault();let oe=0;ee.altKey&&(oe|=1),ee.ctrlKey&&(oe|=2),ee.metaKey&&(oe|=4),ee.shiftKey&&(oe|=8),u(`Key: ${ee.key}`),await ye(ee.key,ee.code,ee.key.length===1,oe)},ue=async ee=>{if(ee.key==="Enter"){if(ee.nativeEvent.isComposing)return;if(f){const pe=f;x(""),u(`IME Sent: ${pe}`);try{const oe=await e("input_type",{text:pe});oe!=null&&oe.success||t(`❌ IME error: ${oe==null?void 0:oe.error}`)}catch(oe){t(`❌ IME error: ${oe.message}`)}}else u("Key: Enter"),await ye("Enter","Enter",!1)}};o.useEffect(()=>{const ee=c.current;if(!ee)return;const pe=oe=>{var de;if((de=d.current)!=null&&de.contains(oe.target)){oe.preventDefault();const ae=Date.now();if(ae-A.current<40)return;A.current=ae;const Q=fe(oe.clientX,oe.clientY);if(!Q)return;u(`Scroll: ${Math.round(oe.deltaY)}`),e("input_wheel",{nx:Q.nx,ny:Q.ny,deltaX:Math.round(oe.deltaX),deltaY:Math.round(oe.deltaY)}).catch(()=>{})}};return ee.addEventListener("wheel",pe,{passive:!1}),()=>ee.removeEventListener("wheel",pe)},[e]);const{cursorPos:ke,handleToggleInputMode:he,handleZoomReset:ve}=nm({containerRef:c,viewportRef:l,imgRef:d,inputMode:M,setInputMode:I,minZoom:D,zoomRef:F,panXRef:_,panYRef:E,setPanX:z,setPanY:k,setZoom:T,lastWheelTimeRef:A,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:X,clampPan:ie,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:se,onContextMenu:ee=>ee.preventDefault(),onFocus:()=>N(!0),onBlur:()=>N(!1),tabIndex:0,children:[s.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[Y?s.jsx("img",{ref:d,src:Y,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${P}) translate(${H}%, ${R}%)`,transformOrigin:"center center",cursor:M==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:le,onContextMenu:ee=>ee.preventDefault(),onDragStart:ee=>ee.preventDefault()}):s.jsx(sm,{waitingLabel:be,waitingHint:ce,transportType:i}),M==="mouse"&&Y&&s.jsx(em,{cursorPos:ke,viewportRef:l,imgRef:d}),y.map(ee=>{const oe={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ee.type];return s.jsxs("div",{style:{position:"absolute",left:ee.x,top:ee.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${oe}, 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(${oe}, 0.9)`,boxShadow:`0 0 12px rgba(${oe}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ee.id)})]}),s.jsx(tm,{inputMode:M,onToggleInputMode:he,isImeOpen:C,setIsImeOpen:S,isMenuOpen:b,setIsMenuOpen:h,imeText:f,setImeText:x,handleImeSubmit:ue,isConnActive:K,zoom:P,isMobile:v,mobileFillZoom:j,onZoomOut:()=>T(ee=>Math.max(.5,ee-.25)),onZoomReset:ve,onZoomIn:()=>T(ee=>Math.min(5,ee+.25)),transportType:i,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,i=Date.now()-e,c=Math.floor(i/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 vc=e=>gn(e);function am(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 om(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...am(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),i=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:i,isConnecting:c,isGenerating:l,isWaiting:d,inboxBucket:m?"needs_attention":u?"working":x?"task_complete":"idle"}}function im(e,t,r){return yn(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function wc({activeConv:e,onModalButton:t}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Ks(e).isWaiting||!e.modalButtons)return null;const i=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(ur,{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,N=r!==null;return s.jsx("button",{onClick:()=>i(l),disabled:N,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"} ${N&&!x?"opacity-40":"opacity-100"} ${N?"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 Xa="adhdev_controls_bar_visible",ka="adhdev:controlsbarvisibilitychange";function _n(e){if(!e)return!1;try{return e.getItem(Xa)==="1"}catch{return!1}}function cm(e,t){if(t)try{t.setItem(Xa,e?"1":"0")}catch{}}function lm(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ka,{detail:{visible:e}}))}function Ja(){const[e,t]=o.useState(()=>typeof window>"u"?!1:_n(window.localStorage)),r=o.useRef(e),n=o.useCallback((c,l=!0)=>{r.current=c,t(c),typeof window<"u"&&cm(c,window.localStorage),l&&lm(c)},[]);o.useEffect(()=>{const c=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:_n(window.localStorage);r.current=u,t(u)},l=d=>{if(d.key!==Xa)return;const m=_n(window.localStorage);r.current=m,t(m)};return window.addEventListener(ka,c),window.addEventListener("storage",l),()=>{window.removeEventListener(ka,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{n(c)},[n]),i=o.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:i}}var dm=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function um(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function bt(e,t){if(um(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":dm.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 qo(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 mm(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),i=r%24;return`${a}d ${i}h`}function Dn(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(/[\\/]+$/,""),i=a.split(/[\\/]/).filter(Boolean);return i[i.length-1]||a}function fm(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 pm(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function hm(e){return fm(e.trim().replace(/\.local$/i,""))}function xm(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function jc(e,t={}){var a,i;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(i=e.system)==null?void 0:i.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!pm(c));if(r&&r!=="Unknown")return hm(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Tt(e,t={}){return xm(e)||jc(e,t)}function kc(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 Sc(e,t,r={}){const n=String(t).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(i=>String((i==null?void 0:i.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function hs(e,t){return kc(e).join(" · ")}function mr(e){return e.transport==="pty"}function Ts(e){return e.transport==="acp"}function bm(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 Yo(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=it(r||"").trim().toLowerCase();return n===a||n===i||n===c}function gm(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=>qo(x.status,{activeModal:x.activeModal})||rn(x.status));if(a)return bt(a.status,{activeModal:a.activeModal});const i=r.find(x=>qo(x.status,{activeModal:x.activeModal})||rn(x.status));if(i)return bt(i.status,{activeModal:i.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 ym(e){return bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function vm(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,"-"),i=t.get(a),c=bt(n.status);if(!i){t.set(a,{...n,status:c});continue}const l=r.indexOf(i.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 wm(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 jm(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&&wm(t.receivedAt)||0}function km(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Sa(e){return Math.max(km(e),jm(e.activeChat))}function Sm(e,t,r,n,a,i){const c=t-e;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:a.localeCompare(i)}function Qa(e,t){return Sm(Sa(e),Sa(t),Tt(e,{fallbackId:e.id}),Tt(t,{fallbackId:t.id}),e.id,t.id)}const Nc="adhdev_notification_prefs",Xo={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Nm(){try{const e=localStorage.getItem(Nc);if(e){const t=JSON.parse(e);return{...Xo,...t}}}catch{}return{...Xo}}function Cm(e){try{localStorage.setItem(Nc,JSON.stringify(e))}catch{}}let Ft=Nm(),Hr=[];function Tm(){Hr.forEach(e=>e())}function Mm(e){Ft={...Ft,...e},Cm(Ft),Tm()}function Im(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Hr.push(r),()=>{Hr=Hr.filter(n=>n!==r)}},[]);const t=o.useCallback(r=>{Mm(r)},[]);return[{...Ft},t]}function rr(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 Am={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Cc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Tc(){return"Notification"in window&&Notification.permission==="granted"}let es=null;function Rm(e){return e!==!1}async function Lm(){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 Na(e,t,r){if(Tc())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 Pm(e,t={}){const r={...Am,...t},n=o.useRef(new Map),a=o.useRef(0),[i,c]=o.useState(null);o.useEffect(()=>{let d=!1;return Lm().then(m=>{d||c(m)}),()=>{d=!0}},[]);const l=o.useCallback((d,m,u)=>{const f=Date.now();f-a.current<r.throttleMs||(a.current=f,Na(d,m,u))},[r.throttleMs]);o.useEffect(()=>{var d;if(!(!r.enabled||!Tc())&&rr("browser")&&!Rm(i)){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&&rr("approval")&&f==="waiting_approval"&&u!=="waiting_approval"){const N=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";l(`🔔 ${x} — Approval needed`,N.slice(0,120),`approval-${m.id}`)}r.onComplete&&rr("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,i,l])}const _m=/^(run|approve|accept|yes|allow|always)/,Dm=/^(run|approve|accept|yes|allow|always|proceed|save)/,Em=/^(reject|deny|delete|remove|abort|cancel|no)/;function Za(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function $m(e){const t=Za(e).toLowerCase();return _m.test(t)?"primary":Em.test(t)?"danger":"default"}function Bm(e){return Dm.test(Za(e).toLowerCase())?"approve":"reject"}function Om(e){return e.map((t,r)=>({label:Za(t),variant:$m(t),action:Bm(t),button:t,buttonIndex:r}))}function Km(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Wm(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 Fm{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,i]of this.dedupMap)r-i>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(i=>i.id===t.daemonId&&i.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 i=this.ides.find(c=>c.id===a&&c.type==="adhdev-daemon");if(i)return i}}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 y;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),i=n||t.daemonId||"",c=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),l=`${i}:${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="",N="info";if(t.event==="agent:generating_completed"){const p=t.duration?` (${t.duration}s)`:"";x=`✅ ${u} agent task completed${p}`,N="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`,N="warning",(y=t.modalButtons)!=null&&y.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(t);if(!p)return;const g=this.resolveActionFn,b=Om(t.modalButtons).map(S=>({label:S.label,variant:S.variant,onClick:()=>{g(p,"resolve_action",{action:S.action,button:S.button,buttonIndex:S.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),h=Km(u,t.modalMessage,x),C=Date.now();this.emitToast({id:C,message:h,type:N,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}`,N="warning",rr("browser")&&!document.hasFocus()&&Na(`⚠️ ${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",g=t.requestId,b=t.orgId;if(x=`👁️ ${p} wants to view your session`,N="warning",g&&b&&this.viewRequestRespondFn){const h=Date.now(),C=Wm(b,g,this.viewRequestRespondFn,(S,v)=>console.error(`[EventManager] ${S} view request failed:`,v));this.emitToast({id:h,message:x,type:N,timestamp:h,actions:C,duration:3e4}),x=""}rr("browser")&&!document.hasFocus()&&Na("👁️ View Request",`${p} wants to view your session`,`view-request-${g}`)}else t.event==="team:view_request_approved"?(x="✅ View request approved",N="success"):t.event==="team:view_request_rejected"&&(x=`❌ ${t.targetName||"Team member"} declined your view request`,N="warning");if(x){const p=Date.now();this.emitToast({id:p,message:x,type:N,timestamp:p,targetKey:n||t.daemonId,duration:5e3})}}}const nt=new Fm,Jo=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 Hm(e){const t=wn(e);return!t||!nn(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function Ir(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 Ar(e){const t=wn(e);return!!t&&t.success===!1}function Um(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 zm(e,t){return e&&Ms(e.currentValue)?e.currentValue:t}function Vm(e,t){return Ms(t)?Ms(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Gm(e,t){var i,c;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(Ms(l))return l}const n=(i=t.controlValues)==null?void 0:i[e];if(Ms(n))return n;const a=(c=t.defaultValues)==null?void 0:c[e];return Ms(a)?a:void 0}function Ur(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 Ym(e,t,r){var n;return((n=qm[t])==null?void 0:n.has(r.id))===!0}function eo(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Ym(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function En(e,t){return{value:t}}function Xm(e,t,r){var a;return r?((a=Ur(e,t).find(i=>i.value===r))==null?void 0:a.label)||r:""}const Jm={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Qm({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=gt(),d=`${e}:${t||n}`,m=Jm[n]||"#94a3b8",[u,f]=o.useState({}),x=o.useRef({}),N=o.useRef(c);x.current=u,N.current=c;const y=o.useRef(0),p={};for(const A of i||[])A.defaultValue!==void 0&&(p[A.id]=A.defaultValue);const g={...p,...c||{},...Date.now()<y.current?u:{}};o.useEffect(()=>{c&&Date.now()>y.current&&f({})},[c]);const[b,h]=o.useState(Jo.get(d)||{}),[C,S]=o.useState(null),[v,M]=o.useState(null),I=o.useCallback(async(A,F={})=>{const _={...F,...t&&{targetSessionId:t}};return await l(e,A,_)},[e,t,l]),j=o.useCallback(async(A,F={})=>{const _=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await I("invoke_provider_script",{..._,scriptName:A,...F})},[I,n,r,t]),w=o.useCallback((A,F,_)=>{const E=zm(_,F);f(K=>({...K,[A.id]:E})),Um(_==null?void 0:_.effects)},[]),B=o.useCallback((A,F)=>{f(_=>{const E={..._};return F===void 0?delete E[A.id]:E[A.id]=F,E}),y.current=0},[]);if(!i||i.length===0)return null;const P=eo(i,{hostIdeType:r,providerType:n});if(P.length===0)return null;const T=async A=>{if(C===A.id){S(null);return}if(Ur(A,b).length>0){S(A.id);return}if(A.dynamic&&A.listScript){M(A.id);try{const _=await j(A.listScript,{}),E=Hm(_);if(!E){const be=Us(_);be&&nt.showToast(be,"warning");return}const K=E.options;h(be=>{const ce={...be,[A.id]:K};return Jo.set(d,ce),ce});const Y=Gm(A.id,{localOverrideUntil:y.current,localValues:x.current,controlValues:N.current,defaultValues:p});if(Vm(Y,E.currentValue)){const be=E.currentValue;f(ce=>({...ce,[A.id]:be}))}S(A.id)}catch(_){const E=_ instanceof Error?_.message:`Could not load ${A.label}`;nt.showToast(E,"warning")}finally{M(null)}}},H=async(A,F)=>{S(null);const _=(c==null?void 0:c[A.id])??p[A.id];f(E=>({...E,[A.id]:F})),y.current=Date.now()+5e3;try{if(!A.setScript)return;const E=await j(A.setScript,En(A,F)),K=Ir(E);if(K&&!K.ok||Ar(E))throw new Error((K==null?void 0:K.error)||Us(E)||`Could not update ${A.label}`);w(A,F,K)}catch(E){B(A,_);const K=E instanceof Error?E.message:`Could not update ${A.label}`;nt.showToast(K,"warning")}},z=async A=>{const F=Ur(A,b).map(ce=>ce.value);if(F.length===0)return;const _=String(g[A.id]||""),K=(F.indexOf(_)+1)%F.length,Y=F[K];if(typeof Y!="string")return;const be=(c==null?void 0:c[A.id])??p[A.id];f(ce=>({...ce,[A.id]:Y})),y.current=Date.now()+5e3;try{if(!A.setScript)return;const ce=await j(A.setScript,En(A,Y)),D=Ir(ce);if(D&&!D.ok||Ar(ce))throw new Error((D==null?void 0:D.error)||Us(ce)||`Could not update ${A.label}`);w(A,Y,D)}catch(ce){B(A,be);const D=ce instanceof Error?ce.message:`Could not update ${A.label}`;nt.showToast(D,"warning")}},R=async A=>{const _=!g[A.id],E=(c==null?void 0:c[A.id])??p[A.id];f(K=>({...K,[A.id]:_})),y.current=Date.now()+5e3;try{if(!A.setScript)return;const K=await j(A.setScript,En(A,_)),Y=Ir(K);if(Y&&!Y.ok||Ar(K))throw new Error((Y==null?void 0:Y.error)||Us(K)||`Could not update ${A.label}`);w(A,_,Y)}catch(K){B(A,E);const Y=K instanceof Error?K.message:`Could not update ${A.label}`;nt.showToast(Y,"warning")}},k=async A=>{if(!A.invokeScript)return;if(A.confirmMessage){const _=[A.confirmTitle,A.confirmMessage,A.confirmLabel].filter(K=>typeof K=="string"&&K.trim().length>0);if(!window.confirm(_.join(`
|
|
28
|
+
|
|
29
|
+
`)))return}const F=(c==null?void 0:c[A.id])??p[A.id];try{const _=await j(A.invokeScript),E=Ir(_);if(E&&!E.ok||Ar(_))throw new Error((E==null?void 0:E.error)||Us(_)||`Could not run ${A.label}`);E&&w(A,F??!0,E)}catch(_){B(A,F);const E=_ instanceof Error?_.message:`Could not run ${A.label}`;nt.showToast(E,"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 F=String(g[A.id]||""),_=Xm(A,b,F),E=C===A.id,K=v===A.id,Y=Ur(A,b),be="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:`${be} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:E?`${m}55`:"var(--border-default)",background:E?`${m}10`:"var(--surface-tertiary)",color:F?"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:K?"Loading…":_||A.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),E&&Y.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>S(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}),Y.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===F?`${m}14`:"transparent",color:ce.value===F?"var(--text-primary)":"var(--text-secondary)",borderLeft:ce.value===F?`2px solid ${m}`:"2px solid transparent"},title:ce.description||ce.label,onMouseEnter:D=>{D.currentTarget.style.background=`${m}10`},onMouseLeave:D=>{D.currentTarget.style.background=ce.value===F?`${m}14`:"transparent"},onClick:()=>void H(A,ce.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ce.label}),ce.value===F&&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:`${be} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:F?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void z(A),title:`Click to cycle: ${Y.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:`${be} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:F?`${m}44`:"var(--border-default)",background:F?`${m}14`:"var(--surface-tertiary)",color:F?m:"var(--text-muted)"},onClick:()=>void R(A),"aria-pressed":!!F,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:`${be} 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"&&F?`${A.label}: ${F}`: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:F?"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:F?`${A.label}: ${F}`:A.label})]},A.id);default:return null}})]})})}function Zm({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:d}){const{isVisible:m}=Ja(),u=eo(l,{hostIdeType:a,providerType:i});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(Qm,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:u,controlValues:d})})}function ef({hasDraft:e,isBusy:t=!1}){return!e||t}const Mc=o.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:d=!1,animateVisibility:m=!0,onControlsToggle:u}){const f=o.useRef(null),[x,N]=o.useState(""),y=o.useRef(!1),{isVisible:p,toggleVisibility:g}=Ja();o.useEffect(()=>{N("")},[t]),o.useEffect(()=>{var h;l&&((h=f.current)==null||h.focus({preventScroll:!0}))},[t,l]);const b=async()=>{const h=x.trim();if(!(!h||a)&&!y.current){y.current=!0;try{await c(h)!==!1&&N("")}finally{y.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:()=>{g(),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:i||`Send message to ${r}...`,value:x,onChange:h=>N(h.target.value),onPaste:h=>{const C=h.clipboardData.getData("text");C&&N(S=>S+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:ef({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"})})})]}),i&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),tt=e=>e.transport==="pty",Ws=(e,t)=>tt(e)?e.mode||"terminal":"chat",Ic=(e,t)=>tt(e)&&Ws(e)==="terminal",Ze=e=>e.transport==="acp",tf=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 Ac(e){return e.machineName||""}function xr(e){return ys(e)}function Kt(e){return e.agentType||""}function an(e){return e.hostIdeType||""}function to(e){return e.displayPrimary||e.agentName||"Agent"}function Rc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function sf(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Lc(e){const t=sf(e),r=Rs(t==null?void 0:t.content),n=Rs(e.lastMessagePreview);return r||n||""}function rf(e,t=tf){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 nf(e){return rf(Lc(e)||e.displaySecondary||"")}function Pc(e){return[e.displaySecondary,Ac(e)].filter(Boolean)}function Ps(e){return e.agentName||it(Kt(e))}function af(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 Qo(e){return Jt(e)?"native":e.tabKey}function of(e){return e.sessionId}function cf(e,t){if(t)return Jt(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function lf(e,t){const r=Kt(e),n=Jt(e),a=tt(e)||Ze(e),i=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:Ic(e),providerType:r,displayLabel:i,targetEntry:cf(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?xr(e):""}function zs(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function so(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function df(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 Dc(){return"select_session"}function uf(){return"open_panel"}function mf({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function ff(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Zo(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 ro(e){return e instanceof Error?e.message:String(e||"")}function ei(e){const t=ro(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function ti(e,t){const r=ro(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,i]=o.useState(!1),[c,l]=o.useState(!1),[d,m]=o.useState(null),u=o.useRef(!1),f=o.useRef(null);o.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const x=o.useCallback(async g=>{if(!t||u.current)return!1;const b=g.trim(),h=so(t);if(mf({hasMessage:!!b,blockedMessage:h,sendInFlight:u.current}))return h&&m(h),!1;const C=Date.now(),S={tabKey:t.tabKey,message:b,timestamp:C};if(ff(f.current,S))return m(null),!0;u.current=!0,l(!0),m(null),f.current=S;try{const v=_s(t);if(!v)return f.current=Zo(f.current,S),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=ro(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=Zo(f.current,S),m(df(v)),!1}finally{u.current=!1,l(!1)}},[t,e]),N=o.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(g){console.error("Relaunch failed",g)}},[t,e]),y=o.useCallback(async g=>{if(t)try{const h=(t.modalButtons||[]).indexOf(g),C=g.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(C),v=_s(t);if(!v)return;const M=await e(v,"resolve_action",{button:g,action:S?"approve":"reject",...h>=0&&{buttonIndex:h},...as(t)}),I=on(M);I.success||r(j=>[...j,{routeId:t.tabKey,text:ti(g,I==null?void 0:I.error),timestamp:Date.now()}])}catch(b){ei(b)||console.error("[ModalButton] Error:",b),r(h=>[...h,{routeId:t.tabKey,text:ei(b)?ti(g,b):`❌ **${g}** error`,timestamp:Date.now()}])}},[t,e,r]),p=o.useCallback(async()=>{if(!(!t||a)){i(!0);try{await e(t.routeId,uf(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(g){console.error("Focus agent failed",g)}finally{i(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:x,handleRelaunch:N,handleModalButton:y,handleFocusAgent:p}}const pf=10,hf=8e3,xf=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function bf(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 Ca(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(xf.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=bf(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=>Ca(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,Ca(a,n,r+1)]))}function Vs(e,t){return Array.isArray(e)?e.slice(-t):[]}function gf(e,t=Date.now()){const r=e&&t-e.firstAt<=hf,n=r?e.count+1:1;return n>=pf?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function Ec(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(i=>i.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 Ca(r)}function $c(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 Bc(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 Oc(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 $n(e,t){return`${e}:${t}`}function yf(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Gs(e,t){yf()&&console.debug(`[subscription-manager] ${e}`,t)}class vf{constructor(){Xe(this,"active",new Map);Xe(this,"retryTimers",new Map)}subscribe(t,r,n,a,i){var u;const c=$n(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&&(i!=null&&i.retryIntervalMs)&&this.scheduleRetry(c,t,i.retryIntervalMs)}const m=()=>{var N;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}),(N=t.sendData)==null||N.call(t,r,x)};return m.initialSendAccepted=d,m}publish(t){const r=$n(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=$n(t,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.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(i=>i.daemonId===t);Gs("resubscribe_daemon",{daemonId:t,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(a=r.sendData)==null||a.call(r,i.daemonId,i.request)}scheduleRetry(t,r,n){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var l;this.retryTimers.delete(t);const i=this.active.get(t);if(!i)return;const c=((l=r.sendData)==null?void 0:l.call(r,i.daemonId,i.request))??!1;Gs("subscribe_retry",{id:t,accepted:c,topic:i.request.topic,key:i.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 vf;function wf(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 i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const c=r.get(i.id)||{};r.set(i.id,{...c,...i})}}return r}function jf(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:i,timestamp:c}=t,l=c||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:m,childrenByParent:u}=jf(d),f=wf(i,n),x=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,N=m.filter(g=>g.kind==="workspace"&&g.transport==="cdp-page"),y=m.filter(g=>g.kind==="agent"&&g.transport==="pty"),p=m.filter(g=>g.kind==="agent"&&g.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:N.some(g=>!!g.cdpConnected)});for(const g of N){const b=f.get(g.id),h=er(g,b),C=(u.get(g.id)||[]).map(S=>er(S,f.get(S.id)));r.push({id:`${n}:ide:${g.id}`,sessionId:g.id,providerSessionId:g.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:g.id,workspace:h.workspace,terminals:0,childSessions:C,agents:C.map(S=>({id:S.id,name:S.providerName||S.providerType,type:S.providerType,status:S.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 g of y){const b=f.get(g.id),h=er(g,b);r.push({id:`${n}:cli:${g.id}`,sessionId:g.id,providerSessionId:g.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:g.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 g of p){const b=f.get(g.id),h=er(g,b);r.push({id:`${n}:acp:${g.id}`,sessionId:g.id,providerSessionId:g.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:g.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 kf=15e3,Sf=15e3,Nf=6e4,Cf=1200,si=12,Tf=8e3,Mf=4e3,Bn=new Map,On=new Map,Rr=new Set,nr=new Map;function If(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 ri(e,t){const r=nr.get(e);!r||r.size===0||(nr.delete(e),r.forEach(n=>n(t)))}function Af(e,t){return new Promise(r=>{const n=nr.get(e)||new Set;nr.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&nr.delete(e),r(c)},i=setTimeout(()=>a(!1),t);n.add(a)})}function br(){const{sendCommand:e,sendData:t}=gt(),{injectEntries:r,getIdes:n}=dr();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??Nf,l=On.get(a)||0;if(!(i!=null&&i.force)&&Rr.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const d=Bn.get(a);if(d)return d;const m=(async()=>{if(t&&!Rr.has(a)){const p=Ut.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},g=>{const b=n(),h=b.find(S=>S.id===a),C=cn(g.status,{daemonId:a,existingDaemon:h,existingEntries:b,timestamp:g.timestamp});C.length>0&&r(C),On.set(a,Date.now()),ri(a,!0)});if(p.initialSendAccepted?Rr.add(a):Rr.delete(a),!(i!=null&&i.force)&&p.initialSendAccepted&&await Af(a,Cf))return}const u=await e(a,"get_status_metadata"),f=If(u);if(!f)return;const x=n(),N=x.find(p=>p.id===a),y=cn(f,{daemonId:a,existingDaemon:N,existingEntries:x,timestamp:f.timestamp||Date.now()});y.length>0&&r(y,{authoritativeDaemonIds:[a]}),On.set(a,Date.now()),ri(a,!0)})().finally(()=>{Bn.delete(a)});return Bn.set(a,m),m},[n,r,e,t])}function Rf(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const Lf=60,Pf=50;function Kc(e={}){return e.isCliLike?Pf:Lf}function _f(e={}){return Kc(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 Wc(e){return St(e.providerSessionId)||St(e.sessionId)||St(e.tabKey)||St(e.routeId)}function no(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 Df(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 ao(e){return Ht("provider",e.providerSessionId)||Ht("session",e.sessionId)||Ht("tab",e.tabKey)||Ht("route",e.routeId)||"unknown:"}function gr(e){return no(e)[0]}function Ef(e){const t=St(e.providerSessionId),r=St(e.sessionId),n=St(e.tabKey),a=St(e.routeId),i=[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=ao({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:Wc({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:gr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function Ta(e,t){const r=Ef(e);return Df(t).some(n=>r.lookupKeys.includes(n))}const yr=60,$f=1e3,oo=12e4,Bf=new Set(["generating","waiting_approval","starting","streaming","working"]),ni=new Map;function Fc(e,t){return`${e}::${t}`}function Ma(e=yr){return{liveMessages:[],hasLiveSnapshot:!1,cursor:Of([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Of(e,t=yr){return{tailLimit:t}}function ai(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 Kf{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=Ma(Math.max(0,t.tailLimit??yr))}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),i=await t({offset:this.snapshot.historyOffset,excludeRecentCount:a}),c=Array.isArray(i.messages)?i.messages:[],l=!n&&c.length===0&&i.hasMore!==!0&&this.fallbackRecentCount>0;this.snapshot={...this.snapshot,historyMessages:[...c,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+c.length,hasMoreHistory:l?!0:i.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:$f}))}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};ai(this.snapshot.liveMessages)===ai(r)&&this.snapshot.cursor.tailLimit===n.tailLimit||(this.snapshot={...this.snapshot,liveMessages:r,hasLiveSnapshot:!0,cursor:n},this.emit())}}function Hc(e){const t=Fc(e.daemonId,e.sessionId),r=ni.get(t);if(r)return r.updateOptions(e),r;const n=new Kf(e);return ni.set(t,n),n}function Wf(e,t){return{...e,loadHistoryPage:t}}function Ff(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Hf(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Bf.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??oo)),i=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return i>0?n-i<=a:Array.isArray(e.messages)&&e.messages.length>0}function Uf(e=oo){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function zf(e,t={}){const r=new Set,n=[];for(const a of e){if(!Hf(a,t))continue;const i=xr(a),c=a.sessionId||"";if(!i||!c)continue;const l=Fc(i,c);if(r.has(l))continue;r.add(l);const d=gr(a);n.push({daemonId:i,sessionId:c,historySessionId:d||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(Ff),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Vf(e,t){const{sendData:r,sendCommand:n}=gt(),a=(t==null?void 0:t.enabled)!==!1,i=xr(e),c=e.sessionId||"",l=gr(e)||c,d=`daemon:${i}:session:${c}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??yr),u=o.useMemo(()=>!a||!i||!c?null:Hc({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:d,sendData:r,tailLimit:m,fallbackRecentCount:e.messages.length}),[e.messages.length,i,a,l,r,c,d,m]),[f,x]=o.useState(()=>(u==null?void 0:u.getSnapshot())||Ma(m));o.useEffect(()=>{if(!u){x(Ma(m));return}u.retain(),x(u.getSnapshot());const y=u.subscribe(p=>{x(p)});return()=>{y(),u.release()}},[u,m]);const N=o.useCallback(async()=>{!u||!i||!c||await u.loadHistoryPage(async({offset:y,excludeRecentCount:p})=>{const g=e.agentType,b=await n(i,"chat_history",{agentType:g,offset:y,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,i,l,n,c]);return o.useMemo(()=>Wf(f,N),[N,f])}function Gf(e,t){const{sendData:r}=gt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??yr),i=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??oo)),c=Uf(i),[l,d]=o.useState(0);o.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(f=>f+1)},c);return()=>{clearInterval(u)}},[e.length,n,c]);const m=o.useMemo(()=>zf(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const u=m.descriptors.map(f=>Hc({...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 oi(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 Yf(e,t){if(e.length===0)return[];if(t.some(oi))return[];const r=[],n=new Set;for(let a=e.length-1;a>=0&&r.length<2;a-=1){const i=e[a];if(!i||!oi(i))continue;const c=String(i.role||"").toLowerCase();n.has(c)||(n.add(c),r.unshift(i))}return r}function Xf(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,a=Math.max(0,r.length-n),i=a>0?r.slice(0,a):[],c=a>0?r.slice(-n):r,l=Yf(i,c),d=l.length>0?[...l,...c]:c;return t.length===0?d:[...t,...d]}function Jf(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Qf(e){return Jf(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function Zf(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function ep(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function tp(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Uc(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function zc(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 sp(e){return Uc(e)?!1:e.inboxBucket==="task_complete"&&zc(e).length>0}function ii(e){return e.branch||"detached HEAD"}function rp(e){if(e.error)return`${ii(e)} · Git error: ${e.error}`;const t=[ii(e)];return e.changedFiles>0?t.push(Zf(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 np(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${rp(t)}`}function ap(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function op(e,t={}){if(t.enabled===!1)return[];if(!tp(e))return[];const r=Uc(e)?"working":sp(e)?"complete":null;if(!r)return[];const n=r==="complete"?zc(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${ep(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:np(r,e.git),timestamp:ap(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 ip=60;function Ia({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:d,scrollToBottomRequestNonce:m,isInputActive:u=!0,isVisible:f=!0}){var le,ye,se,ue,ke,he,ve;const x=o.useRef(new Map),N=o.useRef(void 0),y=br(),{sendCommand:p}=gt(),{isVisible:g}=Ja();hr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const b=Ct.useMemo(()=>Ks(e),[e.status,e.connectionState]),h=o.useMemo(()=>lf(e,t),[e,t]),C=o.useMemo(()=>{var ee;return eo((ee=h.targetEntry)==null?void 0:ee.providerControls,{hostIdeType:e.hostIdeType,providerType:h.providerType})},[e.hostIdeType,h.providerType,(le=h.targetEntry)==null?void 0:le.providerControls]),S=Kc({isCliLike:h.isCli||h.isAcp}),v=_f({isCliLike:h.isCli||h.isAcp}),M=Vf(e,{enabled:f&&!!e.sessionId,tailLimit:v}),[I,j]=o.useState(S),w=e.tabKey,B=M.historyMessages,P=M.hasMoreHistory,T=M.historyError,H=qf(e,M);o.useEffect(()=>{j(S)},[S,w]);const z=Math.max(0,H.length-I),R=to(e),k=xr(e),A=Qf(e),F=so(e),_=a||F,E=!!F,[K,Y]=o.useState(!1);o.useEffect(()=>{const ee=h.targetEntry;k&&(!ee||ee.providerControls===void 0||ee.controlValues===void 0)&&y(k,{minFreshMs:3e4}).catch(()=>{})},[k,h.isAcp,(ye=h.targetEntry)==null?void 0:ye.providerControls,(se=h.targetEntry)==null?void 0:se.controlValues,y]);const be=o.useCallback(async()=>{if(!K){if(H.length>I){j(ee=>Math.min(H.length,ee+ip));return}Y(!0);try{await M.loadHistoryPage()}finally{Y(!1)}}},[M,K,H.length,I]),{allMessages:ce,receivedAtMap:D}=o.useMemo(()=>{const ee=Xf({historyMessages:B,liveMessages:H,visibleLiveCount:I}),pe=op(e),oe=pe.length>0?[...ee,...pe]:ee,de={};return oe.forEach((ae,Q)=>{const me=`${e.tabKey}:${tn(ae,Q)}`;let J=Rf(ae)||x.current.get(me)||0;J||(J=Date.now(),x.current.set(me,J)),de[tn(ae,Q)]=J}),{allMessages:oe,receivedAtMap:de}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,z,B,H,I]),ie=o.useMemo(()=>l.filter(ee=>ee.routeId===e.tabKey).sort((ee,pe)=>ee.timestamp-pe.timestamp),[l,e.tabKey]),fe=o.useCallback(async()=>{var Q,me;if(!k)return;const ee=Ec({activeConv:e,visibleMessages:ce,actionLogs:l,controls:(Q=h.targetEntry)==null?void 0:Q.providerControls,controlValues:(me=h.targetEntry)==null?void 0:me.controlValues,visibleBarControlCount:C.length,chatTailState:{liveMessages:M.liveMessages,hasLiveSnapshot:M.hasLiveSnapshot,hasMoreHistory:P,historyError:T,historyMessages:B},ui:{controlsVisible:g,visibleLiveCount:I,hiddenLiveCount:z,isInputActive:u,isVisible:f}}),pe=await p(k,"get_chat_debug_bundle",{agentType:h.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:ee}),oe=on(pe),de=Oc(oe),ae=await Bc(de);ae==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),nt.showToast($c(oe,{locatorCopyStatus:ae}),ae==="failed"?"warning":"success")},[e,l,ce,g,M.hasLiveSnapshot,M.liveMessages,h.providerType,(ue=h.targetEntry)==null?void 0:ue.controlValues,(ke=h.targetEntry)==null?void 0:ke.providerControls,k,P,z,B,u,f,T,p,C.length,I]),xe=o.useCallback(()=>{const ee=gf(N.current);N.current=ee.state,ee.shouldCollect&&fe().catch(pe=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",pe),nt.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[fe]),X=o.useMemo(()=>{if(H.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")&&Y(!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:i,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 ",R," 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(uc,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ps,{size:14})," Open ",R," 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"&&!K)return!P&&B.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,i,P,B.length,c,K,H.length,R,b.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[s.jsx(Xu,{messages:ce,actionLogs:ie,agentName:Ps(e)||R||"Agent",userName:d,isCliMode:h.isCli||h.isAcp,isWorking:b.isGenerating,contextKey:e.tabKey,receivedAtMap:D,lastMessageHash:e.lastMessageHash,onLoadMore:be,isLoadingMore:K,hasMoreHistory:P,hiddenLiveCount:z,loadError:T??void 0,emptyState:X,scrollToBottomRequestNonce:m,isVisible:f}),s.jsx(Zm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:h.providerType,displayLabel:h.displayLabel,controls:(he=h.targetEntry)==null?void 0:he.providerControls,controlValues:(ve=h.targetEntry)==null?void 0:ve.controlValues,isActive:u,isCliTerminal:h.isCliTerminal}),!h.isCliTerminal&&s.jsx(Mc,{contextKey:e.tabKey,panelLabel:R,isSending:n,isBusy:E,statusMessage:_,onSend:r,isActive:u,showControlsToggle:C.length>0,onControlsToggle:xe})]})}let Vc=Zt;function Gc(){return Vc()}class cp{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 qc=new cp;class lp{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 lp;function dp(e){e.dashboardWS&&(qc=e.dashboardWS),e.connectionManager&&(ut=e.connectionManager),e.useDaemonsHook&&(Vc=e.useDaemonsHook)}const up=.5,mp=1.25;function lt(e){return to(e)}function xs(e){return Pc(e).join(" · ")}function Yc(e){const t=Lc(e);return t||(e.title?e.title:xs(e)||"No messages yet")}function Xc(e,t){const{isReconnecting:r,isConnecting:n}=Ks(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function fp(e,t){const r=["Chat",...Pc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function os(e){return Xc(e)||xs(e)}function pp(e){return`${lt(e)} · ${Yc(e)}`}function hp(e){const t=an(e),r=t?it(t):Ps(e);return`${lt(e)} — ${r||"Agent"}`}function xp(e){return Ps(e)||"CLI"}function Jc(e){return Rc(e)}function Qc(e){return e?`Remote · ${lt(e)||e.workspaceName||"Session"}`:"Remote"}function bp({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var te;Zt();const{sendPtyInput:d}=gt(),[m,u]=o.useState(!1),f=o.useRef(!1);f.current=m;const[x,N]=o.useState("Runtime terminal unavailable"),[y,p]=o.useState(!1),[g,b]=o.useState(null),[h,C]=o.useState(!1),[S,v]=o.useState(!1),[M,I]=o.useState(1),[j,w]=o.useState(!1),[B,P]=o.useState({width:0,height:0}),[T,H]=o.useState({width:0,height:0}),[z,R]=o.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[k,A]=o.useState(null),F=o.useRef(null),_=o.useRef(null),E=o.useRef(!1),K=o.useRef(!1),Y=o.useRef(c),be=o.useRef(0),ce=o.useRef(!1),D=o.useRef(""),ie=o.useRef(null),fe=o.useRef(!1),xe=o.useRef(!1),X=o.useRef(null),le=o.useRef(null),ye=o.useRef(null),se=32*1024,ue=()=>{var $,q,Z,re;return((q=($=F.current)==null?void 0:$.ownerDocument)==null?void 0:q.defaultView)||((re=(Z=_.current)==null?void 0:Z.ownerDocument)==null?void 0:re.defaultView)||window},ke=$=>{const q=ue();return{ownerWindow:q,frameId:q.requestAnimationFrame($)}},he=()=>{const $=X.current;if($){try{$.ownerWindow.cancelAnimationFrame($.frameId)}catch{}X.current=null}},ve=()=>{const $=le.current;if($){try{$.ownerWindow.clearTimeout($.timeoutId)}catch{}le.current=null}},ee=()=>{const $=ye.current;if($){try{$.ownerWindow.clearTimeout($.timeoutId)}catch{}ye.current=null}},pe=()=>{c&&X.current===null&&(X.current=ke(()=>{st()}))},oe=e.tabKey,de=e.sessionId||"",ae=e.daemonId||((te=e.routeId)==null?void 0:te.split(":")[0])||e.routeId||"",Q=so(e),me=m?i||Q:x,J=up,Ae=mp,Te=.05,$e=()=>{const $=T.width,q=T.height;if(!Number.isFinite(B.width)||B.width<=0||!Number.isFinite(B.height)||B.height<=0||!Number.isFinite($)||$<=0||!Number.isFinite(q)||q<=0)return 1;const Z=B.width/$,re=B.height/q;return Number(Math.min(Ae,Math.max(J,Math.min(Z,re))).toFixed(2))},Ue=$e(),O=E.current&&M>Ue,Se=Number.isFinite(T.width)&&T.width>0?Math.max(B.width,Math.round(T.width*M)):B.width,Me=Number.isFinite(T.height)&&T.height>0?Math.max(B.height,Math.round(T.height*M)):B.height,De=()=>{ke(()=>{const $=_.current;$&&($.scrollLeft=0,$.scrollTop=$.scrollHeight-$.clientHeight)})},Oe=()=>{var $,q;be.current=0,ce.current=!1,D.current="",ie.current=null,fe.current=!1,xe.current=!1,E.current||(K.current=!1,I(1)),X.current!==null&&he(),u(!1),N("Runtime terminal unavailable"),ee(),ve(),b(null),A(null),w(!1),p(!1),C(!1),v(!1),(q=($=r.current)==null?void 0:$.reset)==null||q.call($)},He=()=>{var $,q;be.current=0,ce.current=!1,D.current="",ie.current=null,fe.current=!1,xe.current=!1,X.current!==null&&he(),u(!0),N(""),ee(),ve(),b(null),A(null),w(!1),p(!1),C(!1),v(!1),(q=($=r.current)==null?void 0:$.reset)==null||q.call($)},Je=()=>{xe.current&&(xe.current=!1,ke(()=>{var $,q;(q=($=r.current)==null?void 0:$.scrollToTop)==null||q.call($)}))},st=()=>{if(X.current=null,!c)return;const $=D.current;if(!$)return;const q=$.slice(0,se);D.current=$.slice(q.length);const Z=r.current;if(!Z){D.current=q+D.current,pe();return}Z.write(q,()=>{if(D.current.length>0){pe();return}Je()})},mt=$=>{$&&(D.current+=$,pe())},ht=($,q=0,Z,re,je={})=>{var _e,Ne,Ee,Be;const Le=!!je.force;!Le&&q>0&&be.current>=q||!Le&&q===0&&ce.current||(be.current=q,q>0&&C(!0),u(!0),N(""),typeof Z=="number"&&typeof re=="number"&&Z>0&&re>0&&((Ne=(_e=r.current)==null?void 0:_e.resize)==null||Ne.call(_e,Z,re)),D.current="",(Be=(Ee=r.current)==null?void 0:Ee.reset)==null||Be.call(Ee),$?mt($):Je())};o.useEffect(()=>{Oe()},[de]),o.useEffect(()=>{var q;if(!de)return;const $=((q=ut.onRuntimeEvent)==null?void 0:q.call(ut,de,Z=>{if(!(!Z||Z.sessionId!==de)){if(Z.type==="runtime_snapshot"){if(!c){ie.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"&&(be.current=Math.max(be.current,Z.seq),Z.seq>0&&C(!0)),f.current||u(!0),f.current||N(""),typeof Z.data=="string"&&mt(Z.data);return}if(Z.type==="session_cleared"){if(!c){fe.current=!0,D.current="",ie.current=null;return}He();return}if(Z.type==="session_io_error"){const re=typeof Z.error=="string"&&Z.error?Z.error:typeof Z.reason=="string"&&Z.reason?Z.reason:"unknown error";u(!1),N(`Runtime input failed: ${re}`);return}}},ae))||(()=>{});return()=>{$()}},[ae,de,r,c]);const xt=async($={})=>{var q;if(!ae||!de)return{success:!1,error:"daemonId and sessionId are required"};$.preserveStatus||N($.loadingMessage||"Loading runtime terminal...");try{const Z=await((q=ut.requestRuntimeSnapshot)==null?void 0:q.call(ut,ae,de,{sinceSeq:$.sinceSeq,force:$.force}));return Z&&Z.success===!1?($.preserveStatus||(u(!1),N(`Runtime terminal unavailable: ${Z.error}`)),Z):Z||{success:!0}}catch(Z){const re=(Z==null?void 0:Z.message)||String(Z);return $.preserveStatus||(u(!1),N(`Runtime terminal unavailable: ${re}`)),{success:!1,error:re}}},Ce=async $=>{var Le,_e;const q=((Le=F.current)==null?void 0:Le.ownerDocument)||document,Z=q.defaultView||window,re=(_e=Z.navigator)==null?void 0:_e.clipboard;if(re!=null&&re.writeText&&Z.isSecureContext)try{return await re.writeText($),!0}catch{}let je=null;try{return je=q.createElement("textarea"),je.value=$,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=$=>{ve(),A($);const q=ue();le.current={ownerWindow:q,timeoutId:q.setTimeout(()=>{le.current=null,A(Z=>Z===$?null:Z)},2200)}},Qe=$=>{ee(),b($);const q=ue();ye.current={ownerWindow:q,timeoutId:q.setTimeout(()=>{ye.current=null,b(Z=>Z===$?null:Z)},2200)}},Ge=async()=>{var je,Le,_e,Ne;const $=((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=$.trimEnd()||q.trimEnd();if(!Z){ze("Nothing to copy");return}if(!await Ce(Z)){ze("Copy failed");return}ze($.trimEnd()?"Copied selection":"Copied visible terminal")},rt=$=>{if(!m||!c)return;((d==null?void 0:d(ae,de,$))??!1)||ze("Terminal input failed")},W=async()=>{if(y)return;p(!0),b("Loading older terminal output..."),xe.current=!0;const $=await xt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(p(!1),($==null?void 0:$.success)===!1){xe.current=!1,b(`Older terminal output unavailable: ${$.error}`);return}v(!0),Qe("Older terminal output loaded"),ke(()=>{var q;(q=r.current)==null||q.bumpResize()})};o.useEffect(()=>{var q,Z;if(!de)return;ae&&((q=ut.getState)==null?void 0:q.call(ut,ae))==="connected"&&xt();const $=(Z=ut.onStateChange)==null?void 0:Z.call(ut,(re,je)=>{re!==ae||je!=="connected"||xt()});return()=>{$==null||$()}},[ae,de,r]),o.useEffect(()=>{t&&Oe()},[t,oe,r]),o.useEffect(()=>{var re,je;const $=F.current,q=(je=(re=$==null?void 0:$.ownerDocument)==null?void 0:re.defaultView)==null?void 0:je.ResizeObserver;if(!$||!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($),()=>Z.disconnect()},[]),o.useEffect(()=>{if(E.current)return;const $=$e();!Number.isFinite($)||$<=0||I(q=>K.current?$<q-Te?$:q:(K.current=!0,$))},[T.height,T.width,B.height,B.width]),o.useEffect(()=>{O&&De()},[O,Me,Se]),o.useEffect(()=>{var Z;const $=Y.current;if(Y.current=c,!c)return;$||v(!1),fe.current&&(fe.current=!1,He());const q=ie.current;q&&(ie.current=null,ht(q.text,q.seq,q.cols,q.rows,{force:!!q.force})),ae&&de&&((Z=ut.getState)==null?void 0:Z.call(ut,ae))==="connected"&&xt(),D.current&&X.current===null&&pe(),ke(()=>{var re;(re=r.current)==null||re.bumpResize()})},[ae,c,de]),o.useEffect(()=>()=>{X.current!==null&&he(),ve(),ee()},[]),o.useEffect(()=>{const $=re=>{var Le;const je=re.detail;je!=null&&je.sessionId&&je.sessionId!==de||m&&((Le=r.current)==null||Le.bumpResize())},q=ue(),Z=q===window?[window]:[window,q];for(const re of Z)re.addEventListener("adhdev:fit-cli-terminal",$);return()=>{for(const re of Z)re.removeEventListener("adhdev:fit-cli-terminal",$)}},[m,de,r]);const G=m&&h&&!S&&(z.atTop||!z.canScroll)||y||!!g;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:F,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:!de||y,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:y?"Loading older...":"Load older terminal output"}),g&&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:g})]}),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($=>!$),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:()=>{E.current=!0,I($=>{const q=Math.max(Ue,Number(($-.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:()=>{E.current=!0,I($=>{const q=Math.min(Ae,Number(($+.1).toFixed(2)));return q>Ue&&De(),q})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:_,className:O?"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(gc,{ref:r,readOnly:!m||!c,sizingMode:"measured",onViewportMetrics:H,onScrollMetrics:R,onInput:$=>{!m||(d==null||d(ae,de,$))}})})})}),!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(Mc,{contextKey:e.tabKey,panelLabel:lt(e),isSending:a,isBusy:!!Q,statusMessage:me,onSend:async $=>Q?!1:n($),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const gp=5e3,yp=12e3;function vp(e){return e==="disconnected"||e==="reconnecting"}function wp({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=gp,reconnectActionDelayMs:i=yp}){const c=vp(e),[l,d]=o.useState(()=>!c||a<=0),[m,u]=o.useState(()=>!c||i<=0),f=o.useRef(!1);o.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]),o.useEffect(()=>{if(!c){u(!1);return}if(i<=0){u(!0);return}u(!1);const v=setTimeout(()=>{u(!0)},i);return()=>clearTimeout(v)},[i,c]);const x=c?l:e==="offline"||e==="auth_failed",N=!!(n&&e!=="auth_failed"&&(!c||m)),y=o.useMemo(()=>!t||e!=="connected"?!1:a<=0||f.current,[a,t,e]),p=e==="auth_failed"?"red":e==="offline"?"orange":"accent",g={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",S={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:S,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:g[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.")]}),N&&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"})]})}),y&&s.jsx("div",{className:C,style:S,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 jp({terminalBackend:e,isStandalone:t=!1,machineLabel:r,machineKey:n}){const a=o.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,c]=o.useState(!1);if(o.useEffect(()=>{if(!a){c(!1);return}try{c(localStorage.getItem(a)==="1")}catch{c(!1)}},[a]),!t||!e||e.backend!=="xterm"||i)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 io({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(Ga,{size:n}):s.jsx(zt,{size:n})})}const Bt="New session",Zc="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 kp(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 Sp(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 Np(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=kp(e),a=Sp(e);if(!n||!a)return null;const i=[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 ${Np(a)} ${t}`.trim(),title:i.join(" · ")||n,"data-git-tone":a,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:n})]})}function Cp({wsStatus:e,isConnected:t,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),i=a.filter(l=>l==="connected").length,c=a.filter(l=>l==="connecting"||l==="new"||l==="checking").length;return r>0&&c>0&&i===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 ci({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function li({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){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(),i()},children:"Delete"})]})]})}function Tp({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:f,onShowAllHidden:x,onResetPanelsToMain:N,inboxOpen:y,onInboxOpenChange:p,hiddenOpen:g,onHiddenOpenChange:b,onOpenNewSession:h,onOpenDashboardGuide:C,guideNudgeVisible:S=!1,actionShortcuts:v,notifications:M,notificationUnreadCount:I,onOpenNotification:j,onMarkNotificationRead:w,onMarkNotificationUnread:B,onDeleteNotification:P,onOpenGitDialog:T}){const{ides:H,p2pStates:z={}}=Zt(),R=!!e&&tt(e)&&!Ze(e),k=!!e&&Ze(e),A=l||(e?Ic(e)?"terminal":"chat":null),[F,_]=o.useState(!1),E=o.useRef(null),K=o.useRef(null),Y=H.filter(se=>se.type==="adhdev-daemon"),be=Cp({wsStatus:t,isConnected:r,daemonCount:Y.length,p2pStates:z}),ce=be.subtitle,D=be.tone==="connected"?"#22c55e":be.tone==="limited"?"#eab308":"#ef4444",ie=be.tone==="connected"?"0 0 4px #22c55e80":be.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",fe=o.useMemo(()=>M.filter(se=>!se.readAt),[M]),xe=o.useMemo(()=>M.filter(se=>!!se.readAt),[M]),X=o.useMemo(()=>fe.slice(0,9),[fe]),le=I;o.useEffect(()=>{if(!y)return;const se=ue=>{var ke;(ke=E.current)!=null&&ke.contains(ue.target)||p(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[y,p]),o.useEffect(()=>{if(!g)return;const se=ue=>{var ke;(ke=K.current)!=null&&ke.contains(ue.target)||b(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[g,b]),o.useEffect(()=>{if(!g&&!y)return;const se=ue=>{if(!ue.altKey)return;const ke=ue.code.match(/^Digit([1-9])$/);if(!ke)return;const he=Number(ke[1])-1,ve=g?u[he]:void 0,ee=y?X[he]:void 0;if(!(!ve&&!ee)){if(ue.preventDefault(),ue.stopPropagation(),ve){f==null||f(ve),b(!1);return}ee&&(j(ee),p(!1))}};return window.addEventListener("keydown",se,!0),()=>window.removeEventListener("keydown",se,!0)},[u,g,y,X,b,p,j,f]);const ye=se=>{if(!se)return;const ue=n.find(ke=>ke.tabKey===se);ue&&(m==null||m(ue))};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:be.title,"aria-label":be.title,className:"header-title-status-dot",style:{background:D,boxShadow:ie}}),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:D,boxShadow:ie}})})]}),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(fc,{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:"?"}),S&&s.jsx("span",{children:"Guide"})]}),e&&(R||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"}),(R||k)&&c&&s.jsxs(s.Fragment,{children:[R&&d&&A&&s.jsx(io,{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(za,{size:14})}),!R&&!Ze(e)&&s.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Mt,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:E,children:[s.jsxs("div",{className:`dashboard-header-hidden${F?" is-drop-target":""}`,ref:K,onDragEnter:se=>{se.dataTransfer.types.includes("text/tab-key")&&(se.preventDefault(),_(!0))},onDragOver:se=>{se.dataTransfer.types.includes("text/tab-key")&&(se.preventDefault(),se.dataTransfer.dropEffect="move",_(!0))},onDragLeave:se=>{se.currentTarget.contains(se.relatedTarget)||_(!1)},onDrop:se=>{const ue=se.dataTransfer.getData("text/tab-key");se.preventDefault(),_(!1),ye(ue)},children:[s.jsxs("button",{type:"button",onClick:()=>b(!g),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(Va,{size:16}),u.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),g&&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(ci,{value:v==null?void 0:v.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[N&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:N,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(ci,{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(se=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{f==null||f(se),b(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:lt(se)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(se)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(se)+1]}):null,xs(se)]})]},se.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!y),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(bn,{size:16}),le>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:le})]}),y&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[fe.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),fe.map(se=>s.jsx(li,{notification:se,shortcutIndex:X.indexOf(se)>=0?X.indexOf(se)+1:void 0,onOpen:()=>j(se),onMarkRead:()=>w(se.id),onMarkUnread:()=>B(se.id),onDelete:()=>P(se.id)},se.id))]}),xe.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),xe.map(se=>s.jsx(li,{notification:se,onOpen:()=>j(se),onMarkRead:()=>w(se.id),onMarkUnread:()=>B(se.id),onDelete:()=>P(se.id)},se.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 Mp(e,t){return String(e||"")!==String(t||"")}function Ip(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),i=!!t.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(d=>String(d||"").toLowerCase()).join(`
|
|
39
|
+
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!kc(c.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
40
|
+
`).includes(a)))}function Ap(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 i=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(i!==0)return i}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function el(e,t={}){return Ap(Ip(e,t),t.sortMode||"recent")}function ln(e){return e?"Resume saved history":"Start fresh"}function co(e){return e?"Resuming saved history…":"Starting fresh…"}function Rp(){return"Start fresh"}function tl(e,t=!1){return e==="cli"?ln(t):e==="ide"?"Start IDE":"Start ACP session"}function sl(e,t=!1){return e==="cli"?co(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Lp(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Pp(){return"Open saved history"}function _p(){return"Saved History"}function lo(){return"Use saved history when you want continuity in the same provider conversation."}function Dp(){return"No saved history found yet."}function Ep(){return"Refresh saved history"}function $p(){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 uo(e){return`Resume saved history with ${e}?`}function mo(){return"Review or change the target workspace before resuming saved history."}function Bp(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 fo({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:m,onClose:u,onNewChat:f,onSwitchSession:x,onRefreshHistory:N,onResumeSavedSession:y}){var P;const p=t.find(T=>T.id===e.routeId),g=(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,S]=o.useState(()=>wt()),v=l||C,M=String(d||"").trim(),I=T=>{if(m){m(T);return}S(T)},j=o.useMemo(()=>a.map(T=>{const H=String(T.workspace||"").trim();return T.canResume||H||!M?T:{...T,workspace:M,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[M,a]),w=o.useMemo(()=>el(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]),B=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?_p():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:hp(e)}),h&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:lo()})]}),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 H=e.providerSessionId===T.providerSessionId,z=H||!T.canResume||!!c,R=T.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{z||!y||y(T)},disabled:z,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${H?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${z?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${H?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:T.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Bp(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",R?" · selected workspace":"",hs(T.summaryMetadata)?` · ${hs(T.summaryMetadata)}`:"",T.messageCount>0?` · ${T.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:H?"ACTIVE":T.canResume?R?"RESUME IN SELECTED WORKSPACE":c===T.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},T.id)})]}):g.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&&!i&&w.length===0||!h&&g.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(ju,{size:32})}),s.jsx("div",{className:"text-[13px]",children:h?a.length>0?"No saved history matches these filters.":Dp():"No recent chat sessions found."})]}),h&&i&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:$p()})})]}),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:N,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(pr,{size:13})," ",h?Ep():"Refresh History"]})})})]})]});return typeof document>"u"?B:lr.createPortal(B,document.body)}const di={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 rl({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=di[n.type]||di.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 i;(i=n.actions)!=null&&i.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:i=>{i.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((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.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)"}:i.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(),i.onClick(),t(n.id)},children:i.label},c))})]})]},n.id)})})}const Op=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Kp(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Wp(e){return e.sessionId||e.instanceId||e.agentType}function Kn(e,t){return e||t}function nl(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Tt(r,{fallbackId:r.id}));return t}function al(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 po(e,t={}){return Fp(e,al(e,t))}function Fp(e,t={}){var f,x,N,y,p;const r=[],n=t.machineName,a=t.connectionState,i=Kp(e),c=e.workspace||"",l=bm(e.type,{agentName:e.cliName}),d=tt(e)||Ze(e)?l:it(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(g=>{var b,h;return{sessionId:g.id,instanceId:g.id,providerSessionId:g.providerSessionId,transport:g.transport,sessionCapabilities:g.capabilities,agentType:g.providerType,agentName:g.providerName||it(g.providerType),status:g.status,title:g.title,lastMessagePreview:g.lastMessagePreview,lastMessageRole:g.lastMessageRole,lastMessageAt:g.lastMessageAt,lastMessageHash:g.lastMessageHash,messages:((b=g.activeChat)==null?void 0:b.messages)||[],activeModal:((h=g.activeChat)==null?void 0:h.activeModal)||void 0,unread:g.unread,lastSeenAt:g.lastSeenAt,lastUpdated:g.lastUpdated,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,surfaceHidden:g.surfaceHidden,git:g.git,settings:g.settings}}):[],u=Op(e);if(u){const g=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)":"",S=l+C,v=(N=e.activeChat)==null?void 0:N.activeModal,M=v&&Array.isArray(v.buttons)&&v.buttons.length>0,I=gm(e.activeChat,[{status:e.status,activeModal:(y=e.activeChat)==null?void 0:y.activeModal}],e.agents||[]),j=e.activeChat||{title:"",messages:[]};let w=j.title&&String(j.title).trim()?String(j.title).trim():"";const B=(p=e.activeChat)==null?void 0:p.id,P=e.chats;if(B&&Array.isArray(P)&&P.length>0){const R=P.find(k=>k.id===B||k.id&&String(k.id)===String(B));R!=null&&R.title&&String(R.title).trim()&&(w=String(R.title).trim())}const T=(tt(e)||Ze(e),e.type),H=(tt(e)||Ze(e))&&Yo(w,S,T)?"":w,z=j.messages||[];r.push({routeId:e.id,sessionId:g,providerSessionId:e.providerSessionId,nativeSessionId:g,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:tt(e)?e.mode||"terminal":"chat",agentName:S,agentType:T,status:I,title:H,messages:z,resume:e.resume,hostIdeType:!tt(e)&&!Ze(e)?e.type:void 0,workspaceName:i,workspacePath:c,git:e.git,displayPrimary:H||i||(tt(e)?e.mode==="chat"?S:`Terminal${C}`:S),displaySecondary:tt(e)&&i?S:d,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:M?v.buttons:void 0,modalMessage:M?v.message:void 0,streamSource:"native",tabKey:Kn(g,e.id),machineName:n,connectionState:a,settings:e.settings})}if(u&&(tt(e)||Ze(e)))return r;for(const g of m){const b=g.activeModal&&Array.isArray(g.activeModal.buttons)&&g.activeModal.buttons.length>0,h=ym(g),C=Wp(g),S=`${e.id}:${C}`,v=g.title&&String(g.title).trim()||"",M=Yo(v,g.agentName,g.agentType)?"":v,I=g.messages||[];(g.transport==="cdp-webview"||g.sessionId||g.providerSessionId||I.length>0||b||M||!["idle","panel_hidden","disconnected","not_monitored"].includes(h))&&r.push({routeId:e.id,sessionId:g.sessionId||g.instanceId,providerSessionId:g.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:g.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:g.sessionCapabilities,mode:"chat",agentName:g.agentName,agentType:g.agentType,status:h,title:M,messages:I,hostIdeType:e.type,workspaceName:i,workspacePath:c,git:g.git||e.git,displayPrimary:M||i||g.agentName||d,displaySecondary:`${d} · ${g.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:g.lastMessagePreview,lastMessageRole:g.lastMessageRole,lastMessageAt:g.lastMessageAt,lastMessageHash:g.lastMessageHash,lastUpdated:g.lastUpdated||e.lastUpdated,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,modalButtons:b?g.activeModal.buttons:void 0,modalMessage:b?g.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Kn(g.sessionId||g.instanceId,S),machineName:n,connectionState:a,settings:g.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:i,workspacePath:c,git:e.git,displayPrimary:i||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Kn(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings}),r}function Hp(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 ol(e,t){const r=Hp(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const il=[{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:"🏄"}],cl=[{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:"🧩"}],ll=[{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:"🟠"}],Up=il,zp=cl,Vp=ll;function Vt(...e){return Dd(Ed(e))}function Gp({icon:e,title:t,subtitle:r,badge:n,actions:a,className:i}){return s.jsxs("div",{className:Vt("dashboard-header",i),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 ar({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(Gp,{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",i,c),children:l})})]})}const Aa="adhdev:themechange";function qp(){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"?qp():e}function dl(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function zr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Aa,{detail:{preference:e,theme:t}}))}function Yp(){const e=js(),t=ks(e);dl(t),zr(e,t)}function ho(){const[e,t]=o.useState(js),[r,n]=o.useState(()=>ks(js()));o.useEffect(()=>{dl(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=d=>{if(e==="system"){const m=d.matches?"light":"dark";n(m),zr("system",m)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.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(Aa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(Aa,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=ks(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}zr(c,l)},[]),i=o.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",d=ks(l);n(d);try{localStorage.setItem("theme",l)}catch{}return zr(l,d),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const ui={dark:"Dark",light:"Light",system:"System"};function Xp({collapsed:e}){const{preference:t,cycleTheme:r}=ho(),n=t==="dark"?s.jsx(Su,{size:16}):t==="light"?s.jsx(ku,{size:16}):s.jsx(Nu,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${ui[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:ui[t]})]})}function Wn(e,t){return e?typeof e=="function"?e(t):e:null}function Jp({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:i,footerActions:c,preMainContent:l,collapsedStorageKey:d="sidebar-collapsed"}){const[m,u]=o.useState(!1),[f,x]=o.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),N=()=>u(!0),y=()=>u(!1),p=()=>{x(C=>{const S=!C;try{localStorage.setItem(d,S?"1":"0")}catch{}return S})},g=o.useMemo(()=>({collapsed:f,mobileMenuOpen:m,openMobileMenu:N,closeMobileMenu:y,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(),y()},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:N,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:y,onKeyDown:C=>C.key==="Escape"&&y()}),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:Wn(t,g)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:y,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),Wn(i,g),s.jsx(Xp,{collapsed:f}),Wn(c,g)]})]}),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:i}){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})]}),i]})}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 Qp={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"},Zp={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]",Qp[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Zp[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 qs(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 eh={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"},th={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function sh({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",eh[e],r),children:[s.jsx("span",{className:Vt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",th[e])}),n]})}function ss({label:e,description:t,checked:r,disabled:n,onChange:a,extra:i}){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:[i,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 rh({onPrefChange:e}){const[t,r]=Im(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.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 i=(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=>i("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=>i("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:()=>{Cc().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(Cu,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(ss,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Tu,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>i("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=>i("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 nh(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 ul(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function or(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||nh(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 ah(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Fn(e,t){return e instanceof Error?e.message:t}function oh({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.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:i.map(c=>s.jsx(ch,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function mi({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:i}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return lr.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,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:i,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 ih(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Up,...zp,...Vp].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 ch({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var z,R;const[i,c]=o.useState("idle"),[l,d]=o.useState(""),[m,u]=o.useState(null),[f,x]=o.useState("idle"),[N,y]=o.useState(""),p=e.version||null,g=((z=e.machine)==null?void 0:z.platform)||((R=e.system)==null?void 0:R.platform)||"",b=Tt(e,{fallbackId:e.id}),h=g==="win32"?"🪟":g==="darwin"?"🍎":"🐧",C=t.filter(k=>k.daemonId===e.id&&k.transport==="cdp-page"),S=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=ah(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(Fn(k,"Connection lost during upgrade"))}}},j=async()=>{if(u(null),!!n){x("loading");try{await n(e.id),x("done"),y("Machine disconnected.")}catch(k){x("error"),y(Fn(k,"Failed to disconnect"))}}},w=async()=>{if(u(null),!!a){x("loading");try{await a(e.id),x("done"),y("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(k){x("error"),y(Fn(k,"Failed to revoke token"))}}},B="0.9.75",P=ul(e,B),T=or(e,B),H=C.length+S.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:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${B}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${T?"↑ Update now":`↑ Update${` to v${B}`}`}`}),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(sh,{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&&H>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),H>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[C.map(k=>{const A=ih(k.type),F=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}),F!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${F?"bg-green-400":"animate-pulse"}`,style:F?void 0:{background:"var(--status-warning)"},title:F?"CDP connected":"CDP connecting..."})]},k.id)}),S.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||N)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-red-400":i==="done"||f==="done"?"text-green-400":"text-text-muted"}`,children:N||l})]}),m==="disconnect"&&s.jsx(mi,{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(mi,{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 lh=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function dh(){const{preference:e,setPreference:t}=ho();return s.jsx("div",{className:"flex gap-2",children:lh.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 uh(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 mh(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Hn(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function fi(e){const{r:t,g:r,b:n}=mh(e);return .2126*Hn(t)+.7152*Hn(r)+.0722*Hn(n)}function pi(e,t){const r=fi(e),n=fi(t),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function ml(e){const t=uh(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return pi(t,r)>=pi(t,n)?r:n}const Ra={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},La={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},fh=[{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"}}}],fl="adhdev-chat-theme",pl="adhdev-chat-theme-custom";function Vr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(fl)||"ember"}catch{return"ember"}}function Dt(e){try{const t=localStorage.getItem(pl);if(t){const r=JSON.parse(t);return{...e==="dark"?Ra:La,...r[e]}}}catch{}return e==="dark"?Ra:La}function Lr(e,t){try{localStorage.setItem(pl,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 ph={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function ir(e,t){var a;const r=(a=ph[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",ml(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",ml(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 xo(){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 hh(e){try{localStorage.setItem(fl,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ds()?"dark":"light";ls(Dt(t))}else xo(),ir(e,ds()?"dark":"light")}function xh(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Vr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ds()?"dark":"light";ls(Dt(t))}else xo(),ir(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 Ys({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 bh({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=o.useState(()=>Dt(r));o.useEffect(()=>{a(Dt(r))},[r]);const i=o.useCallback((c,l)=>{a(d=>{const m={...d,[c]:l},f=Dt(r==="dark"?"light":"dark");return r==="dark"?Lr(m,f):Lr(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(Ys,{title:"App Background",children:[s.jsx(kt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(kt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(kt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Ys,{title:"App Text",children:[s.jsx(kt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(kt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(kt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Ys,{title:"Borders & Accent",children:[s.jsx(kt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(kt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(kt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Ys,{title:"Chat Bubbles",children:[s.jsx(kt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(kt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),s.jsx(kt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(kt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Ys,{title:"Chat Layout",children:[s.jsx(kt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(kt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(kt,{label:"Input border",value:n.inputBorder,onChange:c=>i("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=>i("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?Ra:La,d=Dt(e?"light":"dark");e?Lr(c,d):Lr(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 gh(){const[e,t]=o.useState(Vr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Dt("dark"));o.useEffect(()=>{n(ds());const d=new MutationObserver(()=>{const f=ds();n(f);const x=Vr();x==="custom"?ls(Dt(f?"dark":"light")):ir(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=Vr();x==="custom"?ls(Dt(f?"dark":"light")):ir(x,f?"dark":"light")};return m.addEventListener("change",u),()=>{d.disconnect(),m.removeEventListener("change",u)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ls(Dt(r?"dark":"light")):(xo(),ir(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Dt(r?"dark":"light"))},[r]);const c=d=>{t(d),hh(d)},l=[...fh,{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(bh,{dark:r,onColorsChange:d=>i(d)})]})}const bo="adhdev_mobileDashboardMode_v1",Pa="adhdev:mobile-dashboard-mode-change";function go(){try{return localStorage.getItem(bo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function yh(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??go())},r=a=>{const i=a.detail;t(i)},n=a=>{a.key&&a.key!==bo||t()};return window.addEventListener(Pa,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Pa,r),window.removeEventListener("storage",n)}}function vh(e){try{localStorage.setItem(bo,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Pa,{detail:e}))}function wh(){const[e,t]=o.useState(!0);return o.useEffect(()=>{t(go()==="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),vh(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Un=new Map,hi=new Map;function jh(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 kh(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 hl(){const{sendCommand:e}=gt(),{injectEntries:t,getIdes:r}=dr();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??Sf,c=hi.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=Un.get(n);if(l)return l;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=jh(m);if(!u)return;const f=r().find(N=>N.id===n),x=kh(f,n,u.machine,u.timestamp||Date.now());t([x]),hi.set(n,Date.now())})().finally(()=>{Un.delete(n)});return Un.set(n,d),d},[r,t,e])}function Sh(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 Nh(e,t){const{sendData:r}=gt(),{injectEntries:n,getIdes:a}=dr(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const c=i?i.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(N=>N.id===d),x=Sh(f,d,u);n([x])}));return()=>{l.forEach(d=>d())}},[i,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function Ch(e,t){const{sendData:r}=gt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.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)},Mf):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:i,applyDiagnostics:a}}function Th(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function xl(e){const{sendData:t}=gt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=Th(e);if(!a||!e.sessionId||!t){n({});return}const i=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 i.initialSendAccepted||n({}),()=>{i()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const bl="adhdev_hiddenTabs";function Mh(){try{const e=localStorage.getItem(bl);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function vs(e){try{localStorage.setItem(bl,JSON.stringify([...e]))}catch{}}function zn(e){return ao(e)}function yo(e,t){return Is(t).some(r=>e.has(r))}function Ih(){const[e,t]=o.useState(Mh),r=o.useCallback(m=>{const u=zn(m);t(f=>{const x=new Set(f);return x.has(u)?x.delete(u):x.add(u),vs(x),x})},[]),n=o.useCallback(m=>{const u=zn(m);t(f=>{if(f.has(u))return f;const x=new Set(f);return x.add(u),vs(x),x})},[]),a=o.useCallback(m=>{const u=zn(m);t(f=>{if(!f.has(u))return f;const x=new Set(f);return x.delete(u),vs(x),x})},[]),i=o.useCallback(()=>{t(m=>{if(m.size===0)return m;const u=new Set;return vs(u),u})},[]),c=o.useCallback((m,u)=>{t(f=>{const x=new Set(f);for(const N of u)x.add(N);return vs(x),x})},[]),l=o.useCallback((m,u)=>{t(f=>{const x=new Set(f);for(const N of u)x.delete(N);return vs(x),x})},[]),d=o.useCallback(m=>yo(e,m),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:d}}function gl(e){return e instanceof Error?e.message:String(e||"")}function yl(e){const t=gl(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 vl(e){const t=gl(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function wl({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!tt(e)||Ze(e))return;const i=Ws(e);if(i===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=vl(l);c&&!d&&a(m=>{const u={...m};return i===jl(r,c)?delete u[c]:u[c]=i,u}),yl(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 xi(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 Ah(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 i=xi(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(d=>xi(d,t)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function jl(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 Rh(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,i]of Object.entries(e))jl(t,a)===i&&(delete n[a],r=!0);return r?n:e}function Lh({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Cc()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:Jc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Pm(a),o.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]),o.useEffect(()=>{const i=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(i)},[n]),null}function bi(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=bi(t==null?void 0:t.receivedAt)||bi(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 kl(e){return us(e)||e.lastUpdated||0}function Sl(e,t,r=kl){const n=r(t)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const i=e.displayPrimary.localeCompare(t.displayPrimary);if(i!==0)return i;const c=e.displaySecondary.localeCompare(t.displaySecondary);return c!==0?c:e.tabKey.localeCompare(t.tabKey)}function Da(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 Ph(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Da(e)&&!e.title.trim()}function _h(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(Da(r))-Number(Da(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:Sl(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"),i=_h(a);return n?i&&Ph(n)?i:n:i||r[0]||null}function Dh(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 i=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function Vn(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 Eh(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 gi(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Eh(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 $h(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||""),gi(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||""),gi(r.activeChat)].join(":"))].join("|")}function Bh(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 Oh(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const i of Is({routeId:n.routeId}))r.set(i,a);for(const i of Is({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of Is({tabKey:n.tabKey}))r.set(i,n)}return r}function Kh(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Wh(e){const t=Kh(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 Fh({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>Dh(e),[e]),i=o.useMemo(()=>nl(e),[e]),c=o.useRef([]),l=o.useRef([]),d=o.useRef([]),m=o.useRef(new Map),u=o.useRef(new Map),f=o.useMemo(()=>{const S=new Map,v=[];for(const w of a){const{connectionState:B="new",machineName:P}=al(w,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),T=$h(w),H=m.current.get(w.id);if(H&&H.ide===w&&H.sourceSignature===T&&H.connectionState===B&&H.machineName===P){S.set(w.id,H),v.push(...H.conversations);continue}const z=po(w,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),R={ide:w,sourceSignature:T,connectionState:B,machineName:P,conversations:z};S.set(w.id,R),v.push(...z)}m.current=S;const M=new Map,I=w=>{const B=Wh(w),P=u.current.get(w.tabKey);if(P&&P.signature===B)return M.set(w.tabKey,P),P.timestamp;const T={signature:B,timestamp:kl(w)||(P==null?void 0:P.timestamp)||0};return M.set(w.tabKey,T),T.timestamp},j=[...v].sort((w,B)=>Sl(w,B,I));return u.current=M,j},[a,t,i]),x=o.useMemo(()=>{const S=Bh(f,r);return Vn(c.current,S)?c.current:(c.current=S,S)},[f,r]),N=o.useMemo(()=>{const S=new Map,v=Array.from(new Set(x.map(M=>M.routeId)));for(const M of v){const I=Et(x,M);I&&S.set(M,I)}return S},[x]),y=o.useMemo(()=>{const S=new Map;for(const v of x){const M=N.get(v.routeId),I=v.streamSource==="native"&&M?M:v;for(const j of Is({providerSessionId:v.providerSessionId,sessionId:v.sessionId}))S.set(j,I)}return S},[x,N]),p=o.useMemo(()=>Oh(x,N),[x,N]),g=o.useCallback(S=>{if(S)return y.get(S)},[y]),b=o.useCallback(S=>{if(S)return p.get(S)},[p]),h=o.useMemo(()=>{const S=x.filter(v=>!yo(n,v));return Vn(l.current,S)?l.current:(l.current=S,S)},[x,n]),C=o.useMemo(()=>{const S=h.map(v=>v.tabKey);return Vn(d.current,S)?d.current:(d.current=S,S)},[h]);return{chatIdes:a,conversations:x,visibleConversations:h,visibleTabKeys:C,resolveConversationBySessionId:g,resolveConversationByTarget:b}}function Hh({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),i=o.useMemo(()=>{var l;return!e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),c=o.useCallback(()=>{t&&n(l=>{const d=new URLSearchParams(l);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Uh({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){o.useEffect(()=>{nt.setIdes(e)},[e]),o.useEffect(()=>{nt.setResolveAction((a,i,c)=>{t(a,i,c).catch(()=>{})})},[t]),o.useEffect(()=>{const a=nt.onToast(i=>{r(l=>l.some(m=>m.message===i.message&&i.timestamp-m.timestamp<3e3)?l:[...l.slice(-4),{id:i.id,message:i.message,type:i.type,timestamp:i.timestamp,targetKey:i.targetKey,actions:i.actions}]);const c=i.duration||5e3;setTimeout(()=>r(l=>l.filter(d=>d.id!==i.id)),c)});return()=>{a()}},[r]),o.useEffect(()=>{const a=qc.on("status_event",i=>{nt.handleRawEvent(i,"ws")});return()=>{a()}},[]),o.useEffect(()=>{var i;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",N=String(x).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),y=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N);t(u,"resolve_action",{action:y?"approve":"reject",button:x,...Number.isFinite(f)&&{buttonIndex:f},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(g=>console.error("[SW Action] approval failed:",g))};return(i=navigator.serviceWorker)==null||i.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,t])}const zh="adhdev_dashboardLayout_v1",Vh="adhdev_dashboardDockview_v1",Gh="adhdev_dashboardDockviewHiddenRestore_v1",Xs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function vo(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function qh(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Nl(e){return`${zh}:${e}`}function Yh(e){const t=Nl(e);return vo(t,null)}function Xh(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=Nl(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Cl(e){return`${Vh}:${e}`}function Jh(e){const t=Cl(e);return vo(t,null)}function Qh(e,t){try{const r=Cl(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Tl(e){return`${Gh}:${e}`}function Zh(e){const t=Tl(e);return vo(t,{})}function ex(e,t){try{const r=Tl(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function tx(){return{groupAssignments:[...Xs.groupAssignments],focusedGroup:Xs.focusedGroup,groupActiveTabIds:{...Xs.groupActiveTabIds},groupTabOrders:{...Xs.groupTabOrders},groupSizes:[...Xs.groupSizes]}}function sx(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function rx(){const[e]=o.useState(()=>qh(typeof window<"u"?window.innerWidth:1280)),[t,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,d]=o.useState({}),[m,u]=o.useState([]),[f,x]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[N,y]=o.useState(!1),p=o.useCallback(()=>{if(N)return;const w=Yh(e)??tx();r(new Map(w.groupAssignments)),a(w.focusedGroup),c(w.groupActiveTabIds),d(w.groupTabOrders),u(w.groupSizes),y(!0)},[N,e]);o.useEffect(()=>{N&&Xh(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:m})},[N,e,t,n,i,l,m]),o.useEffect(()=>{const w=window.matchMedia("(max-width: 767px)"),B=P=>x(P.matches);return w.addEventListener("change",B),()=>w.removeEventListener("change",B)},[]);const g=o.useCallback(w=>{r(w)},[]),b=o.useCallback(w=>{a(w)},[]),h=o.useCallback(w=>{c(w)},[]),C=o.useCallback(w=>{d(w)},[]),S=o.useCallback(w=>{u(w)},[]),v=o.useCallback(w=>{b(w)},[b]),M=o.useCallback((w,B)=>{c(P=>(P[w]??null)===(B??null)?P:{...P,[w]:B})},[]),I=o.useCallback((w,B)=>{d(P=>{const T=P[w];return sx(T,B)?P:{...P,[w]:B}})},[]),j=o.useCallback((w,B)=>{const P=B.get(w)??0;return M(P,w),v(P),P},[v,M]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:g,focusedGroup:n,updateFocusedGroup:b,focusGroup:v,groupActiveTabIds:i,updateGroupActiveTabIds:h,setGroupActiveTab:M,groupTabOrders:l,updateGroupTabOrders:C,setGroupTabOrder:I,groupSizes:m,updateGroupSizes:S,isMobile:f,hasHydratedStoredLayout:N,hydrateStoredLayout:p,focusConversationTab:j}}function nx(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=no(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function ax({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,focusConversationTab:c,setSearchParams:l,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,ides:f,handleRefreshHistory:x}){const N=o.useRef(!1),y=o.useRef(!1),p=o.useRef(null),g=o.useRef(!1);o.useEffect(()=>{if(!e||N.current||t.length===0)return;if(!a){i();return}const b=r(e);b&&(c(b.tabKey,n),N.current=!0,y.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,i,c,l]),o.useEffect(()=>{if(!(y.current||a)&&t.length!==0){if(!e){i(),y.current=!0;return}if(N.current){y.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(y.current||a)&&(i(),y.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,i]),o.useEffect(()=>{if(!d){g.current=!1;return}if(!m||g.current||u)return;const b=f.find(h=>h.id===m.routeId);b&&(!b.chats||b.chats.length===0||nx(b.chats,m))&&(g.current=!0,x())},[d,m,u,f,x])}function Gn(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=no(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Ml({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:i}){const[c,l]=o.useState(!1),[d,m]=o.useState(!1),u=o.useCallback(async y=>{try{await e("standalone","launch_ide",{ideType:y,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),f=o.useCallback(async(y,p)=>{try{const g=y||(t==null?void 0:t.daemonId)||"",b=await e(g,"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(g){console.error("Switch failed",g),zs(a,`❌ Switch failed: ${g.message||"connection error"}`)}},[t,e,a]),x=o.useCallback(async()=>{if(!(!t||c)){l(!0);try{const y=_s(t);await e(y,"new_chat",{...as(t)}),i(p=>({...p,[t.tabKey]:Date.now()}))}catch(y){console.error("New chat failed",y)}finally{l(!1)}}},[t,c,e,i]),N=o.useCallback(async()=>{var y,p;if(!(!t||d)){m(!0);try{const g=_s(t),b=async()=>e(g,"list_chats",{forceExpand:!0,...as(t)});let h=await b(),C=(h==null?void 0:h.chats)||((y=h==null?void 0:h.result)==null?void 0:y.chats);Gn(C,t)&&(await new Promise(S=>setTimeout(S,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),Gn(C,t)&&!Gn(r,t)&&zs(a,"⚠️ History dialog did not fully open — try once more"))}catch(g){console.error("Refresh history failed",g)}finally{m(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:f,handleNewChat:x,handleRefreshHistory:N}}function ox(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 ix(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function yi(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 Pr(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 i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const d=a[l];typeof d=="number"&&d>0&&i.set(c,d)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function vi(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=t[Number(n)];typeof i=="number"&&(r[i]=a)}return r}function cx(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 lx(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),i=a.reduce((c,l)=>c+l,0);return i>0?a.map(c=>c/i*100):Array(r).fill(100/r)}function wi(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=Number(n);r[i>=t?i+1:i]=a}return r}function ji(e){return Array(e).fill(100/e)}function dx({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:i,updateGroupSizes:c,isMobile:l,visibleConversations:d,visibleTabKeys:m}){const u=o.useRef(null),f=o.useMemo(()=>Pr(e,m),[e,m]),x=f.assignments,N=o.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),y=N>1,p=o.useCallback((v,M)=>{t(I=>{const j=new Map(Pr(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]),g=o.useCallback(v=>{t(M=>{const I=Pr(M,m).assignments,j=new Map;for(const[w,B]of I)B!==v&&(B>v?j.set(w,B-1):j.set(w,B));return j}),c(M=>{if(M.length<=1)return[];const I=[...M];I.splice(v,1);const j=I.reduce((w,B)=>w+B,0);return j>0?I.map(w=>w/j*100):[]}),r(0)},[t,m,c,r]),b=o.useCallback((v,M)=>{M.preventDefault();const I=u.current;if(!I)return;const j=M.clientX,w=I.offsetWidth,B=i.length===N?[...i]:ji(N),P=H=>{const R=(H.clientX-j)/w*100,k=[...B];k[v]=Math.max(15,B[v]+R),k[v+1]=Math.max(15,B[v+1]-R),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)},[i,N,c]),h=o.useCallback((v,M,I)=>{if(N>=4)return;const j=I==="left"?M:M+1;t(w=>{const B=Pr(w,m).assignments,P=new Map;for(const T of d){const H=B.get(T.tabKey)??0,z=H>=j?H+1:H;z>0&&P.set(T.tabKey,z)}return j>0&&P.set(v,j),P}),c(w=>{const B=w.length===N?[...w]:ji(N),P=B[M]??100/N,T=Math.max(15,P/2),H=Math.max(15,P/2),z=[...B];z[M]=T,z.splice(j,0,H);const R=z.reduce((k,A)=>k+A,0);return z.map(k=>k/R*100)}),n(w=>{const B=wi(w,j);return B[j]=v,B}),a(w=>{const B=wi(w,j);return B[j]=[v],B}),r(j)},[N,t,m,d,c,n,a,r]);o.useEffect(()=>{ox(e,x)||t(x)},[e,x,t]),o.useEffect(()=>{const{mapping:v,usedGroups:M}=f;n(I=>{const j=vi(I,v);return yi(I,j)?I:j}),a(I=>{const j=vi(I,v);return yi(I,j)?I:j}),r(I=>{const j=l?0:cx(I,M,v);return I===j?I:j}),c(I=>{const j=l?[]:lx(I,M,f.groupCount);return ix(I,j)?I:j})},[f,l,n,a,r,c]);const C=o.useMemo(()=>{const v=Array.from({length:N},()=>[]);for(const M of d){const I=x.get(M.tabKey)??0,j=Math.min(I,N-1);v[j].push(M)}return v},[d,x,N]),S=o.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:x,numGroups:N,isSplitMode:y,groupedConvs:C,moveTabToGroup:p,closeGroup:g,handleResizeStart:b,splitTabRelative:h,clearAllSplits:S}}function qn(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 ux(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 _r(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function wo(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=qn(t.channel)||qn(e.updateChannel)||qn(e.releaseChannel)||void 0,n=ux(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=_r(t.targetVersion)||_r(e.serverVersion)||void 0,i=_r(t.minVersion)||void 0,c=_r(t.updateCommand)||(r?`adhdev update --channel ${r}`:void 0);return{...r?{channel:r}:{},...n?{npmTag:n}:{},...a?{targetVersion:a}:{},...i?{minVersion:i}:{},...c?{updateCommand:c}:{}}}function Ss(e,t=null){return wo(e).targetVersion||t}function Il(e){return wo(e).channel||null}function Al(e){const t=wo(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 mx({ides:e,sendDaemonCommand:t}){const r="0.9.75",n=o.useMemo(()=>e.filter(f=>f.type!=="adhdev-daemon"?!1:ul(f,Ss(f,r))).sort((f,x)=>Number(or(x,Ss(x,r)))-Number(or(f,Ss(f,r)))),[r,e]),a=o.useMemo(()=>n.some(f=>or(f,Ss(f,r))),[r,n]),i=o.useMemo(()=>n.map(f=>Ss(f,r)).find(f=>typeof f=="string"&&f.trim().length>0)||r,[r,n]),[c,l]=o.useState(!1),[d,m]=o.useState({}),u=o.useCallback(async f=>{var N,y;const x=e.find(p=>p.id===f);if(x){m(p=>({...p,[f]:"upgrading"}));try{const p=await t(f,"daemon_upgrade",Al(x));(N=p==null?void 0:p.result)!=null&&N.upgraded||(y=p==null?void 0:p.result)!=null&&y.success?m(g=>({...g,[f]:"done"})):m(g=>({...g,[f]:"error"}))}catch{m(p=>({...p,[f]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:i,versionBannerDismissed:c,setVersionBannerDismissed:l,upgradingDaemons:d,handleBannerUpgrade:u}}const Rl=80;function Gr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function fx(e){return{...e,createdAt:Gr(e.createdAt),updatedAt:Gr(e.updatedAt,e.createdAt),lastEventAt:Gr(e.lastEventAt,e.updatedAt||e.createdAt)}}function px(e){const t=ao(e);return t==="unknown:"?e.id:t}function hx(e){return[e.type,Wc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function xx(e,t=Rl){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=px(n),i=r.get(a);if(!i){r.set(a,n);continue}(n.updatedAt>i.updatedAt||n.updatedAt===i.updatedAt&&n.createdAt>i.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const i=a.updatedAt-n.updatedAt;return i!==0?i:a.createdAt-n.createdAt}).slice(0,Math.max(0,t))}function bx(e,t){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?t.get(a.sessionId):void 0;if(i!=null&&i.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=Gr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),m=hx({type:l,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(i==null?void 0:i.lastUpdated)||a.lastUpdated});n.push(fx({id:m,dedupKey:m,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Rc(a),preview:nf(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return xx(n)}function gx(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function yx(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Rl}=e,a=o.useMemo(()=>bx(t,r).slice(0,Math.max(0,n)),[t,r,n]),i=o.useMemo(()=>gx(a),[a]);return{notifications:a,unreadCount:i}}function vx({notifications:e,sendDaemonCommand:t}){const r=o.useCallback(i=>{const c=e.find(d=>d.id===i),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=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]),a=o.useCallback(i=>{const c=e.find(l=>l.id===i);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 wx=o.createContext(null);function jx(){return o.useContext(wx)}function kn(...e){const t=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();t.has(c)||(t.add(c),r.push(i))};for(const a of e){if(Array.isArray(a)){for(const i of a)n(i);continue}n(a)}return r}function kx(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 Sn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=kx(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 Sx(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 Nx(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Nn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=Nx(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 i=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=i.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(i,m.name)})).sort((m,u)=>m.name.localeCompare(u.name)):[];return{path:i,directories:d}}function Cx(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 Ll(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:Cx(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function Tx(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 Cn(e){return gr(e)||e.tabKey||e.routeId||null}function Pl(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(i=>i.routeId===n);return a?Cn(a):null}function ns(e){return String(e||"").trim()}function _l(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 Mx(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Ix(e,t){const r=ns(e.providerSessionId),n=ns(e.targetSessionId),a=t.find(i=>{const c=[i.providerSessionId,i.sessionId,i.nativeSessionId,i.tabKey,i.routeId].map(ns).filter(Boolean);return!!(r&&c.includes(r)||n&&c.includes(n))});return a?Cn(a):n||r||null}function Ax(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=_l(t.daemonId);if(n&&n!==e.machineId)return null;const a=ns(t.providerType);if(e.providerType&&a!==e.providerType)return null;const i=ns(e.resumeSessionId),c=ns(t.providerSessionId),l=ns(t.targetSessionId);if(i&&i!==c&&i!==l)return null;const d=fn(e.workspacePath);if(d){const m=fn(t.workspaceName);if(m&&!Mx(m,d))return null}return Ix(t,r)}function ki(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Rx({ides:e,conversations:t,onOpenSession:r}){const[n,a]=o.useState(null),i=o.useRef(null),c=o.useCallback(()=>{i.current=null,a(null)},[]),l=o.useCallback(d=>{i.current=d,a(d)},[]);return o.useEffect(()=>{if(!n)return;const d=fn(n.workspacePath),m=e.find(f=>{var g,b,h,C;if(!f||f.type==="adhdev-daemon"||_l(f.daemonId||f.id)!==n.machineId||(mr(f)?"cli":Ts(f)?"acp":"ide")!==n.kind)return!1;const y=String(f.agentType||f.type||"");if(n.providerType&&y!==n.providerType)return!1;if(n.resumeSessionId)return String(f.providerSessionId||"")===n.resumeSessionId;if(d){const S=fn(f.workspace||f.runtimeWorkspaceLabel);return S?S===d:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((C=(h=(b=(g=f.activeChat)==null?void 0:g.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=Pl({entrySessionId:m.sessionId,entryInstanceId:m.instanceId,entryRouteId:m.id,conversations:t});u&&(c(),r(u))},[c,t,e,r,n]),o.useEffect(()=>nt.onStatusEvent(d=>{const m=i.current;if(!m)return;const u=Ax(m,d,t);u&&(c(),r(u))}),[c,t,r]),o.useEffect(()=>{if(!n)return;const d=window.setTimeout(()=>{a(m=>!m||m.startedAt!==n.startedAt?m:(i.current=null,null))},45e3);return()=>window.clearTimeout(d)},[n]),{trackPendingLaunch:l}}function Lx({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=jx(),l=o.useCallback(async(p,g)=>Nn(e,p,g),[e]),d=o.useCallback(async(p,g)=>{if(!g.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(p,"workspace_add",{path:g.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=o.useCallback(async(p,g,b)=>{var h;try{const C={ideType:g,enableCdp:!0};(h=b==null?void 0:b.workspacePath)!=null&&h.trim()&&(C.workspace=b.workspacePath.trim());const S=await e(p,"launch_ide",C);return!(S!=null&&S.success)&&(S==null?void 0:S.success)!==void 0?{ok:!1,error:(S==null?void 0:S.error)||"Could not launch IDE"}:(t({machineId:p,kind:"ide",providerType:g,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=o.useCallback(async(p,g,b,h)=>{var S,v,M;const C=Date.now();try{const I={cliType:b};(S=h==null?void 0:h.workspacePath)!=null&&S.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,B=(w==null?void 0:w.sessionId)||(w==null?void 0:w.id);return j!=null&&j.success&&B?(r(B),{ok:!0}):j!=null&&j.success?(t({machineId:p,kind:g,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 ${g.toUpperCase()} session`}}catch(I){return ki(I)?(t({machineId:p,kind:g,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 ${g.toUpperCase()} session`}}},[r,e,t]),f=o.useCallback(async p=>{var g;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((g=h==null?void 0:h.result)==null?void 0:g.meshes)?h.result.meshes:[]).map(S=>{var v;return{id:String((S==null?void 0:S.id)||""),name:String((S==null?void 0:S.name)||(S==null?void 0:S.id)||"Untitled mesh"),repoIdentity:(S==null?void 0:S.repoIdentity)||(S==null?void 0:S.repo_identity)||null,workspace:Array.isArray(S==null?void 0:S.nodes)&&S.nodes.length>0?String(((v=S.nodes[0])==null?void 0:v.workspace)||""):null,nodesCount:Array.isArray(S==null?void 0:S.nodes)?S.nodes.length:void 0,status:(S==null?void 0:S.status)||null}}).filter(S=>S.id)}catch(b){throw console.error("List meshes failed",b),b}},[c,e]),x=o.useCallback(async(p,g,b)=>{if(!g.trim())return{ok:!1,error:"Choose a mesh first."};if(c!=null&&c.launchMeshCoordinator)return c.launchMeshCoordinator(p,g,b);const h=Date.now();try{const C={meshId:g.trim()};b.trim()&&(C.cliType=b.trim());const S=await e(p,"launch_mesh_coordinator",C),v=(S==null?void 0:S.result)??S;if((v==null?void 0:v.success)===!1||(S==null?void 0:S.success)===!1){const I=String((v==null?void 0:v.code)||(S==null?void 0:S.code)||""),j=Tx((v==null?void 0:v.meshCoordinatorSetup)||(v==null?void 0:v.manualSetup)||(S==null?void 0:S.meshCoordinatorSetup)||(S==null?void 0:S.manualSetup));return{ok:!1,error:(v==null?void 0:v.error)||(S==null?void 0:S.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 ki(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]),N=o.useCallback(async(p,g)=>{if(!p||!g)return[];try{const b=await e(p,"list_saved_sessions",{providerType:g,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]),y=o.useCallback(async p=>{await wl({conversation:n,mode:p,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:i})},[n,a,e,i]);return{handleBrowseMachineDirectory:l,handleSaveMachineWorkspace:d,handleLaunchMachineIde:m,handleLaunchMachineProvider:u,handleListMachineMeshes:f,handleLaunchMeshCoordinator:x,handleListMachineSavedSessions:N,setActiveCliViewMode:y}}function Px(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 _x(e,t,r=Date.now()){return!e||!Px(t)?null:{tabKey:e,nonce:r}}function Dx({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:i,setSearchParams:c}){const[l,d]=o.useState(null),[m,u]=o.useState(null),f=o.useMemo(()=>{var g,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((g=i[a])==null?void 0:g[0])||((b=i[0])==null?void 0:b[0])},[t,l,a,n,i,e,r]),x=o.useCallback(p=>{d(p)},[]),N=o.useCallback(p=>{d(p.tabKey),c(g=>{const b=new URLSearchParams(g),h=of(p);return h?b.set("activeTab",h):b.delete("activeTab"),b},{replace:!0})},[c]),y=o.useCallback((p,g)=>{const b=_x(p,g);b&&u(b)},[]);return{activeConv:f,openDesktopConversation:N,requestScrollToBottom:y,scrollToBottomRequest:m,setDesktopActiveTab:x}}function Ex(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 $x(e){const t=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,i=[e.tabKey,e.historySessionId||"",t,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&t&&t!==r),autoReadKey:i,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Bx({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=o.useRef(null),i=o.useRef(null),c=o.useRef(null),l=o.useRef(null),d=o.useRef(null);o.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),i.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=$x({tabKey:e.tabKey,historySessionId:gr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:us(e),liveState:u}),x=f.autoReadKey,N=Ex({autoReadKey:x,shouldMarkSeen:f.shouldMarkSeen,completedKey:a.current,pendingKey:i.current});if(!f.shouldMarkSeen){N.shouldCancelPending&&m(),a.current=x;return}if(!N.shouldSchedule)return;N.shouldCancelPending&&m();const y=()=>{if(document.visibilityState!=="visible"||a.current===x)return;a.current=x,i.current=null,c.current=null,l.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const g=f.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:g,completionMarker:f.completionMarker}).catch(()=>{})};if(i.current=N.nextPendingKey,document.visibilityState==="visible"){c.current=setTimeout(y,1500);const g=()=>{document.visibilityState!=="visible"&&c.current&&(clearTimeout(c.current),c.current=null)};d.current=g,document.addEventListener("visibilitychange",g);return}const p=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(y,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=p,document.addEventListener("visibilitychange",p)},[e,t,r,n]),o.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function Yn(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 Ox({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:d}){var A;const[m,u]=o.useState(!1),[f,x]=o.useState([]),[N,y]=o.useState(()=>wt()),[p,g]=o.useState(!1),[b,h]=o.useState(null),C=o.useRef(null),S=o.useMemo(()=>r||t||e,[e,r,t]),v=!!S&&tt(S)&&!Ze(S),M=o.useMemo(()=>{if(!S||!v)return null;const F=S.daemonId||S.routeId||"",_=Kt(S),E=Yn(S);return`${F}:${_}:${S.providerSessionId||""}:${E}`},[S,v]),I=o.useMemo(()=>!S||!v?"":Yn(S),[S,v]),{isCreatingChat:j,isRefreshingHistory:w,handleSwitchSession:B,handleNewChat:P,handleRefreshHistory:T}=Ml({sendDaemonCommand:a,activeConv:S,chats:(A=n.find(F=>F.id===(S==null?void 0:S.routeId)))==null?void 0:A.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),H=o.useCallback(()=>{u(!0)},[]),z=o.useCallback(()=>{u(!1)},[]),R=o.useCallback(async()=>{if(!(!S||!v||p)){g(!0);try{const F=S.daemonId||S.routeId,_=Kt(S),E=Yn(S),K=await a(F,"list_saved_sessions",{agentType:_,providerType:_,kind:"cli",limit:50,...S.providerSessionId?{providerSessionId:S.providerSessionId}:{},...E?{workspace:E}:{}}),Y=(K==null?void 0:K.result)??K;x(Array.isArray(Y==null?void 0:Y.sessions)?Y.sessions:[])}catch(F){console.error("Refresh saved sessions failed",F),x([])}finally{g(!1)}}},[S,p,v,a]);o.useEffect(()=>{if(!m){C.current=null;return}if(!v){C.current=null,x([]),g(!1);return}!M||p||C.current!==M&&(C.current=M,R())},[R,m,p,v,M]);const k=o.useCallback(async F=>{if(!S||!v||!F.providerSessionId||!F.workspace)return;const _=S.daemonId||S.routeId,E=Kt(S);try{h(F.providerSessionId);const K=await a(_,"launch_cli",{cliType:E,dir:F.workspace,resumeSessionId:F.providerSessionId,initialModel:Sc(F.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Y=(K==null?void 0:K.result)??K,be=typeof(Y==null?void 0:Y.sessionId)=="string"?Y.sessionId:typeof(Y==null?void 0:Y.id)=="string"?Y.id:"";be&&d(ce=>{const D=new URLSearchParams(ce);return D.set("activeTab",be),D},{replace:!0}),z()}catch(K){console.error("Resume saved session failed",K)}finally{h(null)}},[z,S,v,a,d]);return{historyModalOpen:m,openHistoryModal:H,closeHistoryModal:z,historyTargetConv:S,isSavedSessionHistoryTarget:v,isHistoryCreatingChat:j,isHistoryRefreshingHistory:w,handleHistorySwitchSession:B,handleHistoryNewChat:P,handleHistoryRefresh:T,savedHistorySessions:f,savedHistoryFilters:N,setSavedHistoryFilters:y,missingWorkspaceResumePath:I,isSavedHistoryLoading:p,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:R,handleResumeSavedHistorySession:k}}function Kx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[d,m]=o.useState(null),[u,f]=o.useState(null),x=o.useMemo(()=>{if(e||!n)return null;const b=l(n);return b&&!tt(b)&&!Ze(b)?b:null},[e,n,l]),N=o.useMemo(()=>{const b=d==null?void 0:d.routeId;if(!b)return null;const h=d!=null&&d.tabKey?i.find(C=>C.tabKey===d.tabKey):a?i.find(C=>C.tabKey===a):null;return(h==null?void 0:h.routeId)===b?h:Et(i,b)},[i,d,a]),y=o.useMemo(()=>{if(N)return c.find(b=>b.id===N.routeId)},[c,N]);o.useEffect(()=>{x&&(m({routeId:x.routeId,tabKey:Qo(x)}),f(x),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,x]);const p=o.useCallback(b=>{b&&(m({routeId:b.routeId,tabKey:Qo(b)}),f(b))},[]),g=o.useCallback(()=>{m(null),f(null)},[]);return{remoteDialogConv:N,remoteDialogIdeEntry:y,remoteDialogActiveConv:u,setRemoteDialogActiveConv:f,openRemoteDialog:p,closeRemoteDialog:g}}function Wx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:f,remoteDialogActiveConv:x,setRemoteDialogActiveConv:N,openRemoteDialog:y,closeRemoteDialog:p}=Kx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[g,b]=o.useState(!1),[h,C]=o.useState(null),S=o.useCallback(async I=>{const j=I||d;!j||!tt(j)&&!Ze(j)||(C(j),b(!0))},[d]),v=o.useCallback(()=>{b(!1),C(null)},[]),M=o.useCallback(async I=>{const j=h||d;if(!j||!tt(j)&&!Ze(j)){v();return}b(!1);try{const w=Kt(j),B=j.routeId||j.daemonId||"";await m(B,"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:N,openRemoteDialog:y,closeRemoteDialog:p,cliStopDialogOpen:g,cliStopTargetConv:h,requestCliStop:S,cancelCliStop:v,confirmCliStop:M}}function Dl({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:i=!1}){var b;const c=Os(),l=ys(e),d=i?null:Ac(e),m=!i&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!i&&e.streamSource==="agent-stream"&&!!e.agentName,f=!i&&!u&&(e.transport==="pty"||e.transport==="acp"),x=Ps(e),N=af(e),y=(b=e.settings)==null?void 0:b.meshNodeFor;if(!m&&!u&&!f&&!d&&!y)return null;const p=o.useCallback(()=>{if(n){n();return}l&&c("/dashboard",{state:{openMachineId:l}})},[l,c,n]),g=o.useCallback(()=>{if(r){r();return}const h=Cn(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:g,title:N,children:[s.jsx(Mt,{size:12}),s.jsx("span",{children:N})]}):s.jsxs("span",{className:"conversation-meta-chip",title:N,children:[s.jsx(Mt,{size:12}),s.jsx("span",{children:N})]})),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})]})),y&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Xt,{size:12}),s.jsx("span",{children:"Mesh Node"})]})]})}function Xn(e,t=!0){return(e??!0)&&t}const jo=o.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u=null,handleFocusAgent:f,isFocusingAgent:x,actionLogs:N,userName:y,scrollToBottomRequestNonce:p,isInputActive:g=!0,isVisible:b=!0}){const h=n,C=!n,S=Xn(b,h),v=Xn(b,C),M=Xn(b),I=xl(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(wc,{activeConv:j,onModalButton:c}),s.jsx(Dl,{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(ur,{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(bp,{activeConv:j,clearToken:r,terminalRef:i,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,isVisible:S,isInputActive:g&&S})}),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(Ia,{activeConv:j,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:f,isFocusingAgent:x,actionLogs:N,userName:y,scrollToBottomRequestNonce:p,isInputActive:g&&v,isVisible:v})})]}):s.jsx(Ia,{activeConv:j,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:f,isFocusingAgent:x,actionLogs:N,userName:y,scrollToBottomRequestNonce:p,isInputActive:g&&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 Fx({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:d,onBack:m,onOpenNativeConversation:u,onOpenMachine:f,onOpenHistory:x,onOpenRemote:N,onStopCli:y,cliViewMode:p,onSetCliViewMode:g,handleSendChat:b,handleFocusAgent:h,handleModalButton:C,handleRelaunch:S}){const v=o.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(Ua,{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(Dl,{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(io,{mode:p,onChange:g,compact:!0}),M&&y&&s.jsx("button",{onClick:()=>{y(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(za,{size:14})}),!t&&!M&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>N(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(jo,{activeConv:e,clearToken:0,isCliTerminal:I,ideEntry:n,terminalRef:v,handleModalButton:C,handleRelaunch:S,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:h,isFocusingAgent:d,actionLogs:a,userName:i})})]})}const Jn={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 Hx(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function El(){const[e,t]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{t(Hx())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Jn[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!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:Jn[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Jn[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 $l({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:i})=>{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(i,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function Dr({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 Js({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 Ux({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 Er({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onCollectChatDebugBundle:i}){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),N=xs(e.conversation),y=Xc(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",g=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",S=d?"text-text-muted opacity-80":"text-text-muted",v=!l&&!m,M="text-[color:var(--status-warning)]",I=j=>{if(!i)return;j.preventDefault(),j.stopPropagation();const w=i==null?void 0:i(e.conversation);Promise.resolve(w).catch(B=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",B)})};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 ${g}`,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(Va,{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 ${S}`,children:vc(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${h}`,children:[s.jsx("span",{className:"truncate",children:N}),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…"})]}):y==="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 Si({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 zx({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:f,onHideConversation:x,onOpenNewSession:N,onOpenMachine:y,onOpenSettings:p,onSectionChange:g,wsStatus:b="connected",isStandalone:h=!1,onCollectChatDebugBundle:C}){const[S,v]=o.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",B=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=o.useCallback(async R=>{const k=_s(R);if(!k)return;const A=Array.isArray(R.messages)?R.messages:[],F=Ec({activeConv:R,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(R),delivery:"daemon_file",frontendSnapshot:F}),E=on(_),K=Oc(E),Y=await Bc(K);Y==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),nt.showToast($c(E,{locatorCopyStatus:Y}),Y==="failed"?"warning":"success")},[d,m]),H=C||T,z=o.useCallback(()=>{S&&(x==null||x(S),v(null))},[S,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 ${B}`,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(Js,{icon:s.jsx(Si,{}),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(Js,{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(El,{})})}):s.jsx(ws,{children:c.map((R,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:()=>y(R.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(R.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:R.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:R.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[R.unread," new"]}):R.total>0?`${R.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:R.subtitle}),R.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[R.total," chat",R.total!==1?"s":"",R.unread>0?` · ${R.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},R.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(Dr,{title:"Needs attention",className:"mb-0"}),s.jsx(ws,{children:t.map((R,k)=>s.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:s.jsx(Er,{item:R,type:"needs_attention",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>v(R.conversation):void 0,onCollectChatDebugBundle:H})},R.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(Dr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(ws,{children:r.map((R,k)=>s.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:s.jsx(Er,{item:R,type:"task_complete",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>v(R.conversation):void 0,onCollectChatDebugBundle:H})},R.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(Dr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(ws,{children:n.map((R,k)=>s.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:s.jsx(Er,{item:R,type:"working",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>v(R.conversation):void 0,onCollectChatDebugBundle:H})},R.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(Dr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(ws,{children:a.map((R,k)=>s.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:s.jsx(Er,{item:R,type:"earlier",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>v(R.conversation):void 0,onCollectChatDebugBundle:H})},R.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(Js,{icon:s.jsx(Si,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):I?s.jsx(Js,{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:Zc,children:N&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:N,"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(Js,{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"&&i.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:[i.length," collapsed ",i.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"&&N&&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:N,"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"})]})}),S&&s.jsx(Ux,{conversation:S,onCancel:()=>v(null),onConfirm:z}),s.jsx($l,{section:e,onSectionChange:g})]})}function Vx(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 Bl(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=Vx(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Tn({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:d,onConfirm:m}){const[u,f]=o.useState(r);o.useEffect(()=>{f(r)},[r]);const x=Sx(r),N=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(Ua,{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:y=>f(y.target.value),onKeyDown:y=>{y.key!=="Enter"||!N||a||(y.preventDefault(),d(N))},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:()=>{!N||a||d(N)},disabled:!N||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…"}):i?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):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(y=>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(y.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:y.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:y.path})]})]},y.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(N||r),disabled:!N&&!r||a,children:c})]})]})})}function ko({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:d=!1,showArgsInput:m,argsValue:u,onArgsChange:f,showModelInput:x,modelValue:N,onModelChange:y,historyProviderNode:p,onConfirm:g,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&&i&&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=>i(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&&y&&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:N||"",onChange:C=>y(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:g,disabled:d,children:[s.jsx(qa,{size:14}),d?l:c]})]})]})})}function Ni(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,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])i.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${Ni(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&&i.push({key:`custom:${c}`,label:Ni(c),description:c,workspaceId:null,workspacePath:c}),n){const d=`saved:${n}`;if(i.some(m=>m.key===d))return{options:i,selectedKey:d}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Gx(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function qx(e){return[Gx(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Yx(e){return e.lastLaunchedAt?gn(e.lastLaunchedAt):""}function Ol(e){return{metaText:qx(e),updatedLabel:Yx(e)}}function Qn(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Xx({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var st,mt,ht,xt;const c=br(),[l,d]=o.useState(!1),m=(((st=e.detectedIdes)==null?void 0:st.length)||0)>0,u=o.useMemo(()=>(e.workspaces||[]).map(Ce=>({id:Ce.id,path:Ce.path,label:Ce.label})),[e]),f=e.defaultWorkspaceId||null,[x,N]=o.useState(f||((mt=u[0])==null?void 0:mt.id)||""),[y,p]=o.useState(""),[g,b]=o.useState(""),[h,C]=o.useState([]),[S,v]=o.useState(!1),[M,I]=o.useState(""),[j,w]=o.useState(!1),[B,P]=o.useState(Qn(m,t.length,r.length)),T=o.useRef(null),[H,z]=o.useState(null),R=o.useRef("__home__"),[k,A]=o.useState("__home__"),[F,_]=o.useState(""),[E,K]=o.useState(""),[Y,be]=o.useState(""),[ce,D]=o.useState([]),[ie,fe]=o.useState(()=>wt().textQuery),[xe,X]=o.useState(()=>wt().workspaceQuery),[le,ye]=o.useState(()=>wt().modelQuery),[se,ue]=o.useState(()=>wt().resumableOnly),[ke,he]=o.useState(()=>wt().sortMode),[ve,ee]=o.useState(!1),[pe,oe]=o.useState(!1),de=o.useRef(null),ae=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const Q=x==="__custom__"?y.trim():((ht=u.find(Ce=>Ce.id===x))==null?void 0:ht.path)||"",me=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=o.useMemo(()=>(e.recentLaunches||[]).map(Ce=>Ce.workspace),[e]),Te=o.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=o.useCallback(()=>{var ze;N("__custom__"),w(!0);const Ce=Sn(e.platform,kn(y.trim(),J,Ae,e.defaultWorkspacePath,(ze=u.find(Qe=>Qe.id===f))==null?void 0:ze.path,u.map(Qe=>Qe.path)));Te(Ce)},[y,f,Te,Ae,J,e.platform,u]),Ue=o.useCallback(Ce=>{if(Ce!=null&&Ce.workspaceId){N(Ce.workspaceId),p("");return}if(Ce!=null&&Ce.workspacePath){N("__custom__"),p(Ce.workspacePath);return}N(""),p("")},[]),O=o.useCallback(Ce=>{if(N(Ce),Ce==="__custom__"){$e();return}p("")},[$e]),Se=o.useCallback(Ce=>{N("__custom__"),p(Ce)},[]),Me=o.useCallback((Ce,ze)=>{T.current=ze,R.current=Ce.selectedWorkspaceKey||"__home__",A(Ce.selectedWorkspaceKey||"__home__"),_(Ce.initialArgs||""),K(Ce.initialModel||""),be(""),D([]);const Qe=Ce.providerType?`${e.id}:${Ce.providerType}`:null;if(Mp(ae.current,Qe)){const Ge=wt();fe(Ge.textQuery),X(Ge.workspaceQuery),ye(Ge.modelQuery),ue(Ge.resumableOnly),he(Ge.sortMode)}ae.current=Qe,z(Ce),Ce.providerType&&i&&(ee(!0),i(Ce.providerType).then(Ge=>D(Ge||[])).catch(Ge=>console.warn("Failed to load saved sessions",Ge)).finally(()=>ee(!1)))},[i,e.id]),De=o.useMemo(()=>el(ce,{textQuery:ie,workspaceQuery:xe,modelQuery:le,resumableOnly:se,sortMode:ke}),[le,se,ce,ke,ie,xe]);o.useEffect(()=>{Y&&(De.some(Ce=>Ce.providerSessionId===Y)||be(""))},[De,Y]);const Oe=o.useCallback(()=>{T.current&&(oe(!0),T.current().finally(()=>{T.current=null,oe(!1),z(null)}))},[]),He=o.useCallback(()=>{T.current=null,z(null)},[]),Je=o.useCallback(Ce=>{R.current=Ce,A(Ce)},[]);return o.useEffect(()=>{var Ce;de.current!==e.id&&(de.current=e.id,N(f||((Ce=u[0])==null?void 0:Ce.id)||"__custom__"),p(""),b(""),C([]),I(""),w(!1),fe(wt().textQuery),X(wt().workspaceQuery),ye(wt().modelQuery),ue(wt().resumableOnly),he(wt().sortMode),ae.current=null,P(Qn(m,t.length,r.length)))},[r.length,t.length,f,m,e.id,u]),o.useEffect(()=>{var Ce;x!=="__custom__"&&(x&&u.some(ze=>ze.id===x)||N(f||((Ce=u[0])==null?void 0:Ce.id)||"__custom__"))},[f,x,u]),o.useEffect(()=>{B==="ide"&&m||B==="cli"&&t.length>0||B==="acp"&&r.length>0||P(Qn(m,t.length,r.length))},[B,r.length,t.length,m]),{showAllRecent:l,setShowAllRecent:d,hasIdeOptions:m,workspaceRows:u,defaultWorkspaceId:f,workspaceChoice:x,customWorkspacePath:y,browseCurrentPath:g,browseDirectories:h,browseBusy:S,browseError:M,browseDialogOpen:j,activeLauncherKind:B,launchConfirm:H,launchConfirmWorkspaceKeyRef:R,launchConfirmWorkspaceKey:k,launchConfirmArgs:F,launchConfirmModel:E,launchConfirmResumeId:Y,launchConfirmSavedSessions:ce,launchConfirmTextFilter:ie,launchConfirmWorkspaceFilter:xe,launchConfirmModelFilter:le,launchConfirmResumableOnly:se,launchConfirmSortMode:ke,filteredLaunchConfirmSavedSessions:De,launchConfirmSessionsLoading:ve,launchConfirmBusy:pe,resolvedWorkspacePath:Q,canCreateMissingWorkspace:me,openBrowseDialog:$e,loadBrowsePath:Te,handleWorkspaceChoiceChange:O,chooseCustomWorkspacePath:Se,setCustomWorkspacePath:p,setBrowseDialogOpen:w,setActiveLauncherKind:P,openLaunchConfirm:Me,handleConfirmLaunch:Oe,closeLaunchConfirm:He,setWorkspaceSelectionFromOption:Ue,setLaunchConfirmWorkspaceKeyAndSync:Je,setLaunchConfirmArgs:_,setLaunchConfirmModel:K,setLaunchConfirmResumeId:be,setLaunchConfirmTextFilter:fe,setLaunchConfirmWorkspaceFilter:X,setLaunchConfirmModelFilter:ye,setLaunchConfirmResumableOnly:ue,setLaunchConfirmSortMode:he}}function Jx({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:d,section:m,showBottomNav:u,onBack:f,onSectionChange:x,onOpenConversation:N,onOpenRecent:y,onOpenMachineDetails:p,onMachineUpgrade:g,onLaunchDetectedIde:b,onAddWorkspace:h,onBrowseDirectory:C,onLaunchWorkspaceProvider:S,onListSavedSessions:v}){const M=k=>k==="ide"?"IDE":k==="cli"?"CLI":"ACP",I=r.slice(0,4),j=t.slice(0,3),w=Xx({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:C,onListSavedSessions:v}),B=o.useMemo(()=>I.map(k=>{const{metaText:A,updatedLabel:F}=Ol(k);return{key:`recent-launch:${k.id}`,primary:k.label,secondary:A,updatedLabel:F,onClick:()=>{const{options:_,selectedKey:E}=ms({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspacePath:k.workspace});w.openLaunchConfirm({title:k.kind==="ide"?is("restart-ide",k.label):k.providerSessionId?uo(k.label):is("start-fresh",k.label),description:k.kind==="ide"?cs("restart-ide"):k.providerSessionId?mo():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?co(!0):$s("start-fresh"),workspaceOptions:_,selectedWorkspaceKey:E,details:[{label:"Mode",value:M(k.kind)},...k.providerType?[{label:"Provider",value:k.providerType}]:[]]},async()=>{const K=_.find(Y=>Y.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(K),await y({...k,workspace:(K==null?void 0:K.workspacePath)??null})})}}}),[w,y,I]),P=o.useMemo(()=>j.map(k=>({key:`recent-chat:${k.conversation.tabKey}`,primary:lt(k.conversation),secondary:fp(k.conversation,{timestampLabel:k.timestamp?vc(k.timestamp):null}),unread:k.unread,onClick:()=>N(k.conversation)})),[N,j]),T=w.showAllRecent?B:B.slice(0,4),H=B.length>0,z=P.length>0,R=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 ${R} 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(Ua,{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:[z&&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))})]}),H&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:T.map(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))}),B.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 ${B.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:F}=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:F,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:k.name}]},async()=>{const _=A.find(E=>E.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:F,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:F,selectedWorkspaceKey:_,details:[{label:"Mode",value:A.toUpperCase()},{label:"Provider",value:k.displayName}],showArgsInput:!0,showModelInput:A==="acp",initialArgs:"",initialModel:"",providerType:k.type},async()=>{const E=F.find(K=>K.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(E),S(A,k.type,{workspaceId:(E==null?void 0:E.workspaceId)??null,workspacePath:(E==null?void 0:E.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:[i&&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:g,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(Tn,{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(ko,{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:lo()}),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:Rp()}),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(F=>F.providerSessionId===w.launchConfirmResumeId);if(!k)return null;const A=Bl(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($l,{section:m,onSectionChange:x})]})}function qr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Qx(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:qr(e)}function Zx(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 eb(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=mr(n)?"cli":Ts(n)?"acp":"ide",i=hs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(mr(n)?n.cliName||n.type:Ts(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ts(n)?i||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 tb(e,t){const r=new Map;for(const n of t){const a=ys(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((f,x)=>x.timestamp-f.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=Sa(n),d=a.filter(f=>f.unread||f.requiresAction).length,m=Zx(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:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?pp(c):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,a)=>{const i=n.latestTimestamp||n.fallbackActivityAt||0,c=a.latestTimestamp||a.fallbackActivityAt||0;return c!==i?c-i:n.label.localeCompare(a.label)})}function sb(e){return e==="chat"}function $r(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 rb({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:x,onRequestedMobileSectionConsumed:N,setSelectedTabKey:y,setScreen:p,setSelectedMachineId:g,setSection:b,setMachineBackTarget:h,resetMachineAction:C}){const S=o.useRef(null),v=o.useCallback(M=>{if(!(M!=null&&M.sessionId))return;const I=sn(M,c),j=Math.max(Date.now(),us(M),I.lastUpdated||0);$r("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=>{$r("mark_read:result",{tabKey:M.tabKey,sessionId:M.sessionId,result:w})}).catch(w=>{$r("mark_read:error",{tabKey:M.tabKey,sessionId:M.sessionId,error:w instanceof Error?w.message:String(w)})})},[c,l]);return o.useEffect(()=>{var I;if(!n){sb(i)&&p("inbox"),y(((I=e[0])==null?void 0:I.tabKey)||null),S.current=null;return}if(i!=="chat"){S.current=null;return}const M=`${n.tabKey}:${n.sessionId||""}`;S.current!==M&&(S.current=M,v(n))},[e,v,i,n,p,y]),o.useEffect(()=>{if(!d)return;const M=e.find(I=>I.tabKey===d);M&&(y(M.tabKey),p("chat"),m==null||m())},[e,m,d,p,y]),o.useEffect(()=>{if(!u)return;const M=t.find(I=>I.id===u);M&&(g(M.id),C(),b("machines"),h("inbox"),p("machine"),f==null||f())},[t,f,u,C,h,p,b,g]),o.useEffect(()=>{x&&(b(x),p("inbox"),N==null||N())},[N,x,p,b]),o.useEffect(()=>{const M=r.filter(I=>I.inboxBucket==="task_complete"||I.unread);M.length!==0&&$r("inbox_state",{screen:i,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,i,a]),{markConversationRead:v}}function nb(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Ci(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ab(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function ob({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[d,m]=o.useState(null),u=o.useCallback(()=>{i("idle"),l(""),m(null)},[]),f=o.useCallback(async(h,C,S)=>{var v;try{i("loading"),l(`Launching ${C}…`);const M={ideType:C,enableCdp:!0};(v=S==null?void 0:S.workspacePath)!=null&&v.trim()&&(M.workspace=S.workspacePath.trim()),await e(h,"launch_ide",M),i("done"),l(`${C} launch requested`)}catch(M){i("error"),l(M instanceof Error?M.message:"Launch IDE failed"),console.error("Launch IDE failed",M)}},[e]),x=o.useCallback(async(h,C,S)=>{if(C.trim())try{i("loading"),l(S!=null&&S.createIfMissing?"Creating folder…":"Saving workspace…");const v=await e(h,"workspace_add",{path:C.trim(),createIfMissing:(S==null?void 0:S.createIfMissing)===!0});if(v!=null&&v.success){i("done"),l(S!=null&&S.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((v==null?void 0:v.error)||"Could not save workspace")}catch(v){i("error"),l(v instanceof Error?v.message:"Could not save workspace")}},[e]),N=o.useCallback(async h=>{var C,S,v,M,I,j;try{i("loading"),l("Starting daemon upgrade…");const w=await e(h,"daemon_upgrade",{});if((C=w==null?void 0:w.result)!=null&&C.alreadyLatest){i("done"),l(`Already on v${((S=w==null?void 0:w.result)==null?void 0:S.version)||"latest"}.`);return}if((v=w==null?void 0:w.result)!=null&&v.upgraded||(M=w==null?void 0:w.result)!=null&&M.success){i("done"),l(`Upgrade to v${((I=w==null?void 0:w.result)==null?void 0:I.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((j=w==null?void 0:w.result)==null?void 0:j.error)||"Upgrade failed")}catch(w){i("error"),l(w instanceof Error?w.message:"Upgrade failed")}},[e]),y=o.useCallback(async(h,C,S,v)=>{var j,w,B;const M=Date.now(),I={machineId:h,kind:C,providerType:S,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{i("loading"),l(`Launching ${S}…`),m(I);const P={cliType:S};(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)),(B=v==null?void 0:v.model)!=null&&B.trim()&&(P.initialModel=v.model.trim());const T=await e(h,"launch_cli",P),H=(T==null?void 0:T.result)||T,z=(H==null?void 0:H.sessionId)||(H==null?void 0:H.id);if(T!=null&&T.success&&z){m(null),i("done"),l(`${S} launched`),t(Qt(z));return}if(T!=null&&T.success){i("loading"),l(`${S} launch requested — waiting for session…`);return}m(null),i("error"),l((T==null?void 0:T.error)||(H==null?void 0:H.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(P){if(ab(P)){i("loading"),l(`${S} launch requested — waiting for session…`);return}m(null),i("error"),l(P instanceof Error?P.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),p=o.useCallback(async(h,C)=>{try{const S=await e(h,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),v=(S==null?void 0:S.result)??S;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(S){return console.error("Failed to list saved sessions on mobile:",S),[]}},[e]),g=o.useCallback(async(h,C)=>Nn(e,h,C),[e]);o.useEffect(()=>{if(!d)return;const h=Ci(d.workspacePath),C=r.find(v=>{var P,T,H,z;if(!v||v.type==="adhdev-daemon"||nb(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 R=Ci(v.workspace||v.runtimeWorkspaceLabel);return R?R===h:!1}return Number(v.lastUpdated||v._lastUpdate||v.timestamp||((z=(H=(T=(P=v.activeChat)==null?void 0:P.messages)==null?void 0:T.at)==null?void 0:H.call(T,-1))==null?void 0:z.timestamp)||0)>=d.startedAt-5e3});if(!C)return;const S=Pl({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:n});S&&(m(null),i("done"),l(`${d.providerType} launched`),t(Qt(S)))},[n,r,t,d]),o.useEffect(()=>{if(!d)return;const h=window.setTimeout(()=>{m(C=>!C||C.startedAt!==d.startedAt?C:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[d]);const b=o.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 y(h,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[f,y]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:f,handleAddWorkspace:x,handleMachineUpgrade:N,handleLaunchWorkspaceProvider:y,handleListSavedSessions:p,handleBrowseDirectory:g,handleOpenRecent:b}}function ib({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:d,setMachineBackTarget:m}){const u=o.useCallback(b=>{i(b.tabKey),c("chat"),n(b)},[n,c,i]),f=o.useCallback(b=>{const h=e.find(C=>C.routeId===b.routeId&&C.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),x=o.useCallback(()=>{n(t),c("inbox")},[n,t,c]),N=o.useCallback((b,h="inbox")=>{l(b),a(),d("machines"),m(h),c("machine")},[a,m,c,d,l]),y=o.useCallback(b=>{const h=ys(b);h&&N(h,"chat")},[N]),p=o.useCallback(()=>{a(),c(r)},[r,a,c]),g=o.useCallback(b=>{d(b),c("inbox")},[c,d]);return{openConversation:u,openNativeConversation:f,backFromConversation:x,openMachine:N,openConversationMachine:y,backFromMachine:p,changeMachineSection:g}}function bs(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function cb(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function lb({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:x,onRequestedMobileSectionConsumed:N,onOpenHistory:y,onOpenRemote:p,onStopCli:g,wsStatus:b,isConnected:h,onShowAllHiddenConversations:C,onHideConversation:S,onOpenNewSession:v,liveSessionInboxState:M,setCliViewModeOverrides:I}){const[j,w]=o.useState(()=>{var J;return((J=e[0])==null?void 0:J.tabKey)||null}),[B,P]=o.useState(()=>e[0]?"chat":"inbox"),[T,H]=o.useState("chats"),[z,R]=o.useState(null),[k,A]=o.useState("inbox"),F=o.useRef([]),_=Os(),E="0.9.75",K=o.useMemo(()=>e.find(J=>J.tabKey===j)||e[0]||null,[e,j]),Y=o.useMemo(()=>K?r.find(J=>J.id===K.routeId):void 0,[r,K]),be=o.useMemo(()=>!K||Ze(K)||!tt(K)?null:Ws(K),[K]),ce=o.useMemo(()=>r.filter(J=>J.type==="adhdev-daemon").sort(Qa),[r]),D=o.useMemo(()=>ce.find(J=>J.id===z)||null,[ce,z]),ie=jn({sendDaemonCommand:a,activeConv:K||void 0,setActionLogs:i,isStandalone:c}),fe=ob({sendDaemonCommand:a,navigate:_,ides:r,conversations:e}),xe=o.useMemo(()=>e.map(J=>{const Ae=B==="chat"&&(K==null?void 0:K.tabKey)===J.tabKey,Te=yn(J,M,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ae}),$e=us(J),Ue=Yc(J);return{conversation:J,timestamp:$e,preview:Ue,unread:Te.unread,requiresAction:Te.requiresAction,isWorking:Te.isWorking,inboxBucket:Te.inboxBucket}}),[e,M,B,K]),{markConversationRead:X}=rb({conversations:e,machineEntries:ce,items:xe,selectedConversation:K,selectedTabKey:j,screen:B,liveSessionInboxState:M,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:x,onRequestedMobileSectionConsumed:N,setSelectedTabKey:w,setScreen:P,setSelectedMachineId:R,setSection:H,setMachineBackTarget:A,resetMachineAction:fe.resetMachineAction}),le=ib({conversations:e,selectedConversation:K,machineBackTarget:k,markConversationRead:X,resetMachineAction:fe.resetMachineAction,setSelectedTabKey:w,setScreen:P,setSelectedMachineId:R,setSection:H,setMachineBackTarget:A}),ye=o.useMemo(()=>qr(xe.filter(J=>J.requiresAction)),[xe]),se=o.useMemo(()=>qr(xe.filter(J=>J.unread&&!J.requiresAction)),[xe]),ue=o.useMemo(()=>Qx(xe.filter(J=>!J.unread&&!J.requiresAction&&J.isWorking),F.current),[xe]);o.useEffect(()=>{F.current=ue.map(J=>J.conversation.tabKey)},[ue]);const ke=o.useMemo(()=>qr(xe.filter(J=>!J.unread&&!J.requiresAction&&!J.isWorking)),[xe]),he=o.useMemo(()=>D?xe.filter(J=>ys(J.conversation)===D.id):[],[xe,D]),ve=o.useMemo(()=>eb(D,r),[r,D]),ee=(D==null?void 0:D.version)||null,pe=!!D&&!!ee&&!0&&ee!==E,oe=o.useMemo(()=>(D==null?void 0:D.availableProviders)||[],[D]),de=o.useMemo(()=>oe.filter(J=>bs(J,"cli")).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[oe]),ae=o.useMemo(()=>oe.filter(J=>bs(J,"acp")).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[oe]),Q=o.useMemo(()=>tb(ce,xe),[xe,ce]),me=o.useCallback(async J=>{D&&await fe.handleOpenRecent(D.id,J)},[fe,D]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:B==="chat"&&K?s.jsx(Fx,{selectedConversation:K,isAcp:Ze(K),isStandalone:c,selectedIdeEntry:Y,actionLogs:n,userName:l,isSendingChat:ie.isSendingChat,sendFeedbackMessage:ie.sendFeedbackMessage,isFocusingAgent:ie.isFocusingAgent,handleModalButton:ie.handleModalButton,handleRelaunch:ie.handleRelaunch,onBack:le.backFromConversation,onOpenNativeConversation:le.openNativeConversation,onOpenMachine:le.openConversationMachine,onOpenHistory:y,onOpenRemote:p,onStopCli:g,cliViewMode:be,onSetCliViewMode:async J=>{await wl({conversation:K,mode:J,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:I})},handleSendChat:ie.handleSendChat,handleFocusAgent:ie.handleFocusAgent}):B==="machine"&&D?s.jsx(Jx,{selectedMachineEntry:D,selectedMachineConversations:he,selectedMachineRecentLaunches:ve,cliProviders:de,acpProviders:ae,selectedMachineNeedsUpgrade:pe,appVersion:E,machineAction:fe.machineAction,isStandalone:c,section:T,showBottomNav:k==="inbox",onBack:le.backFromMachine,onSectionChange:le.changeMachineSection,onOpenConversation:le.openConversation,onOpenRecent:me,onOpenMachineDetails:()=>_(`/machines/${D.id}`),onMachineUpgrade:()=>fe.handleMachineUpgrade(D.id),onLaunchDetectedIde:(J,Ae)=>fe.handleLaunchDetectedIde(D.id,J,Ae),onAddWorkspace:(J,Ae)=>fe.handleAddWorkspace(D.id,J,Ae),onBrowseDirectory:J=>fe.handleBrowseDirectory(D.id,J),onLaunchWorkspaceProvider:(J,Ae,Te)=>fe.handleLaunchWorkspaceProvider(D.id,J,Ae,Te),onListSavedSessions:J=>fe.handleListSavedSessions(D.id,J)}):s.jsx(zx,{section:T,attentionItems:ye,unreadItems:se,workingItems:ue,completedItems:ke,hiddenConversations:t,machineCards:Q,getAvatarText:cb,actionLogs:n,sendDaemonCommand:a,onOpenConversation:le.openConversation,onShowAllHidden:C,onHideConversation:S,onOpenNewSession:v,onOpenMachine:le.openMachine,onOpenSettings:()=>_("/settings"),onSectionChange:H,wsStatus:b,isConnected:h,isStandalone:c})})}function Zn(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function db({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,d]=o.useState(!1),[m,u]=o.useState(null),f=o.useCallback(()=>{c.current=0,d(!1),u(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",f),window.addEventListener("drop",f),()=>{window.removeEventListener("dragend",f),window.removeEventListener("drop",f)}),[f]);const x=o.useCallback(g=>{g.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,d(!0))},[]),N=o.useCallback(g=>{if(!g.dataTransfer.types.includes("text/tab-key"))return;if(g.preventDefault(),!Zn(t,r)){u("merge");return}const b=g.currentTarget.getBoundingClientRect(),h=g.clientX-b.left,C=b.width/3;h<C?u("split-left"):h>C*2?u("split-right"):u("merge")},[t,r]),y=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,d(!1),u(null))},[]),p=o.useCallback(g=>{c.current=0,d(!1);const b=g.dataTransfer.getData("text/tab-key"),h=b?e.some(S=>S.tabKey===b):!1,C=m;if(u(null),i(),!!b){if(g.preventDefault(),C==="split-left"&&Zn(t,r)){r==null||r(b,"split-left");return}if(C==="split-right"&&Zn(t,r)){r==null||r(b,"split-right");return}if(h){a(b);return}n==null||n(b)}},[e,m,t,r,n,a,i]);return{dragOver:l,dropAction:m,resetDragState:f,handleDragEnter:x,handleDragOver:N,handleDragLeave:y,handleDrop:p}}function ub(e,t){const r=new Set(t.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),a=t.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...a]}function mb({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(t??null),[l,d]=o.useState(r??[]),[m,u]=o.useState(null),f=o.useRef(null),x=o.useRef(null),N=o.useRef(n),y=o.useRef(a);o.useEffect(()=>{N.current=n},[n]),o.useEffect(()=>{y.current=a},[a]),o.useEffect(()=>{t&&t!==i&&c(t)},[t,i]),o.useEffect(()=>{d(I=>{const j=ub(I,e);return j.length===I.length&&j.every((w,B)=>w===I[B])?I:j})},[e]);const p=o.useMemo(()=>{const I=m??l;if(I.length===0)return e;const j=new Map(I.map((w,B)=>[w,B]));return[...e].sort((w,B)=>{const P=j.get(w.tabKey)??999,T=j.get(B.tabKey)??999;return P-T})},[e,m,l]);o.useEffect(()=>{var j,w;if(p.length===0){i!==null&&(c(null),(j=N.current)==null||j.call(N,null));return}if(i&&p.some(B=>B.tabKey===i))return;const I=p[0].tabKey;I!==i&&(c(I),(w=N.current)==null||w.call(N,I))},[p,i]);const g=o.useMemo(()=>p.find(I=>I.tabKey===i),[p,i]),b=o.useCallback(I=>{var j;c(I),(j=N.current)==null||j.call(N,I)},[]),h=o.useCallback((I,j,w)=>{d(B=>{var z;const P=B.filter(R=>R!==I),T=P.indexOf(j);if(T<0)return B;const H=w==="left"?T:T+1;return P.splice(H,0,I),(z=y.current)==null||z.call(y,P),P}),u(null)},[]),C=o.useCallback((I,j,w)=>{const P=(l.length>0?l:e.map(z=>z.tabKey)).filter(z=>z!==I),T=P.indexOf(j);if(T<0)return;const H=w==="left"?T:T+1;P.splice(H,0,I),f.current=P,u(P)},[l,e]),S=o.useCallback(()=>{var j;const I=f.current;I&&(d(I),(j=y.current)==null||j.call(y,I))},[]),v=o.useCallback(()=>{f.current=null,u(null)},[]),M=o.useCallback(I=>{d(j=>{var B;const w=j.filter(P=>P!==I);return w.push(I),(B=y.current)==null||B.call(y,w),w})},[]);return{activeTabId:i,activeConv:g,sortedConversations:p,previewOrderRef:f,draggingTabRef:x,selectTab:b,handleTabReorder:h,updatePreviewOrder:C,commitPreviewOrder:S,clearPreviewOrder:v,moveTabToEnd:M,setDraggingTabKey:I=>{x.current=I}}}function fb({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 So({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:i}){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&&!!i,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?Zc: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:i,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Bt,"aria-label":Bt,children:[s.jsx(fc,{size:14}),s.jsx("span",{children:Bt})]})}),c&&s.jsx(El,{}),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 Kl="adhdev-tab-shortcuts";function Wl(){try{return JSON.parse(localStorage.getItem(Kl)||"{}")}catch{return{}}}function Fl({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>Wl()),[l,d]=o.useState(null),m=o.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=o.useCallback(f=>{c(f);try{localStorage.setItem(Kl,JSON.stringify(f))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const f=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){d(null);return}const N=m(x);if(!N)return;const y={...i};for(const[p,g]of Object.entries(y))g===N&&delete y[p];y[l]=N,u(y),d(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[e,l,i,u,m]),o.useEffect(()=>{if(!e)return;const f=x=>{if(!(!x.ctrlKey&&!x.metaKey&&!x.altKey)){for(const[N,y]of Object.entries(i))if(t.includes(N)&&m(x)===y){x.preventDefault(),r(),n(N);return}}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,i,t,r,n,m]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:d,saveShortcuts:u}}const ea=e=>{e.preventDefault()},pb=o.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:f,onReorderTab:x,onCommitPreviewOrder:N,onClearPreviewOrder:y,onDragStateReset:p,onDragTabKeyChange:g,onReceiveTab:b,onOpenContextMenu:h,longPressTimer:C,isGroupActive:S}){const v=Ks(t),M=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",I=v.isReconnecting,j=o.useCallback(A=>{l.current=t.tabKey,g(t.tabKey),A.dataTransfer.setData("text/tab-key",t.tabKey),A.dataTransfer.effectAllowed="move"},[t.tabKey,l,g]),w=o.useCallback(()=>{l.current=null,g(null),N(),y(),p()},[l,g,N,y,p]),B=o.useCallback(A=>{const F=l.current;if(!(!F||F===t.tabKey)&&A.dataTransfer.types.includes("text/tab-key")){A.preventDefault(),A.stopPropagation();const _=A.currentTarget.getBoundingClientRect(),E=A.clientX<_.left+_.width/2?"left":"right";f(F,t.tabKey,E)}},[t.tabKey,l,f]),P=o.useCallback(A=>{A.preventDefault(),A.stopPropagation();const F=A.dataTransfer.getData("text/tab-key");if(F&&F!==t.tabKey){const _=A.currentTarget.getBoundingClientRect(),E=A.clientX<_.left+_.width/2?"left":"right";c.includes(F)?x(F,t.tabKey,E):b&&b(F)}y()},[t.tabKey,c,x,b,y]),T=o.useCallback(A=>{A.stopPropagation(),d(),m(t.tabKey),u(t)},[t,u,d,m]),H=o.useCallback(A=>{A.preventDefault(),h(A.clientX,A.clientY,t.tabKey)},[t.tabKey,h]),z=o.useCallback(A=>{const F=A.touches[0];C.current=setTimeout(()=>{h(F.clientX,F.clientY,t.tabKey)},600)},[t.tabKey,C,h]),R=o.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),k=["adhdev-dockview-tab",M,r&&"is-active",S&&"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:B,onDrop:P,onClick:T,onContextMenu:H,onTouchStart:z,onTouchEnd:R,onTouchMove:R,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"})]})]}),i&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(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 hb({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:x,onDragTabKeyChange:N,onReceiveTab:y,onHideTab:p,isGroupActive:g,allowTabShortcuts:b=!0}){const[h,C]=o.useState(null),S=o.useRef(null),v=o.useRef(null),M=o.useMemo(()=>e.map(H=>H.tabKey),[e]);hr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:I,tabShortcuts:j,shortcutListening:w,setShortcutListening:B,saveShortcuts:P}=Fl({enabled:b,sortedTabKeys:e.map(H=>H.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const H=z=>{const R=document.querySelector("[data-pane-context-menu]");R&&R.contains(z.target)||C(null)};return window.addEventListener("mousedown",H,!0),()=>window.removeEventListener("mousedown",H,!0)},[h]),o.useEffect(()=>{const H=v.current;if(!H)return;const z=R=>{Math.abs(R.deltaY)<=Math.abs(R.deltaX)||(R.preventDefault(),H.scrollLeft+=R.deltaY)};return H.addEventListener("wheel",z,{passive:!1}),()=>H.removeEventListener("wheel",z)},[]);const T=o.useCallback((H,z,R)=>{C({x:H,y:z,tabKey:R})},[]);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(H=>s.jsx(pb,{conv:H,isActive:t===H.tabKey,isDraggedTab:a.current===H.tabKey,isTaskCompleteUnread:n.has(H.tabKey),shortcut:b?j[H.tabKey]:void 0,conversationKeys:M,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:x,onDragTabKeyChange:N,onReceiveTab:y,onOpenContextMenu:T,longPressTimer:S,isGroupActive:g},H.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),h&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:h.x,top:h.y},children:[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:ea,onClick:H=>{H.stopPropagation(),B(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:ea,onClick:()=>{const H={...j};delete H[h.tabKey],P(H),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:ea,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:()=>B(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:H=>H.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",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 xb({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,userName:d,groupIndex:m,onFocus:u,isSplitMode:f,numGroups:x,onMoveTab:N,onReceiveTab:y,style:p,onActiveTabChange:g,initialActiveTabId:b,initialTabOrder:h,onTabOrderChange:C,onHideTab:S,isFocused:v,allowTabShortcuts:M=!0,onOpenNewSession:I,liveSessionInboxState:j}){const{sendCommand:w}=gt(),B=o.useRef(null),{activeTabId:P,activeConv:T,sortedConversations:H,draggingTabRef:z,selectTab:R,handleTabReorder:k,updatePreviewOrder:A,commitPreviewOrder:F,clearPreviewOrder:_,moveTabToEnd:E,setDraggingTabKey:K}=mb({conversations:e,initialActiveTabId:b,initialTabOrder:h,onActiveTabChange:g,onTabOrderChange:C}),Y=jn({sendDaemonCommand:a,activeConv:T,setActionLogs:i,isStandalone:c}),{dragOver:be,dropAction:ce,resetDragState:D,handleDragEnter:ie,handleDragOver:fe,handleDragLeave:xe,handleDrop:X}=db({conversations:e,numGroups:x,onMoveTab:N,onReceiveTab:y,onOwnTabDrop:E,onClearPreviewOrder:_}),le=T&&!Ze(T)&&Ws(T)==="terminal",ye=o.useMemo(()=>T?t.find(he=>he.id===T.routeId):void 0,[t,T]),se=o.useMemo(()=>T?n.filter(he=>he.routeId===T.tabKey):[],[n,T]),ue=o.useMemo(()=>new Set(H.filter(he=>im(he,j,{isOpenConversation:he.tabKey===P})).map(he=>he.tabKey)),[P,j,H]);hr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:P,dragOver:be});const ke=o.useCallback(he=>{he.streamSource==="agent-stream"&&he.agentType&&w(he.routeId,Dc(),{agentType:he.agentType,...he.sessionId&&{targetSessionId:he.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:be?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(hb,{conversations:H,activeTabId:P,groupIndex:m,numGroups:x,unreadTabKeys:ue,draggingTabRef:z,onFocus:u,onSelectTab:R,onConversationActivated:ke,onPreviewReorder:A,onReorderTab:k,onCommitPreviewOrder:F,onClearPreviewOrder:_,onDragStateReset:D,onDragTabKeyChange:K,onMoveTab:N,onReceiveTab:y,onHideTab:S,isGroupActive:v??!1,allowTabShortcuts:M}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ie,onDragOver:fe,onDragLeave:xe,onDrop:X,children:[be&&s.jsx(fb,{dropAction:ce,canSplit:!!(x<4&&N)}),T?s.jsx(jo,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!le,ideEntry:ye,terminalRef:B,handleModalButton:Y.handleModalButton,handleRelaunch:Y.handleRelaunch,handleSendChat:Y.handleSendChat,isSendingChat:Y.isSendingChat,sendFeedbackMessage:Y.sendFeedbackMessage,handleFocusAgent:Y.handleFocusAgent,isFocusingAgent:Y.isFocusingAgent,actionLogs:se,userName:d,isInputActive:!f||!!v}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(So,{conversationsCount:e.length,isSplitMode:f,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:I})})]})]})}function bb({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:f,userName:x,focusedGroup:N,focusGroup:y,moveTabToGroup:p,splitTabRelative:g,closeGroup:b,handleResizeStart:h,groupActiveTabIds:C,setGroupActiveTab:S,groupTabOrders:v,setGroupTabOrder:M,toggleHiddenTab:I,onOpenNewSession:j,allowTabShortcuts:w=!0,liveSessionInboxState:B}){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 H=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:z=>h(T-1,z),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(xb,{style:t?{flexBasis:H??`${100/r}%`,flexGrow:H?0:1,flexShrink:H?0:1}:void 0,conversations:P,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:f,userName:x,groupIndex:T,isFocused:t&&N===T,onFocus:()=>y(T),isSplitMode:t,numGroups:r,onMoveTab:(z,R)=>{R==="left"&&T>0?p(z,T-1):R==="right"&&T<r-1?p(z,T+1):R==="split-left"&&r<4?g(z,T,"left"):R==="split-right"&&r<4&&g(z,T,"right")},onReceiveTab:z=>p(z,T),onActiveTabChange:z=>S(T,z),initialActiveTabId:C[T],initialTabOrder:v[T],onTabOrderChange:z=>M(T,z),onHideTab:I,onOpenNewSession:j,allowTabShortcuts:w,liveSessionInboxState:B})]},T)})})}function Hl({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?ut.onScreenshot("ide-page",(u,f)=>{if(u!==e)return;const x=new FileReader;x.onload=()=>i(x.result),x.readAsDataURL(f)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.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]),o.useEffect(()=>{i(null)},[e,t]),o.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=o.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 Ul="adhdev-dashboard-action-shortcuts",gb=1200,yb=[["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 vb(){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 zl(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 Ea(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(zl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Ul)||"{}"),n={...t,...r};for(const[a,i]of yb)n[a]===i&&(n[a]=t[a]);return n}catch{return t}}function Vl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function wb({enabled:e=!0,onTrigger:t}){const r=vb(),[n,a]=o.useState(()=>pn(r)),[i,c]=o.useState(null),[l,d]=o.useState([]),m=o.useRef({parts:[],timer:null}),u=o.useCallback(p=>{const g=[];return p.metaKey&&g.push(r?"⌘":"Meta"),p.ctrlKey&&g.push("Ctrl"),p.altKey&&g.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&g.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(g.push(Vl(p.key)),g.join("+"))},[r]),f=o.useCallback(p=>{a(p);try{localStorage.setItem(Ul,JSON.stringify(p))}catch{}},[]);o.useEffect(()=>{const p=pn(r),g=Object.entries(n),b=Object.entries(p);g.length===b.length&&g.every(([h,C])=>p[h]===C)||f(p)},[n,r,f]);const x=o.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),N=o.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},gb))},[]);o.useEffect(()=>{if(!i)return;const p=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){c(null),d([]);return}const b=u(g);if(!b)return;const C=!(g.metaKey||g.ctrlKey||g.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[i]=v,f(M),c(null),d([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,u,f,i,l]),o.useEffect(()=>{if(!e||i)return;const p=g=>{if(g.defaultPrevented)return;const b=u(g);if(!b)return;const h=g.metaKey||g.ctrlKey||g.altKey;if(Ea(g.target))return;const C=m.current.parts,S=h?[b]:[...C.slice(-1),b].slice(-2),v=S.join(" "),M=S[S.length-1],I=Object.entries(n).filter(([,T])=>!!T),j=I.find(([,T])=>T===v);if(j){g.preventDefault(),x(),t(j[0]);return}if(I.some(([,T])=>T.startsWith(`${v} `))){g.preventDefault(),m.current.parts=S,N();return}const B=I.find(([,T])=>T===M);if(B){g.preventDefault(),x(),t(B[0]);return}if(I.some(([,T])=>T.startsWith(`${M} `))){g.preventDefault(),m.current.parts=[M],N();return}x()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,N,e,u,t,x,i]),o.useEffect(()=>()=>x(),[x]);const y=o.useMemo(()=>zl(r),[r]);return{isMac:r,actionDefinitions:y,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:d,saveShortcuts:f}}function jb({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 Gl(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Ti({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!Gl(n):!0}function kb({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:Gl(r)}const ql=1e3,Sb=4;function Mi(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Ii(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function Nb({detachDelayMs:e=ql,stillnessThresholdPx:t=Sb,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let i=null,c=null,l=null,d=null,m=null,u=!1;const f=()=>{m!=null&&(a(m),m=null)},x=()=>{f(),l=null},N=()=>{f(),i=null,c=null,l=null,d=null,u=!1},y=()=>{!i||!l||!d||u||m!=null||(m=n(()=>{m=null,!(!i||!l||!d||u)&&Mi(d,c)&&(Ii(l,d,t)||(u=!0,r({panelId:i,clientX:d.clientX,clientY:d.clientY})))},e))},p=b=>{if(!(!i||u)){if(!Mi(b,c)){d={clientX:b.clientX,clientY:b.clientY},x();return}(!l||Ii(l,b,t))&&(f(),l={clientX:b.clientX,clientY:b.clientY}),d={clientX:b.clientX,clientY:b.clientY},y()}},g=b=>{!i||u||(b&&(d={clientX:b.clientX,clientY:b.clientY}),x())};return{startDrag:b=>{f(),i=b.panelId,c=b.selfPanelBounds??null,l=null,d={clientX:b.clientX,clientY:b.clientY},u=!1},markSelfPanel:p,markNonSelfPanel:g,markNoDropTarget:g,markDockTarget:g,endDrag:N,isDragging:()=>i!=null,hasDetached:()=>u,dispose:N}}function Cb(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Br(e){return e.isActive}function Ai(e){return e.isVisible}const Yl=o.createContext(null);function Mn(){const e=o.useContext(Yl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Yr(e){return lt(e)||e.tabKey}function Tb(e){return`remote:${e}`}function Pt(e){return e.startsWith("remote:")}function Ri(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Mb(e){e.preventDefault()}function ta(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 sa(e,t){e.classList.remove(ba.className,ga.className),e.classList.add(t==="light"?ba.className:ga.className)}function Li(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 Ib(e){const[,t]=o.useState(0);o.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 Ab(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:Yr(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 Pi(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!==Yr(n)&&a.api.setTitle(Yr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Yr(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 _i(e,t,r){var d,m;const n=r?Tb(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 i=e.getPanel(n),c=Qc(a);if(i){i.title!==c&&i.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 Rb({params:e,api:t}){var N;const r=Mn(),n=o.useRef(null),[a,i]=o.useState(()=>Br(t)),[c,l]=o.useState(()=>Ai(t)),d=r.conversationsByTabKey.get(e.tabKey),m=jn({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(Br(t)),l(Ai(t));const y=[t.onDidActiveChange(p=>i(p.isActive)),t.onDidActiveGroupChange(p=>{if(!Br(t)&&!p.isActive){i(!1);return}i(Br(t))}),t.onDidVisibilityChange(p=>l(p.isVisible))];return()=>{for(const p of y)p.dispose()}},[t]);const u=o.useMemo(()=>d?r.ides.find(y=>y.id===d.routeId):void 0,[r.ides,d]),f=o.useMemo(()=>d?r.actionLogs.filter(y=>y.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(So,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const x=!Ze(d)&&Ws(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(jo,{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:((N=r.scrollToBottomRequest)==null?void 0:N.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:c})})}function Lb({params:e}){var d;const t=Mn(),r=o.useMemo(()=>Et([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=o.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:i,screenshotUsage:c,handleRemoteAction:l}=Hl({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(yc,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,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 Pb(){const e=Mn();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(So,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function _b(e){var N,y;Ib(e);const t=Mn(),r=o.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),g=((N=e.api.group.activePanel)==null?void 0:N.id)===e.api.id,b=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${g?" 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=((y=e.api.group.activePanel)==null?void 0:y.id)===e.api.id,i=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":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:lt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var g;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((g=p.target)==null?void 0:g.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 Db({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:d,userName:m,toggleHiddenTab:u,actionShortcuts:f,registerActionHandlers:x,onActiveTabChange:N,onOpenNewSession:y,onRequestScrollToBottom:p,requestedActiveTabKey:g,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:h,scrollToBottomRequest:C,liveSessionInboxState:S,layoutProfile:v}){var Qe,Ge,rt;const{theme:M}=ho(),{sendCommand:I}=gt(),j=o.useRef(null),w=o.useRef(null),B=o.useRef(null),P=o.useRef(!1),T=o.useRef(!1),H=o.useRef(!1),z=o.useRef(null),R=o.useRef([]),[k,A]=o.useState(null),[F,_]=o.useState(0),E=o.useRef(typeof window>"u"?{}:Zh(v)),K=o.useMemo(()=>new Map(e.map(W=>[W.tabKey,W])),[e]),Y=o.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(te=>K.has(te.id))}catch{return!1}}):!1},[K,F,e]),be=o.useCallback(()=>{var W;(W=j.current)==null||W.focus()},[]),ce=o.useCallback((W,U)=>{p==null||p(W,U)},[p]),D=o.useCallback(W=>{const U=document,G=W.document;for(const re of U.querySelectorAll('link[rel="stylesheet"]')){const je=G.createElement("link");je.rel="stylesheet",je.href=re.href,re.crossOrigin&&(je.crossOrigin=re.crossOrigin),G.head.appendChild(je)}for(const re of U.querySelectorAll("style")){const je=G.createElement("style");je.textContent=re.textContent,G.head.appendChild(je)}const te=[];for(const re of U.styleSheets)try{for(const je of re.cssRules)je instanceof CSSStyleRule&&(je.selectorText===":root"||je.selectorText==="html")&&te.push(je.cssText)}catch{}if(te.length>0){const re=G.createElement("style");re.textContent=te.join(`
|
|
52
|
+
`),G.head.appendChild(re)}const $=U.documentElement.getAttribute("data-theme");$&&G.documentElement.setAttribute("data-theme",$),G.documentElement.style.colorScheme=$==="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"),sa(Z,M))},[M]),ie=o.useCallback(()=>{var U;const W=j.current;if(W)for(const G of W.groups)try{const te=(U=G.element)==null?void 0:U.ownerDocument;if(!te||te===document)continue;const $=te.getElementById("dv-popout-window");$ instanceof HTMLElement&&($.classList.add("adhdev-dockview"),sa($,M));const q=document.documentElement.getAttribute("data-theme");q&&te.documentElement.setAttribute("data-theme",q),te.documentElement.style.colorScheme=q==="light"?"light":"dark",te.body.className=document.body.className;const Z=document.documentElement.getAttribute("style");Z?te.documentElement.setAttribute("style",Z):te.documentElement.removeAttribute("style")}catch{}},[M]),fe=o.useCallback(W=>{const U=j.current;if(!U)return;const G=U.getPanel(W);G&&U.addPopoutGroup(G,{popoutUrl:"/popout.html",onDidOpen:({window:te})=>{D(te),ve();const $=K.get(W);te.document.title=$?`${lt($)} — ADHDev`:"ADHDev — Popout"}})},[K,D]),xe=o.useCallback(W=>{const U=j.current,G=U==null?void 0:U.getPanel(W);if(!U||!G)return;const te=U.groups.filter($=>{var q;try{return((q=$.element)==null?void 0:q.ownerDocument)===document}catch{return!0}});te.length>0?G.api.moveTo({group:te[0],position:"center"}):G.api.moveTo({position:"center"}),G.api.setActive()},[]),X=o.useCallback(W=>{var te;const U=j.current;if(!U)return!1;const G=U.getPanel(W);if(!G)return!1;try{return((te=G.group.element)==null?void 0:te.ownerDocument)!==document}catch{return!1}},[]),le=o.useCallback(W=>{X(W)&&xe(W),u(W)},[X,xe,u]),ye=o.useCallback(W=>{const U=j.current,G=U==null?void 0:U.getPanel(W);!U||!G||U.addFloatingGroup(G,{width:600,height:500})},[]),se=o.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}},[]),ue=o.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:K.has(W)?W:null},[K]),ke=o.useCallback(W=>{const U=j.current,G=U==null?void 0:U.getPanel(W);if(!U||!G)return;const te=U.groups.filter($=>{try{return $.model.location.type==="grid"}catch{return!0}});te.length>0?G.api.moveTo({group:te[0],position:"center"}):G.api.moveTo({position:"center"}),G.api.setActive()},[]),he=o.useCallback(()=>{var q;const W=j.current;if(!W)return;const G=W.groups.filter(Z=>{var re;try{return((re=Z.element)==null?void 0:re.ownerDocument)===document&&Z.model.location.type==="grid"}catch{return!1}})[0]||null,te=[...W.panels];for(const Z of te){const re=(q=Z.group.element)==null?void 0:q.ownerDocument,je=Z.group.model.location.type;re===document&&je==="grid"||(G&&G.id!==Z.group.id?Z.api.moveTo({group:G,position:"center"}):Z.api.moveTo({position:"center"}))}const $=W.activePanel;$&&($.group.model.openPanel($),$.api.setActive()),ta(document)},[]),ve=o.useCallback(()=>{var U,G;const W=j.current;if(W)for(const te of W.groups){const $=(U=te.element)==null?void 0:U.ownerDocument;if(!$||$===document)continue;const q=$.getElementById("dv-popout-window");if(!(q instanceof HTMLElement))continue;let Z=null,re=$.title||"ADHDev",je="Popout workspace";const Le=te.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([...K.values()],Re);re=Qc(qe),je=qe!=null&&qe.machineName?`Remote view · ${qe.machineName}`:"Remote view"}else{const Re=K.get(Le.id);re=Re?lt(Re):Le.title||Le.id,je=Re?os(Re):"Dockview panel"}$.title=`${re} — ADHDev`;const _e=Array.from($.querySelectorAll("#adhdev-popout-header"));for(const Re of _e)Re.remove();const Ne=$.createElement("div");Ne.id="adhdev-popout-header",$.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;">${Ri(re)}</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;">${Ri(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&&xe(Z),(Re=$.defaultView)==null||Re.focus()})}},[K,xe]),ee=o.useCallback(W=>{var te;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 $=G.group.model.location;$.type==="popout"?$.getWindow().focus():ta((te=G.group.element)==null?void 0:te.ownerDocument)}catch{}}},[ce]),pe=o.useCallback(W=>{const U=j.current,G=U==null?void 0:U.activePanel,te=(U==null?void 0:U.activeGroup)||(G==null?void 0:G.group);if(!U||!G||!te)return;const $=te.panels||[];if($.length<=1)return;const q=$.findIndex(je=>je.id===G.id);if(q<0)return;const Z=(q+W+$.length)%$.length,re=$[Z];re&&(re.group.model.openPanel(re),re.api.setActive(),Pt(re.id)||ce(re.id,"dockview-shortcut"))},[ce]),oe=o.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 te=U.groups||[],$=te.find(Be=>Be.id===G.id);if(!$)return;const q=$.element.getBoundingClientRect(),Z=q.left+q.width/2,re=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-re),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-re),dt=je(q.top,q.bottom,Re.top,Re.bottom)):W==="above"?(yt=et<re,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>re,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 te){if(Be.id===$.id)continue;const Re=Le(Be);Number.isFinite(Re)&&(Re>=Ne||(Ne=Re,_e=Be))}return _e||void 0},[]),de=o.useCallback(W=>{var te;const U=oe(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"),ta((te=U.element)==null?void 0:te.ownerDocument))},[oe,ce]),ae=o.useCallback((W,U)=>{const G=j.current,te=G==null?void 0:G.activePanel,$=(G==null?void 0:G.activeGroup)||(te==null?void 0:te.group);if(!G||!te||!$)return;let q=oe(W);!q&&(U!=null&&U.createGroupIfMissing)&&(q=G.addGroup({referenceGroup:$,direction:W})),q&&(te.api.moveTo({group:q,position:"center"}),te.group.model.openPanel(te),te.api.setActive(),Pt(te.id)||ce(te.id,U!=null&&U.createGroupIfMissing?"dockview-split":"dockview-move"))},[oe,ce]),{isMac:Q,tabShortcuts:me,shortcutListening:J,setShortcutListening:Ae,saveShortcuts:Te}=Fl({sortedTabKeys:e.map(W=>W.tabKey),onFocus:be,onSelectTab:ee}),$e=o.useCallback(()=>{var G;const W=j.current;if(!W)return;const U=W.activePanel;if(U){if(Pt(U.id)){const te=((G=U.params)==null?void 0:G.routeId)||U.id.slice(7),$=Et(e,te);$!=null&&$.tabKey&&Ae($.tabKey);return}K.has(U.id)&&Ae(U.id)}},[K,ee,Ae,e]),Ue=o.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(Vl(W.key)),U.join("+"))},[Q]),O=o.useCallback(W=>{var U,G;switch(W){case"splitActiveTabRight":ae("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":ae("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const te=ue();te&&ye(te);return}case"popoutActiveTab":{const te=ue();te&&fe(te);return}case"dockActiveTab":{const te=ue();if(!te)return;X(te)?xe(te):se(te)&&ke(te);return}case"focusLeftPane":de("left");return;case"focusRightPane":de("right");return;case"focusUpPane":de("above");return;case"focusDownPane":de("below");return;case"moveActiveTabToLeftPane":ae("left");return;case"moveActiveTabToRightPane":ae("right");return;case"moveActiveTabToUpPane":ae("above");return;case"moveActiveTabToDownPane":ae("below");return;case"selectPreviousGroupTab":pe(-1);return;case"selectNextGroupTab":pe(1);return;case"setActiveTabShortcut":$e();return;case"hideCurrentTab":{const te=(G=(U=j.current)==null?void 0:U.activePanel)==null?void 0:G.id;te&&!Pt(te)&&le(te);return}default:return}},[pe,ke,de,ye,ue,le,se,X,xe,ae,fe,$e]);o.useEffect(()=>{if(!k)return;const W=k.sourceDocument,U=W.defaultView??window,G=te=>{const $=W.querySelector("[data-dockview-tab-context-menu]");$&&$.contains(te.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=o.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:K,hasDetachedConversationPanels:Y,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:y,liveSessionInboxState:S,sendDaemonCommand:a,setActionLogs:i,toggleHiddenTab:le,userName:m,scrollToBottomRequest:C,tabShortcuts:me,openTabContextMenu:({x:W,y:U,tabKey:G,sourceDocument:te})=>A({x:W,y:U,tabKey:G,sourceDocument:te??document}),popoutTab:fe,moveTabBackToMain:xe,isTabInPopout:X,floatTab:ye,isTabFloating:se}),[n,t,K,Y,r,c,l,y,S,a,i,le,m,C,me,fe,xe,X,ye,se]),Me=k?jb({isTabInPopout:X(k.tabKey),isTabFloating:se(k.tabKey),tabShortcut:me[k.tabKey],actionShortcuts:f}):[],De=o.useCallback(W=>{var te;const U=j.current;if((((te=U==null?void 0:U.activePanel)==null?void 0:te.id)??null)===W.id){W.group.model.openPanel(W);return}W.group.model.openPanel(W),W.api.setActive()},[]),Oe=o.useCallback((W,U="requested-tab")=>{if(!W)return!1;const G=j.current;if(!G)return!1;const te=G.getPanel(W);return te?(De(te),ce(W,U),h==null||h(),!0):!1},[De,h,ce]),He=o.useCallback(()=>{if(H.current)return!1;const W=Oe(z.current,"stored-layout-restore");return W&&(H.current=!0),W},[Oe]),Je=o.useCallback(()=>{var U;const W=j.current;W&&Qh(v,{activeTabId:((U=W.activePanel)==null?void 0:U.id)??null,layout:W.toJSON()})},[v]),st=o.useCallback(()=>{ex(v,E.current)},[v]),mt=o.useCallback(W=>{var te,$,q,Z;const U=j.current;if(!U)return{kind:"grid"};const G=U.toJSON();for(const re of G.floatingGroups||[])if(($=(te=re.data)==null?void 0:te.views)!=null&&$.includes(W)&&re.position)return{kind:"floating",position:re.position};for(const re of G.popoutGroups||[])if((Z=(q=re.data)==null?void 0:q.views)!=null&&Z.includes(W))return{kind:"popout",position:re.position,popoutUrl:re.url};return{kind:"grid"}},[]),ht=o.useCallback(W=>{const U=j.current;if(!U)return;const G=U.getPanel(W),te=E.current[W];if(!G||!te||te.kind==="grid")return;if(G.group.model.location.type===te.kind){delete E.current[W],st();return}if(te.kind==="floating"){U.addFloatingGroup(G,{x:te.position.left??24,y:te.position.top??24,width:te.position.width,height:te.position.height}),delete E.current[W],st();return}delete E.current[W],st()},[st]);o.useEffect(()=>(x==null||x({setShortcutForActiveTab:$e,restoreHiddenTabToSavedLocation:ht,activateConversationTab:ee,resetAllPanelsToMain:he,activatePreviousTabInGroup:()=>pe(-1),activateNextTabInGroup:()=>pe(1),floatActiveTab:()=>{const W=ue();W&&ye(W)},popoutActiveTab:()=>{const W=ue();W&&fe(W)},dockActiveTab:()=>{const W=ue();W&&(X(W)?xe(W):se(W)&&ke(W))},splitActiveTabRight:()=>ae("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>ae("below",{createGroupIfMissing:!0}),focusLeftPane:()=>de("left"),focusRightPane:()=>de("right"),focusUpPane:()=>de("above"),focusDownPane:()=>de("below"),moveActiveTabToLeftPane:()=>ae("left"),moveActiveTabToRightPane:()=>ae("right"),moveActiveTabToUpPane:()=>ae("above"),moveActiveTabToDownPane:()=>ae("below")}),()=>x==null?void 0:x(null)),[pe,ke,ye,de,ue,se,X,ae,xe,fe,x,he,ht,ee,$e]),o.useEffect(()=>()=>{var W;(W=B.current)==null||W.call(B),B.current=null},[]);const xt=o.useCallback(W=>{var G,te;j.current=W.api,(G=B.current)==null||G.call(B),B.current=null;const U=Jh(v);if(z.current=(U==null?void 0:U.activeTabId)??null,U!=null&&U.layout&&W.api.fromJSON(U.layout,{reuseExistingPanels:!1}),T.current=Ti({hasStoredLayout:!!(U!=null&&U.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),T.current||(Pi(W.api,e),_i(W.api,e,b)),W.api.totalPanels===0&&e.length>0){const $=Ab(W.api,e,g);if($){const q=W.api.getPanel($);q&&De(q)}}else!T.current&&!Oe(g)&&He();if(P.current=!0,W.api.onDidActivePanelChange($=>{var Z;if(z.current=($==null?void 0:$.id)??null,H.current=!0,ve(),$&&Pt($.id)){const re=((Z=$.params)==null?void 0:Z.routeId)||$.id.slice(7),je=Et(e,re);N((je==null?void 0:je.tabKey)??null),Je();return}if(N(($==null?void 0:$.id)??null),Je(),!$)return;const q=K.get($.id);(q==null?void 0:q.streamSource)==="agent-stream"&&q.agentType&&I(q.routeId,Dc(),{agentType:q.agentType,...q.sessionId&&{targetSessionId:q.sessionId}}).catch(()=>{})}),W.api.onDidLayoutChange(()=>{Je(),ve(),_($=>$+1)}),Cb()){const $=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},re=Nb({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}re.startDrag({panelId:Ne.panel.id,selfPanelBounds:q(Ne.panel.group.element),...$(Ne.nativeEvent)})}}),W.api.onWillShowOverlay(Ne=>{if(re.hasDetached()){Ne.preventDefault();return}re.markDockTarget($(Ne.nativeEvent))}),W.api.onWillDrop(Ne=>{if(re.hasDetached()){Ne.preventDefault(),re.endDrag();return}re.markDockTarget($(Ne.nativeEvent))}),W.api.onDidDrop(()=>re.endDrag()),W.api.onUnhandledDragOverEvent(Ne=>{re.isDragging()&&re.markSelfPanel($(Ne.nativeEvent))})],Le=Ne=>{if(!re.isDragging())return;const Ee=$(Ne);Z(Ee)&&re.markNonSelfPanel(Ee)},_e=()=>re.endDrag();window.addEventListener("dragover",Le,!0),window.addEventListener("drop",_e,!0),window.addEventListener("dragend",_e,!0),B.current=()=>{re.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($=>{requestAnimationFrame(()=>{var q,Z;try{const re=(q=$.element)==null?void 0:q.ownerDocument;if(!re||re===document)return;(Z=re.getElementById("dv-popout-window"))==null||Z.classList.add("adhdev-dockview");const je=document.documentElement.getAttribute("data-theme");je&&re.documentElement.setAttribute("data-theme",je),re.body.className=document.body.className;const Le=document.documentElement.getAttribute("style");Le&&re.documentElement.setAttribute("style",Le)}catch{}ve(),_(re=>re+1)})}),N(((te=W.api.activePanel)==null?void 0:te.id)??null)},[De,Oe,K,r,d,v,N,Je,g,b,I,ve,e]);o.useLayoutEffect(()=>{const W=j.current;if(!W||!P.current||T.current&&Ti({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;T.current&&(T.current=!1);const U=R.current,G=new Set(U),te=e.map(_e=>_e.tabKey),$=new Set(te),q=kb({previousVisibleConversationCount:U.length,visibleConversationCount:e.length,ides:r});let Z=!1;for(const _e of U)$.has(_e)||q||(E.current[_e]=mt(_e),Z=!0);Z&&st(),q||(Pi(W,e),_i(W,e,b));const re=te.filter(_e=>!G.has(_e));let je=!1;for(const _e of re){const Ne=W.getPanel(_e),Ee=E.current[_e];if(!Ne||!Ee||Ee.kind==="grid")continue;if(Ne.group.model.location.type===Ee.kind){delete E.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 E.current[_e],je=!0;continue}}if(je&&st(),R.current=te,g&&Oe(g))return;!W.activePanel&&W.panels[0]&&De(W.panels[0]),!!(W.activePanel&&W.getPanel(W.activePanel.id))||He()},[De,Oe,He,r,d,st,mt,g,b,e]),o.useEffect(()=>{P.current&&Oe(g)},[Oe,g]),o.useEffect(()=>{const W=G=>{const te=G.target;if(!te)return;const $=te.querySelector("[data-tab-key]")||te.closest("[data-tab-key]");if($){const q=$.getAttribute("data-tab-key");if(q&&G.dataTransfer){const Z=te.closest(".dv-tab")||$.closest(".dv-tab")||$;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=Li(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)}},[F]),o.useEffect(()=>{var U;const W=(U=w.current)==null?void 0:U.querySelector(".adhdev-dockview");W instanceof HTMLElement&&sa(W,M),ie(),ve()},[ve,ie,M]),o.useEffect(()=>{ve()},[ve]),o.useEffect(()=>{const W=U=>{if(U.defaultPrevented||J)return;const G=Ue(U);if(!G)return;const te=U.metaKey||U.ctrlKey||U.altKey;Ea(U.target)&&!te||pn(Q).setActiveTabShortcut!==G||(U.preventDefault(),U.stopPropagation(),$e())};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[Ue,Q,J,$e]),o.useEffect(()=>{const W=w.current;if(!W)return;const U=G=>{var re,je;if(!G.isTrusted)return;const te=(je=(re=G.target)==null?void 0:re.closest)==null?void 0:je.call(re,".dv-scrollable");if(!te)return;G.preventDefault(),G.stopPropagation();const $=Math.abs(G.deltaX),q=Math.abs(G.deltaY),Z=$>q?G.deltaX:G.deltaY;te.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})},[]),o.useEffect(()=>{const W=Li(j.current);if(W.length===0)return;const U=W.map(G=>{let te=[],$=null;const q=()=>{$!=null&&G.clearTimeout($),$=null,te=[]},Z=()=>{$!=null&&G.clearTimeout($),$=G.setTimeout(()=>{$=null,te=[]},1200)},re=Le=>{if(!Le.ctrlKey&&!Le.metaKey&&!Le.altKey)return;const _e=Ue(Le);if(!_e)return;const Ne=Wl();for(const[Ee,Be]of Object.entries(Ne))if(e.some(Re=>Re.tabKey===Ee)&&Be===_e){Le.preventDefault(),ee(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(Ea(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]:[...te.slice(-1),_e].slice(-2),qe=Re.join(" "),et=Re[Re.length-1],ct=Be.find(([,Ve])=>Ve===qe);if(ct){Le.preventDefault(),q(),O(ct[0]);return}if(Be.some(([,Ve])=>Ve.startsWith(`${qe} `))){Le.preventDefault(),te=Re,Z();return}const dt=Be.find(([,Ve])=>Ve===et);if(dt){Le.preventDefault(),q(),O(dt[0]);return}if(Be.some(([,Ve])=>Ve.startsWith(`${et} `))){Le.preventDefault(),te=[et],Z();return}q()};return G.addEventListener("keydown",re),G.addEventListener("keydown",je),()=>{q(),G.removeEventListener("keydown",re),G.removeEventListener("keydown",je)}});return()=>{for(const G of U)G()}},[Ue,Q,F,ee,J,O,e]);const Ce=M==="light"?ba:ga,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(Yl.Provider,{value:Se,children:[s.jsx("div",{ref:w,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx($d,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:Rb,remote:Lb},defaultTabComponent:_b,watermarkComponent:Pb,onReady:xt,singleTabMode:"default",tabAnimation:"smooth",theme:Ce,popoutUrl:"/popout.html"})}),k&&lr.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(Lu,{size:13,className:"shrink-0 opacity-70"}),G=()=>{};switch(W.id){case"dockInWindow":case"dockBackToGrid":U=s.jsx(_u,{size:13,className:"shrink-0 opacity-70"}),G=()=>{ke(k.tabKey),A(null)};break;case"moveBackToMain":U=s.jsx(Ru,{size:13,className:"shrink-0 opacity-70"}),G=()=>{xe(k.tabKey),A(null)};break;case"floatAsPanel":U=s.jsx(Pu,{size:13,className:"shrink-0 opacity-70"}),G=()=>{ye(k.tabKey),A(null)};break;case"openInNewWindow":U=s.jsx(Au,{size:13,className:"shrink-0 opacity-70"}),G=()=>{fe(k.tabKey),A(null)};break;case"setShortcut":G=te=>{te.stopPropagation(),Ae(k.tabKey),A(null)};break;case"removeShortcut":U=s.jsx(vt,{size:13,className:"shrink-0 opacity-70"}),G=()=>{const te={...me};delete te[k.tabKey],Te(te),A(null)};break;case"hideTab":U=s.jsx(Va,{size:13,className:"shrink-0 opacity-70"}),G=()=>{le(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:Mb,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&&lr.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 Xl="adhdev-recent-launch-args-v1",Eb=8;function Jl(e){return String(e||"").trim().replace(/\s+/g," ")}function No(e,t){return`${e.trim()}::${t.trim()}`}function Co(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Xl)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function Ql(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Xl,JSON.stringify(e))}catch{}}function $a(e,t){var i;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((i=Co().byKey[No(r,n)])==null?void 0:i.items)||[]}function Zl(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),i=Jl(r);if(!n||!a||!i)return;const c=Co(),l=No(n,a),d=((u=c.byKey[l])==null?void 0:u.items)||[],m=[i,...d.filter(f=>f!==i)].slice(0,Eb);c.byKey[l]={items:m},Ql(c)}function $b(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),i=Jl(r);if(!n||!a||!i)return;const c=Co(),l=No(n,a),m=(((u=c.byKey[l])==null?void 0:u.items)||[]).filter(f=>f!==i);m.length>0?c.byKey[l]={items:m}:delete c.byKey[l],Ql(c)}function ed(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Xr({title:e,description:t,action:r,children:n,className:a="",contentClassName:i=""}){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 ${i}`.trim():i,children:n}):null]})}function Bb({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 td({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:i,onRefresh:c,onOpenHistory:l,onClearSelection:d}){const m=i?Bl(i):null,u=Bb({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Xr,{title:"Saved history",description:lo(),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:Pp()})]}),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 sd({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 Ob({workspaceMode:e,activeKind:t,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:i,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||i,children:l.label},l.id))})]})}function ra(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 Or(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Kb({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:i,onLaunchProvider:c,onListMeshes:l,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Ve,we;const u=br(),f=o.useMemo(()=>[...e].sort(Qa),[e]),[x,N]=o.useState(((Ve=f[0])==null?void 0:Ve.id)||""),y=o.useMemo(()=>f.find(V=>V.id===x)||f[0],[x,f]),p=o.useMemo(()=>((y==null?void 0:y.workspaces)||[]).map(V=>({id:V.id,path:V.path,label:V.label})),[y]),g=(y==null?void 0:y.defaultWorkspaceId)||null,[b,h]=o.useState("workspace"),[C,S]=o.useState(""),[v,M]=o.useState(""),[I,j]=o.useState([]),[w,B]=o.useState(""),[P,T]=o.useState(!1),[H,z]=o.useState(null),[R,k]=o.useState(""),[A,F]=o.useState(ra(f[0])),[_,E]=o.useState(""),[K,Y]=o.useState(""),[be,ce]=o.useState([]),[D,ie]=o.useState(""),[fe,xe]=o.useState([]),[X,le]=o.useState(!1),[ye,se]=o.useState(!1),[ue,ke]=o.useState(""),[he,ve]=o.useState(!1),[ee,pe]=o.useState(()=>wt()),[oe,de]=o.useState(null),[ae,Q]=o.useState(!1),[me,J]=o.useState(""),[Ae,Te]=o.useState(null),[$e,Ue]=o.useState(!1),[O,Se]=o.useState(""),[Me,De]=o.useState([]),[Oe,He]=o.useState(!1),[Je,st]=o.useState(""),[mt,ht]=o.useState(!1),xt=o.useRef(null),Ce=o.useRef(0);o.useEffect(()=>{var V;!x&&((V=f[0])!=null&&V.id)&&N(f[0].id)},[x,f]),o.useEffect(()=>{!y||!(!y.workspaces||!y.availableProviders||!y.detectedIdes||!y.recentLaunches)||u(y.id,{minFreshMs:3e4}).catch(()=>{})},[u,y]);const ze=o.useMemo(()=>((y==null?void 0:y.availableProviders)||[]).filter(V=>bs(V,"cli")),[y]),Qe=o.useMemo(()=>((y==null?void 0:y.availableProviders)||[]).filter(V=>bs(V,"acp")),[y]),Ge=o.useMemo(()=>((y==null?void 0:y.detectedIdes)||[]).map(V=>({id:V.type,label:V.name||V.type,meta:V.running?"Detected locally":"Available to open"})),[y]),rt=o.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=o.useMemo(()=>I.find(V=>V.id===w)||null,[I,w]),U=o.useMemo(()=>ze.find(V=>V.type===_)||null,[ze,_]),G=o.useMemo(()=>Ll(U==null?void 0:U.meshCoordinator,{meshId:(W==null?void 0:W.id)||"",workspace:(W==null?void 0:W.workspace)||""}),[U,W]),te=Ae||G,$=o.useCallback(async V=>{T(!0),k("");try{const Ie=await l(V);j(Ie),B(L=>{var ne;return Ie.some(ge=>ge.id===L)?L:((ne=Ie[0])==null?void 0:ne.id)||""}),z(V)}catch(Ie){j([]),B(""),z(V),k(Ie instanceof Error?Ie.message:"Could not load meshes")}finally{T(!1)}},[l]);o.useEffect(()=>{var Ie;if(!y)return;if(xt.current!==y.id){xt.current=y.id,h("workspace"),S(g||((Ie=p[0])==null?void 0:Ie.id)||"__home__"),M(""),j([]),B(""),z(null),k(""),F(ra(y)),E(""),Y(""),ie(""),xe([]),se(!1),ke(""),pe(wt()),J(""),Te(null);return}S(L=>{var ne;return L==="__custom__"||L==="__home__"||p.some(ge=>ge.id===L)?L:g||((ne=p[0])==null?void 0:ne.id)||"__home__"}),F(L=>L==="ide"&&Ge.length>0||L==="cli"&&ze.length>0||L==="acp"&&Qe.length>0?L:ra(y))},[Qe.length,ze.length,g,Ge.length,y,p]),o.useEffect(()=>{!y||b!=="mesh"||H===y.id||P||$(y.id)},[$,H,P,y,b]),o.useEffect(()=>{b==="mesh"&&A!=="cli"&&ze.length>0&&F("cli")},[A,ze.length,b]),o.useEffect(()=>{var V;A&&(rt.some(Ie=>Ie.id===_)||E(((V=rt[0])==null?void 0:V.id)||""))},[A,rt,_]),o.useEffect(()=>{Te(null)},[y==null?void 0:y.id,w,_,b]);const q=o.useCallback(async(V,Ie)=>{const L=Ce.current+1;return Ce.current=L,le(!0),ke(""),m(V,Ie).then(ne=>{Ce.current===L&&xe(ne)}).catch(ne=>{Ce.current===L&&(xe([]),ke(ne instanceof Error?ne.message:"Could not load saved sessions"))}).finally(()=>{Ce.current===L&&(le(!1),se(!0))})},[m]),Z=o.useCallback((V,Ie)=>{ce($a(V,Ie))},[]);o.useEffect(()=>{Ce.current+=1,ie(""),pe(wt()),!y||!_||A==="ide"?ce([]):Z(y.id,_),se(!1),xe([]),ke(""),le(!1)},[A,Z,q,y,_]),o.useEffect(()=>{if(!D)return;const V=fe.find(Ie=>Ie.providerSessionId===D);V!=null&&V.canResume||ie("")},[fe,D]);const re=C==="__custom__"?v.trim():C==="__home__"?"":((we=p.find(V=>V.id===C))==null?void 0:we.path)||"",je=o.useMemo(()=>y?t.filter(V=>V.id!==y.id&&V.daemonId===y.id).map(V=>V.workspace):[],[t,y]),Le=o.useMemo(()=>((y==null?void 0:y.recentLaunches)||[]).map(V=>V.workspace),[y]),_e=o.useCallback(V=>{const Ie=String(V.workspace||"").trim();if(!Ie)return;const L=p.find(ne=>Or(ne.path)===Or(Ie));if(L){S(L.id),M("");return}S("__custom__"),M(Ie)},[p]),Ne=o.useCallback(V=>{const Ie=String(V.workspace||"").trim();if(!Ie)return{workspaceId:null,workspacePath:null};const L=p.find(ne=>Or(ne.path)===Or(Ie));return L?{workspaceId:L.id,workspacePath:null}:{workspaceId:null,workspacePath:Ie}},[p]),Ee=o.useMemo(()=>fe.find(V=>V.providerSessionId===D)||null,[fe,D]),Be=o.useMemo(()=>{var Ie;if(A!=="cli"||!y||!_)return null;const V=((Ie=ze.find(L=>L.type===_))==null?void 0:Ie.displayName)||_;return{routeId:y.id,daemonId:y.id,providerSessionId:D||void 0,transport:"pty",mode:"chat",agentName:V,agentType:_,status:"idle",title:V,messages:[],ideType:_,workspaceName:re,workspacePath:re,displayPrimary:V,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${y.id}:${_}`,machineName:Tt(y,{fallbackId:y.id})}},[A,ze,re,y,D,_]),Re=o.useCallback(()=>{var Ie;if(!y)return;S("__custom__"),Ue(!0),st("");const V=Sn(y.platform,kn(v.trim(),re,je,Le,y.defaultWorkspacePath,(Ie=p.find(L=>L.id===g))==null?void 0:Ie.path,p.map(L=>L.path)));He(!0),n(y.id,V).then(L=>{Se(L.path),M(L.path),De(L.directories)}).catch(L=>{st(L instanceof Error?L.message:"Could not load folder")}).finally(()=>He(!1))},[v,g,Le,je,n,re,y,p]),qe=o.useCallback(V=>{y&&(He(!0),st(""),n(y.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,y]),et=o.useCallback(async()=>{if(!y||!re)return;ht(!0),J("");const V=await a(y.id,re);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,re,y]),ct=o.useCallback(async()=>{if(!y)return;if(b==="mesh"){if(!w||!_)return;Q(!0),J(""),Te(null);const L=await d(y.id,w,_);if(Q(!1),!L.ok){if(L.code==="mesh_coordinator_manual_mcp_setup_required"&&L.manualSetup){Te(L.manualSetup),J("Manual MCP setup required before this provider can act as mesh coordinator.");return}J(L.error||"Could not start mesh coordinator");return}r();return}if(!A||!_)return;Q(!0),J("");const V=K.trim()?K.trim().split(/\s+/).filter(Boolean):[],Ie=A==="ide"?await i(y.id,_,{workspacePath:re||null}):await c(y.id,A,_,{workspaceId:C!=="__home__"&&C!=="__custom__"?C:null,workspacePath:C==="__custom__"&&re||null,resumeSessionId:A==="cli"&&D?D:null,cliArgs:V});if(Q(!1),!Ie.ok){J(Ie.error||"Could not start session");return}A!=="ide"&&K.trim()&&(Zl(y.id,_,K),Z(y.id,_)),r()},[A,K,Z,r,i,d,c,re,y,w,D,_,C,b]),ft=b==="mesh"?"Start mesh coordinator":A?tl(A,A==="cli"&&!!D):"Start",dt=b==="mesh"?"Starting coordinator…":A?sl(A,A==="cli"&&!!D):"Starting…",yt=f.length>5;return y?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(Xr,{title:"Machine",children:yt?s.jsx("select",{"aria-label":"Machine",value:y.id,onChange:V=>N(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:ae,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}),L=y.id===V.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${Ie}`,"aria-pressed":L,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${L?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/60 text-text-secondary hover:bg-bg-secondary hover:text-text-primary"}`,onClick:()=>N(V.id),disabled:ae,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(Xr,{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:ae,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"&&y&&H!==y.id&&!P&&$(y.id)},disabled:ae,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;S(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:ae,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),p.map(V=>s.jsxs("option",{value:V.id,children:[V.id===g?"⭐ ":"",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.":re||"Select a workspace folder."}),C==="__custom__"&&re&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Re,disabled:ae,children:[s.jsx(ps,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:et,disabled:ae||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&&R&&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:R}),!P&&!R&&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:()=>B(V.id),disabled:ae,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(Ob,{workspaceMode:b,activeKind:A,cliEnabled:ze.length>0,ideEnabled:Ge.length>0,acpEnabled:Qe.length>0,busy:ae,onSelect:F}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children: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:()=>E(V.id),disabled:ae,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"&&te&&s.jsx(sd,{setup:te,providerName:(U==null?void 0:U.displayName)||(U==null?void 0:U.name)||_}),b!=="mesh"&&A!=="ide"&&s.jsxs(Xr,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:K,onChange:V=>Y(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:ae}),be.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:be.map(V=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>Y(V),disabled:ae,title:V,children:V},V))})]}),b!=="mesh"&&A==="cli"&&s.jsx(td,{busy:ae,savedSessionsLoading:X,savedSessionsError:ue,selectedSession:Ee,onRefresh:()=>{!y||!_||q(y.id,_)},onOpenHistory:()=>{!y||!_||(ve(!0),ed({hasLoadedInitialResults:ye,isLoading:X})&&q(y.id,_))},onClearSelection:()=>ie("")}),me&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${me.includes("saved")||me.includes("requested")||me.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:me})]}),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:ae,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:ae||(b==="mesh"?!w||!_||A!=="cli"||P:!A||!_||C==="__custom__"&&!re),children:[s.jsx(qa,{size:14}),ae?dt:ft]})]})]})}),$e&&s.jsx(Tn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:O,directories:Me,busy:Oe,error:Je,onClose:()=>Ue(!1),onNavigate:qe,onConfirm:V=>{M(V),Se(V),S("__custom__"),Ue(!1)}}),he&&Be&&s.jsx(fo,{activeConv:Be,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:fe,isSavedSessionsLoading:X,isResumingSavedSessionId:oe,savedHistoryFilters:ee,missingWorkspaceResumePath:re||null,onSavedHistoryFiltersChange:pe,onClose:()=>ve(!1),onNewChat:()=>{ie(""),ve(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!y||!_||q(y.id,_)},onResumeSavedSession:V=>{if(!y||!_||oe||!V.canResume)return;const Ie=Ne(V);ie(V.providerSessionId),_e(V),de(V.providerSessionId),ve(!1),Q(!0),J(""),c(y.id,"cli",_,{workspaceId:Ie.workspaceId,workspacePath:Ie.workspacePath,resumeSessionId:V.providerSessionId}).then(L=>{if(!L.ok){J(L.error||"Could not resume session");return}r()}).finally(()=>{Q(!1),de(L=>L===V.providerSessionId?null:L)})}})]}):null}function Wb(e,t){const{sendCommand:r}=gt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);o.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=Fb(n);return{remoteUrl:n,githubUrl:l,loading:i}}function Fb(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 rd=5e3;function Hb(e){return`git:${e}`}function Ub({workspace:e,includeDiffSummary:t=!1,intervalMs:r=rd}){return{type:"subscribe",topic:"workspace.git",key:Hb(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function To(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 zb(e){const t=To(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 Vb(e){const t=To(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 na(e){return e===void 0||typeof e=="boolean"}function Gb(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&na(t.binary)&&na(t.truncated)&&na(t.staged)}function qb(e){const t=To(e);return(t==null?void 0:t.success)===!1?{diff:null,error:gs(t,"Git file diff request failed")}:Gb(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 Yb({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=rd}){const{sendCommand:i,sendData:c}=gt(),l=typeof t=="string"?t.trim():"",d=!!(r&&e&&l),[m,u]=o.useState(null),[f,x]=o.useState(null),[N,y]=o.useState(!1),[p,g]=o.useState(null),b=o.useCallback(async()=>{if(!(!d||!e||!l)){y(!0),g(null);try{const C=zb(await i(e,"git_status",{workspace:l}));if(C.error){u(null),x(null),g(C.error);return}if(u(C.status),!n){x(null);return}const S=Vb(await i(e,"git_diff_summary",{workspace:l}));if(S.error){x(null),g(S.error);return}x(S.diffSummary)}catch(C){g(gs(C,"Git status request failed"))}finally{y(!1)}}},[d,e,n,i,l]),h=o.useMemo(()=>l?Ub({workspace:l,includeDiffSummary:n,intervalMs:a}):null,[n,a,l]);return o.useEffect(()=>{if(!d||!e||!l||!h){u(null),x(null),y(!1),g(null);return}const C=c?Ut.subscribe({sendData:c},e,h,S=>{var v,M;S.workspace===l&&(u(S.status),x(S.diffSummary??null),g(((v=S.status)==null?void 0:v.error)||((M=S.diffSummary)==null?void 0:M.error)||null),y(!1))},{retryIntervalMs:1e3}):null;return b(),()=>{C==null||C()}},[d,e,b,h,c,l]),{status:m,diffSummary:f,loading:N,error:p,refresh:b}}const Xb={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},Jb={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 Di(e){return e.split("/").pop()??e}function Qb(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function Zb({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(i=>{const c=n===i.path,l=Xb[i.status]??"?",d=Jb[i.status]??"text-zinc-400",m=Qb(i.path),u=Di(i.path),f=i.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(i),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:i.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}),i.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",Di(i.oldPath)]}),f]}),!i.binary&&(i.insertions>0||i.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[i.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",i.insertions]}),i.insertions>0&&i.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),i.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",i.deletions]})]}),i.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${i.path}-${i.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 eg(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 tg({diff:e,binary:t,truncated:r,loading:n,error:a,className:i=""}){const c=o.useRef(null);if(o.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 ${i}`,children:"Loading diff…"});if(a)return s.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${i}`,children:a});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${i}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${i}`,children:"No diff available."});const l=e.split(`
|
|
63
|
+
`);return s.jsxs("div",{ref:c,className:`overflow-auto ${i}`,children:[s.jsx("div",{className:"py-1",children:l.map((d,m)=>eg(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 sg(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,i]of Object.entries(n))r.push(`${a}: ${i.slice(0,5).join(", ")}${i.length>5?` (+${i.length-5} more)`:""}`);return r.join(`
|
|
64
|
+
`)}function nd({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=gt(),{status:a,diffSummary:i,loading:c,error:l,refresh:d}=Yb({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=o.useState(null),[f,x]=o.useState(null),[N,y]=o.useState(""),[p,g]=o.useState(!1),[b,h]=o.useState(!1),[C,S]=o.useState(null),[v,M]=o.useState(null),{githubUrl:I}=Wb(e,t),j=o.useCallback(async z=>{if(!((m==null?void 0:m.path)===z.path&&!m.loading)){u({path:z.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const R=await n(e,"git_diff_file",{workspace:t,path:z.path,staged:z.staged}),k=qb(R);if(k.error||!k.diff){u({path:z.path,diff:"",binary:!1,truncated:!1,loading:!1,error:k.error??"Failed to load diff"});return}u({path:z.path,diff:k.diff.diff,binary:k.diff.binary??!1,truncated:k.diff.truncated??!1,loading:!1,error:null})}catch(R){const k=R instanceof Error?R.message:"Failed to load diff";u({path:z.path,diff:"",binary:!1,truncated:!1,loading:!1,error:k})}}},[e,n,m,t]),w=o.useCallback(z=>{y(""),g(!1),S(null),M(null),x(z)},[]),B=o.useCallback(()=>{x(null),S(null),h(!1)},[]),P=o.useCallback(async()=>{var z,R,k;if(f){h(!0),S(null);try{let A;f==="checkpoint"?A=await n(e,"git_checkpoint",{workspace:t,message:N,includeUntracked:p}):f==="stash"?A=await n(e,"git_stash_push",{workspace:t,message:N,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 F=(A==null?void 0:A.result)??A;if((F==null?void 0:F.success)===!1||F!=null&&F.error){S((F==null?void 0:F.error)??"Action failed"),h(!1);return}f==="checkpoint"?M(`Checkpoint created: ${((R=(z=F==null?void 0:F.checkpoint)==null?void 0:z.commit)==null?void 0:R.slice(0,7))??"done"}`):f==="stash"?M(`Stashed as ${((k=F==null?void 0:F.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){S(A instanceof Error?A.message:"Action failed")}finally{h(!1)}}},[f,n,e,t,N,p,m,d]),T=!!(a!=null&&a.hasConflicts),H=a?a.staged+a.modified+a.untracked+a.deleted+a.renamed:null;return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:z=>{z.target===z.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"}),H===0&&!a.error&&s.jsx("span",{className:"text-emerald-500",children:"clean"}),i&&i.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[i.files.length," file",i.files.length!==1?"s":"",i.totalInsertions>0&&s.jsxs("span",{className:"text-emerald-500",children:[" +",i.totalInsertions]}),i.totalDeletions>0&&s.jsxs("span",{className:"text-red-400",children:[" -",i.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&&!i&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),i&&s.jsx(Zb,{files:i.files,truncated:i.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:j}),!c&&!i&&!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(tg,{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"}),i&&i.files.length>0&&s.jsx("button",{onClick:()=>{const z=sg((a==null?void 0:a.branch)??null,i);navigator.clipboard.writeText(z),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:N,onChange:z=>y(z.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:z=>g(z.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:B,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")&&!N.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 rg({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=o.useState(!1),[i,c]=o.useState(!1),[l,d]=o.useState(!1),[m,u]=o.useState(!1),[f,x]=o.useState(!1),[N,y]=o.useState("quickstart"),[p,g]=o.useState("workspace"),b=o.useMemo(()=>!t&&!e,[t,e]),h=o.useCallback(j=>{a(j),j&&c(!1)},[]),C=o.useCallback(j=>{c(j),j&&a(!1)},[]),S=o.useCallback(()=>{y(r===0?"quickstart":"shortcuts"),g("workspace"),d(!0),a(!1),c(!1)},[r]),v=o.useCallback(()=>{d(!1)},[]),M=o.useCallback(()=>{u(!0)},[]),I=o.useCallback(()=>{u(!1)},[]);return o.useEffect(()=>{if(!b){x(!1);return}x(!0);const j=window.setTimeout(()=>{x(!1)},1e4);return()=>window.clearTimeout(j)},[b]),{inboxOpen:n,hiddenOpen:i,shortcutHelpOpen:l,newSessionOpen:m,guideNudgeVisible:f,guideTab:N,shortcutSection:p,isDesktopDashboard:b,setGuideTab:y,setShortcutSection:g,handleInboxOpenChange:h,handleHiddenOpenChange:C,handleOpenShortcutHelp:S,closeShortcutHelp:v,openNewSession:M,closeNewSession:I}}function ng(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 ag(e){return e instanceof Error?e.message:String(e||"")}function og(e){const t=ag(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function ig({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:f,ides:x,actionLogs:N,sendDaemonCommand:y,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:b,initialDataLoaded:h,userName:C,requestedMobileTabKey:S,onRequestedMobileTabConsumed:v,requestedMachineId:M,onRequestedMachineConsumed:I,requestedMobileSection:j,onRequestedMobileSectionConsumed:w,containerRef:B,isSplitMode:P,numGroups:T,groupSizes:H,groupedConvs:z,clearedTabs:R,focusedGroup:k,focusGroup:A,moveTabToGroup:F,splitTabRelative:_,closeGroup:E,handleResizeStart:K,groupActiveTabIds:Y,setGroupActiveTab:be,groupTabOrders:ce,setGroupTabOrder:D,toggleHiddenTab:ie,visibleConversations:fe,requestedDesktopTabKey:xe,onRequestedDesktopTabConsumed:X,onDesktopActiveTabChange:le,onRequestScrollToBottom:ye,onHideConversation:se,onShowHiddenConversation:ue,onShowAllHiddenConversations:ke,scrollToBottomRequest:he,machineEntries:ve,layoutProfile:ee,onBrowseMachineDirectory:pe,onSaveMachineWorkspace:oe,onLaunchMachineIde:de,onLaunchMachineProvider:ae,onListMachineMeshes:Q,onLaunchMeshCoordinator:me,onListMachineSavedSessions:J,notifications:Ae,notificationUnreadCount:Te,liveSessionInboxState:$e,onMarkNotificationRead:Ue,onMarkNotificationUnread:O,onDeleteNotification:Se}){const Me=Ct.useRef(null),{inboxOpen:De,hiddenOpen:Oe,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}=rg({isMobile:t,showMobileChatMode:e,visibleConversationCount:fe.length}),[te,$]=Ct.useState(null),q=Ct.useCallback((we,V)=>{$({daemonId:we,workspace:V})},[]),Z=Ct.useCallback(we=>{var V;lr.flushSync(()=>{ue(we)}),(V=Me.current)==null||V.restoreHiddenTabToSavedLocation(we.tabKey)},[ue]),re=Ct.useCallback(we=>{var Ie;const V=u.find(L=>Ta(L,we))||f.find(L=>Ta(L,we));V&&(f.some(L=>L.tabKey===V.tabKey)&&Z(V),le(V.tabKey),(Ie=Me.current)==null||Ie.activateConversationTab(V.tabKey),ye(V.tabKey,"notification-open")),Ue(we.id),Qe(!1)},[Z,f,u,le,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 ge;if(!r)return;const V=(ge=r.modalButtons)==null?void 0:ge[we];if(!V)return;const Ie=_s(r);if(!Ie)return;const L=V.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),ne=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(L);try{await y(Ie,"resolve_action",{button:V,action:ne?"approve":"reject",buttonIndex:we,...as(r)})}catch(Ke){og(Ke)||console.error("[Shortcut approval] Failed:",Ke)}},[r,y]),{isMac:_e,actionDefinitions:Ne,actionShortcuts:Ee,shortcutListening:Be,shortcutListeningDraft:Re,setShortcutListening:qe,setShortcutListeningDraft:et,saveShortcuts:ct}=wb({enabled:xt&&!He,onTrigger:we=>{var V,Ie,L,ne,ge,Ke,Pe,We,ot,Nt,pt,Gt,vr,wr,jr,kr;if(we==="openShortcutHelp"){rt();return}if(we==="openNewSession"){U();return}if(we==="hideCurrentTab"){r&&se(r);return}if(we==="toggleHiddenTabs"){Ge(!Oe);return}if(we==="openHistoryForActiveTab"){r&&!Ze(r)&&i(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"){(L=Me.current)==null||L.floatActiveTab();return}if(we==="popoutActiveTab"){(ne=Me.current)==null||ne.popoutActiveTab();return}if(we==="dockActiveTab"){(ge=Me.current)==null||ge.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"){(We=Me.current)==null||We.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"){(vr=Me.current)==null||vr.moveActiveTabToDownPane();return}if(we==="triggerPrimaryApprovalAction"){Le(0);return}if(we==="triggerSecondaryApprovalAction"){Le(1);return}if(we==="triggerTertiaryApprovalAction"){Le(2);return}if(we==="setActiveTabShortcut"){(wr=Me.current)==null||wr.setShortcutForActiveTab();return}if(we==="selectPreviousGroupTab"){(jr=Me.current)==null||jr.activatePreviousTabInGroup();return}if(we==="selectNextGroupTab"){(kr=Me.current)==null||kr.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=>ng(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&&se&&se(r))};return window.addEventListener("keydown",we),()=>window.removeEventListener("keydown",we)},[r,se]),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(Tp,{activeConv:r,wsStatus:n,isConnected:a,conversations:fe,hiddenConversations:f,onOpenHistory:i,onHideConversation:se,onShowConversation:Z,onShowAllHidden:ke,onResetPanelsToMain:je,notifications:Ae,notificationUnreadCount:Te,onOpenNotification:re,onMarkNotificationRead:Ue,onMarkNotificationUnread:O,onDeleteNotification:Se,inboxOpen:De,onInboxOpenChange:Qe,hiddenOpen:Oe,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(lb,{conversations:u,hiddenConversations:f,ides:x,actionLogs:N,sendDaemonCommand:y,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:b,userName:C,requestedActiveTabKey:S,onRequestedActiveTabConsumed:v,requestedMachineId:M,onRequestedMachineConsumed:I,requestedMobileSection:j,onRequestedMobileSectionConsumed:w,onOpenHistory:i,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowAllHiddenConversations:ke,onHideConversation:se,onOpenNewSession:U,liveSessionInboxState:$e}):t?s.jsx(bb,{containerRef:B,isSplitMode:P,numGroups:T,groupSizes:H,groupedConvs:z,clearedTabs:R,ides:x,actionLogs:N,sendDaemonCommand:y,setActionLogs:p,isStandalone:b,hasRegisteredMachines:ve.length>0,userName:C,focusedGroup:k,focusGroup:A,moveTabToGroup:F,splitTabRelative:_,closeGroup:E,handleResizeStart:K,groupActiveTabIds:Y,setGroupActiveTab:be,groupTabOrders:ce,setGroupTabOrder:D,toggleHiddenTab:ie,onOpenNewSession:U,allowTabShortcuts:!1,liveSessionInboxState:$e}):s.jsx(Db,{visibleConversations:fe,clearedTabs:R,ides:x,actionLogs:N,sendDaemonCommand:y,setActionLogs:p,isStandalone:b,hasRegisteredMachines:ve.length>0,initialDataLoaded:h,userName:C,toggleHiddenTab:ie,actionShortcuts:Ee,registerActionHandlers:we=>{Me.current=we},onActiveTabChange:le,requestedActiveTabKey:xe,onRequestedActiveTabConsumed:X,onRequestScrollToBottom:ye,scrollToBottomRequest:he,onOpenNewSession:U,liveSessionInboxState:$e,layoutProfile:ee}),Je&&s.jsx(Kb,{machines:ve,ides:x,onClose:G,onBrowseDirectory:pe,onSaveWorkspace:oe,onLaunchIde:de,onLaunchProvider:ae,onListMeshes:Q,onLaunchMeshCoordinator:me,onListSavedSessions:J}),te&&s.jsx(nd,{daemonId:te.daemonId,workspace:te.workspace,onClose:()=>$(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 aa=[{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 cg({onClose:e}){const[t,r]=o.useState(0),n=aa[t],a=t===aa.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:i=>{i.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:aa.map((i,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(i=>i+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 lg({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(i=>{const c=r===i.tabKey,l=i.status==="waiting_approval",d=i.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(i.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"}}),i.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:"!"})]},i.tabKey)})]}):null}function dg({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[i,c]=o.useState(()=>a||"native"),l=o.useMemo(()=>nl(t),[t]),d=o.useMemo(()=>e?po(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),m=o.useMemo(()=>d.find(p=>p.streamSource==="native"),[d]),u=o.useMemo(()=>d.filter(p=>p.streamSource==="agent-stream"),[d]),f=o.useMemo(()=>e?Et(d,e.id):null,[d,e]);o.useEffect(()=>{a&&c(a)},[a]),o.useEffect(()=>{if(a||!f)return;const p=f.streamSource==="native"?"native":f.tabKey;!p||i===p||i==="native"&&c(p)},[i,f,a]),o.useEffect(()=>{var p;i!=="native"&&(u.some(g=>g.tabKey===i)||c(((p=u[0])==null?void 0:p.tabKey)||"native"))},[i,u]),o.useEffect(()=>{i==="native"&&(m||u[0]&&c(u[0].tabKey))},[i,m,u]);const x=o.useMemo(()=>i==="native"&&m?m:u.find(p=>p.tabKey===i)||f||m||u[0],[i,m,f,u]),N=o.useMemo(()=>u.map(p=>({tabKey:p.tabKey,title:Jc(p)||n,status:p.status})),[u,n]),y=o.useCallback(p=>{if(p)return d.find(g=>Ta(g,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[d]);return{activeChatTab:i,setActiveChatTab:c,activeConv:x,conversations:d,extensionTabs:N,hasExtensions:N.length>0,resolveConversationByTarget:y}}function ug({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:i,setActionLogs:c,isStandalone:l,userName:d,onOpenHistory:m,onConversationChange:u,onClose:f}){const[x,N]=o.useState("split"),[y,p]=o.useState(()=>Jt(e)?"native":e.tabKey),g=o.useRef(null),b=o.useMemo(()=>t||r.find(A=>A.id===e.routeId),[e.routeId,t,r]),h=o.useMemo(()=>it((b==null?void 0:b.type)||""),[b==null?void 0:b.type]),{conversations:C,extensionTabs:S,hasExtensions:v}=dg({ideData:b,allIdes:r,connectionStates:n,ideName:h||"IDE",preferredTabKey:Jt(e)?void 0:e.tabKey}),M=o.useMemo(()=>b?Et(C,b.id):null,[b,C]);o.useEffect(()=>{const A=g.current,F={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(g.current=F,!(A&&A.routeId===F.routeId&&A.tabKey===F.tabKey&&A.streamSource===F.streamSource)){if(Jt(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(y==="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===y)){if((M==null?void 0:M.streamSource)==="agent-stream"){p(M.tabKey);return}p("native")}},[C,y,M]);const I=o.useMemo(()=>y==="native"?C.find(A=>A.streamSource==="native")||e:C.find(A=>A.tabKey===y)||e,[e,C,y]),j=xl(I),w=o.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]),B=xr(w),P=jn({sendDaemonCommand:i,activeConv:w,setActionLogs:c,isStandalone:l}),{connScreenshot:T,screenshotUsage:H,handleRemoteAction:z}=Hl({doId:B,targetSessionId:_c(w),connState:w.connectionState||"new",viewMode:x}),R=o.useMemo(()=>a.filter(A=>A.routeId===w.tabKey),[a,w.tabKey]);o.useEffect(()=>{u==null||u(w)},[w,u]),o.useEffect(()=>{const A=F=>{F.key==="Escape"&&f()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[f]);const k=o.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:to(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 F=x===A;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${F?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>N(A),title:A==="split"?"Split view":"Remote only",children:A==="split"?s.jsx(gu,{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(za,{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(lg,{hasExtensions:v,ideName:h||"IDE",activeChatTab:y,extensionTabs:S,onSelectTab:p}),s.jsx(wc,{activeConv:w,onModalButton:P.handleModalButton}),s.jsx(Ia,{activeConv:w,ideEntry:b,showMetaChips:!1,handleSendChat:P.handleSendChat,isSendingChat:P.isSendingChat,sendFeedbackMessage:P.sendFeedbackMessage,handleFocusAgent:P.handleFocusAgent,isFocusingAgent:P.isFocusingAgent,actionLogs:R,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(yc,{addLog:()=>{},connState:w.connectionState||"new",connScreenshot:T,screenshotUsage:H,transportType:w.transport,onAction:z})})]})]})})}function mg({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=xp(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 ",i,"?"]}),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 fg({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(wp,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(fo,{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(ug,{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(mg,{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(rl,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),i.open&&s.jsx(cg,{onClose:i.onClose})]})}function pg({daemons:e,targetVersion:t,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:i}){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(pr,{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=Il(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:i,title:"Dismiss",children:s.jsx(vt,{size:16})})]})}function hg(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function xg(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 bg(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>xg(t)).map(t=>t.id)}}function gg(){var _o,Do,Eo,$o;const{sendCommand:e}=gt(),t=br(),r=hl(),n=Fa(),a=Os(),[i,c]=Bd(),l=i.get("activeTab"),d=((_o=n.state)==null?void 0:_o.openRemoteForTabKey)||null,m=((Do=n.state)==null?void 0:Do.openMachineId)||null,u=((Eo=n.state)==null?void 0:Eo.mobileSection)||null,f=Gc(),x=f.ides||[],N=f.initialLoaded??!0,{updateRouteChats:y,setToasts:p}=f,[g,b]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),h=f.toasts||[],C=f.wsStatus||"connected",S=f.isConnected??!0,v=f.connectionStates||{},M=f.showReconnected||!1,{layoutProfile:I,groupAssignments:j,updateGroupAssignments:w,focusedGroup:B,updateFocusedGroup:P,focusGroup:T,groupActiveTabIds:H,updateGroupActiveTabIds:z,setGroupActiveTab:R,groupTabOrders:k,updateGroupTabOrders:A,setGroupTabOrder:F,groupSizes:_,updateGroupSizes:E,isMobile:K,hasHydratedStoredLayout:Y,hydrateStoredLayout:be,focusConversationTab:ce}=rx(),[D,ie]=o.useState(()=>go());o.useEffect(()=>yh(ie),[]);const fe=o.useMemo(()=>hg({isMobile:K,mobileViewMode:D}),[K,D]),[xe,X]=o.useState([]),[le,ye]=o.useState({}),[se,ue]=o.useState({});hr("Dashboard",{ideCount:x.length,toastCount:h.length,focusedGroup:B,groupCount:Object.keys(j).length,actionLogCount:xe.length});const ke=o.useMemo(()=>x.filter(Ye=>Ye.type==="adhdev-daemon").sort(Qa),[x]),he=ke[0],ve=!!he;o.useEffect(()=>{const{metadataDaemonIds:Ye,runtimeDaemonIds:Lt}=bg(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 ee=(he==null?void 0:he.terminalBackend)||null,pe=he?Tt(he,{fallbackId:he.id}):null,oe=(he==null?void 0:he.id)||null,de=o.useMemo(()=>Ah(x,le),[x,le]),{hiddenTabs:ae,hideTarget:Q,toggleTarget:me,showTarget:J,showAllTabs:Ae}=Ih(),{conversations:Te,visibleConversations:$e,visibleTabKeys:Ue,resolveConversationBySessionId:O,resolveConversationByTarget:Se}=Fh({ides:de,connectionStates:v,clearedTabs:se,hiddenTabs:ae}),Me=o.useMemo(()=>new Map(Te.map(Ye=>[Ye.tabKey,Ye])),[Te]);Gf($e,fe),o.useEffect(()=>{Object.keys(le).length!==0&&ye(Ye=>Rh(Ye,x))},[x,le]);const De=o.useMemo(()=>om(x),[x]),{notifications:Oe,unreadCount:He}=yx({conversations:Te,liveSessionInboxState:De}),{handleMarkDashboardNotificationRead:Je,handleMarkDashboardNotificationUnread:st,handleDeleteDashboardNotification:mt}=vx({notifications:Oe,sendDaemonCommand:e}),{containerRef:ht,normalizedGroupAssignments:xt,numGroups:Ce,isSplitMode:ze,groupedConvs:Qe,moveTabToGroup:Ge,closeGroup:rt,handleResizeStart:W,splitTabRelative:U}=dx({groupAssignments:j,updateGroupAssignments:w,updateFocusedGroup:P,updateGroupActiveTabIds:z,updateGroupTabOrders:A,groupSizes:_,updateGroupSizes:E,isMobile:K,visibleConversations:$e,visibleTabKeys:Ue}),{activeConv:G,openDesktopConversation:te,requestScrollToBottom:$,scrollToBottomRequest:q,setDesktopActiveTab:Z}=Dx({isMobile:K,conversations:Te,visibleConversations:$e,groupActiveTabIds:H,focusedGroup:B,groupedConvs:Qe,setSearchParams:c});Bx({activeConv:G,isMobile:K,liveSessionInboxState:De,sendDaemonCommand:e});const{requestedDesktopTabKey:re,requestedMobileTabKey:je,consumeRequestedActiveTab:Le}=Hh({isMobile:K,urlActiveTab:l,resolveConversationBySessionId:O,setSearchParams:c}),{remoteDialogConv:_e,remoteDialogIdeEntry:Ne,remoteDialogActiveConv:Ee,setRemoteDialogActiveConv:Be,openRemoteDialog:Re,closeRemoteDialog:qe,cliStopDialogOpen:et,cliStopTargetConv:ct,requestCliStop:ft,cancelCliStop:dt,confirmCliStop:yt}=Wx({isMobile:K,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:re,conversations:Te,ides:x,resolveConversationByTarget:Se,activeConv:G,sendDaemonCommand:e}),{historyModalOpen:Ve,openHistoryModal:we,closeHistoryModal:V,historyTargetConv:Ie,isSavedSessionHistoryTarget:L,isHistoryCreatingChat:ne,isHistoryRefreshingHistory:ge,handleHistorySwitchSession:Ke,handleHistoryNewChat:Pe,handleHistoryRefresh:We,savedHistorySessions:ot,savedHistoryFilters:Nt,setSavedHistoryFilters:pt,missingWorkspaceResumePath:Gt,isSavedHistoryLoading:vr,resumingSavedHistorySessionId:wr,handleRefreshSavedHistory:jr,handleResumeSavedHistorySession:kr}=Ox({activeConv:G,remoteDialogConv:_e,remoteDialogActiveConv:Ee,ides:x,sendDaemonCommand:e,updateRouteChats:y,setToasts:p,setClearedTabs:ue,setSearchParams:c}),ld=o.useMemo(()=>$e,[$e]),Sr=K&&D==="chat",dd=o.useMemo(()=>Te.filter(Ye=>yo(ae,Ye)),[Te,ae]),Ro=o.useCallback(Ye=>{const Lt=new URLSearchParams(i);Lt.set("activeTab",Ye),c(Lt,{replace:!0})},[i,c]),{trackPendingLaunch:ud}=Rx({ides:x,conversations:Te,onOpenSession:Ro}),{handleBrowseMachineDirectory:md,handleSaveMachineWorkspace:fd,handleLaunchMachineIde:pd,handleLaunchMachineProvider:hd,handleListMachineMeshes:xd,handleLaunchMeshCoordinator:bd,handleListMachineSavedSessions:gd,setActiveCliViewMode:yd}=Lx({sendDaemonCommand:e,trackPendingLaunch:ud,onOpenSession:Ro,activeConv:G,ides:x,setCliViewModeOverrides:ye});Lh({visibleConversations:$e,clearedTabs:se,setClearedTabs:ue,setActionLogs:X}),Uh({ides:x,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Se});const{isRefreshingHistory:vd,handleRefreshHistory:wd}=Ml({sendDaemonCommand:e,activeConv:G,chats:($o=x.find(Ye=>Ye.id===(G==null?void 0:G.routeId)))==null?void 0:$o.chats,updateRouteChats:y,setToasts:p,setClearedTabs:ue});ax({urlActiveTab:K&&!Sr?l:null,conversations:Te,resolveConversationBySessionId:O,normalizedGroupAssignments:xt,hasHydratedStoredLayout:K&&!Sr?Y:!0,hydrateStoredLayout:K&&!Sr?be:()=>{},focusConversationTab:ce,setSearchParams:c,historyModalOpen:Ve,activeConv:G,isRefreshingHistory:vd,ides:x,handleRefreshHistory:wd});const jd=o.useMemo(()=>!G||!tt(G)||Ze(G)?null:Ws(G),[G]),{versionMismatchDaemons:kd,hasRequiredVersionDaemons:Lo,targetVersion:Sd,versionBannerDismissed:Nd,setVersionBannerDismissed:Cd,upgradingDaemons:Td,handleBannerUpgrade:Md}=mx({ides:x,sendDaemonCommand:e}),Po=o.useCallback(Ye=>{J(Ye),te(Ye)},[te,J]),Id=o.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(jp,{terminalBackend:ee,isStandalone:ve,machineLabel:pe,machineKey:oe}),(!Nd||Lo)&&s.jsx(pg,{daemons:kd,targetVersion:Sd,required:Lo,upgradingDaemons:Td,onUpgrade:Md,onDismiss:()=>Cd(!0)}),s.jsx(ig,{showMobileChatMode:Sr,isMobile:K,activeConv:G,wsStatus:C,isConnected:S,onOpenHistory:Ye=>{Ye&&Be(Ye),we()},onOpenRemote:Re,onStopCli:ft,activeCliViewMode:jd,onSetActiveCliViewMode:yd,mobileChatConversations:ld,ides:x,actionLogs:xe,sendDaemonCommand:e,setActionLogs:X,setCliViewModeOverrides:ye,isStandalone:ve,initialDataLoaded:N,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:se,focusedGroup:B,focusGroup:T,moveTabToGroup:Ge,splitTabRelative:U,closeGroup:rt,handleResizeStart:W,groupActiveTabIds:H,setGroupActiveTab:R,groupTabOrders:k,setGroupTabOrder:F,toggleHiddenTab:Ye=>me(Me.get(Ye)||{tabKey:Ye}),visibleConversations:$e,hiddenConversations:dd,requestedDesktopTabKey:re,onRequestedDesktopTabConsumed:Le,onDesktopActiveTabChange:Z,onRequestScrollToBottom:$,onHideConversation:Id,onShowHiddenConversation:Po,onShowAllHiddenConversations:Ae,scrollToBottomRequest:q,machineEntries:ke,layoutProfile:I,onBrowseMachineDirectory:md,onSaveMachineWorkspace:fd,onLaunchMachineIde:pd,onLaunchMachineProvider:hd,onListMachineMeshes:xd,onLaunchMeshCoordinator:bd,onListMachineSavedSessions:gd,notifications:Oe,notificationUnreadCount:He,liveSessionInboxState:De,onMarkNotificationRead:Je,onMarkNotificationUnread:st,onDeleteNotification:mt}),s.jsx("style",{children:`
|
|
68
|
+
body { overflow: hidden; overscroll-behavior: none; }
|
|
69
|
+
`}),s.jsx(fg,{historyModal:{open:Ve,targetConv:Ie,ides:x,isCreatingChat:ne,isRefreshingHistory:L?!1:ge,savedSessions:ot,savedHistoryFilters:Nt,missingWorkspaceResumePath:Gt||null,onSavedHistoryFiltersChange:pt,isSavedSessionsLoading:vr,isResumingSavedSessionId:wr,onClose:V,onNewChat:Pe,onSwitchSession:Ke,onRefreshHistory:L?jr:We,onResumeSavedSession:kr},remoteDialog:{conversation:_e,ideEntry:Ne,ides:x,connectionStates:v,actionLogs:xe,sendDaemonCommand:e,setActionLogs:X,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),Po(Lt),$(Lt.tabKey,"toast-open"))}}},onboarding:{open:g,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}b(!1)}}})]})}function yg({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,d]=o.useState(null),[m,u]=o.useState(null),[f,x]=o.useState(!1),[N,y]=o.useState(null),[p,g]=o.useState(!1),[b,h]=o.useState(""),C=o.useRef(null),S=o.useCallback(_=>{C.current=_},[]),v=o.useCallback((_,E,K=!1)=>{c(Y=>[...Y.slice(-100),{timestamp:Date.now(),level:_,message:E}]),setTimeout(()=>{var Y;return(Y=a.current)==null?void 0:Y.scrollIntoView({behavior:"smooth"})},100),K&&nt.showToast(E,_==="error"||_==="warn"?"warning":"success")},[a]),M=o.useCallback(_=>{const E=_ instanceof Error?_.message:String(_||"");return E.includes("P2P command timeout")||E.includes("P2P not connected")||E.includes("P2P not available")},[]),I=o.useCallback(async(_,E)=>{var K;if(!e||l)return!1;d(_),v("info",`Launching ${it(_)}${E!=null&&E.workspace?` in ${E.workspace}`:""}...`);try{const Y={ideType:_,enableCdp:!0};(K=E==null?void 0:E.workspace)!=null&&K.trim()?Y.workspace=E.workspace.trim():E!=null&&E.useDefaultWorkspace&&(Y.useDefaultWorkspace=!0);const be=await r(e,"launch_ide",Y);return v(be!=null&&be.success?"info":"error",be!=null&&be.success?`${it(_)} launched`:`Failed: ${be==null?void 0:be.error}`,!0),!!(be!=null&&be.success)}catch(Y){return v("error",`Launch error: ${Y.message}`,!0),!1}finally{d(null)}},[e,l,v,r]),j=o.useCallback(async _=>{if(!e)return{success:!1};const{cliType:E,dir:K,workspaceId:Y,useDefaultWorkspace:be,useHome:ce,argsStr:D,model:ie,resumeSessionId:fe}=_;if(!E)return v("warn","Select a CLI or ACP provider first",!0),{success:!1};const xe=D?D.split(/\s+/).filter(Boolean):void 0,X=(K==null?void 0:K.trim())||(Y?"(saved id)":be?"(default workspace)":ce?"(home)":"");v("info",`Launching ${E}${X?` in ${X}`:""}${ie?` (model: ${ie})`:""}...`),u(E);try{const le={cliType:E,cliArgs:xe,initialModel:ie||void 0};K!=null&&K.trim()?le.dir=K.trim():Y?le.workspaceId=Y:be?le.useDefaultWorkspace=!0:ce&&(le.useHome=!0),fe&&(le.resumeSessionId=fe);const ye=await r(e,"launch_cli",le),se=(ye==null?void 0:ye.result)||ye;return ye!=null&&ye.success?(v("info",`${E} launched`,!0),(se==null?void 0:se.launchSource)==="home"?v("info","📂 Running in home directory (explicit choice)"):(se==null?void 0:se.launchSource)==="defaultWorkspace"&&v("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:se==null?void 0:se.sessionId}):(v("error",`Failed: ${(ye==null?void 0:ye.error)||(se==null?void 0:se.error)}`,!0),(ye==null?void 0:ye.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&y({cliType:E,argsStr:D,model:ie}),{success:!1,sessionId:se==null?void 0:se.sessionId})}catch(le){return M(le)?(v("warn",`${E} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(v("error",`Launch error: ${le.message}`,!0),{success:!1})}finally{u(null)}},[e,v,M,r]),w=o.useCallback(async(_,E,K,Y)=>e?_?E.trim()?j({cliType:_,dir:E,argsStr:K,model:Y}):(y({cliType:_,argsStr:K,model:Y}),{success:!1}):(v("warn","Select a provider",!0),{success:!1}):{success:!1},[e,v,j]),B=o.useCallback(async(_,E,K)=>{if(e&&window.confirm(`Stop ${_}?
|
|
70
|
+
This will terminate the process.`))try{const Y=await r(e,"stop_cli",{cliType:_,dir:E,targetSessionId:K});Y!=null&&Y.success?v("info",`${_} stopped`,!0):v("error",`Stop failed: ${(Y==null?void 0:Y.error)||"Unknown error"}`,!0)}catch(Y){v("error",`Stop failed: ${Y.message}`,!0)}},[e,v,r]),P=o.useCallback(async _=>{try{await r(_.daemonId,"restart_ide",{ideType:_.type}),v("info",`${it(_.type)} restart initiated`,!0)}catch(E){v("error",`Restart failed: ${E.message}`,!0)}},[v,r]),T=o.useCallback(async _=>{if(window.confirm(`Stop ${it(_.type)}?
|
|
71
|
+
This will disconnect CDP and optionally kill the process.`))try{const E=await r(_.daemonId,"stop_ide",{ideType:_.type,killProcess:!0});E!=null&&E.success?v("info",`${it(_.type)} stopped`,!0):v("error",`Stop failed: ${(E==null?void 0:E.error)||"Unknown error"}`,!0)}catch(E){v("error",`Stop failed: ${E.message}`,!0)}},[v,r]),H=o.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]),z=o.useCallback(async _=>{if(!e||!_.trim())return!1;x(!0);try{const E=await r(e,"workspace_add",{path:_.trim()});return E!=null&&E.success?(v("info",`Workspace added: ${_.trim()}`),!0):(v("error",(E==null?void 0:E.error)||"workspace_add failed"),!1)}catch(E){return v("error",E.message),!1}finally{x(!1)}},[e,v,r]),R=o.useCallback(async _=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){x(!0);try{const E=await r(e,"workspace_remove",{id:_});E!=null&&E.success?v("info","Workspace removed",!0):v("error",(E==null?void 0:E.error)||"workspace_remove failed",!0)}catch(E){v("error",E.message,!0)}finally{x(!1)}}},[e,v,r]),k=o.useCallback(async _=>{var E;if(e){x(!0);try{const K=await r(e,"workspace_set_default",_===null?{clear:!0}:{id:_});if(K!=null&&K.success){v("info",_?"Default workspace updated":"Default workspace cleared",!0);const Y=typeof K.defaultWorkspacePath=="string"?K.defaultWorkspacePath:"";Y&&((E=C.current)==null||E.call(C,Y))}else v("error",(K==null?void 0:K.error)||"workspace_set_default failed",!0)}catch(K){v("error",K.message,!0)}finally{x(!1)}}},[e,v,r]),A=o.useCallback(async _=>{var K;if(!e||!_.trim())return;const E=_.trim();x(!0);try{const Y=await r(e,"workspace_set_default",{path:E});Y!=null&&Y.success?(v("info","Default workspace set from history"),(K=C.current)==null||K.call(C,E)):v("error",(Y==null?void 0:Y.error)||"Could not set default (path missing on disk?)")}catch(Y){v("error",Y.message)}finally{x(!1)}},[e,v,r]),F=o.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)"}"`),g(!1)}catch(_){v("error",`Failed: ${_.message}`)}},[e,b,t,v,n,r]);return{logs:i,launchingIde:l,launchingAgentType:m,workspaceBusy:f,launchPick:N,setLaunchPick:y,editingNickname:p,setEditingNickname:g,nicknameInput:b,setNicknameInput:h,addLog:v,handleLaunchIde:I,runLaunchCliCore:j,handleLaunchCli:w,handleStopCli:B,handleRestartIde:P,handleStopIde:T,handleDetectIdes:H,handleWorkspaceAdd:z,handleWorkspaceRemove:R,handleWorkspaceSetDefault:k,handleWorkspaceResumePath:A,handleSaveNickname:F,setOnDefaultWorkspaceChanged:S}}function vg({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var P;const{workspaceBusy:l,handleWorkspaceAdd:d,handleWorkspaceRemove:m,handleWorkspaceSetDefault:u}=i,[f,x]=o.useState(!1),[N,y]=o.useState(""),[p,g]=o.useState([]),[b,h]=o.useState(!1),[C,S]=o.useState(""),v=o.useCallback(async T=>{h(!0),S("");try{const H=await Nn(c,e,T);y(H.path),g(H.directories)}catch(H){S(H instanceof Error?H.message:"Could not load folder")}finally{h(!1)}},[e,c]),M=o.useCallback(()=>{x(!0);const T=[...r.map(z=>z.workspace),...n.map(z=>z.workspace),...a.map(z=>z.workspace)],H=Sn(t.platform,kn(T,t.defaultWorkspacePath,(t.workspaces||[]).map(z=>z.path)));v(H)},[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,B=((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(Mr,{icon:s.jsx(mc,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?mm(t.uptime):"Waiting…"}),s.jsx(Mr,{icon:s.jsx(Mt,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(Mr,{icon:s.jsx(Ga,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(Mr,{icon:s.jsx(vu,{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(Vo,{value:I?Math.min(Math.round(B/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:I?`${B.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(Vo,{value:w,max:100,label:"Memory",color:"#3b82f6",detail:I?`${Dn(t.totalMem-j)} / ${Dn(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Dn(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(Tn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:N,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 wg(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 jg(e,t,r){const n=[];for(const[a,i]of Object.entries(e.settings)){const c=r!=null&&r.filterSchema?r.filterSchema(i):i;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 oa(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 Ei(e){if(!e||typeof e!="object")return null;if(oa(e))return e;const t=e,r=t.result;return oa(r)?r:oa(t.sourceConfig)?t.sourceConfig:null}function kg(e){const t=e.trim();return t||null}const $i=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Sg=[{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 Ng({machineId:e,provider:t,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[d,m]=o.useState([]),[u,f]=o.useState(""),[x,N]=o.useState([]),[y,p]=o.useState(""),g=o.useRef(null),b=o.useRef(null),h=j=>{m(w=>w.includes(j)?w.filter(B=>B!==j):[...w,j])},C=()=>m([...$i]),S=()=>m([]);o.useEffect(()=>{var j;(j=g.current)==null||j.scrollIntoView({behavior:"smooth"})},[x]),o.useEffect(()=>()=>{b.current&&clearInterval(b.current)},[]);const v=o.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"&&(i("done"),N(w=>[...w,`
|
|
72
|
+
✅ Auto-fix completed!`]),b.current&&clearInterval(b.current))}catch{}},3e3)},[e,t.type,r,a]),M=async()=>{if(d.length!==0){i("running"),N(["🚀 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)?(N(w=>[...w,"✅ Agent started. Monitoring progress..."]),v()):(i("error"),p((j==null?void 0:j.error)||"Failed to start auto-fix"))}catch(j){i("error"),p((j==null?void 0:j.message)||"Connection failed")}}},I=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:t.type}),N(j=>[...j,`
|
|
73
|
+
⚠️ Auto-fix cancelled.`]),i("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:Sg.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:S,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:$i.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:g})]}),y&&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:y})]})]}),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:()=>{i("config"),N([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Cg({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var v;const i=t.filter(M=>M.category==="ide"),[c,l]=o.useState(((v=i[0])==null?void 0:v.type)||""),[d,m]=o.useState(""),[u,f]=o.useState(""),[x,N]=o.useState(!1),[y,p]=o.useState(""),[g,b]=o.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(" "),S=async()=>{if(!(!d||!u||!c)){N(!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")}N(!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:g?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:d})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.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"})]}),y&&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:y})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:g?s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:S,disabled:!d||!u||x,className:"machine-btn",style:{background:d&&u?"rgba(34,197,94,0.12)":void 0,borderColor:d&&u?"rgba(34,197,94,0.3)":void 0,color:d&&u?"#86efac":void 0,opacity:!d||!u||x?.4:1},children:x?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Bi(e){return e==="cli"||e==="acp"}function Tg(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 Mg(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 Oi(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 Ig({machineId:e,providers:t,sendDaemonCommand:r}){var z;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,d]=o.useState(null),[m,u]=o.useState("all"),[f,x]=o.useState(null),[N,y]=o.useState(!1),[p,g]=o.useState(null),[b,h]=o.useState("normal"),[C,S]=o.useState(""),[v,M]=o.useState(!1),I=o.useCallback(async()=>{if(e)try{const R=await r(e,"get_provider_source_config",{}),k=Ei(R);k&&(g(k),h(k.sourceMode),S(k.explicitProviderDir||""))}catch{}},[e,r]),j=o.useCallback(async()=>{if(e){c(!0);try{const R=await r(e,"get_provider_settings",{}),k=wg(R);if(k){const A=jg(k,t,{filterSchema:F=>F.filter(_=>_.key!=="enabled")});A.sort((F,_)=>F.category.localeCompare(_.category)||F.displayName.localeCompare(_.displayName)),a(A)}}catch{}c(!1)}},[e,t,r]);o.useEffect(()=>{n.length===0&&j(),p||I()},[]);const w=async(R,k,A)=>{d(`${R}.${k}`),a(F=>F.map(_=>_.type===R?{..._,values:{..._.values,[k]:A}}:_));try{const F=await r(e,"set_provider_setting",{providerType:R,key:k,value:A});F!=null&&F.success||j()}catch{j()}d(null)},B=async(R,k)=>{await w(R,"enabled",k),await j()},P=async R=>{d(`${R}.detect`);try{await r(e,"detect_provider",{providerType:R})}finally{await j(),d(null)}},T=async R=>{await w(R,"executablePath",""),await w(R,"executableArgs",""),await j()},H=async()=>{M(!0);try{const R=await r(e,"set_provider_source_config",{providerSourceMode:b,providerDir:kg(C)}),k=Ei(R);k?(g(k),h(k.sourceMode),S(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(R=>s.jsx("button",{onClick:()=>u(R),className:`machine-btn text-[10px] px-2 py-0.5 ${m===R?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:R.toUpperCase()},R))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>y(!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:i,className:"machine-btn",children:i?"⏳ 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:R=>h(R.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:R=>S(R.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void H(),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:"})," ",((z=p==null?void 0:p.providerRoots)==null?void 0:z.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(R=>R.category===m).length>1&&(()=>{const R=n.filter(_=>_.category===m),k=new Map;for(const _ of R)for(const E of _.schema){if(E.type!=="boolean")continue;const K=k.get(E.key),Y=!!(_.values[E.key]??E.default);K?(K.onCount+=Y?1:0,K.total+=1):k.set(E.key,{label:E.label||E.key,onCount:Y?1:0,total:1})}const A=[...k.entries()].filter(([,_])=>_.total===R.length);if(A.length===0)return null;const F=async(_,E)=>{for(const K of R)await w(K.type,_,E)};return s.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[s.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",m.toUpperCase()," providers (",R.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:A.map(([_,E])=>{const K=E.onCount===E.total,Y=E.onCount===0;return s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:"text-text-secondary font-medium",children:E.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",E.onCount,"/",E.total,")"]}),s.jsx("button",{onClick:()=>void F(_,!0),disabled:K,className:`machine-btn text-[9px] px-1.5 py-px ${K?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void F(_,!1),disabled:Y,className:`machine-btn text-[9px] px-1.5 py-px ${Y?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},_)})})]})})(),i&&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(R=>m==="all"||R.category===m).map(R=>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:R.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:R.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:R.category==="acp"?"rgba(139,92,246,0.08)":R.category==="cli"?"rgba(59,130,246,0.08)":R.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:R.category==="acp"?"#a78bfa":R.category==="cli"?"#60a5fa":R.category==="ide"?"#86efac":"var(--status-warning)"},children:R.category}),Bi(R.category)&&(()=>{const k=t.find(_=>_.type===R.type),A=(k==null?void 0:k.enabled)===!0||R.values.enabled===!0,F=(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 ${Mg(F)}`,children:Tg(F)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void B(R.type,!A),disabled:l===`${R.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(R.type),disabled:!A||l===`${R.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(R.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),R.category==="ide"&&s.jsx("button",{onClick:()=>x(t.find(k=>k.type===R.type)||{type:R.type,name:R.displayName,displayName:R.displayName,icon:R.icon,category:R.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"})]}),Bi(R.category)&&(()=>{const k=t.find(A=>A.type===R.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:"})," ",Oi(k==null?void 0:k.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",Oi(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:R.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===`${R.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(R.type,k.key,!(R.values[k.key]??k.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:R.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:R.values[k.key]??k.default?21:3}})}):k.type==="number"?s.jsx("input",{type:"number",value:Number(R.values[k.key]??k.default??0)||0,min:k.min,max:k.max,onChange:A=>{const F=parseInt(A.target.value)||0;k.min!==void 0&&F<k.min||k.max!==void 0&&F>k.max||w(R.type,k.key,F)},className:"machine-input w-20 text-center text-[11px]"}):k.type==="select"&&k.options?s.jsx("select",{value:String(R.values[k.key]??k.default??""),onChange:A=>w(R.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(R.values[k.key]??k.default??""),onBlur:A=>w(R.type,k.key,A.target.value),className:"machine-input w-[120px] text-[11px]"})})]},k.key))})]},R.type))}),f&&s.jsx(Ng,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>x(null)}),N&&s.jsx(Cg,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>y(!1),onCreated:()=>{y(!1),j()}})]})}const Ag=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Rg({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function Lg(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function Pg(e){return e.trim().toLowerCase()}function In(e,t){const r=Pg(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function Mo(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=Mo(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function _g(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 Dg(e,t){return e.filter(r=>In([r.level,r.message],t))}function Ki(e){return`${e.timestamp}:${e.level}:${e.message}`}function Eg(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const c of e.entries)n.set(Ki(c),c);for(const c of t.entries)n.set(Ki(c),c);const a=Array.from(n.values()).sort((c,l)=>c.timestamp-l.timestamp).slice(-r),i=a.reduce((c,l)=>Math.max(c,Number(l.timestamp||0)),e.lastTs);return{entries:a,kind:"structured",rawText:"",lastTs:i}}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 $g(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,i)=>a.ts-i.ts).slice(-r)}function Bg(e,t){return e.split(`
|
|
74
|
+
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>In([r],t))}function Og(e,t){return e.filter(r=>In([r.level,r.category,r.stage,r.interactionId,Mo(r.payload)],t))}function Kg(e,t){return e.filter(r=>In([r.kind,r.topic,r.interactionId,Mo(r.payload)],t))}function Wi(e){return e==="warn"||e==="error"}function Wg({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=>Wi(a.level)).length+r.filter(a=>Wi(a.level)).length}}function Fg({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(i=>`${new Date(i.timestamp).toISOString()} ${i.level.toUpperCase()} ${i.message}`)].join(`
|
|
75
|
+
`)):t.length>0&&a.push(["[daemon logs]",...t].join(`
|
|
76
|
+
`)),r.length>0&&a.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${Bs(i.payload,500)}`.trim())].join(`
|
|
77
|
+
`)),n.length>0&&a.push(["[browser events]",...n.map(i=>`${new Date(i.ts).toISOString()} ${i.kind}${i.topic?` topic=${i.topic}`:""} ${Bs(i.payload,500)}`.trim())].join(`
|
|
78
|
+
`)),a.join(`
|
|
79
|
+
|
|
80
|
+
`)}function Hg({machineId:e,sendDaemonCommand:t}){const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[d,m]=o.useState([]),[u,f]=o.useState([]),[x,N]=o.useState(null),[y,p]=o.useState(!0),[g,b]=o.useState("info"),[h,C]=o.useState("all"),[S,v]=o.useState(!0),[M,I]=o.useState(!0),[j,w]=o.useState(""),[B,P]=o.useState(""),[T,H]=o.useState(0),z=o.useRef(0),R=o.useRef(0),k=o.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),A=o.useRef([]),F=o.useCallback(()=>{const D={entries:[],kind:"empty",rawText:"",lastTs:0};k.current=D,z.current=0,n([]),l(""),i("empty"),v(!0)},[]),_=o.useCallback(()=>{A.current=[],R.current=0,m([]),I(!0)},[]),E=o.useCallback(D=>{D!==g&&(F(),b(D))},[g,F]),K=o.useCallback(D=>{C(ie=>ie===D?ie:D)},[]),Y=o.useCallback(()=>{F(),_(),f([]),N(null),w(""),P(""),As.clear()},[F,_]),be=o.useCallback(()=>{H(D=>D+1)},[]),ce=o.useCallback(async()=>{if(!e)return;const D=z.current,ie=R.current,[fe,xe]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:g,since:D}),t(e,"get_debug_trace",Rg({count:120,since:ie,category:h}))]);if(fe.status==="fulfilled"){const X=fe.value,le=(X==null?void 0:X.result)||X,ye=_g(le),se=Eg(k.current,ye,300);k.current=se,z.current=se.lastTs,v(!1),w((X==null?void 0:X.success)===!1?String((X==null?void 0:X.error)||"Could not load daemon logs"):""),i(se.kind),l(se.rawText),n(se.entries)}else v(!1),w(fe.reason instanceof Error?fe.reason.message:"Could not load daemon logs");if(xe.status==="fulfilled"){const X=xe.value,le=(X==null?void 0:X.result)||X;if((X==null?void 0:X.success)===!1)P(String((X==null?void 0:X.error)||"Could not load daemon trace"));else if(Array.isArray(le==null?void 0:le.trace)){const ye=le.trace,se=$g(A.current,ye,120),ue=ye.reduce((ke,he)=>Math.max(ke,Number(he.ts||0)),ie);A.current=se,ue>ie&&(R.current=ue),P(""),m(se)}else P("");I(!1)}else I(!1),P(xe.reason instanceof Error?xe.reason.message:"Could not load daemon trace");f(As.list({limit:120})),N(Date.now())},[g,e,t,h]);return o.useEffect(()=>{_()},[_,h]),o.useEffect(()=>{if(!e||(ce(),!y))return;const D=setInterval(()=>{ce()},3e3);return()=>clearInterval(D)},[y,ce,e,T]),{daemonLogs:r,daemonLogKind:a,daemonRawText:c,debugTrace:d,webEvents:u,lastUpdatedAt:x,autoRefresh:y,logLevel:g,traceCategory:h,daemonLoading:S,traceLoading:M,daemonFetchError:j,traceFetchError:B,setAutoRefresh:p,setLogLevel:E,setTraceCategory:K,refresh:be,clear:Y}}function Ug({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:i,daemonRawLineCount:c,traceCount:l,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":i>0||c>0?"ok":"empty",detail:r||(a==="text"?`${c} raw file-fallback line(s)`:`${i} 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 Fi(e){return e==="warn"||e==="error"}function zg(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 Vg(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 Hi(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function Gg(e){const t=Bs(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function qg(e){const t=Bs(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function Yg({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.forEach((i,c)=>{a.push({id:`daemon-log-${i.timestamp}-${c}`,source:"daemon_log",ts:Number(i.timestamp||0),severity:i.level,message:i.message,raw:i.message})}),n.forEach(i=>{a.push({id:`browser-event-${i.id}`,source:"browser_event",ts:Number(i.ts||0),severity:"info",message:qg(i),topic:i.topic,interactionId:i.interactionId,payload:i.payload})}),r.forEach(i=>{a.push({id:`daemon-trace-${i.id}`,source:"daemon_trace",ts:Number(i.ts||0),severity:i.level,message:Gg(i),category:i.category,stage:i.stage,interactionId:i.interactionId,payload:i.payload})}),t.forEach((i,c)=>{a.push({id:`raw-file-${c}`,source:"raw_file",ts:Vg(i,c),severity:zg(i),message:i,raw:i})}),a.sort((i,c)=>i.ts!==c.ts?i.ts-c.ts:Hi(i.source)-Hi(c.source))}function Xg(e){return`${e.source}:${e.severity}:${e.message}`}function Jg(e){const t=e.filter(n=>Fi(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!Fi(n.severity))continue;const a=Xg(n),i=r.get(a);i?(i.count+=1,i.firstTs=Math.min(i.firstTs,n.ts),i.lastTs=Math.max(i.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 Qg(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Ui(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${Qg(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function Zg({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]",Ui(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 i=e.slice(-n);return a.push(["[timeline]",...i.length>0?i.map(Ui):["No diagnostic events captured."]].join(`
|
|
85
|
+
`)),a.join(`
|
|
86
|
+
|
|
87
|
+
`)}function ey(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function ty(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function sy({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:i,quickFilter:c,searchQuery:l,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:f}){const x=Lg(n,i),N=Dg(e,l),y=Bg(t,l),p=Og(x,l),g=Kg(a,l),b=ey(N,c),h=c==="all"?y:[],C=ty(p,c),S=c==="issues"?[]:g,v=Wg({daemonLogs:N,daemonRawLines:y,trace:p,webEvents:g}),M=Yg({daemonLogs:b,daemonRawLines:h,trace:C,webEvents:S}),I=Jg(M),j=Ug({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:f,daemonLogKind:r,daemonLogsCount:N.length,daemonRawLineCount:y.length,traceCount:p.length,webEventCount:g.length});return{filteredDaemonLogs:N,filteredDaemonRawLines:y,filteredTraceEntries:p,filteredWebEvents:g,visibleDaemonLogs:b,visibleDaemonRawLines:h,visibleTraceEntries:C,visibleWebEvents:S,quickFilterCounts:v,diagnosticEvents:M,diagnosticsSummary:I,sourceStates:j}}function ry(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function ad(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Ba(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 ia(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 Io(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function ny({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ba(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:ad(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:Io(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 ay({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:i,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=>i(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 oy({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:Ag.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 iy({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:i,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":i?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${ia(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 ${ia(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:[Io(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:ad(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 ${ia(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":i?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",ry(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 cy({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()," · ",Io(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function ly({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:i,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(ny,{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"?`${i.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&&i.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"&&i.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"&&i.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 ${Ba(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 ${Ba(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 dy({machineId:e,sendDaemonCommand:t}){const r=Hg({machineId:e,sendDaemonCommand:t}),[n,a]=o.useState("info"),[i,c]=o.useState(""),[l,d]=o.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=o.useRef(null),u=o.useRef(!1),f=o.useMemo(()=>sy({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:i,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,i,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);o.useEffect(()=>{if(r.autoRefresh&&f.diagnosticEvents.length>0){const y=u.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:y}),u.current=!0},50)}},[f.diagnosticEvents.length,r.autoRefresh]);const x=o.useCallback(async()=>{var p;const y=Fg({daemonLogs:f.visibleDaemonLogs,daemonRawLines:f.visibleDaemonRawLines,trace:f.visibleTraceEntries,webEvents:f.visibleWebEvents});if(!y.trim()){nt.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(y)),nt.showToast("Copied visible logs to clipboard.","success")}catch(g){nt.showToast(g instanceof Error?g.message:"Could not copy visible logs","warning")}},[f.visibleDaemonLogs,f.visibleDaemonRawLines,f.visibleTraceEntries,f.visibleWebEvents]),N=o.useCallback(async()=>{var p;const y=Zg({events:f.diagnosticEvents,summary:f.diagnosticsSummary,sources:f.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(y)),nt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(g){nt.showToast(g instanceof Error?g.message:"Could not copy diagnostic bundle","warning")}},[f.diagnosticEvents,f.diagnosticsSummary,f.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(ay,{quickFilter:n,quickFilterCounts:f.quickFilterCounts,searchQuery:i,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:c,onCopyDiagnostics:()=>{N()},onCopyVisible:()=>{x()},onToggleAutoRefresh:()=>r.setAutoRefresh(y=>!y),onRefresh:r.refresh,onClear:r.clear}),s.jsx(oy,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(iy,{diagnosticsSummary:f.diagnosticsSummary,diagnosticEventsCount:f.diagnosticEvents.length,sourceStates:f.sourceStates,searchQuery:i,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(cy,{patterns:f.diagnosticsSummary.repeatedPatterns}),s.jsx(ly,{streams:r,sectionsOpen:l,setSectionsOpen:d,diagnosticEvents:f.diagnosticEvents,visibleDaemonLogs:f.visibleDaemonLogs,visibleDaemonRawLines:f.visibleDaemonRawLines,visibleTraceEntries:f.visibleTraceEntries,visibleWebEvents:f.visibleWebEvents,quickFilter:n,searchQuery:i}),s.jsx("div",{ref:m})]})}function uy(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 od(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 my(e){var a;const t=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=od((i==null?void 0:i.meta)||void 0),d=((a=i==null?void 0:i.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?t.push(i):(c==="stopped"||c==="failed")&&(d||l)?r.push(i):n.push(i)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function fy(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function ca(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 la(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function da(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function zi(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 py(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function hy(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 xy(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 i=`${n.providerType}::${n.workspace}::${a}`;t.set(i,(t.get(i)||0)+1)}return Array.from(t.values()).filter(n=>n>1).length}function by({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,d]=o.useState(!1),m=Ch(e,{enabled:!!e,includeSessions:!0,limit:si,intervalMs:Tf}),u=m.diagnostics,f=m.loading,x=m.applyDiagnostics,N=o.useMemo(()=>uy({diagnostics:u,loading:f,refreshing:l,error:n}),[u,f,l,n]),y=o.useMemo(()=>new Map(t.map(P=>[P.sessionId||P.id,P])),[t]),p=o.useCallback(async()=>{if(e){d(!0);try{const P=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:si}),T=la(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]);o.useEffect(()=>{!e||u||f||l||p()},[u,f,e,p,l]);const g=o.useCallback(async(P,T)=>{const H=`${P}:${T.sessionId}`;if(!(P==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
|
|
88
|
+
This will terminate the hosted runtime.`))){c(H);try{const z=await r(e,P,{sessionId:T.sessionId}),R=la(z);if(!(R!=null&&R.success))throw new Error((R==null?void 0:R.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(z){const R=z instanceof Error?z.message:"Session host action failed";nt.showToast(R,"warning"),a(R)}finally{c(z=>z===H?null:z)}}},[e,p,r]),b=o.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",{}),H=la(T);if(!(H!=null&&H.success))throw new Error((H==null?void 0:H.error)||"Duplicate prune failed");const z=H.result||{},R=Array.isArray(z.prunedSessionIds)?z.prunedSessionIds.length:0,k=typeof z.duplicateGroupCount=="number"?z.duplicateGroupCount:0;nt.showToast(`Pruned ${R} duplicate runtime(s) across ${k} group(s)`,"success"),await p()}catch(T){const H=T instanceof Error?T.message:"Duplicate prune failed";nt.showToast(H,"warning"),a(H)}finally{c(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,p,r]),h=o.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((P,T)=>(T.lastActivityAt||0)-(P.lastActivityAt||0)),[u==null?void 0:u.sessions]),C=o.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)||[]}:my(h),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,h]),S=C.liveRuntimes,v=C.recoverySnapshots,M=C.inactiveRecords,I=o.useMemo(()=>xy(S),[S]),j=o.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),w=o.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(P=>P.level==="warn"||P.level==="error")||null,[u==null?void 0:u.recentLogs]),B=(P,T)=>{var K;const H=i===`session_host_resume_session:${P.sessionId}`,z=i===`session_host_restart_session:${P.sessionId}`,R=i===`session_host_stop_session:${P.sessionId}`,k=od(P.meta),A=y.get(P.sessionId),F=P.attachedClients.length===1?"1 client":`${P.attachedClients.length} clients`,_=T==="recovery"?"Recover":"Resume",E=fy(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 ${hy(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:((K=P.writeOwner)==null?void 0:K.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:py(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(cc,{size:11})," ",F]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",zi(P.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",E]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[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:!!i,onClick:()=>{g("session_host_resume_session",P)},children:H?`${_}ing…`:_}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{g("session_host_restart_session",P)},children:z?"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:!!i,onClick:()=>{g("session_host_stop_session",P)},children:R?"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:Lp()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[I>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{b()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${I})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${N.toneClass}`,children:N.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:f||l,children:[s.jsx(pr,{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(ur,{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:zi(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:da(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(ur,{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:[da(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(Ga,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ca("live")}),S.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:S.map(P=>B(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:ca("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=>B(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:ca("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:M.map(P=>B(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 H;const T=h.find(z=>z.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)||((H=y.get(P.sessionId))==null?void 0:H.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:da(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 gy({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(i=>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:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.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 ua({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 ma({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 yy({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),d=r.slice(0,4),m="0.9.75",u=Il(e),f=Ss(e,m),x=or(e,f),N=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(ua,{icon:s.jsx(zt,{size:13}),children:"Current Chats"}),s.jsx(ma,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(y=>{const p=_a(y);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(y),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(y)}),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(y)})]},y.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(ua,{icon:s.jsx(mc,{size:13}),children:"Recent Launches"}),s.jsx(ma,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(y=>{const{metaText:p,updatedLabel:g}=Ol(y);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(y),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:y.label}),g&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:g})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:p})]},y.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(ua,{icon:s.jsx(ur,{size:13}),children:"Daemon Update"}),s.jsx(ma,{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(pr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:N})]})]})})]})]})}function vy(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function wy({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:i,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(i(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 jy={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 Kr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function fa({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const f=Os(),{handleLaunchIde:x,handleStopCli:N,handleRestartIde:y,handleStopIde:p,handleDetectIdes:g,launchingIde:b,launchingAgentType:h,addLog:C}=c,[S,v]=o.useState(null),M=o.useCallback(L=>{L&&f(Qt(L))},[f]),I=jy[e],j=e==="ide",w=e==="acp",B=o.useMemo(()=>n.filter(L=>bs(L,e)),[e,n]),P=o.useMemo(()=>new Map(B.map(L=>[L.type,L.displayName||L.type])),[B]),[T,H]=o.useState(""),[z,R]=o.useState(""),[k,A]=o.useState([]),[F,_]=o.useState(""),[E,K]=o.useState(""),[Y,be]=o.useState([]),[ce,D]=o.useState(!1),[ie,fe]=o.useState(!1),[xe,X]=o.useState(""),[le,ye]=o.useState(!1),[se,ue]=o.useState(()=>wt()),[ke,he]=o.useState(null),[ve,ee]=o.useState(m?"__custom__":d||t.defaultWorkspaceId||""),[pe,oe]=o.useState(m||""),[de,ae]=o.useState([]),[Q,me]=o.useState(!1),[J,Ae]=o.useState(""),[Te,$e]=o.useState([]),[Ue,O]=o.useState(!1),[Se,Me]=o.useState(""),De=o.useRef(null),[Oe,He]=o.useState(null),Je=o.useRef("__home__"),[st,mt]=o.useState("__home__"),[ht,xt]=o.useState(!1),Ce=o.useRef(0),ze=de.filter(L=>!a.some(ne=>ne.type===L&&bt(ne.status)!=="stopped")),Qe=o.useRef({});o.useEffect(()=>{t.defaultWorkspaceId&&!ve&&ee(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),o.useEffect(()=>{if(m){ee("__custom__"),oe(m);return}d&&(ee(d),oe(""))},[d,m]),o.useEffect(()=>{j||T&&(B.some(L=>L.type===T)||(H(""),K("")))},[B,j,T]);const Ge=(()=>{if(ve==="__custom__")return pe.trim();if(!ve)return"";const L=(t.workspaces||[]).find(ne=>ne.id===ve);return(L==null?void 0:L.path)||""})(),rt=o.useCallback(L=>{const ne=Qe.current[L];ne&&(clearTimeout(ne),delete Qe.current[L]),ae(ge=>ge.includes(L)?ge.filter(Ke=>Ke!==L):ge)},[]),W=o.useRef(new Set),U=o.useCallback(async L=>{if(l){O(!0),Me("");try{const ne=await Nn(l,r,L);Ae(ne.path),oe(ne.path),$e(ne.directories)}catch(ne){Me(ne instanceof Error?ne.message:"Could not load folder")}finally{O(!1)}}},[r,l]),G=o.useCallback(()=>{if(!l)return;ee("__custom__"),me(!0);const L=a.map(ge=>ge.workspace),ne=Sn(t.platform,kn(pe.trim(),Ge,m,L,t.defaultWorkspacePath,(t.workspaces||[]).map(ge=>ge.path)));U(ne)},[pe,m,U,t.defaultWorkspacePath,t.platform,t.workspaces,a,Ge,l]),te=o.useCallback(L=>{const ne=String(L.workspace||"").trim();if(!ne)return;const ge=(t.workspaces||[]).find(Ke=>Kr(Ke.path)===Kr(ne));if(ge){ee(ge.id),oe("");return}ee("__custom__"),oe(ne)},[t.workspaces]),$=o.useCallback(L=>{const ne=String(L.workspace||"").trim();if(!ne)return{workspaceId:null,workspacePath:"",useHome:!0};const ge=(t.workspaces||[]).find(Ke=>Kr(Ke.path)===Kr(ne));return ge?{workspaceId:ge.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ne,useHome:!1}},[t.workspaces]),q=o.useCallback(async L=>{if(!l||!L||e!=="cli"){be([]),D(!1),fe(!1),X("");return}const ne=Ce.current+1;Ce.current=ne,D(!0),X("");try{const ge=await l(r,"list_saved_sessions",{providerType:L,kind:"cli",limit:30});if(Ce.current!==ne)return;const Ke=(ge==null?void 0:ge.result)??ge;be(Array.isArray(Ke==null?void 0:Ke.sessions)?Ke.sessions:[])}catch(ge){if(Ce.current!==ne)return;be([]),X(ge instanceof Error?ge.message:"Could not load saved sessions")}finally{Ce.current===ne&&(D(!1),fe(!0))}},[e,r,l]),Z=o.useMemo(()=>{if(e!=="cli"||!T)return null;const L=P.get(T)||T;return{routeId:r,daemonId:r,providerSessionId:E||void 0,transport:"pty",mode:"chat",agentName:L,agentType:T,status:"idle",title:L,messages:[],ideType:T,workspaceName:Ge,workspacePath:Ge,displayPrimary:L,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${T}`}},[e,r,P,Ge,E,T]),re=o.useCallback(L=>{if(e==="ide"||!L){A([]);return}A($a(r,L))},[e,r]),je=o.useCallback((L,ne)=>{e==="ide"||!L||($b(r,L,ne),A($a(r,L)))},[e,r]);o.useEffect(()=>{Ce.current+=1,K(""),re(T),fe(!1),be([]),X(""),D(!1)},[e,re,q,T]);const Le=o.useMemo(()=>Y.find(L=>L.providerSessionId===E)||null,[Y,E]);o.useEffect(()=>{if(!E)return;const L=Y.find(ne=>ne.providerSessionId===E);L!=null&&L.canResume||K("")},[Y,E]);const _e=o.useCallback((L,ne)=>{De.current=ne,Je.current=L.selectedWorkspaceKey||"__home__",mt(L.selectedWorkspaceKey||"__home__"),He(L)},[]),Ne=o.useCallback(()=>{De.current&&(xt(!0),De.current().finally(()=>{De.current=null,xt(!1),He(null)}))},[]),Ee=o.useCallback(L=>{if(!L)return;ae(ge=>ge.includes(L)?ge:[...ge,L]);const ne=Qe.current[L];ne&&clearTimeout(ne),Qe.current[L]=setTimeout(()=>{ae(ge=>ge.includes(L)?ge.filter(Ke=>Ke!==L):ge),delete Qe.current[L]},2e4)},[]);o.useEffect(()=>{for(const ne of a)bt(ne.status)!=="stopped"&&(de.includes(ne.type)&&!W.current.has(ne.type)&&(W.current.add(ne.type),C("info",`${P.get(ne.type)||ne.type} launched`,!0)),rt(ne.type));const L=new Set(a.filter(ne=>bt(ne.status)!=="stopped").map(ne=>ne.type));W.current.forEach(ne=>{!de.includes(ne)&&!L.has(ne)&&W.current.delete(ne)})},[C,rt,a,de,P]),o.useEffect(()=>()=>{Object.values(Qe.current).forEach(clearTimeout),Qe.current={}},[]);const[Be,Re]=o.useState({}),[qe,et]=o.useState(null);o.useEffect(()=>{if(!j||!r||!l)return;(async()=>{try{const ne=await l(r,"get_ide_extensions",{}),ge=(ne==null?void 0:ne.result)||ne;ge!=null&&ge.success&&(ge!=null&&ge.ideExtensions)&&Re(ge.ideExtensions)}catch{}})()},[j,r,l]);const ct=L=>j?it(L.type):e==="cli"?L.cliName:L.acpName,ft=j?t.detectedIdes||[]:[],dt=o.useCallback(async L=>{const ne=(L==null?void 0:L.type)||T,ge=(L==null?void 0:L.workspacePath)??Ge;if(j){await x(ne,ge?{workspace:ge}:void 0)&&Ee(ne);return}const Ke=await c.runLaunchCliCore({cliType:ne,dir:L!=null&&L.workspaceId?void 0:ge||void 0,workspaceId:(L==null?void 0:L.workspaceId)||void 0,useHome:(L==null?void 0:L.useHome)||!(L!=null&&L.workspaceId)&&!ge,argsStr:(L==null?void 0:L.argsStr)??(z||void 0),model:(L==null?void 0:L.model)??(w&&F||void 0),resumeSessionId:(L==null?void 0:L.resumeSessionId)||!w&&e==="cli"&&ne===T&&E||void 0});if(Ke.success||Ke.pending){const Pe=(L==null?void 0:L.argsStr)??z;!j&&(Pe!=null&&Pe.trim())&&(Zl(r,ne,Pe),re(ne)),Ee(ne),Ke.success&&Ke.sessionId&&M(Ke.sessionId)}},[c,x,w,j,z,F,re,Ee,r,M,Ge,E,T]),yt=tl(j?"ide":w?"acp":"cli",!j&&!w&&!!E),Ve=sl(j?"ide":w?"acp":"cli",!j&&!w&&!!E),we=()=>{var Pe;const L=j?it(T):P.get(T)||T,ne=!j&&!w&&!!E,{options:ge,selectedKey:Ke}=ms({machine:t,currentWorkspaceId:ve&&ve!=="__custom__"?ve:null,currentWorkspacePath:Ge});_e({title:ne?uo(L):is("start-fresh",L),description:ne?mo():cs("start-fresh"),confirmLabel:yt,busyLabel:Ve,workspaceOptions:ge,selectedWorkspaceKey:Ke,details:[{label:"Mode",value:I.label},{label:"Provider",value:L},...!j&&e==="cli"&&E?[{label:"Resume",value:((Pe=Y.find(We=>We.providerSessionId===E))==null?void 0:Pe.title)||E}]:[],...!j&&z.trim()?[{label:"Arguments",value:z.trim()}]:[],...w&&F.trim()?[{label:"Model",value:F.trim()}]:[]]},async()=>{const We=ge.find(ot=>ot.key===Je.current);We!=null&&We.workspaceId?(ee(We.workspaceId),oe("")):We!=null&&We.workspacePath?(ee("__custom__"),oe(We.workspacePath)):(ee(""),oe("")),await dt({workspaceId:(We==null?void 0:We.workspaceId)??null,workspacePath:(We==null?void 0:We.workspacePath)??"",useHome:!(We!=null&&We.workspaceId)&&!(We!=null&&We.workspacePath)})})},V=L=>{j?p(L):N(L.type,L.workspace,L.id)},Ie=o.useCallback(async(L,ne,ge=!1)=>{if(L.mode===ne){ge&&L.sessionId&&M(L.sessionId);return}if(!l||!L.sessionId){ge&&L.sessionId&&M(L.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:L.sessionId,cliType:L.type,mode:ne}),ge&&M(L.sessionId)}catch(Ke){const Pe=vl(Ke);yl(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(L=>{const ne=a.find(ot=>(ot.type||"").toLowerCase()===(L.type||"").toLowerCase()&&bt(ot.status)!=="stopped"),ge=L.running||!!ne,Ke=!!ne&&ne.cdpConnected,Pe=de.includes(L.type||L.id||""),We=T===(L.type||"");return s.jsxs("button",{onClick:()=>{if(Ke&&ne){const ot=ne.sessionId;ot?f(Qt(ot),{state:{openRemoteForTabKey:ot}}):f("/dashboard",{state:{openRemoteForTabKey:ne.id}});return}Pe||H(ot=>ot===(L.type||"")?"":L.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":We?"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!==L.type?.4:1},children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(L.type)}),ge&&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:L.name||it(L.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Ke?"text-green-400":Pe?"text-orange-400":We?"text-accent-primary":"text-text-muted"}`,children:Ke?"Open Session":Pe?"Starting...":We?"Configure":"Select"})]})]},L.type)}):s.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",s.jsxs("button",{onClick:g,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[s.jsx(xu,{size:14})," Scan System"]})]}):B.length>0?B.map(L=>{const ne=T===L.type,ge=de.includes(L.type),Pe=!!a.find(We=>We.type===L.type&&bt(We.status)!=="stopped");return s.jsxs("button",{onClick:()=>H(We=>We===L.type?"":L.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ne?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:L.icon}),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:L.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ge?"text-orange-400":ne?"text-accent-primary":"text-text-muted"}`,children:ge?"Starting...":ne?"Configure":"Select"})]})]},L.type)}):s.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),T&&(j?ft.find(L=>L.type===T):B.find(L=>L.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(wy,{machine:t,selectedWorkspace:ve,resolvedWorkspacePath:Ge,customPath:pe,canBrowse:!!l,onWorkspaceChange:ee,onCustomPathChange:oe,onOpenBrowseDialog:G}),!j&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&s.jsx(td,{busy:!!h||!!b||de.includes(T),savedSessionsLoading:ce,savedSessionsError:xe,savedSessionsLoaded:ie,savedSessionsCount:Y.length,selectedSession:Le,onRefresh:()=>void q(T),onOpenHistory:()=>{T&&(ye(!0),ed({hasLoadedInitialResults:ie,isLoading:ce})&&q(T))},onClearSelection:()=>K("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[w&&s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),s.jsx("input",{type:"text",placeholder:"Leave empty for default",value:F,onChange:L=>_(L.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),s.jsx("input",{type:"text",placeholder:"Optional flags...",value:z,onChange:L=>R(L.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),k.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:k.map(L=>s.jsxs("div",{className:"inline-flex max-w-full items-stretch overflow-hidden rounded-md border border-[#ffffff1a] bg-bg-tertiary text-xs text-text-secondary transition-colors hover:border-accent-primary/40 hover:text-text-primary",title:L,children:[s.jsx("button",{type:"button",className:"min-w-0 max-w-[220px] truncate px-2.5 py-1.5 text-left",onClick:()=>R(L),children:L}),s.jsx("button",{type:"button",className:"flex items-center justify-center border-l border-[#ffffff1a] px-1.5 text-text-muted transition-colors hover:bg-status-error/10 hover:text-status-error focus:outline-none focus:ring-1 focus:ring-status-error/50",onClick:()=>je(T,L),"aria-label":`Remove startup arguments: ${L}`,title:"Remove startup arguments",children:s.jsx(vt,{size:12})})]},L))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:we,disabled:!!h||!!b||de.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+de.filter(L=>!a.some(ne=>ne.type===L&&bt(ne.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(L=>s.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(L)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:j?it(L):P.get(L)||L}),s.jsx("div",{className:"text-[11px] text-text-muted",children:h===L?"Launching process...":"Waiting for process and session to register..."})]})]}),s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${L}`)),a.map(L=>{const ne=j?L:null,ge=!j&&!w?L:null,Ke=bt(L.status);return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(L.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[ct(L),(ne==null?void 0:ne.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",ne.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex min-w-0 flex-wrap items-center gap-2",children:[s.jsx("span",{className:"truncate",children:L.workspace||"—"}),u&&L.git&&L.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:Pe=>{Pe.stopPropagation(),u(L.daemonId??r,L.workspace)},children:s.jsx(Ds,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Ds,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(ge==null?void 0:ge.mode)&&s.jsx("span",{className:ge.mode==="chat"?"text-violet-400":"text-text-secondary",children:ge.mode==="chat"?"Chat view":"Terminal view"})]}),ge&&(ge.runtimeKey||ge.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ge.runtimeKey&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),s.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",ge.runtimeKey]}),s.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Pe;(Pe=navigator.clipboard)==null||Pe.writeText(`adhdev attach ${ge.runtimeKey}`),v(ge.runtimeKey||null),window.setTimeout(()=>{v(We=>We===ge.runtimeKey?null:We)},1200)},children:S===ge.runtimeKey?"Copied":"Copy"})]}),ge.runtimeWriteOwner&&s.jsx("span",{style:{color:ge.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ge.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:vy(ge.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${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=L.sessionId;if(Pe){f(Qt(Pe),{state:{openRemoteForTabKey:Pe}});return}f("/dashboard",{state:{openRemoteForTabKey:L.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:s.jsx(Mt,{size:13})}),s.jsx("button",{onClick:()=>{const Pe=L.workspace||"",{options:We,selectedKey:ot}=ms({machine:t,currentWorkspacePath:Pe});_e({title:is("restart-ide",it(L.type)),description:cs("restart-ide"),confirmLabel:Es("restart-ide"),busyLabel:$s("restart-ide"),workspaceOptions:We,selectedWorkspaceKey:ot,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:it(L.type)}]},async()=>{const Nt=We.find(Gt=>Gt.key===Je.current),pt=(Nt==null?void 0:Nt.workspacePath)??"";if(pt&&pt!==Pe){await dt({type:L.type,workspacePath:pt});return}await y(L)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:s.jsx(pr,{size:14})})]}),w&&s.jsx("button",{onClick:()=>{const Pe=L.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:!L.sessionId,children:s.jsx(zt,{size:14})}),ge&&Ke!=="stopped"&&s.jsxs(s.Fragment,{children:[ge.mode&&s.jsx(io,{mode:ge.mode,onChange:Pe=>void Ie(ge,Pe,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Pe=L.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:!L.sessionId,children:ge.mode==="chat"?s.jsx(zt,{size:14}):s.jsx(Mt,{size:13})})]}),Ke==="stopped"?s.jsx("button",{onClick:()=>{const Pe=L.workspace||"",We=j?it(L.type):ct(L),{options:ot,selectedKey:Nt}=ms({machine:t,currentWorkspacePath:Pe});_e({title:is("restart-stopped",We),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:We}]},async()=>{const pt=ot.find(Gt=>Gt.key===Je.current);await dt({type:L.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:de.includes(L.type),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-green-500/20 text-green-400 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",title:"Restart",children:de.includes(L.type)?"⏳":s.jsx(qa,{size:14})}):s.jsx("button",{onClick:()=>V(L),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:s.jsx(vt,{size:14})})]})]}),ne&&ne.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ne.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))}),ne&&(Be[ne.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[ne.type]||[]).map(Pe=>s.jsxs("button",{disabled:qe===`${ne.type}.${Pe.type}`,onClick:async()=>{const We=`${ne.type}.${Pe.type}`;et(We);try{await l(r,"set_ide_extension",{ideType:ne.type,extensionType:Pe.type,enabled:!Pe.enabled}),Re(ot=>({...ot,[ne.type]:(ot[ne.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))})]})]},L.id)})]}),Q&&l&&s.jsx(Tn,{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:()=>me(!1),onNavigate:L=>{U(L)},onConfirm:L=>{oe(L),ee("__custom__"),me(!1)}}),Oe&&s.jsx(ko,{title:Oe.title,description:Oe.description,details:Oe.details,workspaceOptions:Oe.workspaceOptions,selectedWorkspaceKey:st,onWorkspaceChange:L=>{Je.current=L,mt(L)},confirmLabel:Oe.confirmLabel,busyLabel:Oe.busyLabel,busy:ht,onConfirm:Ne,onCancel:()=>{De.current=null,He(null)}}),le&&Z&&s.jsx(fo,{activeConv:Z,ides:[],isCreatingChat:!1,isRefreshingHistory:ce,savedSessions:Y,isSavedSessionsLoading:ce,isResumingSavedSessionId:ke,savedHistoryFilters:se,missingWorkspaceResumePath:Ge||null,onSavedHistoryFiltersChange:ue,onClose:()=>ye(!1),onNewChat:()=>{K(""),ye(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{q(T)},onResumeSavedSession:L=>{if(!L.canResume||ke)return;const ne=$(L);K(L.providerSessionId),te(L),he(L.providerSessionId),ye(!1),dt({type:L.providerType,workspaceId:ne.workspaceId,workspacePath:ne.workspacePath,useHome:ne.useHome,resumeSessionId:L.providerSessionId}).finally(()=>{he(ge=>ge===L.providerSessionId?null:ge)})}})]})}const Vi=[{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 ky({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:f,onOpenGitDialog:x}){var g;const[N,y]=o.useState(d);o.useEffect(()=>{y(d)},[d]);const p=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.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:Vi.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 ${N===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>y(b.id),children:[s.jsx("span",{children:b.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${N===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:(g=Vi.find(b=>b.id===N))==null?void 0:g.helper})]}),N==="ide"&&s.jsx(fa,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),N==="cli"&&s.jsx(fa,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),N==="acp"&&s.jsx(fa,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x})]})}function Sy({onNicknameSynced:e}={}){var oe,de,ae,Q,me,J,Ae,Te,$e,Ue;const{id:t}=Od(),r=Os(),n=Fa(),{sendCommand:a}=gt(),i=br(),c=hl(),l=Gc(),d=l.ides||[],m=l.initialLoaded??!0,u=d.find(O=>O.id===t&&O.type==="adhdev-daemon"),f=d.some(O=>O.type==="adhdev-daemon"),x=t?(oe=l.connectionRetryStatuses)==null?void 0:oe[t]:void 0,N=!!(x!=null&&x.blocked),[y,p]=o.useState("workspace"),[g,b]=o.useState(null),h=o.useCallback((O,Se)=>{b({daemonId:O,workspace:Se})},[]),[C,S]=o.useState("ide"),v=o.useRef(null),[M,I]=o.useState(null),j=o.useRef("__home__"),[w,B]=o.useState("__home__"),[P,T]=o.useState(!1),H=o.useRef(null);o.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||i(t,{minFreshMs:3e4}).catch(()=>{})},[i,u,t]),o.useEffect(()=>{if(!t||!u||y!=="overview")return;const O=u.machine;(typeof(O==null?void 0:O.cpus)!="number"||typeof(O==null?void 0:O.totalMem)!="number"||typeof(O==null?void 0:O.arch)!="string"||typeof(O==null?void 0:O.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[y,c,u,t]),Nh(t&&y==="overview"?[t]:[],{enabled:y==="overview",intervalMs:kf});const z=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},R=yg({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:H});o.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(Oe=>Oe.id!==Se.id)),Me)}),[l]);const k=(u==null?void 0:u.availableProviders)||[],A={};for(const O of k)A[O.type]=O.icon;const F=O=>A[O]||"",_=u?{id:u.id,hostname:jc(u,{fallbackId:u.id}),platform:((de=u.machine)==null?void 0:de.platform)||"unknown",arch:((ae=u.machine)==null?void 0:ae.arch)||"",cpus:((Q=u.machine)==null?void 0:Q.cpus)||0,totalMem:((me=u.machine)==null?void 0:me.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,E=d.filter(O=>O.daemonId===t&&O.type!=="adhdev-daemon").filter(O=>!mr(O)&&!Ts(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,version:O.version||"",instanceId:O.instanceId||"",status:O.status,workspace:O.workspace||null,terminals:O.terminals||0,aiAgents:vm(O.aiAgents||(O.agents||[]).map(Se=>({id:Se.name,name:Se.name,status:Se.status,version:Se.version}))),activeChat:O.activeChat||null,chats:O.chats||[],childSessions:O.childSessions||[],cdpConnected:O.cdpConnected||!1,daemonId:t})),K=d.filter(O=>O.daemonId===t&&mr(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,cliName:O.cliName||O.type,status:O.status,workspace:O.workspace||"",activeChat:O.activeChat||null,providerSessionId:O.providerSessionId,mode:O.mode,runtimeKey:O.runtimeKey,runtimeDisplayName:O.runtimeDisplayName,runtimeWorkspaceLabel:O.runtimeWorkspaceLabel,runtimeWriteOwner:O.runtimeWriteOwner||null,runtimeAttachedClients:O.runtimeAttachedClients||[],daemonId:t})),Y=d.filter(O=>O.daemonId===t&&Ts(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,acpName:O.cliName||O.type,status:O.status,workspace:O.workspace||"",activeChat:O.activeChat||null,providerSessionId:O.providerSessionId,daemonId:t})),be=u?Tt(u,{fallbackId:t}):"",ce="workspace",D=n.state,ie=D==null?void 0:D.initialMachineTab,fe=D==null?void 0:D.initialWorkspaceCategory,xe=D==null?void 0:D.initialWorkspaceId,X=D==null?void 0:D.initialWorkspacePath,le=ie==="ides"||ie==="clis"||ie==="acps"?"workspace":ie||ce,ye=ie==="ides"?"ide":ie==="clis"?"cli":ie==="acps"?"acp":fe,se=[...E.map(O=>{var Se,Me,De,Oe,He;return{id:`ide:${O.type}:${O.workspace||""}`,label:((Se=O.activeChat)==null?void 0:Se.title)||O.type,kind:"ide",providerType:O.type,subtitle:O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:((He=(Oe=(De=(Me=O.activeChat)==null?void 0:Me.messages)==null?void 0:De.at)==null?void 0:Oe.call(De,-1))==null?void 0:He.timestamp)||0}}),...K.map(O=>{var Se,Me,De,Oe,He;return{id:`cli:${O.type}:${O.workspace||""}`,label:((Se=O.activeChat)==null?void 0:Se.title)||O.cliName,kind:"cli",providerType:O.type,providerSessionId:O.providerSessionId,subtitle:O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:((He=(Oe=(De=(Me=O.activeChat)==null?void 0:Me.messages)==null?void 0:De.at)==null?void 0:Oe.call(De,-1))==null?void 0:He.timestamp)||0}}),...Y.map(O=>{var Se,Me,De,Oe,He;return{id:`acp:${O.type}:${O.workspace||""}`,label:((Se=O.activeChat)==null?void 0:Se.title)||O.acpName,kind:"acp",providerType:O.type,providerSessionId:O.providerSessionId,subtitle:hs(O.summaryMetadata)||O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:((He=(Oe=(De=(Me=O.activeChat)==null?void 0:Me.messages)==null?void 0:De.at)==null?void 0:Oe.call(De,-1))==null?void 0:He.timestamp)||0}})].sort((O,Se)=>(Se.lastLaunchedAt||0)-(O.lastLaunchedAt||0)),ue=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(O=>({id:O.id,label:O.title||O.providerName||O.providerType,kind:O.kind,providerType:O.providerType,providerSessionId:O.providerSessionId,subtitle:hs(O.summaryMetadata)||O.workspace||void 0,workspace:O.workspace,summaryMetadata:O.summaryMetadata,lastLaunchedAt:O.lastLaunchedAt})):se,ke=o.useMemo(()=>{var Se;const O=((Se=l.connectionStates)==null?void 0:Se[t||""])||void 0;return d.filter(Me=>Me.daemonId===t&&Me.type!=="adhdev-daemon").flatMap(Me=>po(Me,{connectionStates:t&&O?{[t]:O}:void 0,defaultConnectionState:O})).filter(Me=>!(Me.transport==="pty"&&Me.mode==="terminal")).sort((Me,De)=>_a(De)-_a(Me))},[d,l.connectionStates,t]),he=o.useCallback(O=>{const Se=Cn(O);Se&&r(Qt(Se))},[r]),ve=o.useCallback(()=>{v.current&&(T(!0),v.current().finally(()=>{v.current=null,T(!1),I(null)}))},[]),ee=o.useCallback(O=>{if(!_)return;const{options:Se,selectedKey:Me}=ms({machine:_,currentWorkspacePath:O.workspace}),De=async()=>{S(O.kind),p("workspace")};v.current=async()=>{const Oe=Se.find(st=>st.key===j.current),He=(Oe==null?void 0:Oe.workspacePath)??null,Je=(Oe==null?void 0:Oe.workspaceId)??null;if(O.kind==="ide"&&O.providerType){await R.handleLaunchIde(O.providerType,He?{workspace:He}:void 0);return}if((O.kind==="cli"||O.kind==="acp")&&O.providerType){await R.runLaunchCliCore({cliType:O.providerType,dir:Je?void 0:He||"",workspaceId:Je||void 0,model:O.kind==="acp"&&Sc(O.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:O.providerSessionId});return}await De()},j.current=Me,B(Me),I({title:O.kind==="ide"?is("restart-ide",O.label):O.providerSessionId?uo(O.label):is("start-fresh",O.label),description:O.kind==="ide"?cs("restart-ide"):O.providerSessionId?mo():cs("start-fresh"),confirmLabel:O.kind==="ide"?Es("restart-ide"):O.providerSessionId?ln(!0):Es("start-fresh"),busyLabel:O.kind==="ide"?$s("restart-ide"):O.providerSessionId?co(!0):$s("start-fresh"),workspaceOptions:Se,details:[{label:"Mode",value:O.kind.toUpperCase()},...O.providerType?[{label:"Provider",value:O.providerType}]:[]]})},[R,_]);if(o.useEffect(()=>{p(le)},[ce,le,t]),o.useEffect(()=>{ye&&S(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:z,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const pe=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Mt,{size:14})," Workspace"]}),count:E.length+K.length+Y.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(bu,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(pu,{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:z,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:[R.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:R.nicknameInput,onChange:O=>R.setNicknameInput(O.target.value),onKeyDown:O=>{O.key==="Enter"&&R.handleSaveNickname(),O.key==="Escape"&&R.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:R.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:()=>R.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:()=>{R.setEditingNickname(!0),R.setNicknameInput(_.machineNickname||"")},title:"Click to set nickname",children:be}),N?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:pe.map(O=>s.jsxs("button",{onClick:()=>p(O.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${y===O.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[O.label,O.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${y===O.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:O.count})]},O.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[y==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(yy,{machineEntry:u,providers:k,recentLaunches:ue,currentConversations:ke,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",Al(u))}catch{}},onOpenRecent:ee,onOpenConversation:he}),s.jsx(ky,{machine:_,machineId:t,providers:k,ideSessions:E,cliSessions:K,acpSessions:Y,actions:R,getIcon:F,initialCategory:C,initialWorkspaceId:xe,initialWorkspacePath:X,sendDaemonCommand:a,onOpenGitDialog:h})]}),y==="providers"&&s.jsx(Ig,{machineId:t,providers:k,sendDaemonCommand:a}),y==="overview"&&s.jsx(vg,{machineId:t,machine:_,ideSessions:E,cliSessions:K,acpSessions:Y,actions:R,sendDaemonCommand:a}),y==="session-host"&&s.jsx(by,{machineId:t,cliSessions:K,sendDaemonCommand:a}),y==="logs"&&s.jsx(dy,{machineId:t,sendDaemonCommand:a})]})})}),R.launchPick&&_&&s.jsx(gy,{machine:_,launchPick:R.launchPick,actions:R}),M&&s.jsx(ko,{title:M.title,description:M.description,details:M.details,workspaceOptions:M.workspaceOptions,selectedWorkspaceKey:w,onWorkspaceChange:O=>{j.current=O,B(O)},confirmLabel:M.confirmLabel,busyLabel:M.busyLabel,busy:P,onConfirm:ve,onCancel:()=>{v.current=null,I(null)}}),g&&s.jsx(nd,{daemonId:g.daemonId,workspace:g.workspace,onClose:()=>b(null)}),s.jsx(rl,{toasts:l.toasts||[],onDismiss:O=>l.setToasts(Se=>Se.filter(Me=>Me.id!==O)),onClickToast:O=>{O.targetKey&&r(Qt(O.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 Gi="hermes-cli, claude-cli, codex-cli, gemini-cli",Wr=[{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."}],Ny={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"},Cy=new Set(["hermes-cli","claude-cli","codex-cli","gemini-cli"]);function Ty(e){const t=e.trim();if(!t)return;const r=t.toLowerCase();return Cy.has(r)?r:t}function qi(e){const t=new Set;return e.split(/[\s,]+/).map(Ty).filter(r=>!!r).filter(r=>t.has(r)?!1:(t.add(r),!0))}function Yi(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 pa(e){return{...Ny,...(e==null?void 0:e.policy)||{}}}function My({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const i=a.id.toLowerCase(),c=a.name.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||c.includes("hermes")}),n=Ll(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(sd,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function Iy(){var ce;const{sendCommand:e}=gt(),{ides:t}=Zt(),r=t.find(D=>D.daemonMode||D.type==="adhdev-daemon"),n=(r==null?void 0:r.id)||"",a=[];if(r){const D=r.availableProviders||[];for(const ie of D)ie.category==="cli"&&a.push({id:ie.type||ie.id,name:ie.displayName||ie.name||ie.type,meshCoordinator:ie.meshCoordinator})}const[i,c]=o.useState([]),[l,d]=o.useState(null),[m,u]=o.useState(!0),[f,x]=o.useState(null),[N,y]=o.useState(!1),[p,g]=o.useState(null),[b,h]=o.useState({}),[C,S]=o.useState(!1),[v,M]=o.useState(""),[I,j]=o.useState(""),[w,B]=o.useState(!1),[P,T]=o.useState(""),[H,z]=o.useState(Gi),R=i.find(D=>D.id===l)||null;o.useEffect(()=>{h(Object.fromEntries(((R==null?void 0:R.nodes)||[]).map(D=>[D.id,Yi(D).join(", ")])))},[R]);const k=o.useCallback(async()=>{if(n){u(!0);try{const D=await e(n,"list_meshes");D!=null&&D.success?(c(D.meshes||[]),x(null)):x((D==null?void 0:D.error)||"Failed to load meshes")}catch(D){x((D==null?void 0:D.message)||"Failed to load meshes")}finally{u(!1)}}},[n,e]);o.useEffect(()=>{k()},[k]);async function A(){var D;if(!(!n||!v.trim()))try{const ie=await e(n,"create_mesh",{name:v.trim(),repoIdentity:I.trim()||void 0});ie!=null&&ie.success?(S(!1),M(""),j(""),await k(),d(((D=ie.mesh)==null?void 0:D.id)||null)):x((ie==null?void 0:ie.error)||"Create failed")}catch(ie){x((ie==null?void 0:ie.message)||"Create failed")}}async function F(D){if(!(!n||!confirm("Delete this mesh?")))try{await e(n,"delete_mesh",{meshId:D}),d(null),await k()}catch(ie){x((ie==null?void 0:ie.message)||"Delete failed")}}async function _(){if(!(!n||!l||!P.trim()))try{const D=await e(n,"add_mesh_node",{meshId:l,workspace:P.trim(),providerPriority:qi(H)});D!=null&&D.success?(B(!1),T(""),z(Gi),await k()):x((D==null?void 0:D.error)||"Add node failed")}catch(D){x((D==null?void 0:D.message)||"Add node failed")}}async function E(D){var xe;if(!n||!l)return;const ie=pa(R),fe=((xe=Wr.find(X=>X.value===ie.sessionCleanupOnNodeRemove))==null?void 0:xe.label)||"Preserve history and runtimes";if(confirm(`Remove this node?
|
|
95
|
+
|
|
96
|
+
Node removal cleanup policy: ${fe}`))try{await e(n,"remove_mesh_node",{meshId:l,nodeId:D}),await k()}catch(X){x((X==null?void 0:X.message)||"Remove node failed")}}async function K(D){if(!n||!l)return;const ie={...pa(R),...D};try{y(!0),x(null);const fe=await e(n,"update_mesh",{meshId:l,policy:ie});if((fe==null?void 0:fe.success)===!1){x(fe.error||"Policy update failed");return}await k()}catch(fe){x((fe==null?void 0:fe.message)||"Policy update failed")}finally{y(!1)}}async function Y(D){if(!n||!l)return;const ie=qi(b[D.id]||""),fe={...D.policy||{}};delete fe.provider_priority,ie.length?fe.providerPriority=ie:delete fe.providerPriority;try{g(D.id),x(null);const xe=await e(n,"update_mesh_node",{meshId:l,nodeId:D.id,policy:fe});if((xe==null?void 0:xe.success)===!1){x(xe.error||"Node policy update failed");return}await k()}catch(xe){x((xe==null?void 0:xe.message)||"Node policy update failed")}finally{g(null)}}if(!n)return s.jsx(ar,{icon:s.jsx(Nr,{}),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(!R)return s.jsxs(ar,{icon:s.jsx(Nr,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>S(!0),children:"+ Create Mesh"}),children:[f&&s.jsx(Cs,{variant:"error",className:"mb-4",children:f}),C&&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(qs,{value:v,onChange:D=>M(D.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(It,{label:"Repo Identity (optional)",children:s.jsx(qs,{value:I,onChange:D=>j(D.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:A,disabled:!v.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(!1),children:"Cancel"})]})]})}),m?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):i.length===0?s.jsx(dn,{icon:s.jsx(Nr,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(D=>s.jsxs("button",{className:"text-left w-full p-4 rounded-xl border border-border-subtle bg-bg-panel hover:border-accent-primary/40 transition-colors",onClick:()=>d(D.id),children:[s.jsx("div",{className:"font-semibold text-sm",children:D.name}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:D.repoIdentity||"No repo identity"}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[D.nodes.length," node(s)"]})]},D.id))})]});const be=pa(R);return s.jsxs(ar,{icon:s.jsx(Nr,{}),title:R.name,subtitle:R.repoIdentity||"Repo Mesh",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>d(null),children:"← Back"}),s.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>F(R.id),children:"Delete"})]}),children:[f&&s.jsx(Cs,{variant:"error",className:"mb-4",children:f}),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:be.requirePreTaskCheckpoint?"yes":"no",onChange:D=>K({requirePreTaskCheckpoint:D.target.value==="yes"}),disabled:N,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:be.requirePostTaskCheckpoint?"yes":"no",onChange:D=>K({requirePostTaskCheckpoint:D.target.value==="yes"}),disabled:N,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:be.requireApprovalForPush?"required":"not_required",onChange:D=>K({requireApprovalForPush:D.target.value==="required"}),disabled:N,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:be.requireApprovalForDestructiveGit?"required":"not_required",onChange:D=>K({requireApprovalForDestructiveGit:D.target.value==="required"}),disabled:N,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:be.dirtyWorkspaceBehavior||"warn",onChange:D=>K({dirtyWorkspaceBehavior:D.target.value}),disabled:N,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(be.maxParallelTasks??2),onChange:D=>K({maxParallelTasks:Number(D.target.value)}),disabled:N,children:[1,2,3,4,5,6,7,8].map(D=>s.jsx("option",{value:D,children:D},D))})})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(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:be.sessionCleanupOnNodeRemove||"preserve",onChange:D=>K({sessionCleanupOnNodeRemove:D.target.value}),disabled:N,children:Wr.map(D=>s.jsx("option",{value:D.value,children:D.label},D.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((ce=Wr.find(D=>D.value===be.sessionCleanupOnNodeRemove))==null?void 0:ce.description)||Wr[0].description})]}),N&&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:()=>B(!0),children:"+ Add Node"})}),w&&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:()=>B(!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(qs,{value:P,onChange:D=>T(D.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(qs,{value:H,onChange:D=>z(D.target.value),placeholder:"hermes-cli, claude-cli, codex-cli, gemini-cli",onKeyDown:D=>{D.key==="Enter"&&_()}})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:_,disabled:!P.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>B(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),R.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:R.nodes.map(D=>{const ie=Yi(D);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:D.workspace.split("/").pop()}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:D.workspace}),s.jsx("div",{className:"mt-3 max-w-2xl",children:s.jsx(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.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[s.jsx(qs,{value:b[D.id]??ie.join(", "),onChange:fe=>h(xe=>({...xe,[D.id]:fe.target.value})),placeholder:"hermes-cli, claude-cli, codex-cli, gemini-cli",onKeyDown:fe=>{fe.key==="Enter"&&Y(D)}}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>void Y(D),disabled:p===D.id,children:p===D.id?"Saving...":"Save policy"})]})})})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:()=>E(D.id),children:s.jsx(vt,{size:14})})]},D.id)})})]}),s.jsx(My,{meshId:R.id,availableCliAgents:a})]})}function Ao(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Ay(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=Ao();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(Ay(e),{credentials:"same-origin",...t})}function id(){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 Ry{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,i,c){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:i,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 i=await $t(`${a.pathname}${a.search}`);if(!i.ok){let l=`Runtime snapshot unavailable (${i.status})`;try{const d=await i.json();d!=null&&d.error&&(l=d.error)}catch{}return{success:!1,error:l}}const c=await i.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 Wt=new Ry;function Ly(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Ao();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Fr=Ly(),Xi=3e3,Py=3e4;let _t=null,_y=0;const hn=new Map;let ts=null,cr=null;function Ji(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Qs(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function Dy(e){return e==="connected"?"connected":e}async function Jr(e,t,r){const n=ol(e,r||{}),a=_t;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++_y}_${Date.now()}`;return new Promise((c,l)=>{const d=setTimeout(()=>{hn.delete(i),l(new Error(`WS command timeout: ${t}`))},3e4);hn.set(i,{resolve:m=>{clearTimeout(d),c(m)},reject:m=>{clearTimeout(d),l(m)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Oa(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 Ey(e,t,r){const n=_t;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=ol(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 $y{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(i=>i.blob());Wt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ts=setInterval(r,2e3)}stopScreenshots(t){ts&&(clearInterval(ts),ts=null)}}let Rt=null;function By(e){return(!Rt||Rt.daemonId!==e)&&(Rt=new $y(e)),Rt}function Oy({children:e}){const t=o.useRef(dr()),r=dr();t.current=r;const{setUserName:n}=Zt(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),d=o.useCallback((p,g)=>{l(p),cr==null||cr(p,g)},[]),m=o.useRef(null),u=o.useRef(),f=o.useRef(Xi),x=o.useRef(!0),N=o.useRef(!1),y=o.useRef("initial_connect");return o.useEffect(()=>{x.current=!0,N.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 ${Fr}...`),Qs("connect_attempt",{url:Fr,reason:y.current,delayMs:f.current});let b;try{b=new WebSocket(Fr)}catch(S){console.error("[Standalone WS] Failed to create WebSocket:",S),g();return}m.current=b,b.onopen=()=>{if(!x.current){b.close();return}d("connected"),f.current=Xi,Qs("open",{url:Fr,reason:y.current}),Ut.resubscribeAll({sendData:Oa}),console.log("[Standalone WS] Connected")},_t=b,b.onmessage=S=>{var v,M;try{const I=JSON.parse(S.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&&Wt.emitSessionOutput(j,typeof I.data=="string"?I.data:"",typeof I.seq=="number"?I.seq:void 0);return}if(I.type==="runtime_snapshot"){Wt.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:B,getIdes:P}=t.current,T=j.instanceId||"standalone",H=P().find(k=>k.id===T),z=By(T);Wt.register(T,z),Wt.setState(T,"connected"),d("connected",T),Wt.emitStatus(T,j);const R=cn(j,{daemonId:T,existingDaemon:H,existingEntries:P()});Ji("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}))}),Ji("entries",{daemonId:T,entries:R.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}))}),R.length>0&&w(R,{authoritativeDaemonIds:[T]}),B(),c.current!==T&&((M=i.current)==null||M.call(i),c.current=T,i.current=Ut.subscribe({sendData:Oa},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(),F=A.find(E=>E.id===T),_=cn(k.status,{daemonId:T,existingDaemon:F,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=S=>{x.current&&(Rt==null||Rt.stopScreenshots(),Rt&&Wt.setState(Rt.daemonId,"disconnected"),d("disconnected"),m.current=null,y.current=`close:${S.code}${S.wasClean?":clean":":unclean"}`,Qs("close",{code:S.code,reason:S.reason||"",wasClean:S.wasClean}),g())},b.onerror=S=>{N.current||!x.current||(y.current="error",Qs("error",{message:S instanceof Event?"event":String(S),readyState:b.readyState}),console.warn("[Standalone WS] Error, will reconnect:",S))}}function g(){if(!x.current)return;clearTimeout(u.current);const b=f.current;console.log(`[Standalone WS] Reconnecting in ${b}ms...`),Qs("schedule_reconnect",{reason:y.current,delayMs:b}),u.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,Py),p()},b)}return p(),()=>{var b;x.current=!1,N.current=!0,(b=i.current)==null||b.call(i),i.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(),Wt.unregister(Rt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function Ky({children:e}){const[t,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(cr=(c,l)=>{r(c),l&&a(l)},()=>{cr=null}),[]);const i=o.useMemo(()=>{const c=t==="connected",l=Dy(t),d={};return n&&(d[n]=l),d.standalone=l,{wsStatus:t,isConnected:c,connectionStates:d}},[t,n]);return s.jsx(ru,{connectionOverrides:i,children:s.jsx(Oy,{children:e})})}const cd="adhdev_standalone_font_preferences",fs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},An=[{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"}],fr=[{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"}],Wy=new Set(An.map(e=>e.id)),Fy=new Set(fr.map(e=>e.id));function Ot(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():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?Wy:Fy).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}: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"?An:fr;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function Hy(e){const t=Ot(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=Ot(e),n=Hy(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))t.style.setProperty(a,i);return r}function Ka(e){const t=Ot(e);try{localStorage.setItem(cd,JSON.stringify(t))}catch{}return t}function Uy(){try{const e=localStorage.getItem(cd);if(e)return Ot(JSON.parse(e))}catch{}return fs}function zy(){return rs(Uy())}function Zs(e,t){var n;const r=e==="chat"?An:fr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const Vy=[{id:"dashboard",path:"/dashboard",icon:s.jsx(ic,{}),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 Gy({children:e}){const t=Os(),r=Fa(),n=o.useMemo(()=>Vy.map(i=>({...i,active:r.pathname.startsWith(i.path),onSelect:()=>t(i.path)})),[r.pathname,t]),a=o.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Docs"}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(lc,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(dc,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Jp,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.75"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:i?"Expand sidebar":"Collapse sidebar",children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const qy=[{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(uc,{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(lc,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Yy=[{icon:s.jsx(yu,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(ic,{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(fu,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(cc,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(hu,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Xy=[{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 Jy(){return s.jsxs(ar,{icon:s.jsx(dc,{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:qy.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:il.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:ll.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:cl.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:Yy.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:Xy.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(Iu,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function ha(e,t,r){return{...e,[t]:r}}function xa({surface:e,title:t,description:r,value:n,options:a,onChange:i}){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;i(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=>i({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 Qy({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:i,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(xa,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:An,onChange:u=>i(ha(e,"chat",u))}),s.jsx(xa,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:fr,onChange:u=>i(ha(e,"code",u))}),s.jsx(xa,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:fr,onChange:u=>i(ha(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: ",Zs("chat",e.chat.preset)," · Code: ",Zs("code",e.code.preset)," · Terminal: ",Zs("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Zs("chat",fs.chat.preset)," / ",Zs("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 Zy(){const{ides:e}=Zt(),t=e.find(X=>X.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=gt(),{userName:a}=Zt(),[i,c]=o.useState(a||""),[l,d]=o.useState(null),[m,u]=o.useState(null),[f,x]=o.useState(fs),[N,y]=o.useState(!1),[p,g]=o.useState(""),[b,h]=o.useState(""),[C,S]=o.useState("127.0.0.1"),[v,M]=o.useState(""),[I,j]=o.useState(""),[w,B]=o.useState(""),[P,T]=o.useState(""),[H,z]=o.useState(""),[R,k]=o.useState(!1),A=async()=>{const le=await(await $t("/auth/session")).json();d(le)},F=async()=>{const le=await(await $t("/api/v1/standalone/preferences")).json();u(le),S(le.standaloneBindHost);const ye=Ot(le.standaloneFontPreferences);x(ye),rs(ye),Ka(ye)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([A(),F()]).catch(X=>{T(X instanceof Error?X.message:String(X))})},[]),o.useEffect(()=>{rs(f)},[f]);const _=X=>{const le=X.target.value.trim();t!=null&&t.id&&le!==a&&n(t.id,"set_user_name",{userName:le}).catch(console.error)},[E,K]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),Y=X=>{K(X);try{localStorage.setItem("adhdev_sound",X?"1":"0")}catch{}},be=async()=>{g(""),h(""),y(!0);try{const X=Ot(f),le=await $t("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:X})}),ye=await le.json();if(!le.ok)throw new Error((ye==null?void 0:ye.error)||"Failed to save standalone font preferences");const se=Ot(ye.standaloneFontPreferences);u(ye),x(se),rs(se),Ka(se),h("Standalone chat fonts saved for this self-hosted dashboard.")}catch(X){g(X instanceof Error?X.message:String(X))}finally{y(!1)}},ce=()=>{const X=Ot(m==null?void 0:m.standaloneFontPreferences);g(""),h(""),x(X),rs(X)},D=()=>{g(""),h(""),x(fs),rs(fs)},ie=async()=>{T(""),z(""),k(!0);try{const X=await $t("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),le=await X.json();if(!X.ok)throw new Error((le==null?void 0:le.error)||"Failed to save standalone network preference");u(le),S(le.standaloneBindHost),z(le.standaloneBindHost==="0.0.0.0"?"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.":"Default standalone network mode set to localhost only. Restart standalone to apply it.")}catch(X){T(X instanceof Error?X.message:String(X))}finally{k(!1)}},fe=async()=>{if(T(""),z(""),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 X=await $t("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:I})}),le=await X.json();if(!X.ok)throw new Error((le==null?void 0:le.error)||"Failed to save password");d(le),await F(),M(""),j(""),B(""),z(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),id()}catch(X){T(X instanceof Error?X.message:String(X))}finally{k(!1)}},xe=async()=>{T(""),z(""),k(!0);try{const X=await $t("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),le=await X.json();if(!X.ok)throw new Error((le==null?void 0:le.error)||"Failed to clear password");d(le),await F(),M(""),j(""),B(""),z("Standalone password disabled.")}catch(X){T(X instanceof Error?X.message:String(X))}finally{k(!1)}};return s.jsxs(ar,{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:()=>S("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="0.0.0.0",onChange:()=>S("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:()=>{ie()},disabled:R,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 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}),H&&s.jsx(Cs,{variant:"success",children:H}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:v,onChange:X=>M(X.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:I,onChange:X=>j(X.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:w,onChange:X=>B(X.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{fe()},disabled:R,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…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{xe()},disabled:R,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(X=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${X.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:X.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:X.type})]},X.type))})}),s.jsx(jt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(oh,{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(dh,{})]}),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(gh,{})]}),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(Qy,{value:f,savedValue:Ot(m==null?void 0:m.standaloneFontPreferences),saving:N,error:p,notice:b,onChange:x,onSave:()=>{be()},onResetToSaved:ce,onResetToDefaults:D})]}),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(wh,{})]})]})}),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(rh,{}),s.jsx(ss,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Mu,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:Y})]})}),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(mu,{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:i,onChange:X=>c(X.target.value),onBlur:_,onKeyDown:X=>{X.key==="Enter"&&X.currentTarget.blur()}})]})})})]})}Yp();xh();zy();const ev=ac({baseUrl:"",getToken:Ao});function tv({children:e}){const[t,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,d]=o.useState(""),[m,u]=o.useState(!1),f=async()=>{a(!0),d("");try{const y=await(await $t("/auth/session")).json();r(y)}catch(N){d(N instanceof Error?N.message:String(N))}finally{a(!1)}};o.useEffect(()=>{f()},[]),o.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let N=!1;return(async()=>{try{const y=await $t("/api/v1/standalone/preferences");if(!y.ok)return;const p=await y.json();if(N)return;const g=Ot(p.standaloneFontPreferences);rs(g),Ka(g)}catch{}})(),()=>{N=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const x=async N=>{N.preventDefault(),u(!0),d("");try{const y=await $t("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),p=await y.json();if(!y.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),id()}catch(y){d(y instanceof Error?y.message:String(y))}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:i,onChange:N=>c(N.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||!i,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 Qi(){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(ya,{to:`/machines/${r.id}`,replace:!0}):s.jsx(ya,{to:"/dashboard",replace:!0})}function sv(){const e=o.useMemo(()=>({sendCommand:Jr,sendData:Oa,sendPtyInput:Ey}),[]);return s.jsx(Kd,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(ou,{client:ev,children:s.jsx(tv,{children:s.jsx(Ky,{children:s.jsx(cu,{value:e,children:s.jsx(Gy,{children:s.jsxs(Wd,{children:[s.jsx(qt,{path:"/dashboard",element:s.jsx(gg,{})}),s.jsx(qt,{path:"/machine",element:s.jsx(Qi,{})}),s.jsx(qt,{path:"/machines/:id",element:s.jsx(Sy,{})}),s.jsx(qt,{path:"/machines",element:s.jsx(Qi,{})}),s.jsx(qt,{path:"/about",element:s.jsx(Jy,{})}),s.jsx(qt,{path:"/settings",element:s.jsx(Zy,{})}),s.jsx(qt,{path:"/mesh",element:s.jsx(Iy,{})}),s.jsx(qt,{path:"*",element:s.jsx(ya,{to:"/dashboard",replace:!0})})]})})})})})})})}dp({connectionManager:Wt});Fd(document.getElementById("root")).render(s.jsx(sv,{}));
|