@adhdev/daemon-standalone 0.9.76-rc.34 → 0.9.76-rc.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,94 @@
|
|
|
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 Td=Object.defineProperty;var Md=(e,t,r)=>t in e?Td(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Je=(e,t,r)=>Md(e,typeof t!="symbol"?t+"":t,r);import{r as o,j as s,M as Ka,a as Id,b as Ad,c as Rd,R as Ct,d as or,t as Ld,e as Pd,u as Bs,D as _d,f as ha,g as xa,h as Wa,i as Dd,k as Ed,B as $d,l as Bd,m as Gt,N as ba,n as Kd}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 Wd(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 Is=Wd();function Eo(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 Od(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Fd(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Yi(e,t){if(!e)return t??null;if(!t)return e??null;const r=Fd(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 Js(e,t){const r=Od(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:Yi(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 Xi(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?Js(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 $o(e){return!!e&&typeof e=="object"&&"text"in e}function Oa(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:$o(i)?String(i.text||""):"").join(r):$o(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function As(e){return Oa(e,{normalizeWhitespace:!0})}const Ji=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}),Qi=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Bo(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 Zi(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 Hd(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 An(e){if(!e||typeof e!="object")return"";const t=e,r=Hd(As(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 Ud(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=An(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:An(e[0]),last:An(e[e.length-1])}}function ga(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function ya(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(ga(e)&&ga(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)ya(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"&&ya(n[c],a[c],r)}function Zs(e,t){return Array.isArray(e)?e.map(r=>Zs(r,t)):!e||typeof e!="object"?e:ga(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Ud(a,t):Zs(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,Zs(n,t)]))}function zd(e,t){try{const r=new WeakSet;return ya(e,t,r),JSON.stringify(Zs(e,r))===JSON.stringify(Zs(t,r))}catch{return!1}}function va(e,t,r){return zd(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function ec(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Vd(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Ko(e,t,r,n){var l;const a=(l=t.chats)!=null&&l.length?t.chats:e.chats,i=Xi(e.childSessions,t.childSessions,{preserveMissing:n}),c=Yi(t.activeChat,e.activeChat);return Zi(e,t,{...e,...t,chats:a,childSessions:i,activeChat:c,_lastUpdate:r})}function Gd(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=Xi(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"])Vd(n,t,c);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function qd(e,t,r,n){const a=Gd(e,t,n),i=Object.keys(a).length>0?Zi(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return va(e,i,r)}function Yd(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=ec(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 Xd(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 Jd(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function Qd(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}=Yd(e);for(const x of e){const C=i.get(x.id);if(!C){i.set(x.id,{...x,_lastUpdate:n});continue}const y=Bo(x),p=Bo(C),g=ec(x),b=!a.has(g);if(y>p){const S=Ko(C,x,n,b);i.set(x.id,va(C,S,n));continue}if(y<p){i.set(x.id,qd(C,x,n,b));continue}const h=x.timestamp||n,N=C._lastUpdate||C.timestamp||0;if(h>=N){const S=Ko(C,x,n,b);i.set(x.id,va(C,S,n));continue}(u=x.chats)!=null&&u.length&&!((f=C.chats)!=null&&f.length)&&i.set(x.id,{...C,chats:x.chats})}for(const[x,C]of i){const y=C.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-(C._lastUpdate||C.timestamp||0);Xd(C,y,p,c,a,d)&&i.delete(x)}for(const[x,C]of i){const y=C.daemonId||x.split(":")[0];if(Jd(C,y,l,d,i))continue;n-(C._lastUpdate||C.timestamp||0)>3e5&&C.status!=="online"&&i.delete(x)}return Array.from(i.values())}function Zd(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 eu({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(N=>{let S=!1;const v=N.map(M=>M.id!==b||M.chats===h?M:(S=!0,{...M,chats:h}));return S?v:N})},[]),x=o.useCallback((b,h)=>{n(N=>{const S=N.length===0?b:Qd(b,N,h),v=!Zd(N,S);return v&&Is.record({kind:"dashboard.entries_applied",payload:{incoming:Eo(b),next:Eo(S)}}),v?S:N})},[]),C=o.useCallback(()=>i(!0),[]),y=o.useMemo(()=>({injectEntries:x,markLoaded:C,getIdes:()=>u.current}),[x,C]),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(Qi.Provider,{value:y,children:s.jsx(Ji.Provider,{value:g,children:e})})}function Qt(){return o.useContext(Ji)}function ir(){return o.useContext(Qi)}function tc(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,C=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(C)}}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 tu=tc({baseUrl:"http://localhost:3847"}),su=o.createContext(tu);function ru({client:e,children:t}){return s.jsx(su.Provider,{value:e,children:t})}const nu={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},sc=o.createContext(nu);function au({value:e,children:t}){return s.jsx(sc.Provider,{value:e,children:t})}function gt(){return o.useContext(sc)}function ou(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 iu(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function cu(e){return e?ou([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),iu(e.content)]):""}const Fe={size:18};function rc({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 Fa({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 Yt({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 nc({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 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("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 du({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 ac({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 uu({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 hn({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 oc({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 mu({size:e=Fe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Ut({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 Ha({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 fu({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 fs({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 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("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 cr({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 Rs({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 jr({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 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("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 Ua({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 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("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}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("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 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("polyline",{points:"4 17 10 11 4 5"}),s.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function hu({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 Va({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 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("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 xu({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"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 bu({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"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 gu({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 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("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 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("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 vu({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"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 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 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}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:"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 ku({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),s.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}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("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}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("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 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:"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 Tu({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 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("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function Iu({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"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 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:"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 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("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 dc=[Id,{singleTilde:!1}],uc=[dc,Ad,Rd],Lu=[dc],Ga=200,Pu=80,Wo=650,Fs=new Map;function Zr(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}:${cu(n)}`}function Du(e,t,r,n){return e||!t?!1:Zr(r,n)}function Eu({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=Pu,bottomThresholdPx:a=Ga}){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 $u(e){return Eu({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Qs(e,t=Ga){return!!e&&e.fromBottom>=t}function Bu(e,t){return Zr(e,t)?!Qs(e):!0}function Ku({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function Wu({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function Rn(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function mc(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Ou(e,t,r){return Number(e.receivedAt||r[en(e,t)]||0)||0}function Fu(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 fc(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Hu(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function kr(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 Ln(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 Oo(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):fc(e)?s.jsx(Ka,{remarkPlugins:uc,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function Sr({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:Oo(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=Ln(r);return a?s.jsx("img",{src:a,alt:kr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=Ln(r);return a?s.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=Ln(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:kr(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||kr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=kr(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}),Oo(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 en(e,t){const r=e,n=Oa(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 Uu=o.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(Ka,{remarkPlugins:Lu,children:t.text}),s.jsx("span",{className:"action-time",children:mc(t.timestamp)})]})},(e,t)=>e.log===t.log),zu=o.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var M,I,j;const d=(t.role||"").toLowerCase(),m=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),f=Hu(t.content)?t.content:null,x=!!(f!=null&&f.some(w=>w.type!=="text")),C=Oa(t.content,{joiner:`
|
|
4
|
+
`});if(u==="thought"){const w=typeof((M=t.meta)==null?void 0:M.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(gu,{size:13}),s.jsx("span",{children:w})]}),s.jsx("div",{className:"chat-msg-body",children:C})]})}if(u==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),x&&f?s.jsx("div",{className:"tool-text w-full",children:s.jsx(Sr,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:C})]});if(u==="terminal"){const w=(I=t.meta)!=null&&I.isRunning?"⏳":"✅",$=typeof((j=t.meta)==null?void 0:j.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:w}),s.jsx("span",{children:$})]}),x&&f?s.jsx("div",{className:"chat-msg-body",children:s.jsx(Sr,{parts:f,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:C})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:x&&f?s.jsx(Sr,{parts:f,renderAsPreformatted:!1}):C.slice(0,100)});const y=t.meta,g=(typeof(y==null?void 0:y.renderMode)=="string"?y.renderMode.trim():"")==="preformatted",b=C,h=!1,N=b,S=g,v=!S&&fc(N);return s.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${m?"self-end":"self-start"}`,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:mc(r)})]}),(b||x)&&s.jsx("div",{className:"chat-markdown",children:x&&f?s.jsx(Sr,{parts:f,renderAsPreformatted:S}):S?s.jsx("pre",{className:"chat-preformatted",children:N}):v?s.jsx(Ka,{remarkPlugins:uc,children:N}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:N})}),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),Vu=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:C,hiddenLiveCount:y=0,loadError:p,scrollToBottomRequestNonce:g,isVisible:b=!0},h){const N=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),$=o.useRef(null),P=o.useRef(!1),T=o.useRef(null),O=o.useRef(!1),[U,R]=o.useState(new Set),[k,A]=o.useState({showTop:!1,showBottom:!1}),W=o.useRef(!1),_=o.useRef(!1),E=o.useRef(b),F=o.useRef(b),Y=o.useRef(null);F.current=b;const be=()=>{const X=N.current;return X?X.scrollHeight-X.scrollTop-X.clientHeight<Ga:!0},ce=o.useCallback(()=>{const X=N.current,ue=X?$u(X):{showTop:!1,showBottom:!1};A(q=>q.showTop===ue.showTop&&q.showBottom===ue.showBottom?q:ue)},[]),ee=o.useCallback((X="auto")=>{var q;const ue=N.current;ue&&(ue.scrollTo({top:ue.scrollHeight,behavior:X}),(q=ue.ownerDocument.defaultView)==null||q.requestAnimationFrame(()=>ce()))},[ce]),ye=o.useCallback((X="auto")=>{var q;const ue=N.current;ue&&(ue.scrollTo({top:0,behavior:X}),(q=ue.ownerDocument.defaultView)==null||q.requestAnimationFrame(()=>ce()))},[ce]),we=o.useCallback(()=>{var Te;const X=N.current,ue=(Te=window.getSelection)==null?void 0:Te.call(window);if(!X||!ue||ue.rangeCount===0||ue.isCollapsed){O.current=!1;return}const q=ue.anchorNode,Ae=ue.focusNode;O.current=!!(q&&Ae&&X.contains(q)&&X.contains(Ae))},[]),je=o.useMemo(()=>t.filter(Fu),[t]),Q=je.length===t.length?m:void 0,ie=_u(je,Q),he=o.useCallback(()=>{const X=N.current;if(!X||!l||!F.current)return;const ue={top:X.scrollTop,fromBottom:Math.max(0,X.scrollHeight-X.scrollTop-X.clientHeight),messageFingerprint:ie};Y.current={contextKey:l,snapshot:ue},Fs.set(l,ue)},[l,ie]),se=o.useCallback((X="auto")=>{$.current!=null&&cancelAnimationFrame($.current),$.current=requestAnimationFrame(()=>{$.current=null,ee(X)})},[ee]),de=o.useCallback(()=>{W.current=!1,P.current=!0,_.current=!0,T.current!=null&&window.clearTimeout(T.current),T.current=window.setTimeout(()=>{P.current=!1,T.current=null},Wo)},[]);o.useEffect(()=>{const X=!w.current,ue=j.current!==l;if(j.current=l,X||ue){w.current=!0;const Ae=l?Fs.get(l):null,Te=!!Ae&&Zr(Ae,ie);W.current=Te?Qs(Ae):!1,P.current=Bu(Ae,ie),O.current||(Te?requestAnimationFrame(()=>{const $e=N.current;$e&&(Rn($e,Ae),W.current=Qs(Ae),ce(),_.current=!0)}):se("auto")),M.current=je.length,I.current=ie;return}je.length>M.current;const q=ie!==I.current;Ku({hasSelection:O.current,userScrolledUp:W.current,hasChatContentChanged:q})&&se("auto"),M.current=je.length,I.current=ie},[ie,l,je.length,se,ce]),o.useEffect(()=>{g&&(de(),O.current||se("auto"))},[de,se,g]),o.useEffect(()=>{const X=E.current;X&&!b&&he(),F.current=b,E.current=b;const ue=l?Fs.get(l):null;if(Du(X,b,ue,ie)){if(!ue)return;W.current=Qs(ue),P.current=!1,O.current||requestAnimationFrame(()=>{const q=N.current;q&&(Rn(q,ue),ce())});return}},[b,l,ie,de,he,se,ce]),o.useEffect(()=>()=>{const X=Y.current;X&&Fs.set(X.contextKey,X.snapshot),$.current!=null&&cancelAnimationFrame($.current),T.current!=null&&window.clearTimeout(T.current)},[]),o.useEffect(()=>{const X=S.current,ue=N.current;if(!X||!ue)return;const q=()=>{T.current!=null&&window.clearTimeout(T.current),T.current=window.setTimeout(()=>{P.current=!1,T.current=null},Wo)},Ae=new ResizeObserver(()=>{ce();const Te=P.current;Wu({hasSelection:O.current,userScrolledUp:W.current,contextAutoScrollActive:Te})&&(se("auto"),Te&&q())});return Ae.observe(X),ue!==X&&Ae.observe(ue),()=>{Ae.disconnect(),T.current!=null&&(window.clearTimeout(T.current),T.current=null)}},[se,l,ce]),o.useImperativeHandle(h,()=>({scrollToBottom:(X="smooth")=>{ee(X)}}),[ee]),o.useEffect(()=>{const X=N.current;if(!X)return;let ue;const q=()=>{he(),clearTimeout(ue),ue=setTimeout(()=>{W.current=!be(),ce()},50)};return X.addEventListener("scroll",q,{passive:!0}),()=>{X.removeEventListener("scroll",q),clearTimeout(ue)}},[he,ce]),o.useEffect(()=>(document.addEventListener("selectionchange",we),()=>document.removeEventListener("selectionchange",we)),[we]);const ke=o.useRef(0),fe=o.useRef(!1);o.useEffect(()=>{const X=N.current;if(!X||!fe.current||ke.current===0)return;const ue=X.scrollHeight-ke.current;ue>0&&(X.scrollTop=ue),ce(),he(),ke.current=0,fe.current=!1},[je.length,he,ce]),o.useEffect(()=>{if(_.current||!l)return;const X=Fs.get(l),ue=N.current;if(!(!X||!ue)){if(!Zr(X,ie)){ee("auto"),_.current=!0;return}Rn(ue,X),W.current=Qs(X),ce(),_.current=!0}},[l,ie,je.length,ee,ce]);const xe=()=>{const X=N.current;X&&(ke.current=X.scrollHeight),fe.current=!0,f==null||f()},Z=()=>{W.current=!0,ye("smooth"),he()},me=()=>{de(),ee("smooth"),he()},oe=o.useMemo(()=>{const X=je.map((Te,$e)=>({type:"message",data:Te,index:$e,ts:Ou(Te,$e,d)}));if(!r||r.length===0)return X;const ue=[...r].sort((Te,$e)=>Te.timestamp-$e.timestamp).map((Te,$e)=>({type:"action",data:Te,index:$e,ts:Te.timestamp})),q=[];let Ae=0;for(const Te of X){for(;Ae<ue.length&&Te.ts>0&&ue[Ae].ts<Te.ts;)q.push(ue[Ae++]);q.push(Te)}for(;Ae<ue.length;)q.push(ue[Ae++]);return q},[je,r,d]),le=y>0||!!C,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:N,"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..."}),le&&!x&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:xe,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&&!le&&(u||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),oe.map(X=>{if(X.type==="action"){const B=X.data;return s.jsx(Uu,{log:B},`action-${X.index}`)}const ue=X.data,q=X.index,Ae=en(ue,q),Te=ue.receivedAt||d[Ae],$e=`${l}-${Ae}`,Ue=U.has($e);return s.jsx(zu,{message:ue,receivedAt:Te,agentName:n,userName:a,isCliMode:i,isTextExpanded:Ue,onToggleTextExpanded:()=>R(B=>{const Se=new Set(B);return Ue?Se.delete($e):Se.add($e),Se})},`msg-${Ae}`)}),c&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),s.jsx("div",{className:"min-h-10",ref:v})]})}),(k.showTop||k.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[k.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:Z,"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:me,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Gu=o.memo(Vu,(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),qu="modulepreload",Yu=function(e){return"/"+e},Fo={},Xu=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=Yu(d),d in Fo)return;Fo[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":qu,m||(f.as="script"),f.crossOrigin="",f.href=d,l&&f.setAttribute("nonce",l),document.head.appendChild(f),m)return new Promise((x,C)=>{f.addEventListener("load",x),f.addEventListener("error",()=>C(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 Ho=!1;const pc=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),C=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),C.current&&(g.bumpResize(),C.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():C.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 Xu(()=>import("./terminal-BeBmUW3m.js"),__vite__mapDeps([0,1,2])).then(b=>{Ho||(Ho=!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"}})});pc.displayName="CliTerminal";function Nr({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 Uo({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 Ju({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,C;d>m?(u=a.width,f=a.width/d,x=0,C=(a.height-f)/2):(f=a.height,u=a.height*d,x=(a.width-u)/2,C=0);const y=a.left-i.left+x+u*e.nx,p=a.top-i.top+C+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 Qu({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:C,onZoomReset:y,onZoomIn:p,transportType:g,screenshotUsage:b,lastActionStatus:h}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:N=>N.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[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(N=>!N),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:N=>N.stopPropagation(),onChange:N=>l(N.target.value),onKeyDown:N=>{d(N)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{i(N=>!N),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children: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:N=>N.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[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:N=>{N.stopPropagation(),C()},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:N=>{N.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:N=>{N.stopPropagation(),p()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function Zu({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 em(){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 zo(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 mr(e,t){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!em())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,zo(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,zo(t[c])]))}),r.current=t})}function tm({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:C,setLastActionStatus:y,spawnRippleFromNormalized:p,clampPan:g,isMobile:b,mobileFillZoom:h}){const[N,S]=o.useState(null),v=o.useRef(null),M=o.useRef(null),I=o.useRef(null),j=o.useRef(!1),w=o.useRef(null),$=o.useRef(0),P=o.useRef(null),T=o.useRef(1),O=o.useRef({x:0,y:0}),U=o.useRef(!1),R=o.useRef(n),k=o.useRef(C),A=30,W=550,_=18,E=60,F=400,Y=12,be=()=>{if(v.current)return;const ye={nx:.5,ny:.5};v.current=ye,S(ye)};return o.useEffect(()=>{R.current=n,n==="mouse"&&be()},[n]),o.useEffect(()=>{k.current=C},[C]),o.useEffect(()=>{const ye=e.current;if(!ye)return;const we=de=>{if(!r.current)return null;const ke=r.current.getBoundingClientRect();return!ke.width||!ke.height?null:{nx:Math.max(0,Math.min(1,(de.clientX-ke.left)/ke.width)),ny:Math.max(0,Math.min(1,(de.clientY-ke.top)/ke.height))}},je=(de,ke)=>{if(!r.current)return{dnx:0,dny:0};const fe=r.current,xe=fe.getBoundingClientRect(),Z=fe.naturalWidth||xe.width,me=fe.naturalHeight||xe.height,oe=Z/me,le=xe.width/xe.height;let ae,X;return oe>le?(ae=xe.width,X=xe.width/oe):(X=xe.height,ae=xe.height*oe),{dnx:de/ae,dny:ke/X}},Q=(de,ke,fe)=>{if(fe<=1.05)return;const xe=-(de-.5)*100,Z=-(ke-.5)*100,me=g(xe,Z,fe);(Math.abs(me.x-l.current)>.1||Math.abs(me.y-d.current)>.1)&&(m(me.x),u(me.y),l.current=me.x,d.current=me.y)},ie=de=>{const ke=t.current;if(ke&&de.target instanceof Node&&ke.contains(de.target))de.preventDefault();else return;if(de.touches.length===1){const fe=de.touches[0];M.current={x:fe.clientX,y:fe.clientY,time:Date.now()},I.current={x:fe.clientX,y:fe.clientY},U.current||(j.current=!1),w.current=setTimeout(()=>{if(!j.current&&!U.current)if(j.current=!0,R.current==="mouse"){const xe=v.current||{nx:.5,ny:.5};y("Right Click"),p(xe.nx,xe.ny,"right"),k.current("input_click",{...xe,button:"right"}).catch(()=>{})}else{const xe=we(fe);xe&&(y("Right Click"),p(xe.nx,xe.ny,"right"),k.current("input_click",{...xe,button:"right"}).catch(()=>{}))}},500);return}if(de.touches.length===2){w.current&&clearTimeout(w.current),j.current=!0,U.current=!0;const fe=de.touches[1].clientX-de.touches[0].clientX,xe=de.touches[1].clientY-de.touches[0].clientY;P.current=Math.sqrt(fe*fe+xe*xe),T.current=c.current,O.current={x:(de.touches[0].clientX+de.touches[1].clientX)/2,y:(de.touches[0].clientY+de.touches[1].clientY)/2}}},he=de=>{const ke=t.current;if(ke&&de.target instanceof Node&&ke.contains(de.target)&&de.preventDefault(),de.touches.length===1&&I.current){const fe=de.touches[0],xe=fe.clientX-I.current.x,Z=fe.clientY-I.current.y;if(!j.current&&M.current){const me=fe.clientX-M.current.x,oe=fe.clientY-M.current.y;Math.sqrt(me*me+oe*oe)>8&&(j.current=!0,w.current&&clearTimeout(w.current))}if(j.current)if(R.current==="mouse"){const me=je(xe,Z),oe=v.current||{nx:.5,ny:.5},le=Math.max(0,Math.min(1,oe.nx+me.dnx)),ae=Math.max(0,Math.min(1,oe.ny+me.dny));v.current={nx:le,ny:ae},S({nx:le,ny:ae}),y(`Cursor: ${Math.round(le*100)}%, ${Math.round(ae*100)}%`),Q(le,ae,c.current);const X=Date.now();X-x.current>=30&&(x.current=X,k.current("input_mouseMoved",{nx:le,ny:ae}).catch(()=>{}))}else if(c.current>1){const me=t.current;if(me){const oe=me.clientWidth,le=me.clientHeight,ae=l.current+xe/oe*100,X=d.current+Z/le*100,ue=g(ae,X,c.current);m(ue.x),u(ue.y),l.current=ue.x,d.current=ue.y}}else{const me=we(fe);if(me){const oe=Date.now();oe-x.current>=40&&(x.current=oe,y("Scroll"),k.current("input_wheel",{nx:me.nx,ny:me.ny,deltaX:Math.round(-xe*2.5),deltaY:Math.round(-Z*2.5)}).catch(()=>{}))}}I.current={x:fe.clientX,y:fe.clientY};return}if(de.touches.length===2&&P.current!==null){const fe=de.touches[1].clientX-de.touches[0].clientX,xe=de.touches[1].clientY-de.touches[0].clientY,me=Math.sqrt(fe*fe+xe*xe)/P.current,oe=(de.touches[0].clientX+de.touches[1].clientX)/2,le=(de.touches[0].clientY+de.touches[1].clientY)/2,ae=oe-O.current.x,X=le-O.current.y,ue=Math.abs(me-1)>.03;if(R.current==="mouse"){if(ue){const q=Math.max(i,Math.min(5,T.current*me));f(q),c.current=q}else if(Math.abs(ae)>2||Math.abs(X)>2){const q=v.current||{nx:.5,ny:.5},Ae=Date.now();Ae-x.current>=30&&(x.current=Ae,y("Scroll"),k.current("input_wheel",{nx:q.nx,ny:q.ny,deltaX:Math.round(-ae*3),deltaY:Math.round(-X*3)}).catch(()=>{}))}}else{const q=Math.max(i,Math.min(5,T.current*me));f(q),c.current=q;const Ae=t.current;if(Ae&&q>1){const Te=Ae.clientWidth,$e=Ae.clientHeight,Ue=l.current+ae/Te*100,B=d.current+X/$e*100,Se=g(Ue,B,q);m(Se.x),u(Se.y),l.current=Se.x,d.current=Se.y}}O.current={x:oe,y:le}}},se=de=>{var ke;if(w.current&&clearTimeout(w.current),P.current=null,de.touches.length===1&&U.current){const fe=de.touches[0];M.current={x:fe.clientX,y:fe.clientY,time:Date.now()},I.current={x:fe.clientX,y:fe.clientY},j.current=!0;return}if(de.touches.length===0){if(U.current){U.current=!1,j.current=!1;return}if(de.changedTouches.length===1){const fe=de.changedTouches[0],xe=Date.now(),Z=xe-(((ke=M.current)==null?void 0:ke.time)||0),me=M.current?fe.clientX-M.current.x:0,oe=M.current?fe.clientY-M.current.y:0,le=Math.sqrt(me*me+oe*oe);if(R.current==="mouse"){if(Z<A||Z>W||le>_){j.current=!1;return}const ae=v.current||we(fe);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(Z<E||Z>F||le>Y){j.current=!1;return}const ae=we(fe);if(!ae)return;xe-$.current<300?(y("Double tap"),p(ae.nx,ae.ny,"double"),k.current("input_click",{...ae,clickCount:2}).catch(()=>{}),$.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(()=>{}),$.current=xe)}}j.current=!1}};return ye.addEventListener("touchstart",ie,{passive:!1}),ye.addEventListener("touchmove",he,{passive:!1}),ye.addEventListener("touchend",se,{passive:!1}),()=>{ye.removeEventListener("touchstart",ie),ye.removeEventListener("touchmove",he),ye.removeEventListener("touchend",se),w.current&&clearTimeout(w.current)}},[e,t,r,i,c,l,d,m,u,f,x,y,p,g]),{cursorPos:N,cursorPosRef:v,handleToggleInputMode:()=>{a(ye=>{const we=ye==="touch"?"mouse":"touch";return we==="mouse"&&be(),we})},handleZoomReset:()=>{const ye=b?h:1;f(ye),c.current=ye,m(0),u(0),l.current=0,d.current=0}}}function hc({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(""),[,C]=o.useState(!1),[y,p]=o.useState([]),g=o.useRef(0),[b,h]=o.useState(!1),[N,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),$=o.useRef(!1),[P,T]=o.useState(1),[O,U]=o.useState(0),[R,k]=o.useState(0);mr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:M,zoom:P,panX:O,panY:R,isMenuOpen:b,isImeOpen:N});const A=o.useRef(0),W=o.useRef(P),_=o.useRef(O),E=o.useRef(R);o.useEffect(()=>{W.current=P},[P]),o.useEffect(()=>{_.current=O},[O]),o.useEffect(()=>{E.current=R},[R]),o.useEffect(()=>{var Z;(Z=c.current)==null||Z.focus()},[]);const F=r==="connected",Y=n,be=F?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ce=F?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!v||$.current||!Y)return;const Z=d.current,me=l.current;if(!Z||!me)return;const oe=()=>{const le=me.clientWidth,ae=me.clientHeight,X=Z.naturalWidth,ue=Z.naturalHeight;if(!X||!ue||!le||!ae)return;const q=Math.min(le/X,ae/ue),Te=Math.max(le/X,ae/ue)/q;Te>1.01&&(w(Te),T(Te),W.current=Te),$.current=!0};Z.complete&&Z.naturalWidth?oe():Z.addEventListener("load",oe,{once:!0})},[Y,v]);const ee=.5;o.useEffect(()=>{P<=ee&&(U(0),k(0))},[P,ee]);const ye=(Z,me,oe)=>{if(oe<=ee)return{x:0,y:0};const le=(oe-1)/(2*oe)*100,ae=(oe-1)/(2*oe)*100;return{x:Math.max(-le,Math.min(le,Z)),y:Math.max(-ae,Math.min(ae,me))}},we=(Z,me)=>{if(!d.current)return null;const oe=d.current.getBoundingClientRect();return!oe.width||!oe.height?null:{nx:Math.max(0,Math.min(1,(Z-oe.left)/oe.width)),ny:Math.max(0,Math.min(1,(me-oe.top)/oe.height))}},je=(Z,me,oe)=>{const le=l.current;if(!le)return;const ae=le.getBoundingClientRect(),X=++g.current;p(ue=>[...ue,{id:X,x:Z-ae.left,y:me-ae.top,type:oe}]),setTimeout(()=>p(ue=>ue.filter(q=>q.id!==X)),600)},Q=(Z,me,oe)=>{const le=d.current,ae=l.current;if(!le||!ae)return;const X=le.getBoundingClientRect(),ue=ae.getBoundingClientRect(),q=le.naturalWidth||X.width,Ae=le.naturalHeight||X.height,Te=q/Ae,$e=X.width/X.height;let Ue,B,Se,Me;Te>$e?(Ue=X.width,B=X.width/Te,Se=0,Me=(X.height-B)/2):(B=X.height,Ue=X.height*Te,Se=(X.width-Ue)/2,Me=0);const De=X.left-ue.left+Se+Ue*Z,Ke=X.top-ue.top+Me+B*me,He=++g.current;p(Xe=>[...Xe,{id:He,x:De,y:Ke,type:oe}]),setTimeout(()=>p(Xe=>Xe.filter(st=>st.id!==He)),600)},ie=async Z=>{var oe;const me=we(Z.clientX,Z.clientY);if(me){u(`Click: ${Math.round(me.nx*100)}%, ${Math.round(me.ny*100)}%`),je(Z.clientX,Z.clientY,"left"),(oe=c.current)==null||oe.focus();try{const le=await e("input_click",{nx:me.nx,ny:me.ny});le!=null&&le.success||t(`❌ Click failed: ${le==null?void 0:le.error}`)}catch(le){t(`❌ Click error: ${le.message||le}`)}}},he=async(Z,me,oe,le=0)=>{try{await e("input_key",{type:oe?"char":"keyDown",key:Z,code:me,text:oe?Z:void 0,unmodifiedText:oe?Z:void 0,modifiers:le})}catch(ae){t(`❌ Key error: ${ae.message||ae}`)}},se=async Z=>{if(Z.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(Z.key)&&Z.preventDefault();let oe=0;Z.altKey&&(oe|=1),Z.ctrlKey&&(oe|=2),Z.metaKey&&(oe|=4),Z.shiftKey&&(oe|=8),u(`Key: ${Z.key}`),await he(Z.key,Z.code,Z.key.length===1,oe)},de=async Z=>{if(Z.key==="Enter"){if(Z.nativeEvent.isComposing)return;if(f){const me=f;x(""),u(`IME Sent: ${me}`);try{const oe=await e("input_type",{text:me});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 he("Enter","Enter",!1)}};o.useEffect(()=>{const Z=c.current;if(!Z)return;const me=oe=>{var le;if((le=d.current)!=null&&le.contains(oe.target)){oe.preventDefault();const ae=Date.now();if(ae-A.current<40)return;A.current=ae;const X=we(oe.clientX,oe.clientY);if(!X)return;u(`Scroll: ${Math.round(oe.deltaY)}`),e("input_wheel",{nx:X.nx,ny:X.ny,deltaX:Math.round(oe.deltaX),deltaY:Math.round(oe.deltaY)}).catch(()=>{})}};return Z.addEventListener("wheel",me,{passive:!1}),()=>Z.removeEventListener("wheel",me)},[e]);const{cursorPos:ke,handleToggleInputMode:fe,handleZoomReset:xe}=tm({containerRef:c,viewportRef:l,imgRef:d,inputMode:M,setInputMode:I,minZoom:ee,zoomRef:W,panXRef:_,panYRef:E,setPanX:U,setPanY:k,setZoom:T,lastWheelTimeRef:A,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:Q,clampPan:ye,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:Z=>Z.preventDefault(),onFocus:()=>C(!0),onBlur:()=>C(!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(${O}%, ${R}%)`,transformOrigin:"center center",cursor:M==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ie,onContextMenu:Z=>Z.preventDefault(),onDragStart:Z=>Z.preventDefault()}):s.jsx(Zu,{waitingLabel:be,waitingHint:ce,transportType:i}),M==="mouse"&&Y&&s.jsx(Ju,{cursorPos:ke,viewportRef:l,imgRef:d}),y.map(Z=>{const oe={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[Z.type];return s.jsxs("div",{style:{position:"absolute",left:Z.x,top:Z.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}})]},Z.id)})]}),s.jsx(Qu,{inputMode:M,onToggleInputMode:fe,isImeOpen:N,setIsImeOpen:S,isMenuOpen:b,setIsMenuOpen:h,imeText:f,setImeText:x,handleImeSubmit:de,isConnActive:F,zoom:P,isMobile:v,mobileFillZoom:j,onZoomOut:()=>T(Z=>Math.max(.5,Z-.25)),onZoomReset:xe,onZoomIn:()=>T(Z=>Math.min(5,Z+.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 bn(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 xc=e=>bn(e);function sm(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 rm(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...sm(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 tn(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 gn(e,t,r){const n=tn(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 nm(e,t,r){return gn(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function bc({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(cr,{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,C=r!==null;return s.jsx("button",{onClick:()=>i(l),disabled:C,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"} ${C&&!x?"opacity-40":"opacity-100"} ${C?"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 qa="adhdev_controls_bar_visible",wa="adhdev:controlsbarvisibilitychange";function Pn(e){if(!e)return!1;try{return e.getItem(qa)==="1"}catch{return!1}}function am(e,t){if(t)try{t.setItem(qa,e?"1":"0")}catch{}}function om(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(wa,{detail:{visible:e}}))}function Ya(){const[e,t]=o.useState(()=>typeof window>"u"?!1:Pn(window.localStorage)),r=o.useRef(e),n=o.useCallback((c,l=!0)=>{r.current=c,t(c),typeof window<"u"&&am(c,window.localStorage),l&&om(c)},[]);o.useEffect(()=>{const c=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:Pn(window.localStorage);r.current=u,t(u)},l=d=>{if(d.key!==qa)return;const m=Pn(window.localStorage);r.current=m,t(m)};return window.addEventListener(wa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(wa,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 im=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function cm(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function bt(e,t){if(cm(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":im.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 sn(e){return bt(e)==="generating"}function Vo(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 lm(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 _n(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function yn(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 dm(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 um(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function mm(e){return dm(e.trim().replace(/\.local$/i,""))}function fm(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function gc(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&&!um(c));if(r&&r!=="Unknown")return mm(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Tt(e,t={}){return fm(e)||gc(e,t)}function yc(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 vc(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 ps(e,t){return yc(e).join(" · ")}function lr(e){return e.transport==="pty"}function Cs(e){return e.transport==="acp"}function pm(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 Go(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 hm(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=>Vo(x.status,{activeModal:x.activeModal})||sn(x.status));if(a)return bt(a.status,{activeModal:a.activeModal});const i=r.find(x=>Vo(x.status,{activeModal:x.activeModal})||sn(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 xm(e){return bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function bm(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 gm(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 ym(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&&gm(t.receivedAt)||0}function vm(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ja(e){return Math.max(vm(e),ym(e.activeChat))}function wm(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 Xa(e,t){return wm(ja(e),ja(t),Tt(e,{fallbackId:e.id}),Tt(t,{fallbackId:t.id}),e.id,t.id)}const wc="adhdev_notification_prefs",qo={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function jm(){try{const e=localStorage.getItem(wc);if(e){const t=JSON.parse(e);return{...qo,...t}}}catch{}return{...qo}}function km(e){try{localStorage.setItem(wc,JSON.stringify(e))}catch{}}let Ot=jm(),Fr=[];function Sm(){Fr.forEach(e=>e())}function Nm(e){Ot={...Ot,...e},km(Ot),Sm()}function Cm(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Fr.push(r),()=>{Fr=Fr.filter(n=>n!==r)}},[]);const t=o.useCallback(r=>{Nm(r)},[]);return[{...Ot},t]}function er(e){if(!Ot.globalEnabled)return!1;switch(e){case"disconnect":return Ot.disconnectAlert;case"completion":return Ot.completionAlert;case"approval":return Ot.approvalAlert;case"browser":return Ot.browserNotifications;default:return!0}}const Tm={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function jc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function kc(){return"Notification"in window&&Notification.permission==="granted"}let Zt=null;function Mm(e){return e!==!1}async function Im(){if(Zt!==null)return Zt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Zt=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Zt=!!await e.pushManager.getSubscription(),Zt):(Zt=!1,!1)}catch{return Zt=!1,!1}}function ka(e,t,r){if(kc())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 Am(e,t={}){const r={...Tm,...t},n=o.useRef(new Map),a=o.useRef(0),[i,c]=o.useState(null);o.useEffect(()=>{let d=!1;return Im().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,ka(d,m,u))},[r.throttleMs]);o.useEffect(()=>{var d;if(!(!r.enabled||!kc())&&er("browser")&&!Mm(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&&er("approval")&&f==="waiting_approval"&&u!=="waiting_approval"){const C=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";l(`🔔 ${x} — Approval needed`,C.slice(0,120),`approval-${m.id}`)}r.onComplete&&er("completion")&&sn(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 Rm=/^(run|approve|accept|yes|allow|always)/,Lm=/^(run|approve|accept|yes|allow|always|proceed|save)/,Pm=/^(reject|deny|delete|remove|abort|cancel|no)/;function Ja(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=Ja(e).toLowerCase();return Rm.test(t)?"primary":Pm.test(t)?"danger":"default"}function Dm(e){return Lm.test(Ja(e).toLowerCase())?"approve":"reject"}function Em(e){return e.map((t,r)=>({label:Ja(t),variant:_m(t),action:Dm(t),button:t,buttonIndex:r}))}function $m(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Bm(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 Km{constructor(){Je(this,"dedupMap",new Map);Je(this,"DEDUP_WINDOW_MS",5e3);Je(this,"DEDUP_MAX_SIZE",50);Je(this,"DEDUP_CLEANUP_AGE_MS",1e4);Je(this,"toastCallbacks",[]);Je(this,"statusEventCallbacks",[]);Je(this,"resolveActionFn",null);Je(this,"viewRequestRespondFn",null);Je(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="",C="info";if(t.event==="agent:generating_completed"){const p=t.duration?` (${t.duration}s)`:"";x=`✅ ${u} agent task completed${p}`,C="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`,C="warning",(y=t.modalButtons)!=null&&y.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(t);if(!p)return;const g=this.resolveActionFn,b=Em(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=$m(u,t.modalMessage,x),N=Date.now();this.emitToast({id:N,message:h,type:C,timestamp:N,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}`,C="warning",er("browser")&&!document.hasFocus()&&ka(`⚠️ ${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`,C="warning",g&&b&&this.viewRequestRespondFn){const h=Date.now(),N=Bm(b,g,this.viewRequestRespondFn,(S,v)=>console.error(`[EventManager] ${S} view request failed:`,v));this.emitToast({id:h,message:x,type:C,timestamp:h,actions:N,duration:3e4}),x=""}er("browser")&&!document.hasFocus()&&ka("👁️ View Request",`${p} wants to view your session`,`view-request-${g}`)}else t.event==="team:view_request_approved"?(x="✅ View request approved",C="success"):t.event==="team:view_request_rejected"&&(x=`❌ ${t.targetName||"Team member"} declined your view request`,C="warning");if(x){const p=Date.now();this.emitToast({id:p,message:x,type:C,timestamp:p,targetKey:n||t.daemonId,duration:5e3})}}}const nt=new Km,Yo=new Map;function rn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ts(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function vn(e){return rn(e)?rn(e.result)?e.result:e:null}function Wm(e){const t=vn(e);return!t||!rn(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function Cr(e){const t=vn(e);return!t||!rn(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Hs(e){const t=vn(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Tr(e){const t=vn(e);return!!t&&t.success===!1}function Om(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 Fm(e,t){return e&&Ts(e.currentValue)?e.currentValue:t}function Hm(e,t){return Ts(t)?Ts(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Um(e,t){var i,c;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(Ts(l))return l}const n=(i=t.controlValues)==null?void 0:i[e];if(Ts(n))return n;const a=(c=t.defaultValues)==null?void 0:c[e];return Ts(a)?a:void 0}function Hr(e,t){return e.options||t[e.id]||[]}const zm={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 Vm(e,t,r){var n;return((n=zm[t])==null?void 0:n.has(r.id))===!0}function Qa(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Vm(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function Dn(e,t){return{value:t}}function Gm(e,t,r){var a;return r?((a=Hr(e,t).find(i=>i.value===r))==null?void 0:a.label)||r:""}const qm={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Ym({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=gt(),d=`${e}:${t||n}`,m=qm[n]||"#94a3b8",[u,f]=o.useState({}),x=o.useRef({}),C=o.useRef(c);x.current=u,C.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(Yo.get(d)||{}),[N,S]=o.useState(null),[v,M]=o.useState(null),I=o.useCallback(async(A,W={})=>{const _={...W,...t&&{targetSessionId:t}};return await l(e,A,_)},[e,t,l]),j=o.useCallback(async(A,W={})=>{const _=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await I("invoke_provider_script",{..._,scriptName:A,...W})},[I,n,r,t]),w=o.useCallback((A,W,_)=>{const E=Fm(_,W);f(F=>({...F,[A.id]:E})),Om(_==null?void 0:_.effects)},[]),$=o.useCallback((A,W)=>{f(_=>{const E={..._};return W===void 0?delete E[A.id]:E[A.id]=W,E}),y.current=0},[]);if(!i||i.length===0)return null;const P=Qa(i,{hostIdeType:r,providerType:n});if(P.length===0)return null;const T=async A=>{if(N===A.id){S(null);return}if(Hr(A,b).length>0){S(A.id);return}if(A.dynamic&&A.listScript){M(A.id);try{const _=await j(A.listScript,{}),E=Wm(_);if(!E){const be=Hs(_);be&&nt.showToast(be,"warning");return}const F=E.options;h(be=>{const ce={...be,[A.id]:F};return Yo.set(d,ce),ce});const Y=Um(A.id,{localOverrideUntil:y.current,localValues:x.current,controlValues:C.current,defaultValues:p});if(Hm(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)}}},O=async(A,W)=>{S(null);const _=(c==null?void 0:c[A.id])??p[A.id];f(E=>({...E,[A.id]:W})),y.current=Date.now()+5e3;try{if(!A.setScript)return;const E=await j(A.setScript,Dn(A,W)),F=Cr(E);if(F&&!F.ok||Tr(E))throw new Error((F==null?void 0:F.error)||Hs(E)||`Could not update ${A.label}`);w(A,W,F)}catch(E){$(A,_);const F=E instanceof Error?E.message:`Could not update ${A.label}`;nt.showToast(F,"warning")}},U=async A=>{const W=Hr(A,b).map(ce=>ce.value);if(W.length===0)return;const _=String(g[A.id]||""),F=(W.indexOf(_)+1)%W.length,Y=W[F];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,Dn(A,Y)),ee=Cr(ce);if(ee&&!ee.ok||Tr(ce))throw new Error((ee==null?void 0:ee.error)||Hs(ce)||`Could not update ${A.label}`);w(A,Y,ee)}catch(ce){$(A,be);const ee=ce instanceof Error?ce.message:`Could not update ${A.label}`;nt.showToast(ee,"warning")}},R=async A=>{const _=!g[A.id],E=(c==null?void 0:c[A.id])??p[A.id];f(F=>({...F,[A.id]:_})),y.current=Date.now()+5e3;try{if(!A.setScript)return;const F=await j(A.setScript,Dn(A,_)),Y=Cr(F);if(Y&&!Y.ok||Tr(F))throw new Error((Y==null?void 0:Y.error)||Hs(F)||`Could not update ${A.label}`);w(A,_,Y)}catch(F){$(A,E);const Y=F instanceof Error?F.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(F=>typeof F=="string"&&F.trim().length>0);if(!window.confirm(_.join(`
|
|
28
|
+
|
|
29
|
+
`)))return}const W=(c==null?void 0:c[A.id])??p[A.id];try{const _=await j(A.invokeScript),E=Cr(_);if(E&&!E.ok||Tr(_))throw new Error((E==null?void 0:E.error)||Hs(_)||`Could not run ${A.label}`);E&&w(A,W??!0,E)}catch(_){$(A,W);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 W=String(g[A.id]||""),_=Gm(A,b,W),E=N===A.id,F=v===A.id,Y=Hr(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:W?"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:F?"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===W?`${m}14`:"transparent",color:ce.value===W?"var(--text-primary)":"var(--text-secondary)",borderLeft:ce.value===W?`2px solid ${m}`:"2px solid transparent"},title:ce.description||ce.label,onMouseEnter:ee=>{ee.currentTarget.style.background=`${m}10`},onMouseLeave:ee=>{ee.currentTarget.style.background=ce.value===W?`${m}14`:"transparent"},onClick:()=>void O(A,ce.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ce.label}),ce.value===W&&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:W?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void U(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:W?`${m}44`:"var(--border-default)",background:W?`${m}14`:"var(--surface-tertiary)",color:W?m:"var(--text-muted)"},onClick:()=>void R(A),"aria-pressed":!!W,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"&&W?`${A.label}: ${W}`: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:W?"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:W?`${A.label}: ${W}`:A.label})]},A.id);default:return null}})]})})}function Xm({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:d}){const{isVisible:m}=Ya(),u=Qa(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(Ym,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:u,controlValues:d})})}function Jm({hasDraft:e,isBusy:t=!1}){return!e||t}const Sc=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,C]=o.useState(""),y=o.useRef(!1),{isVisible:p,toggleVisibility:g}=Ya();o.useEffect(()=>{C("")},[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&&C("")}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=>C(h.target.value),onPaste:h=>{const N=h.clipboardData.getData("text");N&&C(S=>S+N),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:Jm({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",Nc=(e,t)=>tt(e)&&Ws(e)==="terminal",Ze=e=>e.transport==="acp",Qm=180;function Xt(e){return e.streamSource!=="agent-stream"}function gs(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Cc(e){return e.machineName||""}function fr(e){return gs(e)}function Kt(e){return e.agentType||""}function nn(e){return e.hostIdeType||""}function Za(e){return e.displayPrimary||e.agentName||"Agent"}function Tc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Zm(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Mc(e){const t=Zm(e),r=As(t==null?void 0:t.content),n=As(e.lastMessagePreview);return r||n||""}function ef(e,t=Qm){const r=As(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 tf(e){return ef(Mc(e)||e.displaySecondary||"")}function Ic(e){return[e.displaySecondary,Cc(e)].filter(Boolean)}function Ls(e){return e.agentName||it(Kt(e))}function sf(e){var t,r;if(!Xt(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return it(nn(e)||Kt(e))}function Ac(e){return Xt(e)?e.sessionId:e.nativeSessionId}function Xo(e){return Xt(e)?"native":e.tabKey}function rf(e){return e.sessionId}function nf(e,t){if(t)return Xt(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function af(e,t){const r=Kt(e),n=Xt(e),a=tt(e)||Ze(e),i=n?a?Ls(e)||(t==null?void 0:t.cliName)||it(nn(e)||r):t!=null&&t.type?it(t.type):it(nn(e)||r):Ls(e);return{isNativeConversation:n,isCli:tt(e),isAcp:Ze(e),isCliTerminal:Nc(e),providerType:r,displayLabel:i,targetEntry:nf(e,t)}}function ns(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 Ps(e){return e?fr(e):""}function Us(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function eo(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function of(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 Rc(){return"select_session"}function cf(){return"open_panel"}function lf({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function df(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Jo(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function an(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function to(e){return e instanceof Error?e.message:String(e||"")}function Qo(e){const t=to(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Zo(e,t){const r=to(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function wn({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=eo(t);if(lf({hasMessage:!!b,blockedMessage:h,sendInFlight:u.current}))return h&&m(h),!1;const N=Date.now(),S={tabKey:t.tabKey,message:b,timestamp:N};if(df(f.current,S))return m(null),!0;u.current=!0,l(!0),m(null),f.current=S;try{const v=Ps(t);if(!v)return f.current=Jo(f.current,S),m("Unable to send message right now."),!1;const M=await e(v,"send_chat",{message:b,...ns(t)}),I=an(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=to(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=Jo(f.current,S),m(of(v)),!1}finally{u.current=!1,l(!1)}},[t,e]),C=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),N=g.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N),v=Ps(t);if(!v)return;const M=await e(v,"resolve_action",{button:g,action:S?"approve":"reject",...h>=0&&{buttonIndex:h},...ns(t)}),I=an(M);I.success||r(j=>[...j,{routeId:t.tabKey,text:Zo(g,I==null?void 0:I.error),timestamp:Date.now()}])}catch(b){Qo(b)||console.error("[ModalButton] Error:",b),r(h=>[...h,{routeId:t.tabKey,text:Qo(b)?Zo(g,b):`❌ **${g}** error`,timestamp:Date.now()}])}},[t,e,r]),p=o.useCallback(async()=>{if(!(!t||a)){i(!0);try{await e(t.routeId,cf(),{...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:C,handleModalButton:y,handleFocusAgent:p}}const uf=10,mf=8e3,ff=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function pf(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 Sa(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(ff.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=pf(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=>Sa(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,Sa(a,n,r+1)]))}function Mr(e,t){return Array.isArray(e)?e.slice(-t):[]}function hf(e,t=Date.now()){const r=e&&t-e.firstAt<=mf,n=r?e.count+1:1;return n>=uf?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function Lc(e){var n;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:t.messages.length,visible:e.visibleMessages.length,history:((n=e.chatTailState.historyMessages)==null?void 0:n.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:Mr(t.messages,10),visibleMessagesTail:Mr(e.visibleMessages,5),historyMessagesTail:Mr(e.chatTailState.historyMessages,5),actionLogsTail:Mr(e.actionLogs.filter(a=>a.routeId===t.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chatTail:{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 Sa(r)}function Pc(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 _c(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 Dc(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 En(e,t){return`${e}:${t}`}function xf(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function zs(e,t){xf()&&console.debug(`[subscription-manager] ${e}`,t)}class bf{constructor(){Je(this,"active",new Map);Je(this,"retryTimers",new Map)}subscribe(t,r,n,a,i){var u;const c=En(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),zs("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 C;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};zs("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(C=t.sendData)==null||C.call(t,r,x)};return m.initialSendAccepted=d,m}publish(t){const r=En(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Is.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),Is.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=En(t,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(t){var r;zs("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);zs("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;zs("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 Ht=new bf;function gf(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 yf(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 on(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}=yf(d),f=gf(i,n),x=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,C=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:C.some(g=>!!g.cdpConnected)});for(const g of C){const b=f.get(g.id),h=Js(g,b),N=(u.get(g.id)||[]).map(S=>Js(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:N,agents:N.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=Js(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=Js(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 vf=15e3,wf=15e3,jf=6e4,kf=1200,ei=12,Sf=8e3,Nf=4e3,$n=new Map,Bn=new Map,Ir=new Set,tr=new Map;function Cf(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 ti(e,t){const r=tr.get(e);!r||r.size===0||(tr.delete(e),r.forEach(n=>n(t)))}function Tf(e,t){return new Promise(r=>{const n=tr.get(e)||new Set;tr.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&tr.delete(e),r(c)},i=setTimeout(()=>a(!1),t);n.add(a)})}function pr(){const{sendCommand:e,sendData:t}=gt(),{injectEntries:r,getIdes:n}=ir();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??jf,l=Bn.get(a)||0;if(!(i!=null&&i.force)&&Ir.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const d=$n.get(a);if(d)return d;const m=(async()=>{if(t&&!Ir.has(a)){const p=Ht.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),N=on(g.status,{daemonId:a,existingDaemon:h,existingEntries:b,timestamp:g.timestamp});N.length>0&&r(N),Bn.set(a,Date.now()),ti(a,!0)});if(p.initialSendAccepted?Ir.add(a):Ir.delete(a),!(i!=null&&i.force)&&p.initialSendAccepted&&await Tf(a,kf))return}const u=await e(a,"get_status_metadata"),f=Cf(u);if(!f)return;const x=n(),C=x.find(p=>p.id===a),y=on(f,{daemonId:a,existingDaemon:C,existingEntries:x,timestamp:f.timestamp||Date.now()});y.length>0&&r(y,{authoritativeDaemonIds:[a]}),Bn.set(a,Date.now()),ti(a,!0)})().finally(()=>{$n.delete(a)});return $n.set(a,m),m},[n,r,e,t])}function Mf(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const If=60,Af=50;function Ec(e={}){return e.isCliLike?Af:If}function Rf(e={}){return Ec(e)}function St(e){return(typeof e=="string"?e.trim():"")||void 0}function Ft(e,t){const r=St(t);return r?`${e}:${r}`:void 0}function qt(e,t,r){const n=Ft(t,r),a=St(r);n&&e.push(n),a&&e.push(a)}function Ss(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function $c(e){return St(e.providerSessionId)||St(e.sessionId)||St(e.tabKey)||St(e.routeId)}function so(e){return Ss([St(e.providerSessionId),St(e.sessionId)])}function Ms(e){const t=[];return qt(t,"provider",e.providerSessionId),qt(t,"session",e.sessionId),qt(t,"tab",e.tabKey),qt(t,"route",e.routeId),Ss(t)}function Lf(e){const t=[];return St(e.providerSessionId)?(qt(t,"provider",e.providerSessionId),Ss(t)):St(e.sessionId)?(qt(t,"session",e.sessionId),Ss(t)):St(e.tabKey)?(qt(t,"tab",e.tabKey),Ss(t)):St(e.routeId)?(qt(t,"route",e.routeId),Ss(t)):[]}function ro(e){return Ft("provider",e.providerSessionId)||Ft("session",e.sessionId)||Ft("tab",e.tabKey)||Ft("route",e.routeId)||"unknown:"}function hr(e){return so(e)[0]}function Pf(e){const t=St(e.providerSessionId),r=St(e.sessionId),n=St(e.tabKey),a=St(e.routeId),i=[Ft("provider",t),Ft("session",r),Ft("tab",n),Ft("route",a)].filter(d=>typeof d=="string"),c=Ms({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=ro({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:$c({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:hr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function Na(e,t){const r=Pf(e);return Lf(t).some(n=>r.lookupKeys.includes(n))}const xr=60,_f=1e3,no=12e4,Df=new Set(["generating","waiting_approval","starting","streaming","working"]),si=new Map;function Bc(e,t){return`${e}::${t}`}function Ca(e=xr){return{liveMessages:[],cursor:Ef([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Ef(e,t=xr){return{tailLimit:t}}function ri(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 $f{constructor(t){Je(this,"manager");Je(this,"sendData");Je(this,"daemonId");Je(this,"sessionId");Je(this,"historySessionId");Je(this,"subscriptionKey");Je(this,"snapshot");Je(this,"transportSubscription",null);Je(this,"listeners",new Set);Je(this,"retainCount",0);Je(this,"loadHistoryPromise",null);Je(this,"pendingDisconnectTimer",null);this.manager=t.manager||Ht,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.snapshot=Ca(Math.max(0,t.tailLimit??xr))}updateOptions(t){if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),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=await t({offset:this.snapshot.historyOffset,excludeRecentCount:this.snapshot.liveMessages.length}),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.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};ri(this.snapshot.liveMessages)===ri(r)&&this.snapshot.cursor.tailLimit===n.tailLimit||(this.snapshot={...this.snapshot,liveMessages:r,cursor:n},this.emit())}}function Kc(e){const t=Bc(e.daemonId,e.sessionId),r=si.get(t);if(r)return r.updateOptions(e),r;const n=new $f(e);return si.set(t,n),n}function Bf(e,t){return{...e,loadHistoryPage:t}}function Kf(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Wf(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Df.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??no)),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 Of(e=no){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Ff(e,t={}){const r=new Set,n=[];for(const a of e){if(!Wf(a,t))continue;const i=fr(a),c=a.sessionId||"";if(!i||!c)continue;const l=Bc(i,c);if(r.has(l))continue;r.add(l);const d=hr(a);n.push({daemonId:i,sessionId:c,historySessionId:d||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(Kf),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Hf(e,t){const{sendData:r,sendCommand:n}=gt(),a=(t==null?void 0:t.enabled)!==!1,i=fr(e),c=e.sessionId||"",l=hr(e)||c,d=`daemon:${i}:session:${c}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??xr),u=o.useMemo(()=>!a||!i||!c?null:Kc({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:d,sendData:r,tailLimit:m}),[i,a,l,r,c,d,m]),[f,x]=o.useState(()=>(u==null?void 0:u.getSnapshot())||Ca(m));o.useEffect(()=>{if(!u){x(Ca(m));return}u.retain(),x(u.getSnapshot());const y=u.subscribe(p=>{x(p)});return()=>{y(),u.release()}},[u,m]);const C=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(()=>Bf(f,C),[C,f])}function Uf(e,t){const{sendData:r}=gt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??xr),i=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??no)),c=Of(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(()=>Ff(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const u=m.descriptors.map(f=>Kc({...f,sendData:r,tailLimit:a}));return u.forEach(f=>{f.retain()}),()=>{u.forEach(f=>f.release())}},[m.signature,n,r,a])}function zf(e,t){return t?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function ni(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 Vf(e,t){if(e.length===0)return[];if(t.some(ni))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||!ni(i))continue;const c=String(i.role||"").toLowerCase();n.has(c)||(n.add(c),r.unshift(i))}return r}function Gf(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=Vf(i,c),d=l.length>0?[...l,...c]:c;return t.length===0?d:[...t,...d]}function qf(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Yf(e){return qf(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function Xf(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function Jf(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function Qf(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Wc(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function Oc(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 Zf(e){return Wc(e)?!1:e.inboxBucket==="task_complete"&&Oc(e).length>0}function ai(e){return e.branch||"detached HEAD"}function ep(e){if(e.error)return`${ai(e)} · Git error: ${e.error}`;const t=[ai(e)];return e.changedFiles>0?t.push(Xf(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 tp(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${ep(t)}`}function sp(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function rp(e,t={}){if(t.enabled===!1)return[];if(!Qf(e))return[];const r=Wc(e)?"working":Zf(e)?"complete":null;if(!r)return[];const n=r==="complete"?Oc(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${Jf(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:tp(r,e.git),timestamp:sp(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 np=60;function Ta({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 ie,he,se,de,ke,fe,xe;const x=o.useRef(new Map),C=o.useRef(void 0),y=pr(),{sendCommand:p}=gt(),{isVisible:g}=Ya();mr("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(()=>af(e,t),[e,t]),N=o.useMemo(()=>{var Z;return Qa((Z=h.targetEntry)==null?void 0:Z.providerControls,{hostIdeType:e.hostIdeType,providerType:h.providerType})},[e.hostIdeType,h.providerType,(ie=h.targetEntry)==null?void 0:ie.providerControls]),S=Ec({isCliLike:h.isCli||h.isAcp}),v=Rf({isCliLike:h.isCli||h.isAcp}),M=Hf(e,{enabled:f&&!!e.sessionId,tailLimit:v}),[I,j]=o.useState(S),w=e.tabKey,$=M.historyMessages,P=M.hasMoreHistory,T=M.historyError,O=zf(e,M);o.useEffect(()=>{j(S)},[S,w]);const U=Math.max(0,O.length-I),R=Za(e),k=fr(e),A=Yf(e),W=eo(e),_=a||W,E=!!W,[F,Y]=o.useState(!1);o.useEffect(()=>{const Z=h.targetEntry;k&&(!Z||Z.providerControls===void 0||Z.controlValues===void 0)&&y(k,{minFreshMs:3e4}).catch(()=>{})},[k,h.isAcp,(he=h.targetEntry)==null?void 0:he.providerControls,(se=h.targetEntry)==null?void 0:se.controlValues,y]);const be=o.useCallback(async()=>{if(!F){if(O.length>I){j(Z=>Math.min(O.length,Z+np));return}Y(!0);try{await M.loadHistoryPage()}finally{Y(!1)}}},[M,F,O.length,I]),{allMessages:ce,receivedAtMap:ee}=o.useMemo(()=>{const Z=Gf({historyMessages:$,liveMessages:O,visibleLiveCount:I}),me=rp(e),oe=me.length>0?[...Z,...me]:Z,le={};return oe.forEach((ae,X)=>{const ue=`${e.tabKey}:${en(ae,X)}`;let q=Mf(ae)||x.current.get(ue)||0;q||(q=Date.now(),x.current.set(ue,q)),le[en(ae,X)]=q}),{allMessages:oe,receivedAtMap:le}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,U,$,O,I]),ye=o.useMemo(()=>l.filter(Z=>Z.routeId===e.tabKey).sort((Z,me)=>Z.timestamp-me.timestamp),[l,e.tabKey]),we=o.useCallback(async()=>{var X,ue;if(!k)return;const Z=Lc({activeConv:e,visibleMessages:ce,actionLogs:l,controls:(X=h.targetEntry)==null?void 0:X.providerControls,controlValues:(ue=h.targetEntry)==null?void 0:ue.controlValues,visibleBarControlCount:N.length,chatTailState:{hasMoreHistory:P,historyError:T,historyMessages:$},ui:{controlsVisible:g,visibleLiveCount:I,hiddenLiveCount:U,isInputActive:u,isVisible:f}}),me=await p(k,"get_chat_debug_bundle",{agentType:h.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:Z}),oe=an(me),le=Dc(oe),ae=await _c(le);ae==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),nt.showToast(Pc(oe,{locatorCopyStatus:ae}),ae==="failed"?"warning":"success")},[e,l,ce,g,h.providerType,(de=h.targetEntry)==null?void 0:de.controlValues,(ke=h.targetEntry)==null?void 0:ke.providerControls,k,P,U,$,u,f,T,p,N.length,I]),je=o.useCallback(()=>{const Z=hf(C.current);C.current=Z.state,Z.shouldCollect&&we().catch(me=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",me),nt.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[we]),Q=o.useMemo(()=>{if(O.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(Rs,{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(fs,{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(ic,{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(fs,{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"&&!F)return!P&&$.length===0?s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"No messages yet"})]}):s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,A,i,P,$.length,c,F,O.length,R,b.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[s.jsx(Gu,{messages:ce,actionLogs:ye,agentName:Ls(e)||R||"Agent",userName:d,isCliMode:h.isCli||h.isAcp,isWorking:b.isGenerating,contextKey:e.tabKey,receivedAtMap:ee,lastMessageHash:e.lastMessageHash,onLoadMore:be,isLoadingMore:F,hasMoreHistory:P,hiddenLiveCount:U,loadError:T??void 0,emptyState:Q,scrollToBottomRequestNonce:m,isVisible:f}),s.jsx(Xm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:h.providerType,displayLabel:h.displayLabel,controls:(fe=h.targetEntry)==null?void 0:fe.providerControls,controlValues:(xe=h.targetEntry)==null?void 0:xe.controlValues,isActive:u,isCliTerminal:h.isCliTerminal}),!h.isCliTerminal&&s.jsx(Sc,{contextKey:e.tabKey,panelLabel:R,isSending:n,isBusy:E,statusMessage:_,onSend:r,isActive:u,showControlsToggle:N.length>0,onControlsToggle:je})]})}let Fc=Qt;function Hc(){return Fc()}class ap{constructor(){Je(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 Uc=new ap;class op{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 op;function ip(e){e.dashboardWS&&(Uc=e.dashboardWS),e.connectionManager&&(ut=e.connectionManager),e.useDaemonsHook&&(Fc=e.useDaemonsHook)}const cp=.5,lp=1.25;function lt(e){return Za(e)}function hs(e){return Ic(e).join(" · ")}function zc(e){const t=Mc(e);return t||(e.title?e.title:hs(e)||"No messages yet")}function Vc(e,t){const{isReconnecting:r,isConnecting:n}=Ks(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function dp(e,t){const r=["Chat",...Ic(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function as(e){return Vc(e)||hs(e)}function up(e){return`${lt(e)} · ${zc(e)}`}function mp(e){const t=nn(e),r=t?it(t):Ls(e);return`${lt(e)} — ${r||"Agent"}`}function fp(e){return Ls(e)||"CLI"}function Gc(e){return Tc(e)}function qc(e){return e?`Remote · ${lt(e)||e.workspaceName||"Session"}`:"Remote"}function pp({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var te;Qt();const{sendPtyInput:d}=gt(),[m,u]=o.useState(!1),f=o.useRef(!1);f.current=m;const[x,C]=o.useState("Runtime terminal unavailable"),[y,p]=o.useState(!1),[g,b]=o.useState(null),[h,N]=o.useState(!1),[S,v]=o.useState(!1),[M,I]=o.useState(1),[j,w]=o.useState(!1),[$,P]=o.useState({width:0,height:0}),[T,O]=o.useState({width:0,height:0}),[U,R]=o.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[k,A]=o.useState(null),W=o.useRef(null),_=o.useRef(null),E=o.useRef(!1),F=o.useRef(!1),Y=o.useRef(c),be=o.useRef(0),ce=o.useRef(!1),ee=o.useRef(""),ye=o.useRef(null),we=o.useRef(!1),je=o.useRef(!1),Q=o.useRef(null),ie=o.useRef(null),he=o.useRef(null),se=32*1024,de=()=>{var D,G,J,re;return((G=(D=W.current)==null?void 0:D.ownerDocument)==null?void 0:G.defaultView)||((re=(J=_.current)==null?void 0:J.ownerDocument)==null?void 0:re.defaultView)||window},ke=D=>{const G=de();return{ownerWindow:G,frameId:G.requestAnimationFrame(D)}},fe=()=>{const D=Q.current;if(D){try{D.ownerWindow.cancelAnimationFrame(D.frameId)}catch{}Q.current=null}},xe=()=>{const D=ie.current;if(D){try{D.ownerWindow.clearTimeout(D.timeoutId)}catch{}ie.current=null}},Z=()=>{const D=he.current;if(D){try{D.ownerWindow.clearTimeout(D.timeoutId)}catch{}he.current=null}},me=()=>{c&&Q.current===null&&(Q.current=ke(()=>{st()}))},oe=e.tabKey,le=e.sessionId||"",ae=e.daemonId||((te=e.routeId)==null?void 0:te.split(":")[0])||e.routeId||"",X=eo(e),ue=m?i||X:x,q=cp,Ae=lp,Te=.05,$e=()=>{const D=T.width,G=T.height;if(!Number.isFinite($.width)||$.width<=0||!Number.isFinite($.height)||$.height<=0||!Number.isFinite(D)||D<=0||!Number.isFinite(G)||G<=0)return 1;const J=$.width/D,re=$.height/G;return Number(Math.min(Ae,Math.max(q,Math.min(J,re))).toFixed(2))},Ue=$e(),B=E.current&&M>Ue,Se=Number.isFinite(T.width)&&T.width>0?Math.max($.width,Math.round(T.width*M)):$.width,Me=Number.isFinite(T.height)&&T.height>0?Math.max($.height,Math.round(T.height*M)):$.height,De=()=>{ke(()=>{const D=_.current;D&&(D.scrollLeft=0,D.scrollTop=D.scrollHeight-D.clientHeight)})},Ke=()=>{var D,G;be.current=0,ce.current=!1,ee.current="",ye.current=null,we.current=!1,je.current=!1,E.current||(F.current=!1,I(1)),Q.current!==null&&fe(),u(!1),C("Runtime terminal unavailable"),Z(),xe(),b(null),A(null),w(!1),p(!1),N(!1),v(!1),(G=(D=r.current)==null?void 0:D.reset)==null||G.call(D)},He=()=>{var D,G;be.current=0,ce.current=!1,ee.current="",ye.current=null,we.current=!1,je.current=!1,Q.current!==null&&fe(),u(!0),C(""),Z(),xe(),b(null),A(null),w(!1),p(!1),N(!1),v(!1),(G=(D=r.current)==null?void 0:D.reset)==null||G.call(D)},Xe=()=>{je.current&&(je.current=!1,ke(()=>{var D,G;(G=(D=r.current)==null?void 0:D.scrollToTop)==null||G.call(D)}))},st=()=>{if(Q.current=null,!c)return;const D=ee.current;if(!D)return;const G=D.slice(0,se);ee.current=D.slice(G.length);const J=r.current;if(!J){ee.current=G+ee.current,me();return}J.write(G,()=>{if(ee.current.length>0){me();return}Xe()})},mt=D=>{D&&(ee.current+=D,me())},ht=(D,G=0,J,re,ve={})=>{var _e,Ne,Ee,Be;const Le=!!ve.force;!Le&&G>0&&be.current>=G||!Le&&G===0&&ce.current||(be.current=G,G>0&&N(!0),u(!0),C(""),typeof J=="number"&&typeof re=="number"&&J>0&&re>0&&((Ne=(_e=r.current)==null?void 0:_e.resize)==null||Ne.call(_e,J,re)),ee.current="",(Be=(Ee=r.current)==null?void 0:Ee.reset)==null||Be.call(Ee),D?mt(D):Xe())};o.useEffect(()=>{Ke()},[le]),o.useEffect(()=>{var G;if(!le)return;const D=((G=ut.onRuntimeEvent)==null?void 0:G.call(ut,le,J=>{if(!(!J||J.sessionId!==le)){if(J.type==="runtime_snapshot"){if(!c){ye.current={text:J.text||"",seq:J.seq||0,cols:J.cols,rows:J.rows,force:!!J.force};return}ht(J.text||"",J.seq||0,J.cols,J.rows,{force:!!J.force});return}if(J.type==="session_output"){ce.current=!0,typeof J.seq=="number"&&(be.current=Math.max(be.current,J.seq),J.seq>0&&N(!0)),f.current||u(!0),f.current||C(""),typeof J.data=="string"&&mt(J.data);return}if(J.type==="session_cleared"){if(!c){we.current=!0,ee.current="",ye.current=null;return}He();return}if(J.type==="session_io_error"){const re=typeof J.error=="string"&&J.error?J.error:typeof J.reason=="string"&&J.reason?J.reason:"unknown error";u(!1),C(`Runtime input failed: ${re}`);return}}},ae))||(()=>{});return()=>{D()}},[ae,le,r,c]);const xt=async(D={})=>{var G;if(!ae||!le)return{success:!1,error:"daemonId and sessionId are required"};D.preserveStatus||C(D.loadingMessage||"Loading runtime terminal...");try{const J=await((G=ut.requestRuntimeSnapshot)==null?void 0:G.call(ut,ae,le,{sinceSeq:D.sinceSeq,force:D.force}));return J&&J.success===!1?(D.preserveStatus||(u(!1),C(`Runtime terminal unavailable: ${J.error}`)),J):J||{success:!0}}catch(J){const re=(J==null?void 0:J.message)||String(J);return D.preserveStatus||(u(!1),C(`Runtime terminal unavailable: ${re}`)),{success:!1,error:re}}},Ce=async D=>{var Le,_e;const G=((Le=W.current)==null?void 0:Le.ownerDocument)||document,J=G.defaultView||window,re=(_e=J.navigator)==null?void 0:_e.clipboard;if(re!=null&&re.writeText&&J.isSecureContext)try{return await re.writeText(D),!0}catch{}let ve=null;try{return ve=G.createElement("textarea"),ve.value=D,ve.setAttribute("readonly","true"),ve.style.position="fixed",ve.style.left="-9999px",ve.style.top="0",G.body.appendChild(ve),ve.focus(),ve.select(),G.execCommand("copy")}catch{return!1}finally{ve==null||ve.remove()}},ze=D=>{xe(),A(D);const G=de();ie.current={ownerWindow:G,timeoutId:G.setTimeout(()=>{ie.current=null,A(J=>J===D?null:J)},2200)}},Qe=D=>{Z(),b(D);const G=de();he.current={ownerWindow:G,timeoutId:G.setTimeout(()=>{he.current=null,b(J=>J===D?null:J)},2200)}},Ge=async()=>{var ve,Le,_e,Ne;const D=((Le=(ve=r.current)==null?void 0:ve.getSelection)==null?void 0:Le.call(ve))||"",G=((Ne=(_e=r.current)==null?void 0:_e.getVisibleText)==null?void 0:Ne.call(_e))||"",J=D.trimEnd()||G.trimEnd();if(!J){ze("Nothing to copy");return}if(!await Ce(J)){ze("Copy failed");return}ze(D.trimEnd()?"Copied selection":"Copied visible terminal")},rt=D=>{if(!m||!c)return;((d==null?void 0:d(ae,le,D))??!1)||ze("Terminal input failed")},K=async()=>{if(y)return;p(!0),b("Loading older terminal output..."),je.current=!0;const D=await xt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(p(!1),(D==null?void 0:D.success)===!1){je.current=!1,b(`Older terminal output unavailable: ${D.error}`);return}v(!0),Qe("Older terminal output loaded"),ke(()=>{var G;(G=r.current)==null||G.bumpResize()})};o.useEffect(()=>{var G,J;if(!le)return;ae&&((G=ut.getState)==null?void 0:G.call(ut,ae))==="connected"&&xt();const D=(J=ut.onStateChange)==null?void 0:J.call(ut,(re,ve)=>{re!==ae||ve!=="connected"||xt()});return()=>{D==null||D()}},[ae,le,r]),o.useEffect(()=>{t&&Ke()},[t,oe,r]),o.useEffect(()=>{var re,ve;const D=W.current,G=(ve=(re=D==null?void 0:D.ownerDocument)==null?void 0:re.defaultView)==null?void 0:ve.ResizeObserver;if(!D||!G)return;const J=new G(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 J.observe(D),()=>J.disconnect()},[]),o.useEffect(()=>{if(E.current)return;const D=$e();!Number.isFinite(D)||D<=0||I(G=>F.current?D<G-Te?D:G:(F.current=!0,D))},[T.height,T.width,$.height,$.width]),o.useEffect(()=>{B&&De()},[B,Me,Se]),o.useEffect(()=>{var J;const D=Y.current;if(Y.current=c,!c)return;D||v(!1),we.current&&(we.current=!1,He());const G=ye.current;G&&(ye.current=null,ht(G.text,G.seq,G.cols,G.rows,{force:!!G.force})),ae&&le&&((J=ut.getState)==null?void 0:J.call(ut,ae))==="connected"&&xt(),ee.current&&Q.current===null&&me(),ke(()=>{var re;(re=r.current)==null||re.bumpResize()})},[ae,c,le]),o.useEffect(()=>()=>{Q.current!==null&&fe(),xe(),Z()},[]),o.useEffect(()=>{const D=re=>{var Le;const ve=re.detail;ve!=null&&ve.sessionId&&ve.sessionId!==le||m&&((Le=r.current)==null||Le.bumpResize())},G=de(),J=G===window?[window]:[window,G];for(const re of J)re.addEventListener("adhdev:fit-cli-terminal",D);return()=>{for(const re of J)re.removeEventListener("adhdev:fit-cli-terminal",D)}},[m,le,r]);const V=m&&h&&!S&&(U.atTop||!U.canScroll)||y||!!g;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:W,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[V&&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:()=>{K()},disabled:!le||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(D=>!D),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(D=>{const G=Math.max(Ue,Number((D-.1).toFixed(2)));return G>Ue&&De(),G})},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(D=>{const G=Math.min(Ae,Number((D+.1).toFixed(2)));return G>Ue&&De(),G})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:_,className:B?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:Se>0?`${Se}px`:"100%",height:Me>0?`${Me}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:T.width>0?`${T.width}px`:"100%",height:T.height>0?`${T.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:M},children:s.jsx(pc,{ref:r,readOnly:!m||!c,sizingMode:"measured",onViewportMetrics:O,onScrollMetrics:R,onInput:D=>{!m||(d==null||d(ae,le,D))}})})})}),!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(Sc,{contextKey:e.tabKey,panelLabel:lt(e),isSending:a,isBusy:!!X,statusMessage:ue,onSend:async D=>X?!1:n(D),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const hp=5e3,xp=12e3;function bp(e){return e==="disconnected"||e==="reconnecting"}function gp({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=hp,reconnectActionDelayMs:i=xp}){const c=bp(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",C=!!(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)"},N="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",S={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[x&&s.jsx("div",{className:N,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.")]}),C&&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:N,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 yp({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 ao({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(za,{size:n}):s.jsx(Ut,{size:n})})}const $t="New session",Yc="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 vp(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 wp(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 jp(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 _s({git:e,className:t="",compact:r=!1}){const n=vp(e),a=wp(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 ${jp(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 kp({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 oi({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function ii({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=bn(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 Sp({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:C,inboxOpen:y,onInboxOpenChange:p,hiddenOpen:g,onHiddenOpenChange:b,onOpenNewSession:h,onOpenDashboardGuide:N,guideNudgeVisible:S=!1,actionShortcuts:v,notifications:M,notificationUnreadCount:I,onOpenNotification:j,onMarkNotificationRead:w,onMarkNotificationUnread:$,onDeleteNotification:P,onOpenGitDialog:T}){const{ides:O,p2pStates:U={}}=Qt(),R=!!e&&tt(e)&&!Ze(e),k=!!e&&Ze(e),A=l||(e?Nc(e)?"terminal":"chat":null),[W,_]=o.useState(!1),E=o.useRef(null),F=o.useRef(null),Y=O.filter(se=>se.type==="adhdev-daemon"),be=kp({wsStatus:t,isConnected:r,daemonCount:Y.length,p2pStates:U}),ce=be.subtitle,ee=be.tone==="connected"?"#22c55e":be.tone==="limited"?"#eab308":"#ef4444",ye=be.tone==="connected"?"0 0 4px #22c55e80":be.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",we=o.useMemo(()=>M.filter(se=>!se.readAt),[M]),je=o.useMemo(()=>M.filter(se=>!!se.readAt),[M]),Q=o.useMemo(()=>we.slice(0,9),[we]),ie=I;o.useEffect(()=>{if(!y)return;const se=de=>{var ke;(ke=E.current)!=null&&ke.contains(de.target)||p(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[y,p]),o.useEffect(()=>{if(!g)return;const se=de=>{var ke;(ke=F.current)!=null&&ke.contains(de.target)||b(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[g,b]),o.useEffect(()=>{if(!g&&!y)return;const se=de=>{if(!de.altKey)return;const ke=de.code.match(/^Digit([1-9])$/);if(!ke)return;const fe=Number(ke[1])-1,xe=g?u[fe]:void 0,Z=y?Q[fe]:void 0;if(!(!xe&&!Z)){if(de.preventDefault(),de.stopPropagation(),xe){f==null||f(xe),b(!1);return}Z&&(j(Z),p(!1))}};return window.addEventListener("keydown",se,!0),()=>window.removeEventListener("keydown",se,!0)},[u,g,y,Q,b,p,j,f]);const he=se=>{if(!se)return;const de=n.find(ke=>ke.tabKey===se);de&&(m==null||m(de))};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(Ut,{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:ee,boxShadow:ye}}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:ee,boxShadow:ye}})})]}),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:`${$t}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":$t,children:s.jsx(lc,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[N&&s.jsxs("button",{type:"button",onClick:N,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:"Dashboard guide","aria-label":"Open dashboard guide",children:[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:hs(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(_s,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(_s,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(R||k)&&c&&s.jsxs(s.Fragment,{children:[R&&d&&A&&s.jsx(ao,{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(Ha,{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${W?" is-drop-target":""}`,ref:F,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 de=se.dataTransfer.getData("text/tab-key");se.preventDefault(),_(!1),he(de)},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(Ua,{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(oi,{value:v==null?void 0:v.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[C&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:C,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(oi,{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,hs(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(xn,{size:16}),ie>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ie})]}),y&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[we.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),we.map(se=>s.jsx(ii,{notification:se,shortcutIndex:Q.indexOf(se)>=0?Q.indexOf(se)+1:void 0,onOpen:()=>j(se),onMarkRead:()=>w(se.id),onMarkUnread:()=>$(se.id),onDelete:()=>P(se.id)},se.id))]}),je.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),je.map(se=>s.jsx(ii,{notification:se,onOpen:()=>j(se),onMarkRead:()=>w(se.id),onMarkUnread:()=>$(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 Np(e,t){return String(e||"")!==String(t||"")}function Cp(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&&!yc(c.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
40
|
+
`).includes(a)))}function Tp(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 Xc(e,t={}){return Tp(Cp(e,t),t.sortMode||"recent")}function cn(e){return e?"Resume saved history":"Start fresh"}function oo(e){return e?"Resuming saved history…":"Starting fresh…"}function Mp(){return"Start fresh"}function Jc(e,t=!1){return e==="cli"?cn(t):e==="ide"?"Start IDE":"Start ACP session"}function Qc(e,t=!1){return e==="cli"?oo(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Ip(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Ap(){return"Open saved history"}function Rp(){return"Saved History"}function io(){return"Use saved history when you want continuity in the same provider conversation."}function Lp(){return"No saved history found yet."}function Pp(){return"Refresh saved history"}function _p(){return"Refreshing saved history…"}function os(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function is(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 Ds(e){return e==="start-fresh"?"Start fresh":"Restart"}function Es(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function co(e){return`Resume saved history with ${e}?`}function lo(){return"Review or change the target workspace before resuming saved history."}function Dp(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 uo({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:C,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),[N,S]=o.useState(()=>wt()),v=l||N,M=String(d||"").trim(),I=T=>{if(m){m(T);return}S(T)},j=o.useMemo(()=>a.map(T=>{const O=String(T.workspace||"").trim();return T.canResume||O||!M?T:{...T,workspace:M,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[M,a]),w=o.useMemo(()=>Xc(j,{textQuery:v.textQuery,workspaceQuery:v.workspaceQuery,modelQuery:v.modelQuery,resumableOnly:v.resumableOnly,sortMode:v.sortMode}),[j,v.modelQuery,v.resumableOnly,v.sortMode,v.textQuery,v.workspaceQuery]),$=s.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:h?Rp():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:mp(e)}),h&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:io()})]}),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 O=e.providerSessionId===T.providerSessionId,U=O||!T.canResume||!!c,R=T.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{U||!y||y(T)},disabled:U,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${O?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${U?"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 ${O?"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:Dp(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":"",ps(T.summaryMetadata)?` · ${ps(T.summaryMetadata)}`:"",T.messageCount>0?` · ${T.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:O?"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(yu,{size:32})}),s.jsx("div",{className:"text-[13px]",children:h?a.length>0?"No saved history matches these filters.":Lp():"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:C,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(ur,{size:13})," ",h?Pp():"Refresh History"]})})})]})]});return typeof document>"u"?$:or.createPortal($,document.body)}const ci={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 Zc({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=ci[n.type]||ci.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 Ep=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function $p(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Bp(e){return e.sessionId||e.instanceId||e.agentType}function Kn(e,t){return e||t}function el(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Tt(r,{fallbackId:r.id}));return t}function tl(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 mo(e,t={}){return Kp(e,tl(e,t))}function Kp(e,t={}){var f,x,C,y,p;const r=[],n=t.machineName,a=t.connectionState,i=$p(e),c=e.workspace||"",l=pm(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=Ep(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,N=b?" (Coordinator)":h?" (Mesh Node)":"",S=l+N,v=(C=e.activeChat)==null?void 0:C.activeModal,M=v&&Array.isArray(v.buttons)&&v.buttons.length>0,I=hm(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 $=(p=e.activeChat)==null?void 0:p.id,P=e.chats;if($&&Array.isArray(P)&&P.length>0){const R=P.find(k=>k.id===$||k.id&&String(k.id)===String($));R!=null&&R.title&&String(R.title).trim()&&(w=String(R.title).trim())}const T=(tt(e)||Ze(e),e.type),O=(tt(e)||Ze(e))&&Go(w,S,T)?"":w,U=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:O,messages:U,resume:e.resume,hostIdeType:!tt(e)&&!Ze(e)?e.type:void 0,workspaceName:i,workspacePath:c,git:e.git,displayPrimary:O||i||(tt(e)?e.mode==="chat"?S:`Terminal${N}`: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=xm(g),N=Bp(g),S=`${e.id}:${N}`,v=g.title&&String(g.title).trim()||"",M=Go(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 Wp(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 sl(e,t){const r=Wp(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const rl=[{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:"🏄"}],nl=[{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:"🧩"}],al=[{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:"🟠"}],Op=rl,Fp=nl,Hp=al;function zt(...e){return Ld(Pd(e))}function Up({icon:e,title:t,subtitle:r,badge:n,actions:a,className:i}){return s.jsxs("div",{className:zt("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 sr({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(Up,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:zt("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const Ma="adhdev:themechange";function zp(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ws(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function js(e){return e==="system"?zp():e}function ol(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Ur(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Ma,{detail:{preference:e,theme:t}}))}function Vp(){const e=ws(),t=js(e);ol(t),Ur(e,t)}function fo(){const[e,t]=o.useState(ws),[r,n]=o.useState(()=>js(ws()));o.useEffect(()=>{ol(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),Ur("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:ws()),n(f==="dark"||f==="light"?f:js(ws()))},l=d=>{if(d.key!=="theme")return;const m=ws(),u=js(m);t(m),n(u)};return window.addEventListener(Ma,c),window.addEventListener("storage",l),()=>{window.removeEventListener(Ma,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=js(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Ur(c,l)},[]),i=o.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",d=js(l);n(d);try{localStorage.setItem("theme",l)}catch{}return Ur(l,d),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const li={dark:"Dark",light:"Light",system:"System"};function Gp({collapsed:e}){const{preference:t,cycleTheme:r}=fo(),n=t==="dark"?s.jsx(wu,{size:16}):t==="light"?s.jsx(vu,{size:16}):s.jsx(ju,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${li[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:li[t]})]})}function Wn(e,t){return e?typeof e=="function"?e(t):e:null}function qp({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}}),C=()=>u(!0),y=()=>u(!1),p=()=>{x(N=>{const S=!N;try{localStorage.setItem(d,S?"1":"0")}catch{}return S})},g=o.useMemo(()=>({collapsed:f,mobileMenuOpen:m,openMobileMenu:C,closeMobileMenu:y,toggleCollapsed:p}),[f,m]),b=N=>`nav-item${N.active?" active":""} cursor-pointer ${f?"justify-center py-2.5 px-0":""}${N.className?` ${N.className}`:""}`,h=N=>s.jsxs("div",{className:b(N),id:`nav-${N.id}`,onClick:()=>{N.onSelect(),y()},title:f?N.title??(typeof N.label=="string"?N.label:void 0):N.title,children:[s.jsx("span",{className:"nav-icon",children:N.icon}),!f&&N.label]},N.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:C,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:N=>N.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(N=>s.jsxs("div",{className:N.className??"border-t border-border-subtle pt-2 mt-2",children:[!f&&N.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:N.title}):null,N.items.map(h)]},N.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(h),Wn(i,g),s.jsx(Gp,{collapsed:f}),Wn(c,g)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function kt({title:e,icon:t,description:r,accentColor:n,className:a,children:i}){return s.jsxs("div",{className:zt("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 ln({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:zt("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 Yp={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"},Xp={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ns({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:zt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Yp[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Xp[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 Ar({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:zt("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 Rr(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:zt("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 Jp={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"},Qp={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Zp({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:zt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Jp[e],r),children:[s.jsx("span",{className:zt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Qp[e])}),n]})}function ts({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 eh({onPrefChange:e}){const[t,r]=Cm(),[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(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xn,{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(ts,{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:()=>{jc().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(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ku,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Su,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Rs,{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 dn(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function th(e,t){const r=dn(e),n=dn(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 il(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function rr(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||th(r,t)>=0)return!1;const n=dn(r),a=dn(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function sh(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function On(e,t){return e instanceof Error?e.message:t}function rh({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(ln,{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(ah,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function di({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 or.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 nh(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Op,...Fp,...Hp].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 ah({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var U,R;const[i,c]=o.useState("idle"),[l,d]=o.useState(""),[m,u]=o.useState(null),[f,x]=o.useState("idle"),[C,y]=o.useState(""),p=e.version||null,g=((U=e.machine)==null?void 0:U.platform)||((R=e.system)==null?void 0:R.platform)||"",b=Tt(e,{fallbackId:e.id}),h=g==="win32"?"🪟":g==="darwin"?"🍎":"🐧",N=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=sh(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(On(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(On(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(On(k,"Failed to revoke token"))}}},$="0.9.75",P=il(e,$),T=rr(e,$),O=N.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${$}`,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${$}`}`}`}),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(Zp,{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&&O>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),O>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(k=>{const A=nh(k.type),W=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}),W!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${W?"bg-green-400":"animate-pulse"}`,style:W?void 0:{background:"var(--status-warning)"},title:W?"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||C)&&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:C||l})]}),m==="disconnect"&&s.jsx(di,{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(di,{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 oh=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function ih(){const{preference:e,setPreference:t}=fo();return s.jsx("div",{className:"flex gap-2",children:oh.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 ch(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 lh(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Fn(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function ui(e){const{r:t,g:r,b:n}=lh(e);return .2126*Fn(t)+.7152*Fn(r)+.0722*Fn(n)}function mi(e,t){const r=ui(e),n=ui(t),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function cl(e){const t=ch(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return mi(t,r)>=mi(t,n)?r:n}const Ia={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},Aa={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},dh=[{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"}}}],ll="adhdev-chat-theme",dl="adhdev-chat-theme-custom";function zr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(ll)||"ember"}catch{return"ember"}}function _t(e){try{const t=localStorage.getItem(dl);if(t){const r=JSON.parse(t);return{...e==="dark"?Ia:Aa,...r[e]}}}catch{}return e==="dark"?Ia:Aa}function Lr(e,t){try{localStorage.setItem(dl,JSON.stringify({dark:e,light:t}))}catch{}}function It(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 un(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 uh={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function nr(e,t){var a;const r=(a=uh[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",un(r,24)),n.style.setProperty("--accent-on-primary",cl(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${un(r,18)})`),n.style.setProperty("--border-accent",It(r,.35)),n.style.setProperty("--nav-active-bg",It(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${It(r,.06)}`)}function cs(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",It(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",It(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",It(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",It(e.borderSubtle,.5)),t.style.setProperty("--border-default",It(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",un(e.accentColor,30)),t.style.setProperty("--accent-on-primary",cl(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${un(e.accentColor,40)})`),t.style.setProperty("--border-accent",It(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",It(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${It(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 ${It(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 po(){const e=document.documentElement;["--bg-primary","--bg-secondary","--bg-card","--surface-primary","--surface-secondary","--bg-glass","--bg-glass-hover","--text-primary","--text-secondary","--text-muted","--border-subtle","--border-default","--accent-primary","--accent-primary-light","--accent-on-primary","--accent-gradient","--border-accent","--nav-active-bg","--nav-active-shadow","--chat-user-bg","--chat-user-color","--chat-user-radius","--chat-assistant-bg","--chat-assistant-color","--chat-assistant-radius","--chat-assistant-border","--chat-container-bg","--dashboard-pane-bg","--chat-thought-accent","--chat-tool-accent","--chat-action-color","--chat-send-bg","--chat-input-border"].forEach(r=>e.style.removeProperty(r))}function mh(e){try{localStorage.setItem(ll,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ls()?"dark":"light";cs(_t(t))}else po(),nr(e,ls()?"dark":"light")}function fh(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=zr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ls()?"dark":"light";cs(_t(t))}else po(),nr(e,ls()?"dark":"light")}function ls(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function jt({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 Vs({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 ph({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=o.useState(()=>_t(r));o.useEffect(()=>{a(_t(r))},[r]);const i=o.useCallback((c,l)=>{a(d=>{const m={...d,[c]:l},f=_t(r==="dark"?"light":"dark");return r==="dark"?Lr(m,f):Lr(f,m),cs(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(Vs,{title:"App Background",children:[s.jsx(jt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(jt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(jt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Vs,{title:"App Text",children:[s.jsx(jt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(jt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(jt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Vs,{title:"Borders & Accent",children:[s.jsx(jt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(jt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(jt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Vs,{title:"Chat Bubbles",children:[s.jsx(jt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(jt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),s.jsx(jt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(jt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Vs,{title:"Chat Layout",children:[s.jsx(jt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(jt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(jt,{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?Ia:Aa,d=_t(e?"light":"dark");e?Lr(c,d):Lr(d,c),a(c),cs(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 hh(){const[e,t]=o.useState(zr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>_t("dark"));o.useEffect(()=>{n(ls());const d=new MutationObserver(()=>{const f=ls();n(f);const x=zr();x==="custom"?cs(_t(f?"dark":"light")):nr(x,f?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const f=ls();n(f);const x=zr();x==="custom"?cs(_t(f?"dark":"light")):nr(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"?cs(_t(r?"dark":"light")):(po(),nr(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(_t(r?"dark":"light"))},[r]);const c=d=>{t(d),mh(d)},l=[...dh,{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(ph,{dark:r,onColorsChange:d=>i(d)})]})}const ho="adhdev_mobileDashboardMode_v1",Ra="adhdev:mobile-dashboard-mode-change";function xo(){try{return localStorage.getItem(ho)==="workspace"?"workspace":"chat"}catch{return"chat"}}function xh(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??xo())},r=a=>{const i=a.detail;t(i)},n=a=>{a.key&&a.key!==ho||t()};return window.addEventListener(Ra,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Ra,r),window.removeEventListener("storage",n)}}function bh(e){try{localStorage.setItem(ho,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ra,{detail:e}))}function gh(){const[e,t]=o.useState(!0);return o.useEffect(()=>{t(xo()==="chat")},[]),s.jsx(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ut,{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),bh(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Hn=new Map,fi=new Map;function yh(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 vh(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 ul(){const{sendCommand:e}=gt(),{injectEntries:t,getIdes:r}=ir();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??wf,c=fi.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=Hn.get(n);if(l)return l;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=yh(m);if(!u)return;const f=r().find(C=>C.id===n),x=vh(f,n,u.machine,u.timestamp||Date.now());t([x]),fi.set(n,Date.now())})().finally(()=>{Hn.delete(n)});return Hn.set(n,d),d},[r,t,e])}function wh(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 jh(e,t){const{sendData:r}=gt(),{injectEntries:n,getIdes:a}=ir(),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=>Ht.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(C=>C.id===d),x=wh(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 kh(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=Ht.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)},Nf):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 Sh(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function ml(e){const{sendData:t}=gt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=Sh(e);if(!a||!e.sessionId||!t){n({});return}const i=Ht.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}),Is.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 fl="adhdev_hiddenTabs";function Nh(){try{const e=localStorage.getItem(fl);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ys(e){try{localStorage.setItem(fl,JSON.stringify([...e]))}catch{}}function Un(e){return ro(e)}function bo(e,t){return Ms(t).some(r=>e.has(r))}function Ch(){const[e,t]=o.useState(Nh),r=o.useCallback(m=>{const u=Un(m);t(f=>{const x=new Set(f);return x.has(u)?x.delete(u):x.add(u),ys(x),x})},[]),n=o.useCallback(m=>{const u=Un(m);t(f=>{if(f.has(u))return f;const x=new Set(f);return x.add(u),ys(x),x})},[]),a=o.useCallback(m=>{const u=Un(m);t(f=>{if(!f.has(u))return f;const x=new Set(f);return x.delete(u),ys(x),x})},[]),i=o.useCallback(()=>{t(m=>{if(m.size===0)return m;const u=new Set;return ys(u),u})},[]),c=o.useCallback((m,u)=>{t(f=>{const x=new Set(f);for(const C of u)x.add(C);return ys(x),x})},[]),l=o.useCallback((m,u)=>{t(f=>{const x=new Set(f);for(const C of u)x.delete(C);return ys(x),x})},[]),d=o.useCallback(m=>bo(e,m),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:d}}function pl(e){return e instanceof Error?e.message:String(e||"")}function hl(e){const t=pl(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 xl(e){const t=pl(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function bl({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(gs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Kt(e),mode:t})}catch(l){const d=xl(l);c&&!d&&a(m=>{const u={...m};return i===gl(r,c)?delete u[c]:u[c]=i,u}),hl(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 pi(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 Th(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=pi(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(d=>pi(d,t)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function gl(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 Mh(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))gl(t,a)===i&&(delete n[a],r=!0);return r?n:e}function Ih({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{jc()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:Gc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Am(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 hi(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 ds(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=hi(t==null?void 0:t.receivedAt)||hi(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function La(e,t=0){return ds(e)||e.lastUpdated||t||0}function yl(e){return ds(e)||e.lastUpdated||0}function vl(e,t,r=yl){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 Pa(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 Ah(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Pa(e)&&!e.title.trim()}function Rh(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(Pa(r))-Number(Pa(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:vl(t,r)})[0]||null}function Dt(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=Rh(a);return n?i&&Ah(n)?i:n:i||r[0]||null}function Lh(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 zn(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 Ph(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 xi(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Ph(As(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||""),xi(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||""),xi(r.activeChat)].join(":"))].join("|")}function Dh(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 Eh(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const i of Ms({routeId:n.routeId}))r.set(i,a);for(const i of Ms({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of Ms({tabKey:n.tabKey}))r.set(i,n)}return r}function $h(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Bh(e){const t=$h(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=As(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Kh({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>Lh(e),[e]),i=o.useMemo(()=>el(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:$="new",machineName:P}=tl(w,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),T=_h(w),O=m.current.get(w.id);if(O&&O.ide===w&&O.sourceSignature===T&&O.connectionState===$&&O.machineName===P){S.set(w.id,O),v.push(...O.conversations);continue}const U=mo(w,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),R={ide:w,sourceSignature:T,connectionState:$,machineName:P,conversations:U};S.set(w.id,R),v.push(...U)}m.current=S;const M=new Map,I=w=>{const $=Bh(w),P=u.current.get(w.tabKey);if(P&&P.signature===$)return M.set(w.tabKey,P),P.timestamp;const T={signature:$,timestamp:yl(w)||(P==null?void 0:P.timestamp)||0};return M.set(w.tabKey,T),T.timestamp},j=[...v].sort((w,$)=>vl(w,$,I));return u.current=M,j},[a,t,i]),x=o.useMemo(()=>{const S=Dh(f,r);return zn(c.current,S)?c.current:(c.current=S,S)},[f,r]),C=o.useMemo(()=>{const S=new Map,v=Array.from(new Set(x.map(M=>M.routeId)));for(const M of v){const I=Dt(x,M);I&&S.set(M,I)}return S},[x]),y=o.useMemo(()=>{const S=new Map;for(const v of x){const M=C.get(v.routeId),I=v.streamSource==="native"&&M?M:v;for(const j of Ms({providerSessionId:v.providerSessionId,sessionId:v.sessionId}))S.set(j,I)}return S},[x,C]),p=o.useMemo(()=>Eh(x,C),[x,C]),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=>!bo(n,v));return zn(l.current,S)?l.current:(l.current=S,S)},[x,n]),N=o.useMemo(()=>{const S=h.map(v=>v.tabKey);return zn(d.current,S)?d.current:(d.current=S,S)},[h]);return{chatIdes:a,conversations:x,visibleConversations:h,visibleTabKeys:N,resolveConversationBySessionId:g,resolveConversationByTarget:b}}function Wh({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 Oh({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=Uc.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",C=String(x).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),y=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(C);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 Fh="adhdev_dashboardLayout_v1",Hh="adhdev_dashboardDockview_v1",Uh="adhdev_dashboardDockviewHiddenRestore_v1",Gs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function go(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function zh(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function wl(e){return`${Fh}:${e}`}function Vh(e){const t=wl(e);return go(t,null)}function Gh(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=wl(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function jl(e){return`${Hh}:${e}`}function qh(e){const t=jl(e);return go(t,null)}function Yh(e,t){try{const r=jl(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function kl(e){return`${Uh}:${e}`}function Xh(e){const t=kl(e);return go(t,{})}function Jh(e,t){try{const r=kl(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Qh(){return{groupAssignments:[...Gs.groupAssignments],focusedGroup:Gs.focusedGroup,groupActiveTabIds:{...Gs.groupActiveTabIds},groupTabOrders:{...Gs.groupTabOrders},groupSizes:[...Gs.groupSizes]}}function Zh(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function ex(){const[e]=o.useState(()=>zh(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),[C,y]=o.useState(!1),p=o.useCallback(()=>{if(C)return;const w=Vh(e)??Qh();r(new Map(w.groupAssignments)),a(w.focusedGroup),c(w.groupActiveTabIds),d(w.groupTabOrders),u(w.groupSizes),y(!0)},[C,e]);o.useEffect(()=>{C&&Gh(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:m})},[C,e,t,n,i,l,m]),o.useEffect(()=>{const w=window.matchMedia("(max-width: 767px)"),$=P=>x(P.matches);return w.addEventListener("change",$),()=>w.removeEventListener("change",$)},[]);const g=o.useCallback(w=>{r(w)},[]),b=o.useCallback(w=>{a(w)},[]),h=o.useCallback(w=>{c(w)},[]),N=o.useCallback(w=>{d(w)},[]),S=o.useCallback(w=>{u(w)},[]),v=o.useCallback(w=>{b(w)},[b]),M=o.useCallback((w,$)=>{c(P=>(P[w]??null)===($??null)?P:{...P,[w]:$})},[]),I=o.useCallback((w,$)=>{d(P=>{const T=P[w];return Zh(T,$)?P:{...P,[w]:$}})},[]),j=o.useCallback((w,$)=>{const P=$.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:N,setGroupTabOrder:I,groupSizes:m,updateGroupSizes:S,isMobile:f,hasHydratedStoredLayout:C,hydrateStoredLayout:p,focusConversationTab:j}}function tx(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=so(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function sx({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 C=o.useRef(!1),y=o.useRef(!1),p=o.useRef(null),g=o.useRef(!1);o.useEffect(()=>{if(!e||C.current||t.length===0)return;if(!a){i();return}const b=r(e);b&&(c(b.tabKey,n),C.current=!0,y.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(h=>{const N=new URLSearchParams(h);return N.delete("activeTab"),N},{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(C.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||tx(b.chats,m))&&(g.current=!0,x())},[d,m,u,f,x])}function Vn(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=so(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Sl({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,...ns(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"?Us(a,"⚠️ Session tab not found — try refreshing history"):typeof h=="string"&&h.startsWith("error:")?Us(a,`⚠️ Switch error: ${h}`):Us(a,"⚠️ Session switch failed")}catch(g){console.error("Switch failed",g),Us(a,`❌ Switch failed: ${g.message||"connection error"}`)}},[t,e,a]),x=o.useCallback(async()=>{if(!(!t||c)){l(!0);try{const y=Ps(t);await e(y,"new_chat",{...ns(t)}),i(p=>({...p,[t.tabKey]:Date.now()}))}catch(y){console.error("New chat failed",y)}finally{l(!1)}}},[t,c,e,i]),C=o.useCallback(async()=>{var y,p;if(!(!t||d)){m(!0);try{const g=Ps(t),b=async()=>e(g,"list_chats",{forceExpand:!0,...ns(t)});let h=await b(),N=(h==null?void 0:h.chats)||((y=h==null?void 0:h.result)==null?void 0:y.chats);Vn(N,t)&&(await new Promise(S=>setTimeout(S,450)),h=await b(),N=(h==null?void 0:h.chats)||((p=h==null?void 0:h.result)==null?void 0:p.chats)),h!=null&&h.success&&Array.isArray(N)&&(n(t.routeId,N),Vn(N,t)&&!Vn(r,t)&&Us(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:C}}function rx(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 nx(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function bi(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 gi(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 ax(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 ox(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 yi(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 vi(e){return Array(e).fill(100/e)}function ix({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,C=o.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),y=C>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,$]of I)$!==v&&($>v?j.set(w,$-1):j.set(w,$));return j}),c(M=>{if(M.length<=1)return[];const I=[...M];I.splice(v,1);const j=I.reduce((w,$)=>w+$,0);return j>0?I.map(w=>w/j*100):[]}),r(0)},[t,m,c,r]),b=o.useCallback((v,M)=>{M.preventDefault();const I=u.current;if(!I)return;const j=M.clientX,w=I.offsetWidth,$=i.length===C?[...i]:vi(C),P=O=>{const R=(O.clientX-j)/w*100,k=[...$];k[v]=Math.max(15,$[v]+R),k[v+1]=Math.max(15,$[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,C,c]),h=o.useCallback((v,M,I)=>{if(C>=4)return;const j=I==="left"?M:M+1;t(w=>{const $=Pr(w,m).assignments,P=new Map;for(const T of d){const O=$.get(T.tabKey)??0,U=O>=j?O+1:O;U>0&&P.set(T.tabKey,U)}return j>0&&P.set(v,j),P}),c(w=>{const $=w.length===C?[...w]:vi(C),P=$[M]??100/C,T=Math.max(15,P/2),O=Math.max(15,P/2),U=[...$];U[M]=T,U.splice(j,0,O);const R=U.reduce((k,A)=>k+A,0);return U.map(k=>k/R*100)}),n(w=>{const $=yi(w,j);return $[j]=v,$}),a(w=>{const $=yi(w,j);return $[j]=[v],$}),r(j)},[C,t,m,d,c,n,a,r]);o.useEffect(()=>{rx(e,x)||t(x)},[e,x,t]),o.useEffect(()=>{const{mapping:v,usedGroups:M}=f;n(I=>{const j=gi(I,v);return bi(I,j)?I:j}),a(I=>{const j=gi(I,v);return bi(I,j)?I:j}),r(I=>{const j=l?0:ax(I,M,v);return I===j?I:j}),c(I=>{const j=l?[]:ox(I,M,f.groupCount);return nx(I,j)?I:j})},[f,l,n,a,r,c]);const N=o.useMemo(()=>{const v=Array.from({length:C},()=>[]);for(const M of d){const I=x.get(M.tabKey)??0,j=Math.min(I,C-1);v[j].push(M)}return v},[d,x,C]),S=o.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:x,numGroups:C,isSplitMode:y,groupedConvs:N,moveTabToGroup:p,closeGroup:g,handleResizeStart:b,splitTabRelative:h,clearAllSplits:S}}function Gn(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 cx(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 yo(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=Gn(t.channel)||Gn(e.updateChannel)||Gn(e.releaseChannel)||void 0,n=cx(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 ks(e,t=null){return yo(e).targetVersion||t}function Nl(e){return yo(e).channel||null}function Cl(e){const t=yo(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 lx({ides:e,sendDaemonCommand:t}){const r="0.9.75",n=o.useMemo(()=>e.filter(f=>f.type!=="adhdev-daemon"?!1:il(f,ks(f,r))).sort((f,x)=>Number(rr(x,ks(x,r)))-Number(rr(f,ks(f,r)))),[r,e]),a=o.useMemo(()=>n.some(f=>rr(f,ks(f,r))),[r,n]),i=o.useMemo(()=>n.map(f=>ks(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 C,y;const x=e.find(p=>p.id===f);if(x){m(p=>({...p,[f]:"upgrading"}));try{const p=await t(f,"daemon_upgrade",Cl(x));(C=p==null?void 0:p.result)!=null&&C.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 Tl=80;function Vr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function dx(e){return{...e,createdAt:Vr(e.createdAt),updatedAt:Vr(e.updatedAt,e.createdAt),lastEventAt:Vr(e.lastEventAt,e.updatedAt||e.createdAt)}}function ux(e){const t=ro(e);return t==="unknown:"?e.id:t}function mx(e){return[e.type,$c(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function fx(e,t=Tl){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=ux(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 px(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=gn(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const d=Vr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),m=mx({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(dx({id:m,dedupKey:m,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Tc(a),preview:tf(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return fx(n)}function hx(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function xx(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Tl}=e,a=o.useMemo(()=>px(t,r).slice(0,Math.max(0,n)),[t,r,n]),i=o.useMemo(()=>hx(a),[a]);return{notifications:a,unreadCount:i}}function bx({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 gx=o.createContext(null);function yx(){return o.useContext(gx)}function jn(...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 vx(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 kn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=vx(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 wx(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 jx(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Sn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=jx(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 kx(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 Ml(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:kx(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function Sx(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 Jt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Nn(e){return hr(e)||e.tabKey||e.routeId||null}function Il(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=Dt(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?Nn(a):null}function rs(e){return String(e||"").trim()}function Al(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function mn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Nx(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Cx(e,t){const r=rs(e.providerSessionId),n=rs(e.targetSessionId),a=t.find(i=>{const c=[i.providerSessionId,i.sessionId,i.nativeSessionId,i.tabKey,i.routeId].map(rs).filter(Boolean);return!!(r&&c.includes(r)||n&&c.includes(n))});return a?Nn(a):n||r||null}function Tx(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=Al(t.daemonId);if(n&&n!==e.machineId)return null;const a=rs(t.providerType);if(e.providerType&&a!==e.providerType)return null;const i=rs(e.resumeSessionId),c=rs(t.providerSessionId),l=rs(t.targetSessionId);if(i&&i!==c&&i!==l)return null;const d=mn(e.workspacePath);if(d){const m=mn(t.workspaceName);if(m&&!Nx(m,d))return null}return Cx(t,r)}function wi(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Mx({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=mn(n.workspacePath),m=e.find(f=>{var g,b,h,N;if(!f||f.type==="adhdev-daemon"||Al(f.daemonId||f.id)!==n.machineId||(lr(f)?"cli":Cs(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=mn(f.workspace||f.runtimeWorkspaceLabel);return S?S===d:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((N=(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:N.timestamp)||0)>=n.startedAt-5e3});if(!m)return;const u=Il({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=Tx(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 Ix({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=yx(),l=o.useCallback(async(p,g)=>Sn(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 N={ideType:g,enableCdp:!0};(h=b==null?void 0:b.workspacePath)!=null&&h.trim()&&(N.workspace=b.workspacePath.trim());const S=await e(p,"launch_ide",N);return!(S!=null&&S.success)&&(S==null?void 0:S.success)!==void 0?{ok:!1,error:(S==null?void 0:S.error)||"Could not launch IDE"}:(t({machineId:p,kind:"ide",providerType:g,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(N){return{ok:!1,error:N instanceof Error?N.message:"Could not launch IDE"}}},[e,t]),u=o.useCallback(async(p,g,b,h)=>{var S,v,M;const N=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,$=(w==null?void 0:w.sessionId)||(w==null?void 0:w.id);return j!=null&&j.success&&$?(r($),{ok:!0}):j!=null&&j.success?(t({machineId:p,kind:g,providerType:b,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,startedAt:N}),{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 wi(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:N}),{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 N={meshId:g.trim()};b.trim()&&(N.cliType=b.trim());const S=await e(p,"launch_mesh_coordinator",N),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=Sx((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(N){return wi(N)?(t({machineId:p,kind:"cli",providerType:b.trim()||void 0,startedAt:h}),{ok:!0}):{ok:!1,error:N instanceof Error?N.message:"Could not launch mesh coordinator"}}},[c,r,e,t]),C=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 bl({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:C,setActiveCliViewMode:y}}function Ax(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 Rx(e,t,r=Date.now()){return!e||!Ax(t)?null:{tabKey:e,nonce:r}}function Lx({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(N=>N.tabKey===l);if(h)return h}return r[0]}const p=n[a];if(p){const h=t.find(N=>N.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)},[]),C=o.useCallback(p=>{d(p.tabKey),c(g=>{const b=new URLSearchParams(g),h=rf(p);return h?b.set("activeTab",h):b.delete("activeTab"),b},{replace:!0})},[c]),y=o.useCallback((p,g)=>{const b=Rx(p,g);b&&u(b)},[]);return{activeConv:f,openDesktopConversation:C,requestScrollToBottom:y,scrollToBottomRequest:m,setDesktopActiveTab:x}}function Px(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 Dx({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=tn(e,r),f=_x({tabKey:e.tabKey,historySessionId:hr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:ds(e),liveState:u}),x=f.autoReadKey,C=Px({autoReadKey:x,shouldMarkSeen:f.shouldMarkSeen,completedKey:a.current,pendingKey:i.current});if(!f.shouldMarkSeen){C.shouldCancelPending&&m(),a.current=x;return}if(!C.shouldSchedule)return;C.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=C.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 qn(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 Ex({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([]),[C,y]=o.useState(()=>wt()),[p,g]=o.useState(!1),[b,h]=o.useState(null),N=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 W=S.daemonId||S.routeId||"",_=Kt(S),E=qn(S);return`${W}:${_}:${S.providerSessionId||""}:${E}`},[S,v]),I=o.useMemo(()=>!S||!v?"":qn(S),[S,v]),{isCreatingChat:j,isRefreshingHistory:w,handleSwitchSession:$,handleNewChat:P,handleRefreshHistory:T}=Sl({sendDaemonCommand:a,activeConv:S,chats:(A=n.find(W=>W.id===(S==null?void 0:S.routeId)))==null?void 0:A.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),O=o.useCallback(()=>{u(!0)},[]),U=o.useCallback(()=>{u(!1)},[]),R=o.useCallback(async()=>{if(!(!S||!v||p)){g(!0);try{const W=S.daemonId||S.routeId,_=Kt(S),E=qn(S),F=await a(W,"list_saved_sessions",{agentType:_,providerType:_,kind:"cli",limit:50,...S.providerSessionId?{providerSessionId:S.providerSessionId}:{},...E?{workspace:E}:{}}),Y=(F==null?void 0:F.result)??F;x(Array.isArray(Y==null?void 0:Y.sessions)?Y.sessions:[])}catch(W){console.error("Refresh saved sessions failed",W),x([])}finally{g(!1)}}},[S,p,v,a]);o.useEffect(()=>{if(!m){N.current=null;return}if(!v){N.current=null,x([]),g(!1);return}!M||p||N.current!==M&&(N.current=M,R())},[R,m,p,v,M]);const k=o.useCallback(async W=>{if(!S||!v||!W.providerSessionId||!W.workspace)return;const _=S.daemonId||S.routeId,E=Kt(S);try{h(W.providerSessionId);const F=await a(_,"launch_cli",{cliType:E,dir:W.workspace,resumeSessionId:W.providerSessionId,initialModel:vc(W.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Y=(F==null?void 0:F.result)??F,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 ee=new URLSearchParams(ce);return ee.set("activeTab",be),ee},{replace:!0}),U()}catch(F){console.error("Resume saved session failed",F)}finally{h(null)}},[U,S,v,a,d]);return{historyModalOpen:m,openHistoryModal:O,closeHistoryModal:U,historyTargetConv:S,isSavedSessionHistoryTarget:v,isHistoryCreatingChat:j,isHistoryRefreshingHistory:w,handleHistorySwitchSession:$,handleHistoryNewChat:P,handleHistoryRefresh:T,savedHistorySessions:f,savedHistoryFilters:C,setSavedHistoryFilters:y,missingWorkspaceResumePath:I,isSavedHistoryLoading:p,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:R,handleResumeSavedHistorySession:k}}function $x({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]),C=o.useMemo(()=>{const b=d==null?void 0:d.routeId;if(!b)return null;const h=d!=null&&d.tabKey?i.find(N=>N.tabKey===d.tabKey):a?i.find(N=>N.tabKey===a):null;return(h==null?void 0:h.routeId)===b?h:Dt(i,b)},[i,d,a]),y=o.useMemo(()=>{if(C)return c.find(b=>b.id===C.routeId)},[c,C]);o.useEffect(()=>{x&&(m({routeId:x.routeId,tabKey:Xo(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:Xo(b)}),f(b))},[]),g=o.useCallback(()=>{m(null),f(null)},[]);return{remoteDialogConv:C,remoteDialogIdeEntry:y,remoteDialogActiveConv:u,setRemoteDialogActiveConv:f,openRemoteDialog:p,closeRemoteDialog:g}}function Bx({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:C,openRemoteDialog:y,closeRemoteDialog:p}=$x({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[g,b]=o.useState(!1),[h,N]=o.useState(null),S=o.useCallback(async I=>{const j=I||d;!j||!tt(j)&&!Ze(j)||(N(j),b(!0))},[d]),v=o.useCallback(()=>{b(!1),N(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),$=j.routeId||j.daemonId||"";await m($,"stop_cli",{cliType:w,targetSessionId:j.sessionId,mode:I})}catch(w){console.error("Stop CLI failed:",w)}finally{N(null)}},[d,v,h,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:f,remoteDialogActiveConv:x,setRemoteDialogActiveConv:C,openRemoteDialog:y,closeRemoteDialog:p,cliStopDialogOpen:g,cliStopTargetConv:h,requestCliStop:S,cancelCliStop:v,confirmCliStop:M}}function Rl({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:i=!1}){var b;const c=Bs(),l=gs(e),d=i?null:Cc(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=Ls(e),C=sf(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=Nn(e);h&&c(Jt(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:C,children:[s.jsx(Mt,{size:12}),s.jsx("span",{children:C})]}):s.jsxs("span",{className:"conversation-meta-chip",title:C,children:[s.jsx(Mt,{size:12}),s.jsx("span",{children:C})]})),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(Rs,{size:12}),s.jsx("span",{children:x})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(Rs,{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(Yt,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(Yt,{size:12}),s.jsx("span",{children:d})]})),y&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Yt,{size:12}),s.jsx("span",{children:"Mesh Node"})]})]})}function Yn(e,t=!0){return(e??!0)&&t}const vo=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:C,userName:y,scrollToBottomRequestNonce:p,isInputActive:g=!0,isVisible:b=!0}){const h=n,N=!n,S=Yn(b,h),v=Yn(b,N),M=Yn(b),I=ml(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(bc,{activeConv:j,onModalButton:c}),s.jsx(Rl,{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(cr,{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(pp,{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:N?"visible":"hidden",pointerEvents:N?"auto":"none"},children:s.jsx(Ta,{activeConv:j,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:f,isFocusingAgent:x,actionLogs:C,userName:y,scrollToBottomRequestNonce:p,isInputActive:g&&v,isVisible:v})})]}):s.jsx(Ta,{activeConv:j,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:f,isFocusingAgent:x,actionLogs:C,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 Kx({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:C,onStopCli:y,cliViewMode:p,onSetCliViewMode:g,handleSendChat:b,handleFocusAgent:h,handleModalButton:N,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(Fa,{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(Rl,{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(ao,{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(Ha,{size:14})}),!t&&!M&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>C(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(vo,{activeConv:e,clearToken:0,isCliTerminal:I,ideEntry:n,terminalRef:v,handleModalButton:N,handleRelaunch:S,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:h,isFocusingAgent:d,actionLogs:a,userName:i})})]})}const Xn={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 Wx(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Ll(){const[e,t]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{t(Wx())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Xn[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:Xn[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Xn[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 Pl({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Mt},{key:"chats",label:"Chats",icon:Ut}];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 vs({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 qs({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 Ox({conversation:e,onCancel:t,onConfirm:r}){const n=lt(e),a=hs(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),C=hs(e.conversation),y=Vc(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",N=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($=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",$)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${p}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[c||l?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${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(Ua,{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:xc(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${h}`,children:[s.jsx("span",{className:"truncate",children:C}),s.jsx(_s,{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] ${N}`,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 ji({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 Fx({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:C,onOpenMachine:y,onOpenSettings:p,onSectionChange:g,wsStatus:b="connected",isStandalone:h=!1,onCollectChatDebugBundle:N}){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",$=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=Ps(R);if(!k)return;const A=Array.isArray(R.messages)?R.messages:[],W=Lc({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",{...ns(R),delivery:"daemon_file",frontendSnapshot:W}),E=an(_),F=Dc(E),Y=await _c(F);Y==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),nt.showToast(Pc(E,{locatorCopyStatus:Y}),Y==="failed"?"warning":"success")},[d,m]),O=N||T,U=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 ${$}`,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(xn,{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(hn,{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(qs,{icon:s.jsx(ji,{}),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(qs,{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(Ll,{})})}):s.jsx(vs,{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(vs,{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:O})},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(vs,{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:O})},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(vs,{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:O})},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(vs,{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:O})},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(qs,{icon:s.jsx(ji,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):I?s.jsx(qs,{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(Ut,{size:20})}),title:"No conversations yet",subtitle:Yc,children:C&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:C,"aria-label":$t,title:$t,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:$t})]})}):s.jsx(qs,{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(vs,{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"&&C&&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:C,"aria-label":$t,title:$t,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(Ox,{conversation:S,onCancel:()=>v(null),onConfirm:U}),s.jsx(Pl,{section:e,onSectionChange:g})]})}function Hx(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 _l(e){const t=[e.workspace||"Workspace unknown"],r=ps(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Hx(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Cn({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=wx(r),C=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(Fa,{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"||!C||a||(y.preventDefault(),d(C))},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:()=>{!C||a||d(C)},disabled:!C||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(fs,{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(C||r),disabled:!C&&!r||a,children:c})]})]})})}function wo({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:C,onModelChange:y,historyProviderNode:p,onConfirm:g,onCancel:b}){const h=n==null?void 0:n.find(N=>N.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:N=>i(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:n.map(N=>s.jsx("option",{value:N.key,children:N.label},N.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(N=>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:N.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:N.value})]},`${N.label}:${N.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:C||"",onChange:N=>y(N.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),m&&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:N=>f(N.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),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(Va,{size:14}),d?l:c]})]})]})})}function ki(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function us(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?"⭐ ":""}${ki(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:ki(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 Ux(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function zx(e){return[Ux(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Vx(e){return e.lastLaunchedAt?bn(e.lastLaunchedAt):""}function Dl(e){return{metaText:zx(e),updatedLabel:Vx(e)}}function Jn(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Gx({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var st,mt,ht,xt;const c=pr(),[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,C]=o.useState(f||((mt=u[0])==null?void 0:mt.id)||""),[y,p]=o.useState(""),[g,b]=o.useState(""),[h,N]=o.useState([]),[S,v]=o.useState(!1),[M,I]=o.useState(""),[j,w]=o.useState(!1),[$,P]=o.useState(Jn(m,t.length,r.length)),T=o.useRef(null),[O,U]=o.useState(null),R=o.useRef("__home__"),[k,A]=o.useState("__home__"),[W,_]=o.useState(""),[E,F]=o.useState(""),[Y,be]=o.useState(""),[ce,ee]=o.useState([]),[ye,we]=o.useState(()=>wt().textQuery),[je,Q]=o.useState(()=>wt().workspaceQuery),[ie,he]=o.useState(()=>wt().modelQuery),[se,de]=o.useState(()=>wt().resumableOnly),[ke,fe]=o.useState(()=>wt().sortMode),[xe,Z]=o.useState(!1),[me,oe]=o.useState(!1),le=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 X=x==="__custom__"?y.trim():((ht=u.find(Ce=>Ce.id===x))==null?void 0:ht.path)||"",ue=x==="__custom__"&&!!X&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),q=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),N(ze.directories)}catch(ze){I(ze instanceof Error?ze.message:"Could not load folder")}finally{v(!1)}},[a]),$e=o.useCallback(()=>{var ze;C("__custom__"),w(!0);const Ce=kn(e.platform,jn(y.trim(),q,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,q,e.platform,u]),Ue=o.useCallback(Ce=>{if(Ce!=null&&Ce.workspaceId){C(Ce.workspaceId),p("");return}if(Ce!=null&&Ce.workspacePath){C("__custom__"),p(Ce.workspacePath);return}C(""),p("")},[]),B=o.useCallback(Ce=>{if(C(Ce),Ce==="__custom__"){$e();return}p("")},[$e]),Se=o.useCallback(Ce=>{C("__custom__"),p(Ce)},[]),Me=o.useCallback((Ce,ze)=>{T.current=ze,R.current=Ce.selectedWorkspaceKey||"__home__",A(Ce.selectedWorkspaceKey||"__home__"),_(Ce.initialArgs||""),F(Ce.initialModel||""),be(""),ee([]);const Qe=Ce.providerType?`${e.id}:${Ce.providerType}`:null;if(Np(ae.current,Qe)){const Ge=wt();we(Ge.textQuery),Q(Ge.workspaceQuery),he(Ge.modelQuery),de(Ge.resumableOnly),fe(Ge.sortMode)}ae.current=Qe,U(Ce),Ce.providerType&&i&&(Z(!0),i(Ce.providerType).then(Ge=>ee(Ge||[])).catch(Ge=>console.warn("Failed to load saved sessions",Ge)).finally(()=>Z(!1)))},[i,e.id]),De=o.useMemo(()=>Xc(ce,{textQuery:ye,workspaceQuery:je,modelQuery:ie,resumableOnly:se,sortMode:ke}),[ie,se,ce,ke,ye,je]);o.useEffect(()=>{Y&&(De.some(Ce=>Ce.providerSessionId===Y)||be(""))},[De,Y]);const Ke=o.useCallback(()=>{T.current&&(oe(!0),T.current().finally(()=>{T.current=null,oe(!1),U(null)}))},[]),He=o.useCallback(()=>{T.current=null,U(null)},[]),Xe=o.useCallback(Ce=>{R.current=Ce,A(Ce)},[]);return o.useEffect(()=>{var Ce;le.current!==e.id&&(le.current=e.id,C(f||((Ce=u[0])==null?void 0:Ce.id)||"__custom__"),p(""),b(""),N([]),I(""),w(!1),we(wt().textQuery),Q(wt().workspaceQuery),he(wt().modelQuery),de(wt().resumableOnly),fe(wt().sortMode),ae.current=null,P(Jn(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)||C(f||((Ce=u[0])==null?void 0:Ce.id)||"__custom__"))},[f,x,u]),o.useEffect(()=>{$==="ide"&&m||$==="cli"&&t.length>0||$==="acp"&&r.length>0||P(Jn(m,t.length,r.length))},[$,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:$,launchConfirm:O,launchConfirmWorkspaceKeyRef:R,launchConfirmWorkspaceKey:k,launchConfirmArgs:W,launchConfirmModel:E,launchConfirmResumeId:Y,launchConfirmSavedSessions:ce,launchConfirmTextFilter:ye,launchConfirmWorkspaceFilter:je,launchConfirmModelFilter:ie,launchConfirmResumableOnly:se,launchConfirmSortMode:ke,filteredLaunchConfirmSavedSessions:De,launchConfirmSessionsLoading:xe,launchConfirmBusy:me,resolvedWorkspacePath:X,canCreateMissingWorkspace:ue,openBrowseDialog:$e,loadBrowsePath:Te,handleWorkspaceChoiceChange:B,chooseCustomWorkspacePath:Se,setCustomWorkspacePath:p,setBrowseDialogOpen:w,setActiveLauncherKind:P,openLaunchConfirm:Me,handleConfirmLaunch:Ke,closeLaunchConfirm:He,setWorkspaceSelectionFromOption:Ue,setLaunchConfirmWorkspaceKeyAndSync:Xe,setLaunchConfirmArgs:_,setLaunchConfirmModel:F,setLaunchConfirmResumeId:be,setLaunchConfirmTextFilter:we,setLaunchConfirmWorkspaceFilter:Q,setLaunchConfirmModelFilter:he,setLaunchConfirmResumableOnly:de,setLaunchConfirmSortMode:fe}}function qx({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:C,onOpenRecent:y,onOpenMachineDetails:p,onMachineUpgrade:g,onLaunchDetectedIde:b,onAddWorkspace:h,onBrowseDirectory:N,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=Gx({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:N,onListSavedSessions:v}),$=o.useMemo(()=>I.map(k=>{const{metaText:A,updatedLabel:W}=Dl(k);return{key:`recent-launch:${k.id}`,primary:k.label,secondary:A,updatedLabel:W,onClick:()=>{const{options:_,selectedKey:E}=us({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspacePath:k.workspace});w.openLaunchConfirm({title:k.kind==="ide"?os("restart-ide",k.label):k.providerSessionId?co(k.label):os("start-fresh",k.label),description:k.kind==="ide"?is("restart-ide"):k.providerSessionId?lo():is("start-fresh"),confirmLabel:k.kind==="ide"?Ds("restart-ide"):k.providerSessionId?cn(!0):Ds("start-fresh"),busyLabel:k.kind==="ide"?Es("restart-ide"):k.providerSessionId?oo(!0):Es("start-fresh"),workspaceOptions:_,selectedWorkspaceKey:E,details:[{label:"Mode",value:M(k.kind)},...k.providerType?[{label:"Provider",value:k.providerType}]:[]]},async()=>{const F=_.find(Y=>Y.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(F),await y({...k,workspace:(F==null?void 0:F.workspacePath)??null})})}}}),[w,y,I]),P=o.useMemo(()=>j.map(k=>({key:`recent-chat:${k.conversation.tabKey}`,primary:lt(k.conversation),secondary:dp(k.conversation,{timestampLabel:k.timestamp?xc(k.timestamp):null}),unread:k.unread,onClick:()=>C(k.conversation)})),[C,j]),T=w.showAllRecent?$:$.slice(0,4),O=$.length>0,U=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(Fa,{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:[U&&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))})]}),O&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:T.map(k=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:k.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:k.primary}),k.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:k.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:k.secondary})]},k.key))}),$.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>w.setShowAllRecent(k=>!k),children:w.showAllRecent?"Show fewer":`Show ${$.length-4} more`})})]}),(w.hasIdeOptions||n.length>0||a.length>0)&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:s.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),s.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),s.jsx("select",{value:w.workspaceChoice,onChange:k=>w.handleWorkspaceChoiceChange(k.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:w.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[w.workspaceRows.map(k=>s.jsxs("option",{value:k.id,children:[k.id===w.defaultWorkspaceId?"⭐ ":"",yn(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(fs,{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:W}=us({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:W,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:W,selectedKey:_}=us({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:W,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=W.find(F=>F.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(Cn,{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(wo,{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?cn(!!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:io()}),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:Mp()}),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(W=>W.providerSessionId===w.launchConfirmResumeId);if(!k)return null;const A=_l(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(Pl,{section:m,onSectionChange:x})]})}function Gr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Yx(e,t=[]){const r=new Map(e.map(a=>[a.conversation.tabKey,a])),n=t.map(a=>r.get(a)).filter(a=>!!a);return n.length===e.length?n:Gr(e)}function Xx(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 Jx(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:ps(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=lr(n)?"cli":Cs(n)?"acp":"ide",i=ps(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(lr(n)?n.cliName||n.type:Cs(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Cs(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 Qx(e,t){const r=new Map;for(const n of t){const a=gs(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=ja(n),d=a.filter(f=>f.unread||f.requiresAction).length,m=Xx(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?up(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 Zx(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 eb({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:C,setSelectedTabKey:y,setScreen:p,setSelectedMachineId:g,setSection:b,setMachineBackTarget:h,resetMachineAction:N}){const S=o.useRef(null),v=o.useCallback(M=>{if(!(M!=null&&M.sessionId))return;const I=tn(M,c),j=Math.max(Date.now(),ds(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:ds(M),readAt:j}),l(gs(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){Zx(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),N(),b("machines"),h("inbox"),p("machine"),f==null||f())},[t,f,u,N,h,p,b,g]),o.useEffect(()=>{x&&(b(x),p("inbox"),C==null||C())},[C,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=tn(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:ds(I.conversation)}})})},[r,c,i,a]),{markConversationRead:v}}function tb(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Si(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function sb(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function rb({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,N,S)=>{var v;try{i("loading"),l(`Launching ${N}…`);const M={ideType:N,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(`${N} 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,N,S)=>{if(N.trim())try{i("loading"),l(S!=null&&S.createIfMissing?"Creating folder…":"Saving workspace…");const v=await e(h,"workspace_add",{path:N.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]),C=o.useCallback(async h=>{var N,S,v,M,I,j;try{i("loading"),l("Starting daemon upgrade…");const w=await e(h,"daemon_upgrade",{});if((N=w==null?void 0:w.result)!=null&&N.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,N,S,v)=>{var j,w,$;const M=Date.now(),I={machineId:h,kind:N,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)),($=v==null?void 0:v.model)!=null&&$.trim()&&(P.initialModel=v.model.trim());const T=await e(h,"launch_cli",P),O=(T==null?void 0:T.result)||T,U=(O==null?void 0:O.sessionId)||(O==null?void 0:O.id);if(T!=null&&T.success&&U){m(null),i("done"),l(`${S} launched`),t(Jt(U));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)||(O==null?void 0:O.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(P){if(sb(P)){i("loading"),l(`${S} launch requested — waiting for session…`);return}m(null),i("error"),l(P instanceof Error?P.message:`Could not launch ${N.toUpperCase()} workspace`)}},[t,e]),p=o.useCallback(async(h,N)=>{try{const S=await e(h,"list_saved_sessions",{providerType:N,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,N)=>Sn(e,h,N),[e]);o.useEffect(()=>{if(!d)return;const h=Si(d.workspacePath),N=r.find(v=>{var P,T,O,U;if(!v||v.type==="adhdev-daemon"||tb(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=Si(v.workspace||v.runtimeWorkspaceLabel);return R?R===h:!1}return Number(v.lastUpdated||v._lastUpdate||v.timestamp||((U=(O=(T=(P=v.activeChat)==null?void 0:P.messages)==null?void 0:T.at)==null?void 0:O.call(T,-1))==null?void 0:U.timestamp)||0)>=d.startedAt-5e3});if(!N)return;const S=Il({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});S&&(m(null),i("done"),l(`${d.providerType} launched`),t(Jt(S)))},[n,r,t,d]),o.useEffect(()=>{if(!d)return;const h=window.setTimeout(()=>{m(N=>!N||N.startedAt!==d.startedAt?N:(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,N)=>{if(N.kind==="ide"&&N.providerType){await f(h,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await y(h,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[f,y]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:f,handleAddWorkspace:x,handleMachineUpgrade:C,handleLaunchWorkspaceProvider:y,handleListSavedSessions:p,handleBrowseDirectory:g,handleOpenRecent:b}}function nb({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(N=>N.routeId===b.routeId&&N.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),x=o.useCallback(()=>{n(t),c("inbox")},[n,t,c]),C=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=gs(b);h&&C(h,"chat")},[C]),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:C,openConversationMachine:y,backFromMachine:p,changeMachineSection:g}}function xs(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function ab(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function ob({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:C,onOpenHistory:y,onOpenRemote:p,onStopCli:g,wsStatus:b,isConnected:h,onShowAllHiddenConversations:N,onHideConversation:S,onOpenNewSession:v,liveSessionInboxState:M,setCliViewModeOverrides:I}){const[j,w]=o.useState(()=>{var q;return((q=e[0])==null?void 0:q.tabKey)||null}),[$,P]=o.useState(()=>e[0]?"chat":"inbox"),[T,O]=o.useState("chats"),[U,R]=o.useState(null),[k,A]=o.useState("inbox"),W=o.useRef([]),_=Bs(),E="0.9.75",F=o.useMemo(()=>e.find(q=>q.tabKey===j)||e[0]||null,[e,j]),Y=o.useMemo(()=>F?r.find(q=>q.id===F.routeId):void 0,[r,F]),be=o.useMemo(()=>!F||Ze(F)||!tt(F)?null:Ws(F),[F]),ce=o.useMemo(()=>r.filter(q=>q.type==="adhdev-daemon").sort(Xa),[r]),ee=o.useMemo(()=>ce.find(q=>q.id===U)||null,[ce,U]),ye=wn({sendDaemonCommand:a,activeConv:F||void 0,setActionLogs:i,isStandalone:c}),we=rb({sendDaemonCommand:a,navigate:_,ides:r,conversations:e}),je=o.useMemo(()=>e.map(q=>{const Ae=$==="chat"&&(F==null?void 0:F.tabKey)===q.tabKey,Te=gn(q,M,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ae}),$e=ds(q),Ue=zc(q);return{conversation:q,timestamp:$e,preview:Ue,unread:Te.unread,requiresAction:Te.requiresAction,isWorking:Te.isWorking,inboxBucket:Te.inboxBucket}}),[e,M,$,F]),{markConversationRead:Q}=eb({conversations:e,machineEntries:ce,items:je,selectedConversation:F,selectedTabKey:j,screen:$,liveSessionInboxState:M,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:x,onRequestedMobileSectionConsumed:C,setSelectedTabKey:w,setScreen:P,setSelectedMachineId:R,setSection:O,setMachineBackTarget:A,resetMachineAction:we.resetMachineAction}),ie=nb({conversations:e,selectedConversation:F,machineBackTarget:k,markConversationRead:Q,resetMachineAction:we.resetMachineAction,setSelectedTabKey:w,setScreen:P,setSelectedMachineId:R,setSection:O,setMachineBackTarget:A}),he=o.useMemo(()=>Gr(je.filter(q=>q.requiresAction)),[je]),se=o.useMemo(()=>Gr(je.filter(q=>q.unread&&!q.requiresAction)),[je]),de=o.useMemo(()=>Yx(je.filter(q=>!q.unread&&!q.requiresAction&&q.isWorking),W.current),[je]);o.useEffect(()=>{W.current=de.map(q=>q.conversation.tabKey)},[de]);const ke=o.useMemo(()=>Gr(je.filter(q=>!q.unread&&!q.requiresAction&&!q.isWorking)),[je]),fe=o.useMemo(()=>ee?je.filter(q=>gs(q.conversation)===ee.id):[],[je,ee]),xe=o.useMemo(()=>Jx(ee,r),[r,ee]),Z=(ee==null?void 0:ee.version)||null,me=!!ee&&!!Z&&!0&&Z!==E,oe=o.useMemo(()=>(ee==null?void 0:ee.availableProviders)||[],[ee]),le=o.useMemo(()=>oe.filter(q=>xs(q,"cli")).map(q=>({type:q.type,displayName:q.displayName||q.type,icon:q.icon})),[oe]),ae=o.useMemo(()=>oe.filter(q=>xs(q,"acp")).map(q=>({type:q.type,displayName:q.displayName||q.type,icon:q.icon})),[oe]),X=o.useMemo(()=>Qx(ce,je),[je,ce]),ue=o.useCallback(async q=>{ee&&await we.handleOpenRecent(ee.id,q)},[we,ee]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:$==="chat"&&F?s.jsx(Kx,{selectedConversation:F,isAcp:Ze(F),isStandalone:c,selectedIdeEntry:Y,actionLogs:n,userName:l,isSendingChat:ye.isSendingChat,sendFeedbackMessage:ye.sendFeedbackMessage,isFocusingAgent:ye.isFocusingAgent,handleModalButton:ye.handleModalButton,handleRelaunch:ye.handleRelaunch,onBack:ie.backFromConversation,onOpenNativeConversation:ie.openNativeConversation,onOpenMachine:ie.openConversationMachine,onOpenHistory:y,onOpenRemote:p,onStopCli:g,cliViewMode:be,onSetCliViewMode:async q=>{await bl({conversation:F,mode:q,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:I})},handleSendChat:ye.handleSendChat,handleFocusAgent:ye.handleFocusAgent}):$==="machine"&&ee?s.jsx(qx,{selectedMachineEntry:ee,selectedMachineConversations:fe,selectedMachineRecentLaunches:xe,cliProviders:le,acpProviders:ae,selectedMachineNeedsUpgrade:me,appVersion:E,machineAction:we.machineAction,isStandalone:c,section:T,showBottomNav:k==="inbox",onBack:ie.backFromMachine,onSectionChange:ie.changeMachineSection,onOpenConversation:ie.openConversation,onOpenRecent:ue,onOpenMachineDetails:()=>_(`/machines/${ee.id}`),onMachineUpgrade:()=>we.handleMachineUpgrade(ee.id),onLaunchDetectedIde:(q,Ae)=>we.handleLaunchDetectedIde(ee.id,q,Ae),onAddWorkspace:(q,Ae)=>we.handleAddWorkspace(ee.id,q,Ae),onBrowseDirectory:q=>we.handleBrowseDirectory(ee.id,q),onLaunchWorkspaceProvider:(q,Ae,Te)=>we.handleLaunchWorkspaceProvider(ee.id,q,Ae,Te),onListSavedSessions:q=>we.handleListSavedSessions(ee.id,q)}):s.jsx(Fx,{section:T,attentionItems:he,unreadItems:se,workingItems:de,completedItems:ke,hiddenConversations:t,machineCards:X,getAvatarText:ab,actionLogs:n,sendDaemonCommand:a,onOpenConversation:ie.openConversation,onShowAllHidden:N,onHideConversation:S,onOpenNewSession:v,onOpenMachine:ie.openMachine,onOpenSettings:()=>_("/settings"),onSectionChange:O,wsStatus:b,isConnected:h,isStandalone:c})})}function Qn(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function ib({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))},[]),C=o.useCallback(g=>{if(!g.dataTransfer.types.includes("text/tab-key"))return;if(g.preventDefault(),!Qn(t,r)){u("merge");return}const b=g.currentTarget.getBoundingClientRect(),h=g.clientX-b.left,N=b.width/3;h<N?u("split-left"):h>N*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,N=m;if(u(null),i(),!!b){if(g.preventDefault(),N==="split-left"&&Qn(t,r)){r==null||r(b,"split-left");return}if(N==="split-right"&&Qn(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:C,handleDragLeave:y,handleDrop:p}}function cb(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 lb({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),C=o.useRef(n),y=o.useRef(a);o.useEffect(()=>{C.current=n},[n]),o.useEffect(()=>{y.current=a},[a]),o.useEffect(()=>{t&&t!==i&&c(t)},[t,i]),o.useEffect(()=>{d(I=>{const j=cb(I,e);return j.length===I.length&&j.every((w,$)=>w===I[$])?I:j})},[e]);const p=o.useMemo(()=>{const I=m??l;if(I.length===0)return e;const j=new Map(I.map((w,$)=>[w,$]));return[...e].sort((w,$)=>{const P=j.get(w.tabKey)??999,T=j.get($.tabKey)??999;return P-T})},[e,m,l]);o.useEffect(()=>{var j,w;if(p.length===0){i!==null&&(c(null),(j=C.current)==null||j.call(C,null));return}if(i&&p.some($=>$.tabKey===i))return;const I=p[0].tabKey;I!==i&&(c(I),(w=C.current)==null||w.call(C,I))},[p,i]);const g=o.useMemo(()=>p.find(I=>I.tabKey===i),[p,i]),b=o.useCallback(I=>{var j;c(I),(j=C.current)==null||j.call(C,I)},[]),h=o.useCallback((I,j,w)=>{d($=>{var U;const P=$.filter(R=>R!==I),T=P.indexOf(j);if(T<0)return $;const O=w==="left"?T:T+1;return P.splice(O,0,I),(U=y.current)==null||U.call(y,P),P}),u(null)},[]),N=o.useCallback((I,j,w)=>{const P=(l.length>0?l:e.map(U=>U.tabKey)).filter(U=>U!==I),T=P.indexOf(j);if(T<0)return;const O=w==="left"?T:T+1;P.splice(O,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 $;const w=j.filter(P=>P!==I);return w.push(I),($=y.current)==null||$.call(y,w),w})},[]);return{activeTabId:i,activeConv:g,sortedConversations:p,previewOrderRef:f,draggingTabRef:x,selectTab:b,handleTabReorder:h,updatePreviewOrder:N,commitPreviewOrder:S,clearPreviewOrder:v,moveTabToEnd:M,setDraggingTabKey:I=>{x.current=I}}}function db({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 jo({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?Yc: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:$t,"aria-label":$t,children:[s.jsx(lc,{size:14}),s.jsx("span",{children:$t})]})}),c&&s.jsx(Ll,{}),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 El="adhdev-tab-shortcuts";function $l(){try{return JSON.parse(localStorage.getItem(El)||"{}")}catch{return{}}}function Bl({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>$l()),[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(El,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 C=m(x);if(!C)return;const y={...i};for(const[p,g]of Object.entries(y))g===C&&delete y[p];y[l]=C,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[C,y]of Object.entries(i))if(t.includes(C)&&m(x)===y){x.preventDefault(),r(),n(C);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 Zn=e=>{e.preventDefault()},ub=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:C,onClearPreviewOrder:y,onDragStateReset:p,onDragTabKeyChange:g,onReceiveTab:b,onOpenContextMenu:h,longPressTimer:N,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),C(),y(),p()},[l,g,C,y,p]),$=o.useCallback(A=>{const W=l.current;if(!(!W||W===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(W,t.tabKey,E)}},[t.tabKey,l,f]),P=o.useCallback(A=>{A.preventDefault(),A.stopPropagation();const W=A.dataTransfer.getData("text/tab-key");if(W&&W!==t.tabKey){const _=A.currentTarget.getBoundingClientRect(),E=A.clientX<_.left+_.width/2?"left":"right";c.includes(W)?x(W,t.tabKey,E):b&&b(W)}y()},[t.tabKey,c,x,b,y]),T=o.useCallback(A=>{A.stopPropagation(),d(),m(t.tabKey),u(t)},[t,u,d,m]),O=o.useCallback(A=>{A.preventDefault(),h(A.clientX,A.clientY,t.tabKey)},[t.tabKey,h]),U=o.useCallback(A=>{const W=A.touches[0];N.current=setTimeout(()=>{h(W.clientX,W.clientY,t.tabKey)},600)},[t.tabKey,N,h]),R=o.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),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:$,onDrop:P,onClick:T,onContextMenu:O,onTouchStart:U,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:as(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[as(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:as(t)}),s.jsx(_s,{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 mb({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:C,onReceiveTab:y,onHideTab:p,isGroupActive:g,allowTabShortcuts:b=!0}){const[h,N]=o.useState(null),S=o.useRef(null),v=o.useRef(null),M=o.useMemo(()=>e.map(O=>O.tabKey),[e]);mr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:I,tabShortcuts:j,shortcutListening:w,setShortcutListening:$,saveShortcuts:P}=Bl({enabled:b,sortedTabKeys:e.map(O=>O.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const O=U=>{const R=document.querySelector("[data-pane-context-menu]");R&&R.contains(U.target)||N(null)};return window.addEventListener("mousedown",O,!0),()=>window.removeEventListener("mousedown",O,!0)},[h]),o.useEffect(()=>{const O=v.current;if(!O)return;const U=R=>{Math.abs(R.deltaY)<=Math.abs(R.deltaX)||(R.preventDefault(),O.scrollLeft+=R.deltaY)};return O.addEventListener("wheel",U,{passive:!1}),()=>O.removeEventListener("wheel",U)},[]);const T=o.useCallback((O,U,R)=>{N({x:O,y:U,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(O=>s.jsx(ub,{conv:O,isActive:t===O.tabKey,isDraggedTab:a.current===O.tabKey,isTaskCompleteUnread:n.has(O.tabKey),shortcut:b?j[O.tabKey]:void 0,conversationKeys:M,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:x,onDragTabKeyChange:C,onReceiveTab:y,onOpenContextMenu:T,longPressTimer:S,isGroupActive:g},O.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:Zn,onClick:O=>{O.stopPropagation(),$(h.tabKey),N(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:Zn,onClick:()=>{const O={...j};delete O[h.tabKey],P(O),N(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:Zn,onClick:()=>{p(h.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),b&&w&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>$(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:O=>O.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 fb({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:C,onReceiveTab:y,style:p,onActiveTabChange:g,initialActiveTabId:b,initialTabOrder:h,onTabOrderChange:N,onHideTab:S,isFocused:v,allowTabShortcuts:M=!0,onOpenNewSession:I,liveSessionInboxState:j}){const{sendCommand:w}=gt(),$=o.useRef(null),{activeTabId:P,activeConv:T,sortedConversations:O,draggingTabRef:U,selectTab:R,handleTabReorder:k,updatePreviewOrder:A,commitPreviewOrder:W,clearPreviewOrder:_,moveTabToEnd:E,setDraggingTabKey:F}=lb({conversations:e,initialActiveTabId:b,initialTabOrder:h,onActiveTabChange:g,onTabOrderChange:N}),Y=wn({sendDaemonCommand:a,activeConv:T,setActionLogs:i,isStandalone:c}),{dragOver:be,dropAction:ce,resetDragState:ee,handleDragEnter:ye,handleDragOver:we,handleDragLeave:je,handleDrop:Q}=ib({conversations:e,numGroups:x,onMoveTab:C,onReceiveTab:y,onOwnTabDrop:E,onClearPreviewOrder:_}),ie=T&&!Ze(T)&&Ws(T)==="terminal",he=o.useMemo(()=>T?t.find(fe=>fe.id===T.routeId):void 0,[t,T]),se=o.useMemo(()=>T?n.filter(fe=>fe.routeId===T.tabKey):[],[n,T]),de=o.useMemo(()=>new Set(O.filter(fe=>nm(fe,j,{isOpenConversation:fe.tabKey===P})).map(fe=>fe.tabKey)),[P,j,O]);mr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:P,dragOver:be});const ke=o.useCallback(fe=>{fe.streamSource==="agent-stream"&&fe.agentType&&w(fe.routeId,Rc(),{agentType:fe.agentType,...fe.sessionId&&{targetSessionId:fe.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(mb,{conversations:O,activeTabId:P,groupIndex:m,numGroups:x,unreadTabKeys:de,draggingTabRef:U,onFocus:u,onSelectTab:R,onConversationActivated:ke,onPreviewReorder:A,onReorderTab:k,onCommitPreviewOrder:W,onClearPreviewOrder:_,onDragStateReset:ee,onDragTabKeyChange:F,onMoveTab:C,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:ye,onDragOver:we,onDragLeave:je,onDrop:Q,children:[be&&s.jsx(db,{dropAction:ce,canSplit:!!(x<4&&C)}),T?s.jsx(vo,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!ie,ideEntry:he,terminalRef:$,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(jo,{conversationsCount:e.length,isSplitMode:f,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:I})})]})]})}function pb({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:C,focusGroup:y,moveTabToGroup:p,splitTabRelative:g,closeGroup:b,handleResizeStart:h,groupActiveTabIds:N,setGroupActiveTab:S,groupTabOrders:v,setGroupTabOrder:M,toggleHiddenTab:I,onOpenNewSession:j,allowTabShortcuts:w=!0,liveSessionInboxState:$}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((P,T)=>{const O=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:U=>h(T-1,U),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(fb,{style:t?{flexBasis:O??`${100/r}%`,flexGrow:O?0:1,flexShrink:O?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&&C===T,onFocus:()=>y(T),isSplitMode:t,numGroups:r,onMoveTab:(U,R)=>{R==="left"&&T>0?p(U,T-1):R==="right"&&T<r-1?p(U,T+1):R==="split-left"&&r<4?g(U,T,"left"):R==="split-right"&&r<4&&g(U,T,"right")},onReceiveTab:U=>p(U,T),onActiveTabChange:U=>S(T,U),initialActiveTabId:N[T],initialTabOrder:v[T],onTabOrderChange:U=>M(T,U),onHideTab:I,onOpenNewSession:j,allowTabShortcuts:w,liveSessionInboxState:$})]},T)})})}function Kl({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 Wl="adhdev-dashboard-action-shortcuts",hb=1200,xb=[["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 bb(){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 Ol(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 _a(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function fn(e){const t=Object.fromEntries(Ol(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Wl)||"{}"),n={...t,...r};for(const[a,i]of xb)n[a]===i&&(n[a]=t[a]);return n}catch{return t}}function Fl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function gb({enabled:e=!0,onTrigger:t}){const r=bb(),[n,a]=o.useState(()=>fn(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(Fl(p.key)),g.join("+"))},[r]),f=o.useCallback(p=>{a(p);try{localStorage.setItem(Wl,JSON.stringify(p))}catch{}},[]);o.useEffect(()=>{const p=fn(r),g=Object.entries(n),b=Object.entries(p);g.length===b.length&&g.every(([h,N])=>p[h]===N)||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}},[]),C=o.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},hb))},[]);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 N=!(g.metaKey||g.ctrlKey||g.altKey)&&/^[A-Z0-9]$/.test(b);if(l.length===0&&N){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(_a(g.target))return;const N=m.current.parts,S=h?[b]:[...N.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,C();return}const $=I.find(([,T])=>T===M);if($){g.preventDefault(),x(),t($[0]);return}if(I.some(([,T])=>T.startsWith(`${M} `))){g.preventDefault(),m.current.parts=[M],C();return}x()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,C,e,u,t,x,i]),o.useEffect(()=>()=>x(),[x]);const y=o.useMemo(()=>Ol(r),[r]);return{isMac:r,actionDefinitions:y,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:d,saveShortcuts:f}}function yb({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 Hl(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Ni({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!Hl(n):!0}function vb({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:Hl(r)}const Ul=1e3,wb=4;function Ci(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Ti(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function jb({detachDelayMs:e=Ul,stillnessThresholdPx:t=wb,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},C=()=>{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)&&Ci(d,c)&&(Ti(l,d,t)||(u=!0,r({panelId:i,clientX:d.clientX,clientY:d.clientY})))},e))},p=b=>{if(!(!i||u)){if(!Ci(b,c)){d={clientX:b.clientX,clientY:b.clientY},x();return}(!l||Ti(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:C,isDragging:()=>i!=null,hasDetached:()=>u,dispose:C}}function kb(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Br(e){return e.isActive}function Mi(e){return e.isVisible}const zl=o.createContext(null);function Tn(){const e=o.useContext(zl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function qr(e){return lt(e)||e.tabKey}function Sb(e){return`remote:${e}`}function Lt(e){return e.startsWith("remote:")}function Ii(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Nb(e){e.preventDefault()}function ea(e){var n;const t=e==null?void 0:e.defaultView;if(!t)return;const r=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),r(e==null?void 0:e.body),r(e==null?void 0:e.documentElement),(n=t.requestAnimationFrame)==null||n.call(t,()=>{try{t.focus(),r(e==null?void 0:e.body)}catch{}})}catch{}}function ta(e,t){e.classList.remove(ha.className,xa.className),e.classList.add(t==="light"?ha.className:xa.className)}function Ai(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 Cb(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 Tb(e,t,r){var c;const n=[t];let a;for(const l of n){let d;for(const m of l){const u=e.addPanel({id:m.tabKey,component:"conversation",title:qr(m),params:{kind:"conversation",tabKey:m.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=u.id)}a=d??a}return r??((c=t[0])==null?void 0:c.tabKey)??null}function Ri(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])Lt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of t){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==qr(n)&&a.api.setTitle(qr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:qr(n),params:{kind:"conversation",tabKey:n.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function Li(e,t,r){var d,m;const n=r?Sb(r):null;for(const u of[...e.panels])Lt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Dt(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=>!Lt(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 Mb({params:e,api:t}){var C;const r=Tn(),n=o.useRef(null),[a,i]=o.useState(()=>Br(t)),[c,l]=o.useState(()=>Mi(t)),d=r.conversationsByTabKey.get(e.tabKey),m=wn({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(Br(t)),l(Mi(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(jo,{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(vo,{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:((C=r.scrollToBottomRequest)==null?void 0:C.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:c})})}function Ib({params:e}){var d;const t=Tn(),r=o.useMemo(()=>Dt([...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}=Kl({doId:a,targetSessionId:r?Ac(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(hc,{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 Ab(){const e=Tn();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(jo,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Rb(e){var C,y;Cb(e);const t=Tn(),r=o.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=Dt([...t.conversationsByTabKey.values()],e.params.routeId),g=((C=e.api.group.activePanel)==null?void 0:C.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=gn(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:as(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:as(n)}):s.jsx("span",{children:as(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 Lb({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:C,onOpenNewSession:y,onRequestScrollToBottom:p,requestedActiveTabKey:g,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:h,scrollToBottomRequest:N,liveSessionInboxState:S,layoutProfile:v}){var Qe,Ge,rt;const{theme:M}=fo(),{sendCommand:I}=gt(),j=o.useRef(null),w=o.useRef(null),$=o.useRef(null),P=o.useRef(!1),T=o.useRef(!1),O=o.useRef(!1),U=o.useRef(null),R=o.useRef([]),[k,A]=o.useState(null),[W,_]=o.useState(0),E=o.useRef(typeof window>"u"?{}:Xh(v)),F=o.useMemo(()=>new Map(e.map(K=>[K.tabKey,K])),[e]),Y=o.useMemo(()=>{const K=j.current;return K?K.groups.some(H=>{try{const V=H.model.location.type;return V!=="floating"&&V!=="popout"?!1:H.panels.some(te=>F.has(te.id))}catch{return!1}}):!1},[F,W,e]),be=o.useCallback(()=>{var K;(K=j.current)==null||K.focus()},[]),ce=o.useCallback((K,H)=>{p==null||p(K,H)},[p]),ee=o.useCallback(K=>{const H=document,V=K.document;for(const re of H.querySelectorAll('link[rel="stylesheet"]')){const ve=V.createElement("link");ve.rel="stylesheet",ve.href=re.href,re.crossOrigin&&(ve.crossOrigin=re.crossOrigin),V.head.appendChild(ve)}for(const re of H.querySelectorAll("style")){const ve=V.createElement("style");ve.textContent=re.textContent,V.head.appendChild(ve)}const te=[];for(const re of H.styleSheets)try{for(const ve of re.cssRules)ve instanceof CSSStyleRule&&(ve.selectorText===":root"||ve.selectorText==="html")&&te.push(ve.cssText)}catch{}if(te.length>0){const re=V.createElement("style");re.textContent=te.join(`
|
|
52
|
+
`),V.head.appendChild(re)}const D=H.documentElement.getAttribute("data-theme");D&&V.documentElement.setAttribute("data-theme",D),V.documentElement.style.colorScheme=D==="light"?"light":"dark",V.body.className=H.body.className;const G=H.documentElement.getAttribute("style");G&&V.documentElement.setAttribute("style",G);const J=V.getElementById("dv-popout-window");J instanceof HTMLElement&&(J.classList.add("adhdev-dockview"),ta(J,M))},[M]),ye=o.useCallback(()=>{var H;const K=j.current;if(K)for(const V of K.groups)try{const te=(H=V.element)==null?void 0:H.ownerDocument;if(!te||te===document)continue;const D=te.getElementById("dv-popout-window");D instanceof HTMLElement&&(D.classList.add("adhdev-dockview"),ta(D,M));const G=document.documentElement.getAttribute("data-theme");G&&te.documentElement.setAttribute("data-theme",G),te.documentElement.style.colorScheme=G==="light"?"light":"dark",te.body.className=document.body.className;const J=document.documentElement.getAttribute("style");J?te.documentElement.setAttribute("style",J):te.documentElement.removeAttribute("style")}catch{}},[M]),we=o.useCallback(K=>{const H=j.current;if(!H)return;const V=H.getPanel(K);V&&H.addPopoutGroup(V,{popoutUrl:"/popout.html",onDidOpen:({window:te})=>{ee(te),xe();const D=F.get(K);te.document.title=D?`${lt(D)} — ADHDev`:"ADHDev — Popout"}})},[F,ee]),je=o.useCallback(K=>{const H=j.current,V=H==null?void 0:H.getPanel(K);if(!H||!V)return;const te=H.groups.filter(D=>{var G;try{return((G=D.element)==null?void 0:G.ownerDocument)===document}catch{return!0}});te.length>0?V.api.moveTo({group:te[0],position:"center"}):V.api.moveTo({position:"center"}),V.api.setActive()},[]),Q=o.useCallback(K=>{var te;const H=j.current;if(!H)return!1;const V=H.getPanel(K);if(!V)return!1;try{return((te=V.group.element)==null?void 0:te.ownerDocument)!==document}catch{return!1}},[]),ie=o.useCallback(K=>{Q(K)&&je(K),u(K)},[Q,je,u]),he=o.useCallback(K=>{const H=j.current,V=H==null?void 0:H.getPanel(K);!H||!V||H.addFloatingGroup(V,{width:600,height:500})},[]),se=o.useCallback(K=>{var V;const H=(V=j.current)==null?void 0:V.getPanel(K);if(!H)return!1;try{return H.group.model.location.type==="floating"}catch{return!1}},[]),de=o.useCallback(()=>{var H,V;const K=(V=(H=j.current)==null?void 0:H.activePanel)==null?void 0:V.id;return!K||Lt(K)?null:F.has(K)?K:null},[F]),ke=o.useCallback(K=>{const H=j.current,V=H==null?void 0:H.getPanel(K);if(!H||!V)return;const te=H.groups.filter(D=>{try{return D.model.location.type==="grid"}catch{return!0}});te.length>0?V.api.moveTo({group:te[0],position:"center"}):V.api.moveTo({position:"center"}),V.api.setActive()},[]),fe=o.useCallback(()=>{var G;const K=j.current;if(!K)return;const V=K.groups.filter(J=>{var re;try{return((re=J.element)==null?void 0:re.ownerDocument)===document&&J.model.location.type==="grid"}catch{return!1}})[0]||null,te=[...K.panels];for(const J of te){const re=(G=J.group.element)==null?void 0:G.ownerDocument,ve=J.group.model.location.type;re===document&&ve==="grid"||(V&&V.id!==J.group.id?J.api.moveTo({group:V,position:"center"}):J.api.moveTo({position:"center"}))}const D=K.activePanel;D&&(D.group.model.openPanel(D),D.api.setActive()),ea(document)},[]),xe=o.useCallback(()=>{var H,V;const K=j.current;if(K)for(const te of K.groups){const D=(H=te.element)==null?void 0:H.ownerDocument;if(!D||D===document)continue;const G=D.getElementById("dv-popout-window");if(!(G instanceof HTMLElement))continue;let J=null,re=D.title||"ADHDev",ve="Popout workspace";const Le=te.activePanel;if(Le)if(J=Le.id,Lt(Le.id)){const Re=((V=Le.params)==null?void 0:V.routeId)||Le.id.slice(7),qe=Dt([...F.values()],Re);re=qc(qe),ve=qe!=null&&qe.machineName?`Remote view · ${qe.machineName}`:"Remote view"}else{const Re=F.get(Le.id);re=Re?lt(Re):Le.title||Le.id,ve=Re?as(Re):"Dockview panel"}D.title=`${re} — ADHDev`;const _e=Array.from(D.querySelectorAll("#adhdev-popout-header"));for(const Re of _e)Re.remove();const Ne=D.createElement("div");Ne.id="adhdev-popout-header",D.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;">${Ii(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;">${Ii(ve)}</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
|
+
`,G.style.top="52px",G.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=!J,Be.style.opacity=J?"1":"0.5",Be.style.cursor=J?"pointer":"default",Be.onclick=()=>{var Re;J&&je(J),(Re=D.defaultView)==null||Re.focus()})}},[F,je]),Z=o.useCallback(K=>{var te;const H=j.current,V=H==null?void 0:H.getPanel(K);if(!(!H||!V)){V.group.model.openPanel(V),V.api.setActive(),ce(K,"dockview-shortcut");try{const D=V.group.model.location;D.type==="popout"?D.getWindow().focus():ea((te=V.group.element)==null?void 0:te.ownerDocument)}catch{}}},[ce]),me=o.useCallback(K=>{const H=j.current,V=H==null?void 0:H.activePanel,te=(H==null?void 0:H.activeGroup)||(V==null?void 0:V.group);if(!H||!V||!te)return;const D=te.panels||[];if(D.length<=1)return;const G=D.findIndex(ve=>ve.id===V.id);if(G<0)return;const J=(G+K+D.length)%D.length,re=D[J];re&&(re.group.model.openPanel(re),re.api.setActive(),Lt(re.id)||ce(re.id,"dockview-shortcut"))},[ce]),oe=o.useCallback(K=>{var Ee;const H=j.current,V=(H==null?void 0:H.activeGroup)||((Ee=H==null?void 0:H.activePanel)==null?void 0:Ee.group);if(!H||!V)return;const te=H.groups||[],D=te.find(Be=>Be.id===V.id);if(!D)return;const G=D.element.getBoundingClientRect(),J=G.left+G.width/2,re=G.top+G.height/2,ve=(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(K==="left"?(yt=qe<J,ct=Math.max(0,G.left-Re.right),ft=Math.abs(et-re),dt=ve(G.top,G.bottom,Re.top,Re.bottom)):K==="right"?(yt=qe>J,ct=Math.max(0,Re.left-G.right),ft=Math.abs(et-re),dt=ve(G.top,G.bottom,Re.top,Re.bottom)):K==="above"?(yt=et<re,ct=Math.max(0,G.top-Re.bottom),ft=Math.abs(qe-J),dt=ve(G.left,G.right,Re.left,Re.right)):(yt=et>re,ct=Math.max(0,Re.top-G.bottom),ft=Math.abs(qe-J),dt=ve(G.left,G.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===D.id)continue;const Re=Le(Be);Number.isFinite(Re)&&(Re>=Ne||(Ne=Re,_e=Be))}return _e||void 0},[]),le=o.useCallback(K=>{var te;const H=oe(K);if(!H)return;const V=H.activePanel||H.panels[0];V&&(H.model.openPanel(V),V.api.setActive(),Lt(V.id)||ce(V.id,"dockview-focus"),ea((te=H.element)==null?void 0:te.ownerDocument))},[oe,ce]),ae=o.useCallback((K,H)=>{const V=j.current,te=V==null?void 0:V.activePanel,D=(V==null?void 0:V.activeGroup)||(te==null?void 0:te.group);if(!V||!te||!D)return;let G=oe(K);!G&&(H!=null&&H.createGroupIfMissing)&&(G=V.addGroup({referenceGroup:D,direction:K})),G&&(te.api.moveTo({group:G,position:"center"}),te.group.model.openPanel(te),te.api.setActive(),Lt(te.id)||ce(te.id,H!=null&&H.createGroupIfMissing?"dockview-split":"dockview-move"))},[oe,ce]),{isMac:X,tabShortcuts:ue,shortcutListening:q,setShortcutListening:Ae,saveShortcuts:Te}=Bl({sortedTabKeys:e.map(K=>K.tabKey),onFocus:be,onSelectTab:Z}),$e=o.useCallback(()=>{var V;const K=j.current;if(!K)return;const H=K.activePanel;if(H){if(Lt(H.id)){const te=((V=H.params)==null?void 0:V.routeId)||H.id.slice(7),D=Dt(e,te);D!=null&&D.tabKey&&Ae(D.tabKey);return}F.has(H.id)&&Ae(H.id)}},[F,Z,Ae,e]),Ue=o.useCallback(K=>{const H=[];return K.metaKey&&H.push(X?"⌘":"Meta"),K.ctrlKey&&H.push("Ctrl"),K.altKey&&H.push(X?"⌥":"Alt"),K.shiftKey&&K.key.length!==1&&H.push(X?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(K.key)?null:(H.push(Fl(K.key)),H.join("+"))},[X]),B=o.useCallback(K=>{var H,V;switch(K){case"splitActiveTabRight":ae("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":ae("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const te=de();te&&he(te);return}case"popoutActiveTab":{const te=de();te&&we(te);return}case"dockActiveTab":{const te=de();if(!te)return;Q(te)?je(te):se(te)&&ke(te);return}case"focusLeftPane":le("left");return;case"focusRightPane":le("right");return;case"focusUpPane":le("above");return;case"focusDownPane":le("below");return;case"moveActiveTabToLeftPane":ae("left");return;case"moveActiveTabToRightPane":ae("right");return;case"moveActiveTabToUpPane":ae("above");return;case"moveActiveTabToDownPane":ae("below");return;case"selectPreviousGroupTab":me(-1);return;case"selectNextGroupTab":me(1);return;case"setActiveTabShortcut":$e();return;case"hideCurrentTab":{const te=(V=(H=j.current)==null?void 0:H.activePanel)==null?void 0:V.id;te&&!Lt(te)&&ie(te);return}default:return}},[me,ke,le,he,de,ie,se,Q,je,ae,we,$e]);o.useEffect(()=>{if(!k)return;const K=k.sourceDocument,H=K.defaultView??window,V=te=>{const D=K.querySelector("[data-dockview-tab-context-menu]");D&&D.contains(te.target)||A(null)};return H.addEventListener("mousedown",V,!0),H!==window&&window.addEventListener("mousedown",()=>A(null),!0),()=>{H.removeEventListener("mousedown",V,!0),H!==window&&window.removeEventListener("mousedown",()=>A(null),!0)}},[k]);const Se=o.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:F,hasDetachedConversationPanels:Y,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:y,liveSessionInboxState:S,sendDaemonCommand:a,setActionLogs:i,toggleHiddenTab:ie,userName:m,scrollToBottomRequest:N,tabShortcuts:ue,openTabContextMenu:({x:K,y:H,tabKey:V,sourceDocument:te})=>A({x:K,y:H,tabKey:V,sourceDocument:te??document}),popoutTab:we,moveTabBackToMain:je,isTabInPopout:Q,floatTab:he,isTabFloating:se}),[n,t,F,Y,r,c,l,y,S,a,i,ie,m,N,ue,we,je,Q,he,se]),Me=k?yb({isTabInPopout:Q(k.tabKey),isTabFloating:se(k.tabKey),tabShortcut:ue[k.tabKey],actionShortcuts:f}):[],De=o.useCallback(K=>{var te;const H=j.current;if((((te=H==null?void 0:H.activePanel)==null?void 0:te.id)??null)===K.id){K.group.model.openPanel(K);return}K.group.model.openPanel(K),K.api.setActive()},[]),Ke=o.useCallback((K,H="requested-tab")=>{if(!K)return!1;const V=j.current;if(!V)return!1;const te=V.getPanel(K);return te?(De(te),ce(K,H),h==null||h(),!0):!1},[De,h,ce]),He=o.useCallback(()=>{if(O.current)return!1;const K=Ke(U.current,"stored-layout-restore");return K&&(O.current=!0),K},[Ke]),Xe=o.useCallback(()=>{var H;const K=j.current;K&&Yh(v,{activeTabId:((H=K.activePanel)==null?void 0:H.id)??null,layout:K.toJSON()})},[v]),st=o.useCallback(()=>{Jh(v,E.current)},[v]),mt=o.useCallback(K=>{var te,D,G,J;const H=j.current;if(!H)return{kind:"grid"};const V=H.toJSON();for(const re of V.floatingGroups||[])if((D=(te=re.data)==null?void 0:te.views)!=null&&D.includes(K)&&re.position)return{kind:"floating",position:re.position};for(const re of V.popoutGroups||[])if((J=(G=re.data)==null?void 0:G.views)!=null&&J.includes(K))return{kind:"popout",position:re.position,popoutUrl:re.url};return{kind:"grid"}},[]),ht=o.useCallback(K=>{const H=j.current;if(!H)return;const V=H.getPanel(K),te=E.current[K];if(!V||!te||te.kind==="grid")return;if(V.group.model.location.type===te.kind){delete E.current[K],st();return}if(te.kind==="floating"){H.addFloatingGroup(V,{x:te.position.left??24,y:te.position.top??24,width:te.position.width,height:te.position.height}),delete E.current[K],st();return}delete E.current[K],st()},[st]);o.useEffect(()=>(x==null||x({setShortcutForActiveTab:$e,restoreHiddenTabToSavedLocation:ht,activateConversationTab:Z,resetAllPanelsToMain:fe,activatePreviousTabInGroup:()=>me(-1),activateNextTabInGroup:()=>me(1),floatActiveTab:()=>{const K=de();K&&he(K)},popoutActiveTab:()=>{const K=de();K&&we(K)},dockActiveTab:()=>{const K=de();K&&(Q(K)?je(K):se(K)&&ke(K))},splitActiveTabRight:()=>ae("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>ae("below",{createGroupIfMissing:!0}),focusLeftPane:()=>le("left"),focusRightPane:()=>le("right"),focusUpPane:()=>le("above"),focusDownPane:()=>le("below"),moveActiveTabToLeftPane:()=>ae("left"),moveActiveTabToRightPane:()=>ae("right"),moveActiveTabToUpPane:()=>ae("above"),moveActiveTabToDownPane:()=>ae("below")}),()=>x==null?void 0:x(null)),[me,ke,he,le,de,se,Q,ae,je,we,x,fe,ht,Z,$e]),o.useEffect(()=>()=>{var K;(K=$.current)==null||K.call($),$.current=null},[]);const xt=o.useCallback(K=>{var V,te;j.current=K.api,(V=$.current)==null||V.call($),$.current=null;const H=qh(v);if(U.current=(H==null?void 0:H.activeTabId)??null,H!=null&&H.layout&&K.api.fromJSON(H.layout,{reuseExistingPanels:!1}),T.current=Ni({hasStoredLayout:!!(H!=null&&H.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),T.current||(Ri(K.api,e),Li(K.api,e,b)),K.api.totalPanels===0&&e.length>0){const D=Tb(K.api,e,g);if(D){const G=K.api.getPanel(D);G&&De(G)}}else!T.current&&!Ke(g)&&He();if(P.current=!0,K.api.onDidActivePanelChange(D=>{var J;if(U.current=(D==null?void 0:D.id)??null,O.current=!0,xe(),D&&Lt(D.id)){const re=((J=D.params)==null?void 0:J.routeId)||D.id.slice(7),ve=Dt(e,re);C((ve==null?void 0:ve.tabKey)??null),Xe();return}if(C((D==null?void 0:D.id)??null),Xe(),!D)return;const G=F.get(D.id);(G==null?void 0:G.streamSource)==="agent-stream"&&G.agentType&&I(G.routeId,Rc(),{agentType:G.agentType,...G.sessionId&&{targetSessionId:G.sessionId}}).catch(()=>{})}),K.api.onDidLayoutChange(()=>{Xe(),xe(),_(D=>D+1)}),kb()){const D=Ne=>({clientX:Ne.clientX,clientY:Ne.clientY}),G=Ne=>{const Ee=Ne==null?void 0:Ne.getBoundingClientRect();return Ee?{left:Ee.left,right:Ee.right,top:Ee.top,bottom:Ee.bottom}:null},J=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=jb({detachDelayMs:Ul,onDetach:({panelId:Ne,clientX:Ee,clientY:Be})=>{var dt,yt;const Re=K.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));K.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(),Xe(),xe(),_(Ve=>Ve+1)}}),ve=[K.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:G(Ne.panel.group.element),...D(Ne.nativeEvent)})}}),K.api.onWillShowOverlay(Ne=>{if(re.hasDetached()){Ne.preventDefault();return}re.markDockTarget(D(Ne.nativeEvent))}),K.api.onWillDrop(Ne=>{if(re.hasDetached()){Ne.preventDefault(),re.endDrag();return}re.markDockTarget(D(Ne.nativeEvent))}),K.api.onDidDrop(()=>re.endDrag()),K.api.onUnhandledDragOverEvent(Ne=>{re.isDragging()&&re.markSelfPanel(D(Ne.nativeEvent))})],Le=Ne=>{if(!re.isDragging())return;const Ee=D(Ne);J(Ee)&&re.markNonSelfPanel(Ee)},_e=()=>re.endDrag();window.addEventListener("dragover",Le,!0),window.addEventListener("drop",_e,!0),window.addEventListener("dragend",_e,!0),$.current=()=>{re.dispose();for(const Ne of ve)Ne.dispose();window.removeEventListener("dragover",Le,!0),window.removeEventListener("drop",_e,!0),window.removeEventListener("dragend",_e,!0)}}K.api.onDidAddGroup(D=>{requestAnimationFrame(()=>{var G,J;try{const re=(G=D.element)==null?void 0:G.ownerDocument;if(!re||re===document)return;(J=re.getElementById("dv-popout-window"))==null||J.classList.add("adhdev-dockview");const ve=document.documentElement.getAttribute("data-theme");ve&&re.documentElement.setAttribute("data-theme",ve),re.body.className=document.body.className;const Le=document.documentElement.getAttribute("style");Le&&re.documentElement.setAttribute("style",Le)}catch{}xe(),_(re=>re+1)})}),C(((te=K.api.activePanel)==null?void 0:te.id)??null)},[De,Ke,F,r,d,v,C,Xe,g,b,I,xe,e]);o.useLayoutEffect(()=>{const K=j.current;if(!K||!P.current||T.current&&Ni({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;T.current&&(T.current=!1);const H=R.current,V=new Set(H),te=e.map(_e=>_e.tabKey),D=new Set(te),G=vb({previousVisibleConversationCount:H.length,visibleConversationCount:e.length,ides:r});let J=!1;for(const _e of H)D.has(_e)||G||(E.current[_e]=mt(_e),J=!0);J&&st(),G||(Ri(K,e),Li(K,e,b));const re=te.filter(_e=>!V.has(_e));let ve=!1;for(const _e of re){const Ne=K.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],ve=!0;continue}if(Ee.kind==="floating"){K.addFloatingGroup(Ne,{x:Ee.position.left??24,y:Ee.position.top??24,width:Ee.position.width,height:Ee.position.height}),delete E.current[_e],ve=!0;continue}}if(ve&&st(),R.current=te,g&&Ke(g))return;!K.activePanel&&K.panels[0]&&De(K.panels[0]),!!(K.activePanel&&K.getPanel(K.activePanel.id))||He()},[De,Ke,He,r,d,st,mt,g,b,e]),o.useEffect(()=>{P.current&&Ke(g)},[Ke,g]),o.useEffect(()=>{const K=V=>{const te=V.target;if(!te)return;const D=te.querySelector("[data-tab-key]")||te.closest("[data-tab-key]");if(D){const G=D.getAttribute("data-tab-key");if(G&&V.dataTransfer){const J=te.closest(".dv-tab")||D.closest(".dv-tab")||D;V.dataTransfer.effectAllowed="move",V.dataTransfer.setData("text/tab-key",G),J instanceof HTMLElement&&V.dataTransfer.setDragImage(J,Math.max(12,Math.round(J.clientWidth/2)),Math.max(10,Math.round(J.clientHeight/2)))}}};window.addEventListener("dragstart",K);const H=Ai(j.current);for(const V of H)V.addEventListener("dragstart",K);return()=>{window.removeEventListener("dragstart",K);for(const V of H)V.removeEventListener("dragstart",K)}},[W]),o.useEffect(()=>{var H;const K=(H=w.current)==null?void 0:H.querySelector(".adhdev-dockview");K instanceof HTMLElement&&ta(K,M),ye(),xe()},[xe,ye,M]),o.useEffect(()=>{xe()},[xe]),o.useEffect(()=>{const K=H=>{if(H.defaultPrevented||q)return;const V=Ue(H);if(!V)return;const te=H.metaKey||H.ctrlKey||H.altKey;_a(H.target)&&!te||fn(X).setActiveTabShortcut!==V||(H.preventDefault(),H.stopPropagation(),$e())};return window.addEventListener("keydown",K,!0),()=>window.removeEventListener("keydown",K,!0)},[Ue,X,q,$e]),o.useEffect(()=>{const K=w.current;if(!K)return;const H=V=>{var re,ve;if(!V.isTrusted)return;const te=(ve=(re=V.target)==null?void 0:re.closest)==null?void 0:ve.call(re,".dv-scrollable");if(!te)return;V.preventDefault(),V.stopPropagation();const D=Math.abs(V.deltaX),G=Math.abs(V.deltaY),J=D>G?V.deltaX:V.deltaY;te.dispatchEvent(new WheelEvent("wheel",{deltaY:J,deltaMode:V.deltaMode,bubbles:!1,cancelable:!0}))};return K.addEventListener("wheel",H,{passive:!1,capture:!0}),()=>K.removeEventListener("wheel",H,{capture:!0})},[]),o.useEffect(()=>{const K=Ai(j.current);if(K.length===0)return;const H=K.map(V=>{let te=[],D=null;const G=()=>{D!=null&&V.clearTimeout(D),D=null,te=[]},J=()=>{D!=null&&V.clearTimeout(D),D=V.setTimeout(()=>{D=null,te=[]},1200)},re=Le=>{if(!Le.ctrlKey&&!Le.metaKey&&!Le.altKey)return;const _e=Ue(Le);if(!_e)return;const Ne=$l();for(const[Ee,Be]of Object.entries(Ne))if(e.some(Re=>Re.tabKey===Ee)&&Be===_e){Le.preventDefault(),Z(Ee);return}},ve=Le=>{if(Le.defaultPrevented||q)return;const _e=Ue(Le);if(!_e)return;const Ne=Le.metaKey||Le.ctrlKey||Le.altKey;if(_a(Le.target))return;const Ee=fn(X),Be=Object.entries(Ee).filter(([Ve,ge])=>!!ge&&(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(),G(),B(ct[0]);return}if(Be.some(([,Ve])=>Ve.startsWith(`${qe} `))){Le.preventDefault(),te=Re,J();return}const dt=Be.find(([,Ve])=>Ve===et);if(dt){Le.preventDefault(),G(),B(dt[0]);return}if(Be.some(([,Ve])=>Ve.startsWith(`${et} `))){Le.preventDefault(),te=[et],J();return}G()};return V.addEventListener("keydown",re),V.addEventListener("keydown",ve),()=>{G(),V.removeEventListener("keydown",re),V.removeEventListener("keydown",ve)}});return()=>{for(const V of H)V()}},[Ue,X,W,Z,q,B,e]);const Ce=M==="light"?ha:xa,ze=((rt=(Ge=(Qe=j.current)==null?void 0:Qe.activePanel)==null?void 0:Ge.group.element)==null?void 0:rt.ownerDocument)??document;return s.jsxs(zl.Provider,{value:Se,children:[s.jsx("div",{ref:w,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(_d,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:Mb,remote:Ib},defaultTabComponent:Rb,watermarkComponent:Ab,onReady:xt,singleTabMode:"default",tabAnimation:"smooth",theme:Ce,popoutUrl:"/popout.html"})}),k&&or.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(K=>{if(K.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},K.id);let H=s.jsx(Iu,{size:13,className:"shrink-0 opacity-70"}),V=()=>{};switch(K.id){case"dockInWindow":case"dockBackToGrid":H=s.jsx(Ru,{size:13,className:"shrink-0 opacity-70"}),V=()=>{ke(k.tabKey),A(null)};break;case"moveBackToMain":H=s.jsx(Mu,{size:13,className:"shrink-0 opacity-70"}),V=()=>{je(k.tabKey),A(null)};break;case"floatAsPanel":H=s.jsx(Au,{size:13,className:"shrink-0 opacity-70"}),V=()=>{he(k.tabKey),A(null)};break;case"openInNewWindow":H=s.jsx(Tu,{size:13,className:"shrink-0 opacity-70"}),V=()=>{we(k.tabKey),A(null)};break;case"setShortcut":V=te=>{te.stopPropagation(),Ae(k.tabKey),A(null)};break;case"removeShortcut":H=s.jsx(vt,{size:13,className:"shrink-0 opacity-70"}),V=()=>{const te={...ue};delete te[k.tabKey],Te(te),A(null)};break;case"hideTab":H=s.jsx(Ua,{size:13,className:"shrink-0 opacity-70"}),V=()=>{ie(k.tabKey),A(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${K.tone==="muted"?"text-text-muted":""}`,onMouseDown:Nb,onClick:V,children:[H,s.jsx("span",{className:"flex-1 min-w-0",children:K.label}),K.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:K.shortcut}):null]},K.id)})}),k.sourceDocument.body),q&&or.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:K=>K.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. ",X?"⌘+1":"Ctrl+1",", ",X?"⌥+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 Vl="adhdev-recent-launch-args-v1",Pb=8;function Gl(e){return String(e||"").trim().replace(/\s+/g," ")}function ko(e,t){return`${e.trim()}::${t.trim()}`}function So(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Vl)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function ql(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Vl,JSON.stringify(e))}catch{}}function Da(e,t){var i;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((i=So().byKey[ko(r,n)])==null?void 0:i.items)||[]}function Yl(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),i=Gl(r);if(!n||!a||!i)return;const c=So(),l=ko(n,a),d=((u=c.byKey[l])==null?void 0:u.items)||[],m=[i,...d.filter(f=>f!==i)].slice(0,Pb);c.byKey[l]={items:m},ql(c)}function _b(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),i=Gl(r);if(!n||!a||!i)return;const c=So(),l=ko(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 Xl(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Yr({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 Db({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 Jl({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:i,onRefresh:c,onOpenHistory:l,onClearSelection:d}){const m=i?_l(i):null,u=Db({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Yr,{title:"Saved history",description:io(),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:Ap()})]}),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 Ql({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 Eb({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 sa(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>xs(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>xs(a,"acp"))?"acp":null}function Kr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function $b({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:i,onLaunchProvider:c,onListMeshes:l,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Ve,ge;const u=pr(),f=o.useMemo(()=>[...e].sort(Xa),[e]),[x,C]=o.useState(((Ve=f[0])==null?void 0:Ve.id)||""),y=o.useMemo(()=>f.find(z=>z.id===x)||f[0],[x,f]),p=o.useMemo(()=>((y==null?void 0:y.workspaces)||[]).map(z=>({id:z.id,path:z.path,label:z.label})),[y]),g=(y==null?void 0:y.defaultWorkspaceId)||null,[b,h]=o.useState("workspace"),[N,S]=o.useState(""),[v,M]=o.useState(""),[I,j]=o.useState([]),[w,$]=o.useState(""),[P,T]=o.useState(!1),[O,U]=o.useState(null),[R,k]=o.useState(""),[A,W]=o.useState(sa(f[0])),[_,E]=o.useState(""),[F,Y]=o.useState(""),[be,ce]=o.useState([]),[ee,ye]=o.useState(""),[we,je]=o.useState([]),[Q,ie]=o.useState(!1),[he,se]=o.useState(!1),[de,ke]=o.useState(""),[fe,xe]=o.useState(!1),[Z,me]=o.useState(()=>wt()),[oe,le]=o.useState(null),[ae,X]=o.useState(!1),[ue,q]=o.useState(""),[Ae,Te]=o.useState(null),[$e,Ue]=o.useState(!1),[B,Se]=o.useState(""),[Me,De]=o.useState([]),[Ke,He]=o.useState(!1),[Xe,st]=o.useState(""),[mt,ht]=o.useState(!1),xt=o.useRef(null),Ce=o.useRef(0);o.useEffect(()=>{var z;!x&&((z=f[0])!=null&&z.id)&&C(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(z=>xs(z,"cli")),[y]),Qe=o.useMemo(()=>((y==null?void 0:y.availableProviders)||[]).filter(z=>xs(z,"acp")),[y]),Ge=o.useMemo(()=>((y==null?void 0:y.detectedIdes)||[]).map(z=>({id:z.type,label:z.name||z.type,meta:z.running?"Detected locally":"Available to open"})),[y]),rt=o.useMemo(()=>A==="cli"?ze.map(z=>({id:z.type,label:z.displayName||z.type,meta:"CLI provider"})):A==="acp"?Qe.map(z=>({id:z.type,label:z.displayName||z.type,meta:"ACP provider"})):Ge,[Qe,A,ze,Ge]),K=o.useMemo(()=>I.find(z=>z.id===w)||null,[I,w]),H=o.useMemo(()=>ze.find(z=>z.type===_)||null,[ze,_]),V=o.useMemo(()=>Ml(H==null?void 0:H.meshCoordinator,{meshId:(K==null?void 0:K.id)||"",workspace:(K==null?void 0:K.workspace)||""}),[H,K]),te=Ae||V,D=o.useCallback(async z=>{T(!0),k("");try{const Ie=await l(z);j(Ie),$(L=>{var ne;return Ie.some(pe=>pe.id===L)?L:((ne=Ie[0])==null?void 0:ne.id)||""}),U(z)}catch(Ie){j([]),$(""),U(z),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([]),$(""),U(null),k(""),W(sa(y)),E(""),Y(""),ye(""),je([]),se(!1),ke(""),me(wt()),q(""),Te(null);return}S(L=>{var ne;return L==="__custom__"||L==="__home__"||p.some(pe=>pe.id===L)?L:g||((ne=p[0])==null?void 0:ne.id)||"__home__"}),W(L=>L==="ide"&&Ge.length>0||L==="cli"&&ze.length>0||L==="acp"&&Qe.length>0?L:sa(y))},[Qe.length,ze.length,g,Ge.length,y,p]),o.useEffect(()=>{!y||b!=="mesh"||O===y.id||P||D(y.id)},[D,O,P,y,b]),o.useEffect(()=>{b==="mesh"&&A!=="cli"&&ze.length>0&&W("cli")},[A,ze.length,b]),o.useEffect(()=>{var z;A&&(rt.some(Ie=>Ie.id===_)||E(((z=rt[0])==null?void 0:z.id)||""))},[A,rt,_]),o.useEffect(()=>{Te(null)},[y==null?void 0:y.id,w,_,b]);const G=o.useCallback(async(z,Ie)=>{const L=Ce.current+1;return Ce.current=L,ie(!0),ke(""),m(z,Ie).then(ne=>{Ce.current===L&&je(ne)}).catch(ne=>{Ce.current===L&&(je([]),ke(ne instanceof Error?ne.message:"Could not load saved sessions"))}).finally(()=>{Ce.current===L&&(ie(!1),se(!0))})},[m]),J=o.useCallback((z,Ie)=>{ce(Da(z,Ie))},[]);o.useEffect(()=>{Ce.current+=1,ye(""),me(wt()),!y||!_||A==="ide"?ce([]):J(y.id,_),se(!1),je([]),ke(""),ie(!1)},[A,J,G,y,_]),o.useEffect(()=>{if(!ee)return;const z=we.find(Ie=>Ie.providerSessionId===ee);z!=null&&z.canResume||ye("")},[we,ee]);const re=N==="__custom__"?v.trim():N==="__home__"?"":((ge=p.find(z=>z.id===N))==null?void 0:ge.path)||"",ve=o.useMemo(()=>y?t.filter(z=>z.id!==y.id&&z.daemonId===y.id).map(z=>z.workspace):[],[t,y]),Le=o.useMemo(()=>((y==null?void 0:y.recentLaunches)||[]).map(z=>z.workspace),[y]),_e=o.useCallback(z=>{const Ie=String(z.workspace||"").trim();if(!Ie)return;const L=p.find(ne=>Kr(ne.path)===Kr(Ie));if(L){S(L.id),M("");return}S("__custom__"),M(Ie)},[p]),Ne=o.useCallback(z=>{const Ie=String(z.workspace||"").trim();if(!Ie)return{workspaceId:null,workspacePath:null};const L=p.find(ne=>Kr(ne.path)===Kr(Ie));return L?{workspaceId:L.id,workspacePath:null}:{workspaceId:null,workspacePath:Ie}},[p]),Ee=o.useMemo(()=>we.find(z=>z.providerSessionId===ee)||null,[we,ee]),Be=o.useMemo(()=>{var Ie;if(A!=="cli"||!y||!_)return null;const z=((Ie=ze.find(L=>L.type===_))==null?void 0:Ie.displayName)||_;return{routeId:y.id,daemonId:y.id,providerSessionId:ee||void 0,transport:"pty",mode:"chat",agentName:z,agentType:_,status:"idle",title:z,messages:[],ideType:_,workspaceName:re,workspacePath:re,displayPrimary:z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${y.id}:${_}`,machineName:Tt(y,{fallbackId:y.id})}},[A,ze,re,y,ee,_]),Re=o.useCallback(()=>{var Ie;if(!y)return;S("__custom__"),Ue(!0),st("");const z=kn(y.platform,jn(v.trim(),re,ve,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,z).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,ve,n,re,y,p]),qe=o.useCallback(z=>{y&&(He(!0),st(""),n(y.id,z).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),q("");const z=await a(y.id,re);if(ht(!1),!z.ok){q(z.error||"Could not save workspace");return}q("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;X(!0),q(""),Te(null);const L=await d(y.id,w,_);if(X(!1),!L.ok){if(L.code==="mesh_coordinator_manual_mcp_setup_required"&&L.manualSetup){Te(L.manualSetup),q("Manual MCP setup required before this provider can act as mesh coordinator.");return}q(L.error||"Could not start mesh coordinator");return}r();return}if(!A||!_)return;X(!0),q("");const z=F.trim()?F.trim().split(/\s+/).filter(Boolean):[],Ie=A==="ide"?await i(y.id,_,{workspacePath:re||null}):await c(y.id,A,_,{workspaceId:N!=="__home__"&&N!=="__custom__"?N:null,workspacePath:N==="__custom__"&&re||null,resumeSessionId:A==="cli"&&ee?ee:null,cliArgs:z});if(X(!1),!Ie.ok){q(Ie.error||"Could not start session");return}A!=="ide"&&F.trim()&&(Yl(y.id,_,F),J(y.id,_)),r()},[A,F,J,r,i,d,c,re,y,w,ee,_,N,b]),ft=b==="mesh"?"Start mesh coordinator":A?Jc(A,A==="cli"&&!!ee):"Start",dt=b==="mesh"?"Starting coordinator…":A?Qc(A,A==="cli"&&!!ee):"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(Yr,{title:"Machine",children:yt?s.jsx("select",{"aria-label":"Machine",value:y.id,onChange:z=>C(z.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:ae,children:f.map(z=>s.jsx("option",{value:z.id,children:Tt(z,{fallbackId:z.id})},z.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:f.map(z=>{const Ie=Tt(z,{fallbackId:z.id}),L=y.id===z.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:()=>C(z.id),disabled:ae,title:Ie,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${z.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:Ie})]},z.id)})})}),s.jsxs(Yr,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:b==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Re,disabled: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(z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":b===z.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${b===z.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{h(z.id),q(""),z.id==="mesh"&&y&&O!==y.id&&!P&&D(y.id)},disabled:ae,children:[s.jsx("div",{className:"text-sm font-semibold",children:z.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:z.desc})]},z.id))}),b==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:N,onChange:z=>{const Ie=z.target.value;S(Ie),Ie==="__custom__"?Re():q("")},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(z=>s.jsxs("option",{value:z.id,children:[z.id===g?"⭐ ":"",yn(z.path,z.label)||z.path]},z.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:N==="__home__"?"Launch without a workspace.":re||"Select a workspace folder."}),N==="__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(fs,{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(z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":w===z.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${w===z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(z.id),disabled:ae,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:z.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[z.repoIdentity||"Repo mesh",typeof z.nodesCount=="number"?` · ${z.nodesCount} node${z.nodesCount===1?"":"s"}`:""]}),z.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",z.workspace]})]},z.id))}),K&&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(Eb,{workspaceMode:b,activeKind:A,cliEnabled:ze.length>0,ideEnabled:Ge.length>0,acpEnabled:Qe.length>0,busy:ae,onSelect:W}),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(z=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${_===z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>E(z.id),disabled:ae,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:z.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:z.meta})]},z.id)),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(Ql,{setup:te,providerName:(H==null?void 0:H.displayName)||(H==null?void 0:H.name)||_}),b!=="mesh"&&A!=="ide"&&s.jsxs(Yr,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:F,onChange:z=>Y(z.target.value),placeholder:"Optional flags...",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:ae}),be.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:be.map(z=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>Y(z),disabled:ae,title:z,children:z},z))})]}),b!=="mesh"&&A==="cli"&&s.jsx(Jl,{busy:ae,savedSessionsLoading:Q,savedSessionsError:de,selectedSession:Ee,onRefresh:()=>{!y||!_||G(y.id,_)},onOpenHistory:()=>{!y||!_||(xe(!0),Xl({hasLoadedInitialResults:he,isLoading:Q})&&G(y.id,_))},onClearSelection:()=>ye("")}),ue&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ue.includes("saved")||ue.includes("requested")||ue.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:ue})]}),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||!_||N==="__custom__"&&!re),children:[s.jsx(Va,{size:14}),ae?dt:ft]})]})]})}),$e&&s.jsx(Cn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:B,directories:Me,busy:Ke,error:Xe,onClose:()=>Ue(!1),onNavigate:qe,onConfirm:z=>{M(z),Se(z),S("__custom__"),Ue(!1)}}),fe&&Be&&s.jsx(uo,{activeConv:Be,ides:[],isCreatingChat:!1,isRefreshingHistory:Q,savedSessions:we,isSavedSessionsLoading:Q,isResumingSavedSessionId:oe,savedHistoryFilters:Z,missingWorkspaceResumePath:re||null,onSavedHistoryFiltersChange:me,onClose:()=>xe(!1),onNewChat:()=>{ye(""),xe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!y||!_||G(y.id,_)},onResumeSavedSession:z=>{if(!y||!_||oe||!z.canResume)return;const Ie=Ne(z);ye(z.providerSessionId),_e(z),le(z.providerSessionId),xe(!1),X(!0),q(""),c(y.id,"cli",_,{workspaceId:Ie.workspaceId,workspacePath:Ie.workspacePath,resumeSessionId:z.providerSessionId}).then(L=>{if(!L.ok){q(L.error||"Could not resume session");return}r()}).finally(()=>{X(!1),le(L=>L===z.providerSessionId?null:L)})}})]}):null}function Bb(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=Kb(n);return{remoteUrl:n,githubUrl:l,loading:i}}function Kb(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 Zl=5e3;function Wb(e){return`git:${e}`}function Ob({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Zl}){return{type:"subscribe",topic:"workspace.git",key:Wb(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function No(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function bs(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 Fb(e){const t=No(e);return(t==null?void 0:t.success)===!1?{status:null,error:bs(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:bs(t,"Git status response did not include status")}}function Hb(e){const t=No(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:bs(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:bs(t,"Git diff summary response did not include diffSummary")}}function ra(e){return e===void 0||typeof e=="boolean"}function Ub(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&ra(t.binary)&&ra(t.truncated)&&ra(t.staged)}function zb(e){const t=No(e);return(t==null?void 0:t.success)===!1?{diff:null,error:bs(t,"Git file diff request failed")}:Ub(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:bs(t,"Git file diff response did not include a valid diff object")}}function Vb({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Zl}){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),[C,y]=o.useState(!1),[p,g]=o.useState(null),b=o.useCallback(async()=>{if(!(!d||!e||!l)){y(!0),g(null);try{const N=Fb(await i(e,"git_status",{workspace:l}));if(N.error){u(null),x(null),g(N.error);return}if(u(N.status),!n){x(null);return}const S=Hb(await i(e,"git_diff_summary",{workspace:l}));if(S.error){x(null),g(S.error);return}x(S.diffSummary)}catch(N){g(bs(N,"Git status request failed"))}finally{y(!1)}}},[d,e,n,i,l]),h=o.useMemo(()=>l?Ob({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 N=c?Ht.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(),()=>{N==null||N()}},[d,e,b,h,c,l]),{status:m,diffSummary:f,loading:C,error:p,refresh:b}}const Gb={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},qb={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 Pi(e){return e.split("/").pop()??e}function Yb(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function Xb({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=Gb[i.status]??"?",d=qb[i.status]??"text-zinc-400",m=Yb(i.path),u=Pi(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:["← ",Pi(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 Jb(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 Qb({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)=>Jb(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 Zb(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 ed({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=gt(),{status:a,diffSummary:i,loading:c,error:l,refresh:d}=Vb({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=o.useState(null),[f,x]=o.useState(null),[C,y]=o.useState(""),[p,g]=o.useState(!1),[b,h]=o.useState(!1),[N,S]=o.useState(null),[v,M]=o.useState(null),{githubUrl:I}=Bb(e,t),j=o.useCallback(async U=>{if(!((m==null?void 0:m.path)===U.path&&!m.loading)){u({path:U.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const R=await n(e,"git_diff_file",{workspace:t,path:U.path,staged:U.staged}),k=zb(R);if(k.error||!k.diff){u({path:U.path,diff:"",binary:!1,truncated:!1,loading:!1,error:k.error??"Failed to load diff"});return}u({path:U.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:U.path,diff:"",binary:!1,truncated:!1,loading:!1,error:k})}}},[e,n,m,t]),w=o.useCallback(U=>{y(""),g(!1),S(null),M(null),x(U)},[]),$=o.useCallback(()=>{x(null),S(null),h(!1)},[]),P=o.useCallback(async()=>{var U,R,k;if(f){h(!0),S(null);try{let A;f==="checkpoint"?A=await n(e,"git_checkpoint",{workspace:t,message:C,includeUntracked:p}):f==="stash"?A=await n(e,"git_stash_push",{workspace:t,message:C,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 W=(A==null?void 0:A.result)??A;if((W==null?void 0:W.success)===!1||W!=null&&W.error){S((W==null?void 0:W.error)??"Action failed"),h(!1);return}f==="checkpoint"?M(`Checkpoint created: ${((R=(U=W==null?void 0:W.checkpoint)==null?void 0:U.commit)==null?void 0:R.slice(0,7))??"done"}`):f==="stash"?M(`Stashed as ${((k=W==null?void 0:W.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,C,p,m,d]),T=!!(a!=null&&a.hasConflicts),O=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:U=>{U.target===U.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"}),O===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(Xb,{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(Qb,{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 U=Zb((a==null?void 0:a.branch)??null,i);navigator.clipboard.writeText(U),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:C,onChange:U=>y(U.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:U=>g(U.target.checked)}),"Include untracked files"]})]}),N&&s.jsx("p",{className:"text-xs text-red-400",children:N}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:$,disabled:b,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),s.jsx("button",{onClick:P,disabled:b||(f==="checkpoint"||f==="stash")&&!C.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 eg({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),[C,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)},[]),N=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:C,shortcutSection:p,isDesktopDashboard:b,setGuideTab:y,setShortcutSection:g,handleInboxOpenChange:h,handleHiddenOpenChange:N,handleOpenShortcutHelp:S,closeShortcutHelp:v,openNewSession:M,closeNewSession:I}}function tg(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 sg(e){return e instanceof Error?e.message:String(e||"")}function rg(e){const t=sg(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function ng({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:C,sendDaemonCommand:y,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:b,initialDataLoaded:h,userName:N,requestedMobileTabKey:S,onRequestedMobileTabConsumed:v,requestedMachineId:M,onRequestedMachineConsumed:I,requestedMobileSection:j,onRequestedMobileSectionConsumed:w,containerRef:$,isSplitMode:P,numGroups:T,groupSizes:O,groupedConvs:U,clearedTabs:R,focusedGroup:k,focusGroup:A,moveTabToGroup:W,splitTabRelative:_,closeGroup:E,handleResizeStart:F,groupActiveTabIds:Y,setGroupActiveTab:be,groupTabOrders:ce,setGroupTabOrder:ee,toggleHiddenTab:ye,visibleConversations:we,requestedDesktopTabKey:je,onRequestedDesktopTabConsumed:Q,onDesktopActiveTabChange:ie,onRequestScrollToBottom:he,onHideConversation:se,onShowHiddenConversation:de,onShowAllHiddenConversations:ke,scrollToBottomRequest:fe,machineEntries:xe,layoutProfile:Z,onBrowseMachineDirectory:me,onSaveMachineWorkspace:oe,onLaunchMachineIde:le,onLaunchMachineProvider:ae,onListMachineMeshes:X,onLaunchMeshCoordinator:ue,onListMachineSavedSessions:q,notifications:Ae,notificationUnreadCount:Te,liveSessionInboxState:$e,onMarkNotificationRead:Ue,onMarkNotificationUnread:B,onDeleteNotification:Se}){const Me=Ct.useRef(null),{inboxOpen:De,hiddenOpen:Ke,shortcutHelpOpen:He,newSessionOpen:Xe,guideNudgeVisible:st,guideTab:mt,shortcutSection:ht,isDesktopDashboard:xt,setGuideTab:Ce,setShortcutSection:ze,handleInboxOpenChange:Qe,handleHiddenOpenChange:Ge,handleOpenShortcutHelp:rt,closeShortcutHelp:K,openNewSession:H,closeNewSession:V}=eg({isMobile:t,showMobileChatMode:e,visibleConversationCount:we.length}),[te,D]=Ct.useState(null),G=Ct.useCallback((ge,z)=>{D({daemonId:ge,workspace:z})},[]),J=Ct.useCallback(ge=>{var z;or.flushSync(()=>{de(ge)}),(z=Me.current)==null||z.restoreHiddenTabToSavedLocation(ge.tabKey)},[de]),re=Ct.useCallback(ge=>{var Ie;const z=u.find(L=>Na(L,ge))||f.find(L=>Na(L,ge));z&&(f.some(L=>L.tabKey===z.tabKey)&&J(z),ie(z.tabKey),(Ie=Me.current)==null||Ie.activateConversationTab(z.tabKey),he(z.tabKey,"notification-open")),Ue(ge.id),Qe(!1)},[J,f,u,ie,Ue,he]),ve=Ct.useCallback(()=>{var z;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((z=Me.current)==null||z.resetAllPanelsToMain(),Ge(!1))},[Ge]),Le=Ct.useCallback(async ge=>{var pe;if(!r)return;const z=(pe=r.modalButtons)==null?void 0:pe[ge];if(!z)return;const Ie=Ps(r);if(!Ie)return;const L=z.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),ne=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(L);try{await y(Ie,"resolve_action",{button:z,action:ne?"approve":"reject",buttonIndex:ge,...ns(r)})}catch(We){rg(We)||console.error("[Shortcut approval] Failed:",We)}},[r,y]),{isMac:_e,actionDefinitions:Ne,actionShortcuts:Ee,shortcutListening:Be,shortcutListeningDraft:Re,setShortcutListening:qe,setShortcutListeningDraft:et,saveShortcuts:ct}=gb({enabled:xt&&!He,onTrigger:ge=>{var z,Ie,L,ne,pe,We,Pe,Oe,ot,Nt,pt,Vt,br,gr,yr,vr;if(ge==="openShortcutHelp"){rt();return}if(ge==="openNewSession"){H();return}if(ge==="hideCurrentTab"){r&&se(r);return}if(ge==="toggleHiddenTabs"){Ge(!Ke);return}if(ge==="openHistoryForActiveTab"){r&&!Ze(r)&&i(r);return}if(ge==="openRemoteForActiveTab"){r&&!tt(r)&&!Ze(r)&&c(r);return}if(ge==="splitActiveTabRight"){(z=Me.current)==null||z.splitActiveTabRight();return}if(ge==="splitActiveTabDown"){(Ie=Me.current)==null||Ie.splitActiveTabDown();return}if(ge==="floatActiveTab"){(L=Me.current)==null||L.floatActiveTab();return}if(ge==="popoutActiveTab"){(ne=Me.current)==null||ne.popoutActiveTab();return}if(ge==="dockActiveTab"){(pe=Me.current)==null||pe.dockActiveTab();return}if(ge==="focusLeftPane"){(We=Me.current)==null||We.focusLeftPane();return}if(ge==="focusRightPane"){(Pe=Me.current)==null||Pe.focusRightPane();return}if(ge==="focusUpPane"){(Oe=Me.current)==null||Oe.focusUpPane();return}if(ge==="focusDownPane"){(ot=Me.current)==null||ot.focusDownPane();return}if(ge==="moveActiveTabToLeftPane"){(Nt=Me.current)==null||Nt.moveActiveTabToLeftPane();return}if(ge==="moveActiveTabToRightPane"){(pt=Me.current)==null||pt.moveActiveTabToRightPane();return}if(ge==="moveActiveTabToUpPane"){(Vt=Me.current)==null||Vt.moveActiveTabToUpPane();return}if(ge==="moveActiveTabToDownPane"){(br=Me.current)==null||br.moveActiveTabToDownPane();return}if(ge==="triggerPrimaryApprovalAction"){Le(0);return}if(ge==="triggerSecondaryApprovalAction"){Le(1);return}if(ge==="triggerTertiaryApprovalAction"){Le(2);return}if(ge==="setActiveTabShortcut"){(gr=Me.current)==null||gr.setShortcutForActiveTab();return}if(ge==="selectPreviousGroupTab"){(yr=Me.current)==null||yr.activatePreviousTabInGroup();return}if(ge==="selectNextGroupTab"){(vr=Me.current)==null||vr.activateNextTabInGroup();return}!r||!tt(r)||Ze(r)||ge==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),ft=Ct.useCallback(()=>{K(),qe(null),et([])},[K,qe,et]),dt=Ct.useMemo(()=>ht==="all"?Ne:Ne.filter(ge=>tg(ge)===ht),[Ne,ht]),yt=Ct.useCallback(()=>{const ge=Object.fromEntries(Ne.map(z=>[z.id,""]));ct(ge)},[Ne,ct]),Ve=Ct.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const ge=Object.fromEntries(Ne.map(z=>[z.id,z.defaultShortcut]));ct(ge)},[Ne,ct]);return Ct.useEffect(()=>{const ge=z=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?z.metaKey&&z.key.toLowerCase()==="w":z.ctrlKey&&z.key.toLowerCase()==="w")&&(z.preventDefault(),r&&se&&se(r))};return window.addEventListener("keydown",ge),()=>window.removeEventListener("keydown",ge)},[r,se]),Ct.useEffect(()=>{if(!He||Be)return;const ge=z=>{z.key==="Escape"&&(z.preventDefault(),ft())};return window.addEventListener("keydown",ge,!0),()=>window.removeEventListener("keydown",ge,!0)},[ft,He,Be]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(Sp,{activeConv:r,wsStatus:n,isConnected:a,conversations:we,hiddenConversations:f,onOpenHistory:i,onHideConversation:se,onShowConversation:J,onShowAllHidden:ke,onResetPanelsToMain:ve,notifications:Ae,notificationUnreadCount:Te,onOpenNotification:re,onMarkNotificationRead:Ue,onMarkNotificationUnread:B,onDeleteNotification:Se,inboxOpen:De,onInboxOpenChange:Qe,hiddenOpen:Ke,onHiddenOpenChange:Ge,onOpenNewSession:t?void 0:H,onOpenDashboardGuide:rt,guideNudgeVisible:st,actionShortcuts:Ee,onOpenRemote:()=>{!r||tt(r)||Ze(r)||c(r)},onStopCli:l,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:G}),e?s.jsx(ob,{conversations:u,hiddenConversations:f,ides:x,actionLogs:C,sendDaemonCommand:y,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:b,userName:N,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:H,liveSessionInboxState:$e}):t?s.jsx(pb,{containerRef:$,isSplitMode:P,numGroups:T,groupSizes:O,groupedConvs:U,clearedTabs:R,ides:x,actionLogs:C,sendDaemonCommand:y,setActionLogs:p,isStandalone:b,hasRegisteredMachines:xe.length>0,userName:N,focusedGroup:k,focusGroup:A,moveTabToGroup:W,splitTabRelative:_,closeGroup:E,handleResizeStart:F,groupActiveTabIds:Y,setGroupActiveTab:be,groupTabOrders:ce,setGroupTabOrder:ee,toggleHiddenTab:ye,onOpenNewSession:H,allowTabShortcuts:!1,liveSessionInboxState:$e}):s.jsx(Lb,{visibleConversations:we,clearedTabs:R,ides:x,actionLogs:C,sendDaemonCommand:y,setActionLogs:p,isStandalone:b,hasRegisteredMachines:xe.length>0,initialDataLoaded:h,userName:N,toggleHiddenTab:ye,actionShortcuts:Ee,registerActionHandlers:ge=>{Me.current=ge},onActiveTabChange:ie,requestedActiveTabKey:je,onRequestedActiveTabConsumed:Q,onRequestScrollToBottom:he,scrollToBottomRequest:fe,onOpenNewSession:H,liveSessionInboxState:$e,layoutProfile:Z}),Xe&&s.jsx($b,{machines:xe,ides:x,onClose:V,onBrowseDirectory:me,onSaveWorkspace:oe,onLaunchIde:le,onLaunchProvider:ae,onListMeshes:X,onLaunchMeshCoordinator:ue,onListSavedSessions:q}),te&&s.jsx(ed,{daemonId:te.daemonId,workspace:te.workspace,onClose:()=>D(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:ge=>ge.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(ge=>s.jsx("button",{type:"button",className:`btn btn-sm ${mt===ge.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ce(ge.id),children:ge.label},ge.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(ge=>s.jsx("button",{type:"button",className:`btn btn-sm ${ht===ge.id?"btn-primary":"btn-secondary"}`,onClick:()=>ze(ge.id),children:ge.label},ge.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(ge=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Be===ge.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:ge.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ge.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:ge.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===ge.id?Re.length>0?`${Re.join(" ")} ...`:"Listening...":Ee[ge.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{qe(ge.id),et([])},children:Be===ge.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const z={...Ee};z[ge.id]="",ct(z)},children:"Disable"})]})]})},ge.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 na=[{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 ag({onClose:e}){const[t,r]=o.useState(0),n=na[t],a=t===na.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:na.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 og({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 ig({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[i,c]=o.useState(()=>a||"native"),l=o.useMemo(()=>el(t),[t]),d=o.useMemo(()=>e?mo(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?Dt(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]),C=o.useMemo(()=>u.map(p=>({tabKey:p.tabKey,title:Gc(p)||n,status:p.status})),[u,n]),y=o.useCallback(p=>{if(p)return d.find(g=>Na(g,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[d]);return{activeChatTab:i,setActiveChatTab:c,activeConv:x,conversations:d,extensionTabs:C,hasExtensions:C.length>0,resolveConversationByTarget:y}}function cg({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,C]=o.useState("split"),[y,p]=o.useState(()=>Xt(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:N,extensionTabs:S,hasExtensions:v}=ig({ideData:b,allIdes:r,connectionStates:n,ideName:h||"IDE",preferredTabKey:Xt(e)?void 0:e.tabKey}),M=o.useMemo(()=>b?Dt(N,b.id):null,[b,N]);o.useEffect(()=>{const A=g.current,W={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(g.current=W,!(A&&A.routeId===W.routeId&&A.tabKey===W.tabKey&&A.streamSource===W.streamSource)){if(Xt(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(y==="native"){if(N.some(A=>A.streamSource==="native"))return;(M==null?void 0:M.streamSource)==="agent-stream"&&p(M.tabKey);return}if(!N.some(A=>A.tabKey===y)){if((M==null?void 0:M.streamSource)==="agent-stream"){p(M.tabKey);return}p("native")}},[N,y,M]);const I=o.useMemo(()=>y==="native"?N.find(A=>A.streamSource==="native")||e:N.find(A=>A.tabKey===y)||e,[e,N,y]),j=ml(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]),$=fr(w),P=wn({sendDaemonCommand:i,activeConv:w,setActionLogs:c,isStandalone:l}),{connScreenshot:T,screenshotUsage:O,handleRemoteAction:U}=Kl({doId:$,targetSessionId:Ac(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=W=>{W.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:Za(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 W=x===A;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${W?"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:()=>C(A),title:A==="split"?"Split view":"Remote only",children:A==="split"?s.jsx(hu,{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(Ha,{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(og,{hasExtensions:v,ideName:h||"IDE",activeChatTab:y,extensionTabs:S,onSelectTab:p}),s.jsx(bc,{activeConv:w,onModalButton:P.handleModalButton}),s.jsx(Ta,{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(hc,{addLog:()=>{},connState:w.connectionState||"new",connScreenshot:T,screenshotUsage:O,transportType:w.transport,onAction:U})})]})]})})}function lg({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=fp(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 dg({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(gp,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(uo,{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(cg,{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(lg,{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(Zc,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),i.open&&s.jsx(ag,{onClose:i.onClose})]})}function ug({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(ur,{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=Nl(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 mg(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function fg(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 pg(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>fg(t)).map(t=>t.id)}}function hg(){var Lo,Po,_o,Do;const{sendCommand:e}=gt(),t=pr(),r=ul(),n=Wa(),a=Bs(),[i,c]=Dd(),l=i.get("activeTab"),d=((Lo=n.state)==null?void 0:Lo.openRemoteForTabKey)||null,m=((Po=n.state)==null?void 0:Po.openMachineId)||null,u=((_o=n.state)==null?void 0:_o.mobileSection)||null,f=Hc(),x=f.ides||[],C=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||[],N=f.wsStatus||"connected",S=f.isConnected??!0,v=f.connectionStates||{},M=f.showReconnected||!1,{layoutProfile:I,groupAssignments:j,updateGroupAssignments:w,focusedGroup:$,updateFocusedGroup:P,focusGroup:T,groupActiveTabIds:O,updateGroupActiveTabIds:U,setGroupActiveTab:R,groupTabOrders:k,updateGroupTabOrders:A,setGroupTabOrder:W,groupSizes:_,updateGroupSizes:E,isMobile:F,hasHydratedStoredLayout:Y,hydrateStoredLayout:be,focusConversationTab:ce}=ex(),[ee,ye]=o.useState(()=>xo());o.useEffect(()=>xh(ye),[]);const we=o.useMemo(()=>mg({isMobile:F,mobileViewMode:ee}),[F,ee]),[je,Q]=o.useState([]),[ie,he]=o.useState({}),[se,de]=o.useState({});mr("Dashboard",{ideCount:x.length,toastCount:h.length,focusedGroup:$,groupCount:Object.keys(j).length,actionLogCount:je.length});const ke=o.useMemo(()=>x.filter(Ye=>Ye.type==="adhdev-daemon").sort(Xa),[x]),fe=ke[0],xe=!!fe;o.useEffect(()=>{const{metadataDaemonIds:Ye,runtimeDaemonIds:Rt}=pg(ke);for(const Os of Ye)t(Os,{minFreshMs:3e4}).catch(()=>{});for(const Os of Rt)r(Os,{minFreshMs:3e4}).catch(()=>{})},[t,r,ke]);const Z=(fe==null?void 0:fe.terminalBackend)||null,me=fe?Tt(fe,{fallbackId:fe.id}):null,oe=(fe==null?void 0:fe.id)||null,le=o.useMemo(()=>Th(x,ie),[x,ie]),{hiddenTabs:ae,hideTarget:X,toggleTarget:ue,showTarget:q,showAllTabs:Ae}=Ch(),{conversations:Te,visibleConversations:$e,visibleTabKeys:Ue,resolveConversationBySessionId:B,resolveConversationByTarget:Se}=Kh({ides:le,connectionStates:v,clearedTabs:se,hiddenTabs:ae}),Me=o.useMemo(()=>new Map(Te.map(Ye=>[Ye.tabKey,Ye])),[Te]);Uf($e,we),o.useEffect(()=>{Object.keys(ie).length!==0&&he(Ye=>Mh(Ye,x))},[x,ie]);const De=o.useMemo(()=>rm(x),[x]),{notifications:Ke,unreadCount:He}=xx({conversations:Te,liveSessionInboxState:De}),{handleMarkDashboardNotificationRead:Xe,handleMarkDashboardNotificationUnread:st,handleDeleteDashboardNotification:mt}=bx({notifications:Ke,sendDaemonCommand:e}),{containerRef:ht,normalizedGroupAssignments:xt,numGroups:Ce,isSplitMode:ze,groupedConvs:Qe,moveTabToGroup:Ge,closeGroup:rt,handleResizeStart:K,splitTabRelative:H}=ix({groupAssignments:j,updateGroupAssignments:w,updateFocusedGroup:P,updateGroupActiveTabIds:U,updateGroupTabOrders:A,groupSizes:_,updateGroupSizes:E,isMobile:F,visibleConversations:$e,visibleTabKeys:Ue}),{activeConv:V,openDesktopConversation:te,requestScrollToBottom:D,scrollToBottomRequest:G,setDesktopActiveTab:J}=Lx({isMobile:F,conversations:Te,visibleConversations:$e,groupActiveTabIds:O,focusedGroup:$,groupedConvs:Qe,setSearchParams:c});Dx({activeConv:V,isMobile:F,liveSessionInboxState:De,sendDaemonCommand:e});const{requestedDesktopTabKey:re,requestedMobileTabKey:ve,consumeRequestedActiveTab:Le}=Wh({isMobile:F,urlActiveTab:l,resolveConversationBySessionId:B,setSearchParams:c}),{remoteDialogConv:_e,remoteDialogIdeEntry:Ne,remoteDialogActiveConv:Ee,setRemoteDialogActiveConv:Be,openRemoteDialog:Re,closeRemoteDialog:qe,cliStopDialogOpen:et,cliStopTargetConv:ct,requestCliStop:ft,cancelCliStop:dt,confirmCliStop:yt}=Bx({isMobile:F,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:re,conversations:Te,ides:x,resolveConversationByTarget:Se,activeConv:V,sendDaemonCommand:e}),{historyModalOpen:Ve,openHistoryModal:ge,closeHistoryModal:z,historyTargetConv:Ie,isSavedSessionHistoryTarget:L,isHistoryCreatingChat:ne,isHistoryRefreshingHistory:pe,handleHistorySwitchSession:We,handleHistoryNewChat:Pe,handleHistoryRefresh:Oe,savedHistorySessions:ot,savedHistoryFilters:Nt,setSavedHistoryFilters:pt,missingWorkspaceResumePath:Vt,isSavedHistoryLoading:br,resumingSavedHistorySessionId:gr,handleRefreshSavedHistory:yr,handleResumeSavedHistorySession:vr}=Ex({activeConv:V,remoteDialogConv:_e,remoteDialogActiveConv:Ee,ides:x,sendDaemonCommand:e,updateRouteChats:y,setToasts:p,setClearedTabs:de,setSearchParams:c}),od=o.useMemo(()=>$e,[$e]),wr=F&&ee==="chat",id=o.useMemo(()=>Te.filter(Ye=>bo(ae,Ye)),[Te,ae]),Io=o.useCallback(Ye=>{const Rt=new URLSearchParams(i);Rt.set("activeTab",Ye),c(Rt,{replace:!0})},[i,c]),{trackPendingLaunch:cd}=Mx({ides:x,conversations:Te,onOpenSession:Io}),{handleBrowseMachineDirectory:ld,handleSaveMachineWorkspace:dd,handleLaunchMachineIde:ud,handleLaunchMachineProvider:md,handleListMachineMeshes:fd,handleLaunchMeshCoordinator:pd,handleListMachineSavedSessions:hd,setActiveCliViewMode:xd}=Ix({sendDaemonCommand:e,trackPendingLaunch:cd,onOpenSession:Io,activeConv:V,ides:x,setCliViewModeOverrides:he});Ih({visibleConversations:$e,clearedTabs:se,setClearedTabs:de,setActionLogs:Q}),Oh({ides:x,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Se});const{isRefreshingHistory:bd,handleRefreshHistory:gd}=Sl({sendDaemonCommand:e,activeConv:V,chats:(Do=x.find(Ye=>Ye.id===(V==null?void 0:V.routeId)))==null?void 0:Do.chats,updateRouteChats:y,setToasts:p,setClearedTabs:de});sx({urlActiveTab:F&&!wr?l:null,conversations:Te,resolveConversationBySessionId:B,normalizedGroupAssignments:xt,hasHydratedStoredLayout:F&&!wr?Y:!0,hydrateStoredLayout:F&&!wr?be:()=>{},focusConversationTab:ce,setSearchParams:c,historyModalOpen:Ve,activeConv:V,isRefreshingHistory:bd,ides:x,handleRefreshHistory:gd});const yd=o.useMemo(()=>!V||!tt(V)||Ze(V)?null:Ws(V),[V]),{versionMismatchDaemons:vd,hasRequiredVersionDaemons:Ao,targetVersion:wd,versionBannerDismissed:jd,setVersionBannerDismissed:kd,upgradingDaemons:Sd,handleBannerUpgrade:Nd}=lx({ides:x,sendDaemonCommand:e}),Ro=o.useCallback(Ye=>{q(Ye),te(Ye)},[te,q]),Cd=o.useCallback(Ye=>{X(Ye)},[X]);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(yp,{terminalBackend:Z,isStandalone:xe,machineLabel:me,machineKey:oe}),(!jd||Ao)&&s.jsx(ug,{daemons:vd,targetVersion:wd,required:Ao,upgradingDaemons:Sd,onUpgrade:Nd,onDismiss:()=>kd(!0)}),s.jsx(ng,{showMobileChatMode:wr,isMobile:F,activeConv:V,wsStatus:N,isConnected:S,onOpenHistory:Ye=>{Ye&&Be(Ye),ge()},onOpenRemote:Re,onStopCli:ft,activeCliViewMode:yd,onSetActiveCliViewMode:xd,mobileChatConversations:od,ides:x,actionLogs:je,sendDaemonCommand:e,setActionLogs:Q,setCliViewModeOverrides:he,isStandalone:xe,initialDataLoaded:C,userName:f.userName,requestedMobileTabKey:ve,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:$,focusGroup:T,moveTabToGroup:Ge,splitTabRelative:H,closeGroup:rt,handleResizeStart:K,groupActiveTabIds:O,setGroupActiveTab:R,groupTabOrders:k,setGroupTabOrder:W,toggleHiddenTab:Ye=>ue(Me.get(Ye)||{tabKey:Ye}),visibleConversations:$e,hiddenConversations:id,requestedDesktopTabKey:re,onRequestedDesktopTabConsumed:Le,onDesktopActiveTabChange:J,onRequestScrollToBottom:D,onHideConversation:Cd,onShowHiddenConversation:Ro,onShowAllHiddenConversations:Ae,scrollToBottomRequest:G,machineEntries:ke,layoutProfile:I,onBrowseMachineDirectory:ld,onSaveMachineWorkspace:dd,onLaunchMachineIde:ud,onLaunchMachineProvider:md,onListMachineMeshes:fd,onLaunchMeshCoordinator:pd,onListMachineSavedSessions:hd,notifications:Ke,notificationUnreadCount:He,liveSessionInboxState:De,onMarkNotificationRead:Xe,onMarkNotificationUnread:st,onDeleteNotification:mt}),s.jsx("style",{children:`
|
|
68
|
+
body { overflow: hidden; overscroll-behavior: none; }
|
|
69
|
+
`}),s.jsx(dg,{historyModal:{open:Ve,targetConv:Ie,ides:x,isCreatingChat:ne,isRefreshingHistory:L?!1:pe,savedSessions:ot,savedHistoryFilters:Nt,missingWorkspaceResumePath:Vt||null,onSavedHistoryFiltersChange:pt,isSavedSessionsLoading:br,isResumingSavedSessionId:gr,onClose:z,onNewChat:Pe,onSwitchSession:We,onRefreshHistory:L?yr:Oe,onResumeSavedSession:vr},remoteDialog:{conversation:_e,ideEntry:Ne,ides:x,connectionStates:v,actionLogs:je,sendDaemonCommand:e,setActionLogs:Q,isStandalone:xe,userName:f.userName,onOpenHistory:Ye=>{Ye&&Be(Ye),ge()},onConversationChange:Be,onClose:qe},cliStopDialog:{open:et,targetConv:ct,onCancel:dt,onStopNow:async()=>{await yt("hard")},onSaveAndStop:async()=>{await yt("save")}},connectionBanner:{wsStatus:N,showReconnected:M,loginUrl:f.connectionLoginUrl,onReconnect:f.retryServerConnection},toastOverlay:{toasts:h,onDismiss:Ye=>p(Rt=>Rt.filter(Os=>Os.id!==Ye)),onClick:Ye=>{if(Ye.targetKey){const Rt=Se(Ye.targetKey);Rt&&(ce(Rt.tabKey,xt),Ro(Rt),D(Rt.tabKey,"toast-open"))}}},onboarding:{open:g,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}b(!1)}}})]})}function xg({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),[C,y]=o.useState(null),[p,g]=o.useState(!1),[b,h]=o.useState(""),N=o.useRef(null),S=o.useCallback(_=>{N.current=_},[]),v=o.useCallback((_,E,F=!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),F&&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 F;if(!e||l)return!1;d(_),v("info",`Launching ${it(_)}${E!=null&&E.workspace?` in ${E.workspace}`:""}...`);try{const Y={ideType:_,enableCdp:!0};(F=E==null?void 0:E.workspace)!=null&&F.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:F,workspaceId:Y,useDefaultWorkspace:be,useHome:ce,argsStr:ee,model:ye,resumeSessionId:we}=_;if(!E)return v("warn","Select a CLI or ACP provider first",!0),{success:!1};const je=ee?ee.split(/\s+/).filter(Boolean):void 0,Q=(F==null?void 0:F.trim())||(Y?"(saved id)":be?"(default workspace)":ce?"(home)":"");v("info",`Launching ${E}${Q?` in ${Q}`:""}${ye?` (model: ${ye})`:""}...`),u(E);try{const ie={cliType:E,cliArgs:je,initialModel:ye||void 0};F!=null&&F.trim()?ie.dir=F.trim():Y?ie.workspaceId=Y:be?ie.useDefaultWorkspace=!0:ce&&(ie.useHome=!0),we&&(ie.resumeSessionId=we);const he=await r(e,"launch_cli",ie),se=(he==null?void 0:he.result)||he;return he!=null&&he.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: ${(he==null?void 0:he.error)||(se==null?void 0:se.error)}`,!0),(he==null?void 0:he.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&y({cliType:E,argsStr:ee,model:ye}),{success:!1,sessionId:se==null?void 0:se.sessionId})}catch(ie){return M(ie)?(v("warn",`${E} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(v("error",`Launch error: ${ie.message}`,!0),{success:!1})}finally{u(null)}},[e,v,M,r]),w=o.useCallback(async(_,E,F,Y)=>e?_?E.trim()?j({cliType:_,dir:E,argsStr:F,model:Y}):(y({cliType:_,argsStr:F,model:Y}),{success:!1}):(v("warn","Select a provider",!0),{success:!1}):{success:!1},[e,v,j]),$=o.useCallback(async(_,E,F)=>{if(e&&window.confirm(`Stop ${_}?
|
|
70
|
+
This will terminate the process.`))try{const Y=await r(e,"stop_cli",{cliType:_,dir:E,targetSessionId:F});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]),O=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]),U=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 F=await r(e,"workspace_set_default",_===null?{clear:!0}:{id:_});if(F!=null&&F.success){v("info",_?"Default workspace updated":"Default workspace cleared",!0);const Y=typeof F.defaultWorkspacePath=="string"?F.defaultWorkspacePath:"";Y&&((E=N.current)==null||E.call(N,Y))}else v("error",(F==null?void 0:F.error)||"workspace_set_default failed",!0)}catch(F){v("error",F.message,!0)}finally{x(!1)}}},[e,v,r]),A=o.useCallback(async _=>{var F;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"),(F=N.current)==null||F.call(N,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]),W=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:C,setLaunchPick:y,editingNickname:p,setEditingNickname:g,nicknameInput:b,setNicknameInput:h,addLog:v,handleLaunchIde:I,runLaunchCliCore:j,handleLaunchCli:w,handleStopCli:$,handleRestartIde:P,handleStopIde:T,handleDetectIdes:O,handleWorkspaceAdd:U,handleWorkspaceRemove:R,handleWorkspaceSetDefault:k,handleWorkspaceResumePath:A,handleSaveNickname:W,setOnDefaultWorkspaceChanged:S}}function bg({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),[C,y]=o.useState(""),[p,g]=o.useState([]),[b,h]=o.useState(!1),[N,S]=o.useState(""),v=o.useCallback(async T=>{h(!0),S("");try{const O=await Sn(c,e,T);y(O.path),g(O.directories)}catch(O){S(O instanceof Error?O.message:"Could not load folder")}finally{h(!1)}},[e,c]),M=o.useCallback(()=>{x(!0);const T=[...r.map(U=>U.workspace),...n.map(U=>U.workspace),...a.map(U=>U.workspace)],O=kn(t.platform,jn(T,t.defaultWorkspacePath,(t.workspaces||[]).map(U=>U.path)));v(O)},[a,n,r,v,t.defaultWorkspacePath,t.platform,t.workspaces]),I=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,j=t.availableMem??t.freeMem??t.totalMem,w=I&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-j)/t.totalMem*100))):0,$=((P=t.loadavg)==null?void 0:P[0])||0;return s.jsxs("div",{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[s.jsx(Nr,{icon:s.jsx(cc,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?lm(t.uptime):"Waiting…"}),s.jsx(Nr,{icon:s.jsx(Mt,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(Nr,{icon:s.jsx(za,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(Nr,{icon:s.jsx(bu,{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(Uo,{value:I?Math.min(Math.round($/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:I?`${$.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(Uo,{value:w,max:100,label:"Memory",color:"#3b82f6",detail:I?`${_n(t.totalMem-j)} / ${_n(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${_n(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(fs,{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:yn(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(Cn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:C,directories:p,busy:b,error:N,confirmLabel:"Add workspace",onClose:()=>x(!1),onNavigate:T=>{v(T)},onConfirm:T=>{(async()=>{if(!T)return;await d(T)&&x(!1)})()}})]})}function gg(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 yg(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 aa(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 _i(e){if(!e||typeof e!="object")return null;if(aa(e))return e;const t=e,r=t.result;return aa(r)?r:aa(t.sourceConfig)?t.sourceConfig:null}function vg(e){const t=e.trim();return t||null}const Di=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],wg=[{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 jg({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,C]=o.useState([]),[y,p]=o.useState(""),g=o.useRef(null),b=o.useRef(null),h=j=>{m(w=>w.includes(j)?w.filter($=>$!==j):[...w,j])},N=()=>m([...Di]),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"),C(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"),C(["🚀 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)?(C(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}),C(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:wg.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:N,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:Di.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"),C([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function kg({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,C]=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===N(d))&&f(N(I))},N=M=>M.split("-").map(I=>I.charAt(0).toUpperCase()+I.slice(1)).join(" "),S=async()=>{if(!(!d||!u||!c)){C(!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")}C(!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 Ei(e){return e==="cli"||e==="acp"}function Sg(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 Ng(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 $i(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 Cg({machineId:e,providers:t,sendDaemonCommand:r}){var U;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),[C,y]=o.useState(!1),[p,g]=o.useState(null),[b,h]=o.useState("normal"),[N,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=_i(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=gg(R);if(k){const A=yg(k,t,{filterSchema:W=>W.filter(_=>_.key!=="enabled")});A.sort((W,_)=>W.category.localeCompare(_.category)||W.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(W=>W.map(_=>_.type===R?{..._,values:{..._.values,[k]:A}}:_));try{const W=await r(e,"set_provider_setting",{providerType:R,key:k,value:A});W!=null&&W.success||j()}catch{j()}d(null)},$=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()},O=async()=>{M(!0);try{const R=await r(e,"set_provider_source_config",{providerSourceMode:b,providerDir:vg(N)}),k=_i(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:N,onChange:R=>S(R.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void O(),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:"})," ",((U=p==null?void 0:p.providerRoots)==null?void 0:U.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 F=k.get(E.key),Y=!!(_.values[E.key]??E.default);F?(F.onCount+=Y?1:0,F.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 W=async(_,E)=>{for(const F of R)await w(F.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 F=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 W(_,!0),disabled:F,className:`machine-btn text-[9px] px-1.5 py-px ${F?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void W(_,!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}),Ei(R.category)&&(()=>{const k=t.find(_=>_.type===R.type),A=(k==null?void 0:k.enabled)===!0||R.values.enabled===!0,W=(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 ${Ng(W)}`,children:Sg(W)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void $(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"})]}),Ei(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:"})," ",$i(k==null?void 0:k.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",$i(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 W=parseInt(A.target.value)||0;k.min!==void 0&&W<k.min||k.max!==void 0&&W>k.max||w(R.type,k.key,W)},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(jg,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>x(null)}),C&&s.jsx(kg,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>y(!1),onCreated:()=>{y(!1),j()}})]})}const Tg=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Mg({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function Ig(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function Ag(e){return e.trim().toLowerCase()}function Mn(e,t){const r=Ag(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function Co(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function $s(e,t=220){const r=Co(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function Rg(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 Lg(e,t){return e.filter(r=>Mn([r.level,r.message],t))}function Bi(e){return`${e.timestamp}:${e.level}:${e.message}`}function Pg(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const c of e.entries)n.set(Bi(c),c);for(const c of t.entries)n.set(Bi(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 Dg(e,t){return e.split(`
|
|
74
|
+
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>Mn([r],t))}function Eg(e,t){return e.filter(r=>Mn([r.level,r.category,r.stage,r.interactionId,Co(r.payload)],t))}function $g(e,t){return e.filter(r=>Mn([r.kind,r.topic,r.interactionId,Co(r.payload)],t))}function Ki(e){return e==="warn"||e==="error"}function Bg({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=>Ki(a.level)).length+r.filter(a=>Ki(a.level)).length}}function Kg({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} ${$s(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}`:""} ${$s(i.payload,500)}`.trim())].join(`
|
|
78
|
+
`)),a.join(`
|
|
79
|
+
|
|
80
|
+
`)}function Wg({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,C]=o.useState(null),[y,p]=o.useState(!0),[g,b]=o.useState("info"),[h,N]=o.useState("all"),[S,v]=o.useState(!0),[M,I]=o.useState(!0),[j,w]=o.useState(""),[$,P]=o.useState(""),[T,O]=o.useState(0),U=o.useRef(0),R=o.useRef(0),k=o.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),A=o.useRef([]),W=o.useCallback(()=>{const ee={entries:[],kind:"empty",rawText:"",lastTs:0};k.current=ee,U.current=0,n([]),l(""),i("empty"),v(!0)},[]),_=o.useCallback(()=>{A.current=[],R.current=0,m([]),I(!0)},[]),E=o.useCallback(ee=>{ee!==g&&(W(),b(ee))},[g,W]),F=o.useCallback(ee=>{N(ye=>ye===ee?ye:ee)},[]),Y=o.useCallback(()=>{W(),_(),f([]),C(null),w(""),P(""),Is.clear()},[W,_]),be=o.useCallback(()=>{O(ee=>ee+1)},[]),ce=o.useCallback(async()=>{if(!e)return;const ee=U.current,ye=R.current,[we,je]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:g,since:ee}),t(e,"get_debug_trace",Mg({count:120,since:ye,category:h}))]);if(we.status==="fulfilled"){const Q=we.value,ie=(Q==null?void 0:Q.result)||Q,he=Rg(ie),se=Pg(k.current,he,300);k.current=se,U.current=se.lastTs,v(!1),w((Q==null?void 0:Q.success)===!1?String((Q==null?void 0:Q.error)||"Could not load daemon logs"):""),i(se.kind),l(se.rawText),n(se.entries)}else v(!1),w(we.reason instanceof Error?we.reason.message:"Could not load daemon logs");if(je.status==="fulfilled"){const Q=je.value,ie=(Q==null?void 0:Q.result)||Q;if((Q==null?void 0:Q.success)===!1)P(String((Q==null?void 0:Q.error)||"Could not load daemon trace"));else if(Array.isArray(ie==null?void 0:ie.trace)){const he=ie.trace,se=_g(A.current,he,120),de=he.reduce((ke,fe)=>Math.max(ke,Number(fe.ts||0)),ye);A.current=se,de>ye&&(R.current=de),P(""),m(se)}else P("");I(!1)}else I(!1),P(je.reason instanceof Error?je.reason.message:"Could not load daemon trace");f(Is.list({limit:120})),C(Date.now())},[g,e,t,h]);return o.useEffect(()=>{_()},[_,h]),o.useEffect(()=>{if(!e||(ce(),!y))return;const ee=setInterval(()=>{ce()},3e3);return()=>clearInterval(ee)},[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:$,setAutoRefresh:p,setLogLevel:E,setTraceCategory:F,refresh:be,clear:Y}}function Og({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 Wi(e){return e==="warn"||e==="error"}function Fg(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 Hg(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 Oi(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function Ug(e){const t=$s(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function zg(e){const t=$s(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function Vg({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:zg(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:Ug(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:Hg(i,c),severity:Fg(i),message:i,raw:i})}),a.sort((i,c)=>i.ts!==c.ts?i.ts-c.ts:Oi(i.source)-Oi(c.source))}function Gg(e){return`${e.source}:${e.severity}:${e.message}`}function qg(e){const t=e.filter(n=>Wi(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!Wi(n.severity))continue;const a=Gg(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 Yg(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Fi(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${Yg(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function Xg({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]",Fi(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(Fi):["No diagnostic events captured."]].join(`
|
|
85
|
+
`)),a.join(`
|
|
86
|
+
|
|
87
|
+
`)}function Jg(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Qg(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Zg({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=Ig(n,i),C=Lg(e,l),y=Dg(t,l),p=Eg(x,l),g=$g(a,l),b=Jg(C,c),h=c==="all"?y:[],N=Qg(p,c),S=c==="issues"?[]:g,v=Bg({daemonLogs:C,daemonRawLines:y,trace:p,webEvents:g}),M=Vg({daemonLogs:b,daemonRawLines:h,trace:N,webEvents:S}),I=qg(M),j=Og({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:f,daemonLogKind:r,daemonLogsCount:C.length,daemonRawLineCount:y.length,traceCount:p.length,webEventCount:g.length});return{filteredDaemonLogs:C,filteredDaemonRawLines:y,filteredTraceEntries:p,filteredWebEvents:g,visibleDaemonLogs:b,visibleDaemonRawLines:h,visibleTraceEntries:N,visibleWebEvents:S,quickFilterCounts:v,diagnosticEvents:M,diagnosticsSummary:I,sourceStates:j}}function ey(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function td(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Ea(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 oa(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 To(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function ty({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ea(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:td(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:To(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 sy({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 ry({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:Tg.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 ny({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 ${oa(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 ${oa(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:[To(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:td(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 ${oa(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: ",ey(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 ay({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()," · ",To(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function oy({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(ty,{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 ${Ea(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 ${Ea(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:$s(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:$s(u.payload,360)||"No payload"})]},u.id))]})]})]})}function iy({machineId:e,sendDaemonCommand:t}){const r=Wg({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(()=>Zg({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=Kg({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]),C=o.useCallback(async()=>{var p;const y=Xg({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(sy,{quickFilter:n,quickFilterCounts:f.quickFilterCounts,searchQuery:i,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:c,onCopyDiagnostics:()=>{C()},onCopyVisible:()=>{x()},onToggleAutoRefresh:()=>r.setAutoRefresh(y=>!y),onRefresh:r.refresh,onClear:r.clear}),s.jsx(ry,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(ny,{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(ay,{patterns:f.diagnosticsSummary.repeatedPatterns}),s.jsx(oy,{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 cy(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 sd(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 ly(e){var a;const t=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=sd((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 dy(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function ia(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 ca(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function la(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Hi(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 uy(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function my(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 fy(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 py({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,d]=o.useState(!1),m=kh(e,{enabled:!!e,includeSessions:!0,limit:ei,intervalMs:Sf}),u=m.diagnostics,f=m.loading,x=m.applyDiagnostics,C=o.useMemo(()=>cy({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:ei}),T=ca(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 O=`${P}:${T.sessionId}`;if(!(P==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
|
|
88
|
+
This will terminate the hosted runtime.`))){c(O);try{const U=await r(e,P,{sessionId:T.sessionId}),R=ca(U);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(U){const R=U instanceof Error?U.message:"Session host action failed";nt.showToast(R,"warning"),a(R)}finally{c(U=>U===O?null:U)}}},[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",{}),O=ca(T);if(!(O!=null&&O.success))throw new Error((O==null?void 0:O.error)||"Duplicate prune failed");const U=O.result||{},R=Array.isArray(U.prunedSessionIds)?U.prunedSessionIds.length:0,k=typeof U.duplicateGroupCount=="number"?U.duplicateGroupCount:0;nt.showToast(`Pruned ${R} duplicate runtime(s) across ${k} group(s)`,"success"),await p()}catch(T){const O=T instanceof Error?T.message:"Duplicate prune failed";nt.showToast(O,"warning"),a(O)}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]),N=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)||[]}:ly(h),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,h]),S=N.liveRuntimes,v=N.recoverySnapshots,M=N.inactiveRecords,I=o.useMemo(()=>fy(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]),$=(P,T)=>{var F;const O=i===`session_host_resume_session:${P.sessionId}`,U=i===`session_host_restart_session:${P.sessionId}`,R=i===`session_host_stop_session:${P.sessionId}`,k=sd(P.meta),A=y.get(P.sessionId),W=P.attachedClients.length===1?"1 client":`${P.attachedClients.length} clients`,_=T==="recovery"?"Recover":"Resume",E=dy(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 ${my(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:((F=P.writeOwner)==null?void 0:F.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:uy(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(nc,{size:11})," ",W]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Hi(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:O?`${_}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:U?"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(Yt,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Ip()})]}),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 ${C.toneClass}`,children:C.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:f||l,children:[s.jsx(ur,{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(cr,{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:Hi(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:la(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(cr,{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:[la(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(za,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ia("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=>$(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(Yt,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ia("recovery")}),v.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:v.map(P=>$(P,"recovery"))})]}),M.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ia("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:M.map(P=>$(P,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),j.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:j.map(P=>{var O;const T=h.find(U=>U.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)||((O=y.get(P.sessionId))==null?void 0:O.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:la(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 hy({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 da({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 ua({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 xy({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=Nl(e),f=ks(e,m),x=rr(e,f),C=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(da,{icon:s.jsx(Ut,{size:13}),children:"Current Chats"}),s.jsx(ua,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(y=>{const p=La(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:bn(p)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:hs(y)})]},y.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(da,{icon:s.jsx(cc,{size:13}),children:"Recent Launches"}),s.jsx(ua,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(y=>{const{metaText:p,updatedLabel:g}=Dl(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(da,{icon:s.jsx(cr,{size:13}),children:"Daemon Update"}),s.jsx(ua,{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(ur,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:C})]})]})})]})]})}function by(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function gy({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?"⭐ ":"",yn(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 yy={ide:{label:"IDE",plural:"IDEs",accent:"border-blue-500/[0.12]"},cli:{label:"CLI",plural:"CLIs",accent:"border-violet-500/[0.12]"},acp:{label:"ACP Agent",plural:"ACP agents",accent:"border-emerald-500/[0.12]"}};function Wr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ma({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const f=Bs(),{handleLaunchIde:x,handleStopCli:C,handleRestartIde:y,handleStopIde:p,handleDetectIdes:g,launchingIde:b,launchingAgentType:h,addLog:N}=c,[S,v]=o.useState(null),M=o.useCallback(L=>{L&&f(Jt(L))},[f]),I=yy[e],j=e==="ide",w=e==="acp",$=o.useMemo(()=>n.filter(L=>xs(L,e)),[e,n]),P=o.useMemo(()=>new Map($.map(L=>[L.type,L.displayName||L.type])),[$]),[T,O]=o.useState(""),[U,R]=o.useState(""),[k,A]=o.useState([]),[W,_]=o.useState(""),[E,F]=o.useState(""),[Y,be]=o.useState([]),[ce,ee]=o.useState(!1),[ye,we]=o.useState(!1),[je,Q]=o.useState(""),[ie,he]=o.useState(!1),[se,de]=o.useState(()=>wt()),[ke,fe]=o.useState(null),[xe,Z]=o.useState(m?"__custom__":d||t.defaultWorkspaceId||""),[me,oe]=o.useState(m||""),[le,ae]=o.useState([]),[X,ue]=o.useState(!1),[q,Ae]=o.useState(""),[Te,$e]=o.useState([]),[Ue,B]=o.useState(!1),[Se,Me]=o.useState(""),De=o.useRef(null),[Ke,He]=o.useState(null),Xe=o.useRef("__home__"),[st,mt]=o.useState("__home__"),[ht,xt]=o.useState(!1),Ce=o.useRef(0),ze=le.filter(L=>!a.some(ne=>ne.type===L&&bt(ne.status)!=="stopped")),Qe=o.useRef({});o.useEffect(()=>{t.defaultWorkspaceId&&!xe&&Z(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),o.useEffect(()=>{if(m){Z("__custom__"),oe(m);return}d&&(Z(d),oe(""))},[d,m]),o.useEffect(()=>{j||T&&($.some(L=>L.type===T)||(O(""),F("")))},[$,j,T]);const Ge=(()=>{if(xe==="__custom__")return me.trim();if(!xe)return"";const L=(t.workspaces||[]).find(ne=>ne.id===xe);return(L==null?void 0:L.path)||""})(),rt=o.useCallback(L=>{const ne=Qe.current[L];ne&&(clearTimeout(ne),delete Qe.current[L]),ae(pe=>pe.includes(L)?pe.filter(We=>We!==L):pe)},[]),K=o.useRef(new Set),H=o.useCallback(async L=>{if(l){B(!0),Me("");try{const ne=await Sn(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{B(!1)}}},[r,l]),V=o.useCallback(()=>{if(!l)return;Z("__custom__"),ue(!0);const L=a.map(pe=>pe.workspace),ne=kn(t.platform,jn(me.trim(),Ge,m,L,t.defaultWorkspacePath,(t.workspaces||[]).map(pe=>pe.path)));H(ne)},[me,m,H,t.defaultWorkspacePath,t.platform,t.workspaces,a,Ge,l]),te=o.useCallback(L=>{const ne=String(L.workspace||"").trim();if(!ne)return;const pe=(t.workspaces||[]).find(We=>Wr(We.path)===Wr(ne));if(pe){Z(pe.id),oe("");return}Z("__custom__"),oe(ne)},[t.workspaces]),D=o.useCallback(L=>{const ne=String(L.workspace||"").trim();if(!ne)return{workspaceId:null,workspacePath:"",useHome:!0};const pe=(t.workspaces||[]).find(We=>Wr(We.path)===Wr(ne));return pe?{workspaceId:pe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ne,useHome:!1}},[t.workspaces]),G=o.useCallback(async L=>{if(!l||!L||e!=="cli"){be([]),ee(!1),we(!1),Q("");return}const ne=Ce.current+1;Ce.current=ne,ee(!0),Q("");try{const pe=await l(r,"list_saved_sessions",{providerType:L,kind:"cli",limit:30});if(Ce.current!==ne)return;const We=(pe==null?void 0:pe.result)??pe;be(Array.isArray(We==null?void 0:We.sessions)?We.sessions:[])}catch(pe){if(Ce.current!==ne)return;be([]),Q(pe instanceof Error?pe.message:"Could not load saved sessions")}finally{Ce.current===ne&&(ee(!1),we(!0))}},[e,r,l]),J=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(Da(r,L))},[e,r]),ve=o.useCallback((L,ne)=>{e==="ide"||!L||(_b(r,L,ne),A(Da(r,L)))},[e,r]);o.useEffect(()=>{Ce.current+=1,F(""),re(T),we(!1),be([]),Q(""),ee(!1)},[e,re,G,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||F("")},[Y,E]);const _e=o.useCallback((L,ne)=>{De.current=ne,Xe.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(pe=>pe.includes(L)?pe:[...pe,L]);const ne=Qe.current[L];ne&&clearTimeout(ne),Qe.current[L]=setTimeout(()=>{ae(pe=>pe.includes(L)?pe.filter(We=>We!==L):pe),delete Qe.current[L]},2e4)},[]);o.useEffect(()=>{for(const ne of a)bt(ne.status)!=="stopped"&&(le.includes(ne.type)&&!K.current.has(ne.type)&&(K.current.add(ne.type),N("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));K.current.forEach(ne=>{!le.includes(ne)&&!L.has(ne)&&K.current.delete(ne)})},[N,rt,a,le,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",{}),pe=(ne==null?void 0:ne.result)||ne;pe!=null&&pe.success&&(pe!=null&&pe.ideExtensions)&&Re(pe.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,pe=(L==null?void 0:L.workspacePath)??Ge;if(j){await x(ne,pe?{workspace:pe}:void 0)&&Ee(ne);return}const We=await c.runLaunchCliCore({cliType:ne,dir:L!=null&&L.workspaceId?void 0:pe||void 0,workspaceId:(L==null?void 0:L.workspaceId)||void 0,useHome:(L==null?void 0:L.useHome)||!(L!=null&&L.workspaceId)&&!pe,argsStr:(L==null?void 0:L.argsStr)??(U||void 0),model:(L==null?void 0:L.model)??(w&&W||void 0),resumeSessionId:(L==null?void 0:L.resumeSessionId)||!w&&e==="cli"&&ne===T&&E||void 0});if(We.success||We.pending){const Pe=(L==null?void 0:L.argsStr)??U;!j&&(Pe!=null&&Pe.trim())&&(Yl(r,ne,Pe),re(ne)),Ee(ne),We.success&&We.sessionId&&M(We.sessionId)}},[c,x,w,j,U,W,re,Ee,r,M,Ge,E,T]),yt=Jc(j?"ide":w?"acp":"cli",!j&&!w&&!!E),Ve=Qc(j?"ide":w?"acp":"cli",!j&&!w&&!!E),ge=()=>{var Pe;const L=j?it(T):P.get(T)||T,ne=!j&&!w&&!!E,{options:pe,selectedKey:We}=us({machine:t,currentWorkspaceId:xe&&xe!=="__custom__"?xe:null,currentWorkspacePath:Ge});_e({title:ne?co(L):os("start-fresh",L),description:ne?lo():is("start-fresh"),confirmLabel:yt,busyLabel:Ve,workspaceOptions:pe,selectedWorkspaceKey:We,details:[{label:"Mode",value:I.label},{label:"Provider",value:L},...!j&&e==="cli"&&E?[{label:"Resume",value:((Pe=Y.find(Oe=>Oe.providerSessionId===E))==null?void 0:Pe.title)||E}]:[],...!j&&U.trim()?[{label:"Arguments",value:U.trim()}]:[],...w&&W.trim()?[{label:"Model",value:W.trim()}]:[]]},async()=>{const Oe=pe.find(ot=>ot.key===Xe.current);Oe!=null&&Oe.workspaceId?(Z(Oe.workspaceId),oe("")):Oe!=null&&Oe.workspacePath?(Z("__custom__"),oe(Oe.workspacePath)):(Z(""),oe("")),await dt({workspaceId:(Oe==null?void 0:Oe.workspaceId)??null,workspacePath:(Oe==null?void 0:Oe.workspacePath)??"",useHome:!(Oe!=null&&Oe.workspaceId)&&!(Oe!=null&&Oe.workspacePath)})})},z=L=>{j?p(L):C(L.type,L.workspace,L.id)},Ie=o.useCallback(async(L,ne,pe=!1)=>{if(L.mode===ne){pe&&L.sessionId&&M(L.sessionId);return}if(!l||!L.sessionId){pe&&L.sessionId&&M(L.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:L.sessionId,cliType:L.type,mode:ne}),pe&&M(L.sessionId)}catch(We){const Pe=xl(We);hl(We)?console.warn(Pe?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",We instanceof Error?We.message:String(We)):console.error("Failed to switch CLI view mode:",We)}},[r,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"),pe=L.running||!!ne,We=!!ne&&ne.cdpConnected,Pe=le.includes(L.type||L.id||""),Oe=T===(L.type||"");return s.jsxs("button",{onClick:()=>{if(We&&ne){const ot=ne.sessionId;ot?f(Jt(ot),{state:{openRemoteForTabKey:ot}}):f("/dashboard",{state:{openRemoteForTabKey:ne.id}});return}Pe||O(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 ${We?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Oe?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:b&&b!==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)}),pe&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${We?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:L.name||it(L.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${We?"text-green-400":Pe?"text-orange-400":Oe?"text-accent-primary":"text-text-muted"}`,children:We?"Open Session":Pe?"Starting...":Oe?"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(fu,{size:14})," Scan System"]})]}):$.length>0?$.map(L=>{const ne=T===L.type,pe=le.includes(L.type),Pe=!!a.find(Oe=>Oe.type===L.type&&bt(Oe.status)!=="stopped");return s.jsxs("button",{onClick:()=>O(Oe=>Oe===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 ${pe?"text-orange-400":ne?"text-accent-primary":"text-text-muted"}`,children:pe?"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):$.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(gy,{machine:t,selectedWorkspace:xe,resolvedWorkspacePath:Ge,customPath:me,canBrowse:!!l,onWorkspaceChange:Z,onCustomPathChange:oe,onOpenBrowseDialog:V}),!j&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&s.jsx(Jl,{busy:!!h||!!b||le.includes(T),savedSessionsLoading:ce,savedSessionsError:je,savedSessionsLoaded:ye,savedSessionsCount:Y.length,selectedSession:Le,onRefresh:()=>void G(T),onOpenHistory:()=>{T&&(he(!0),Xl({hasLoadedInitialResults:ye,isLoading:ce})&&G(T))},onClearSelection:()=>F("")}),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:W,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:U,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:()=>ve(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:ge,disabled:!!h||!!b||le.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+le.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,pe=!j&&!w?L:null,We=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(_s,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(_s,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(pe==null?void 0:pe.mode)&&s.jsx("span",{className:pe.mode==="chat"?"text-violet-400":"text-text-secondary",children:pe.mode==="chat"?"Chat view":"Terminal view"})]}),pe&&(pe.runtimeKey||pe.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[pe.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 ",pe.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 ${pe.runtimeKey}`),v(pe.runtimeKey||null),window.setTimeout(()=>{v(Oe=>Oe===pe.runtimeKey?null:Oe)},1200)},children:S===pe.runtimeKey?"Copied":"Copy"})]}),pe.runtimeWriteOwner&&s.jsx("span",{style:{color:pe.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:pe.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:by(pe.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${We==="stopped"?"bg-red-500/[0.08] text-red-500":We==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:We}),j&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Pe=L.sessionId;if(Pe){f(Jt(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:Oe,selectedKey:ot}=us({machine:t,currentWorkspacePath:Pe});_e({title:os("restart-ide",it(L.type)),description:is("restart-ide"),confirmLabel:Ds("restart-ide"),busyLabel:Es("restart-ide"),workspaceOptions:Oe,selectedWorkspaceKey:ot,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:it(L.type)}]},async()=>{const Nt=Oe.find(Vt=>Vt.key===Xe.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(ur,{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(Ut,{size:14})}),pe&&We!=="stopped"&&s.jsxs(s.Fragment,{children:[pe.mode&&s.jsx(ao,{mode:pe.mode,onChange:Pe=>void Ie(pe,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:pe.mode==="chat"?s.jsx(Ut,{size:14}):s.jsx(Mt,{size:13})})]}),We==="stopped"?s.jsx("button",{onClick:()=>{const Pe=L.workspace||"",Oe=j?it(L.type):ct(L),{options:ot,selectedKey:Nt}=us({machine:t,currentWorkspacePath:Pe});_e({title:os("restart-stopped",Oe),description:is("restart-stopped"),confirmLabel:Ds("restart-stopped"),busyLabel:Es("restart-stopped"),workspaceOptions:ot,selectedWorkspaceKey:Nt,details:[{label:"Mode",value:I.label},{label:"Provider",value:Oe}]},async()=>{const pt=ot.find(Vt=>Vt.key===Xe.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:le.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:le.includes(L.type)?"⏳":s.jsx(Va,{size:14})}):s.jsx("button",{onClick:()=>z(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] ${sn(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 Oe=`${ne.type}.${Pe.type}`;et(Oe);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)})]}),X&&l&&s.jsx(Cn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:q,directories:Te,busy:Ue,error:Se,confirmLabel:"Use this folder",onClose:()=>ue(!1),onNavigate:L=>{H(L)},onConfirm:L=>{oe(L),Z("__custom__"),ue(!1)}}),Ke&&s.jsx(wo,{title:Ke.title,description:Ke.description,details:Ke.details,workspaceOptions:Ke.workspaceOptions,selectedWorkspaceKey:st,onWorkspaceChange:L=>{Xe.current=L,mt(L)},confirmLabel:Ke.confirmLabel,busyLabel:Ke.busyLabel,busy:ht,onConfirm:Ne,onCancel:()=>{De.current=null,He(null)}}),ie&&J&&s.jsx(uo,{activeConv:J,ides:[],isCreatingChat:!1,isRefreshingHistory:ce,savedSessions:Y,isSavedSessionsLoading:ce,isResumingSavedSessionId:ke,savedHistoryFilters:se,missingWorkspaceResumePath:Ge||null,onSavedHistoryFiltersChange:de,onClose:()=>he(!1),onNewChat:()=>{F(""),he(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{G(T)},onResumeSavedSession:L=>{if(!L.canResume||ke)return;const ne=D(L);F(L.providerSessionId),te(L),fe(L.providerSessionId),he(!1),dt({type:L.providerType,workspaceId:ne.workspaceId,workspacePath:ne.workspacePath,useHome:ne.useHome,resumeSessionId:L.providerSessionId}).finally(()=>{fe(pe=>pe===L.providerSessionId?null:pe)})}})]})}const Ui=[{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 vy({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[C,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:Ui.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 ${C===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] ${C===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=Ui.find(b=>b.id===C))==null?void 0:g.helper})]}),C==="ide"&&s.jsx(ma,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),C==="cli"&&s.jsx(ma,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),C==="acp"&&s.jsx(ma,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x})]})}function wy({onNicknameSynced:e}={}){var oe,le,ae,X,ue,q,Ae,Te,$e,Ue;const{id:t}=Ed(),r=Bs(),n=Wa(),{sendCommand:a}=gt(),i=pr(),c=ul(),l=Hc(),d=l.ides||[],m=l.initialLoaded??!0,u=d.find(B=>B.id===t&&B.type==="adhdev-daemon"),f=d.some(B=>B.type==="adhdev-daemon"),x=t?(oe=l.connectionRetryStatuses)==null?void 0:oe[t]:void 0,C=!!(x!=null&&x.blocked),[y,p]=o.useState("workspace"),[g,b]=o.useState(null),h=o.useCallback((B,Se)=>{b({daemonId:B,workspace:Se})},[]),[N,S]=o.useState("ide"),v=o.useRef(null),[M,I]=o.useState(null),j=o.useRef("__home__"),[w,$]=o.useState("__home__"),[P,T]=o.useState(!1),O=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 B=u.machine;(typeof(B==null?void 0:B.cpus)!="number"||typeof(B==null?void 0:B.totalMem)!="number"||typeof(B==null?void 0:B.arch)!="string"||typeof(B==null?void 0:B.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[y,c,u,t]),jh(t&&y==="overview"?[t]:[],{enabled:y==="overview",intervalMs:vf});const U=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},R=xg({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:O});o.useEffect(()=>nt.onToast(Se=>{l.setToasts(De=>{if(De.some(Xe=>Xe.message===Se.message&&Se.timestamp-Xe.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(Ke=>Ke.id!==Se.id)),Me)}),[l]);const k=(u==null?void 0:u.availableProviders)||[],A={};for(const B of k)A[B.type]=B.icon;const W=B=>A[B]||"",_=u?{id:u.id,hostname:gc(u,{fallbackId:u.id}),platform:((le=u.machine)==null?void 0:le.platform)||"unknown",arch:((ae=u.machine)==null?void 0:ae.arch)||"",cpus:((X=u.machine)==null?void 0:X.cpus)||0,totalMem:((ue=u.machine)==null?void 0:ue.totalMem)||0,freeMem:(q=u.machine)==null?void 0:q.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(B=>B.daemonId===t&&B.type!=="adhdev-daemon").filter(B=>!lr(B)&&!Cs(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,version:B.version||"",instanceId:B.instanceId||"",status:B.status,workspace:B.workspace||null,terminals:B.terminals||0,aiAgents:bm(B.aiAgents||(B.agents||[]).map(Se=>({id:Se.name,name:Se.name,status:Se.status,version:Se.version}))),activeChat:B.activeChat||null,chats:B.chats||[],childSessions:B.childSessions||[],cdpConnected:B.cdpConnected||!1,daemonId:t})),F=d.filter(B=>B.daemonId===t&&lr(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,cliName:B.cliName||B.type,status:B.status,workspace:B.workspace||"",activeChat:B.activeChat||null,providerSessionId:B.providerSessionId,mode:B.mode,runtimeKey:B.runtimeKey,runtimeDisplayName:B.runtimeDisplayName,runtimeWorkspaceLabel:B.runtimeWorkspaceLabel,runtimeWriteOwner:B.runtimeWriteOwner||null,runtimeAttachedClients:B.runtimeAttachedClients||[],daemonId:t})),Y=d.filter(B=>B.daemonId===t&&Cs(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,acpName:B.cliName||B.type,status:B.status,workspace:B.workspace||"",activeChat:B.activeChat||null,providerSessionId:B.providerSessionId,daemonId:t})),be=u?Tt(u,{fallbackId:t}):"",ce="workspace",ee=n.state,ye=ee==null?void 0:ee.initialMachineTab,we=ee==null?void 0:ee.initialWorkspaceCategory,je=ee==null?void 0:ee.initialWorkspaceId,Q=ee==null?void 0:ee.initialWorkspacePath,ie=ye==="ides"||ye==="clis"||ye==="acps"?"workspace":ye||ce,he=ye==="ides"?"ide":ye==="clis"?"cli":ye==="acps"?"acp":we,se=[...E.map(B=>{var Se,Me,De,Ke,He;return{id:`ide:${B.type}:${B.workspace||""}`,label:((Se=B.activeChat)==null?void 0:Se.title)||B.type,kind:"ide",providerType:B.type,subtitle:B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:((He=(Ke=(De=(Me=B.activeChat)==null?void 0:Me.messages)==null?void 0:De.at)==null?void 0:Ke.call(De,-1))==null?void 0:He.timestamp)||0}}),...F.map(B=>{var Se,Me,De,Ke,He;return{id:`cli:${B.type}:${B.workspace||""}`,label:((Se=B.activeChat)==null?void 0:Se.title)||B.cliName,kind:"cli",providerType:B.type,providerSessionId:B.providerSessionId,subtitle:B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:((He=(Ke=(De=(Me=B.activeChat)==null?void 0:Me.messages)==null?void 0:De.at)==null?void 0:Ke.call(De,-1))==null?void 0:He.timestamp)||0}}),...Y.map(B=>{var Se,Me,De,Ke,He;return{id:`acp:${B.type}:${B.workspace||""}`,label:((Se=B.activeChat)==null?void 0:Se.title)||B.acpName,kind:"acp",providerType:B.type,providerSessionId:B.providerSessionId,subtitle:ps(B.summaryMetadata)||B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:((He=(Ke=(De=(Me=B.activeChat)==null?void 0:Me.messages)==null?void 0:De.at)==null?void 0:Ke.call(De,-1))==null?void 0:He.timestamp)||0}})].sort((B,Se)=>(Se.lastLaunchedAt||0)-(B.lastLaunchedAt||0)),de=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(B=>({id:B.id,label:B.title||B.providerName||B.providerType,kind:B.kind,providerType:B.providerType,providerSessionId:B.providerSessionId,subtitle:ps(B.summaryMetadata)||B.workspace||void 0,workspace:B.workspace,summaryMetadata:B.summaryMetadata,lastLaunchedAt:B.lastLaunchedAt})):se,ke=o.useMemo(()=>{var Se;const B=((Se=l.connectionStates)==null?void 0:Se[t||""])||void 0;return d.filter(Me=>Me.daemonId===t&&Me.type!=="adhdev-daemon").flatMap(Me=>mo(Me,{connectionStates:t&&B?{[t]:B}:void 0,defaultConnectionState:B})).filter(Me=>!(Me.transport==="pty"&&Me.mode==="terminal")).sort((Me,De)=>La(De)-La(Me))},[d,l.connectionStates,t]),fe=o.useCallback(B=>{const Se=Nn(B);Se&&r(Jt(Se))},[r]),xe=o.useCallback(()=>{v.current&&(T(!0),v.current().finally(()=>{v.current=null,T(!1),I(null)}))},[]),Z=o.useCallback(B=>{if(!_)return;const{options:Se,selectedKey:Me}=us({machine:_,currentWorkspacePath:B.workspace}),De=async()=>{S(B.kind),p("workspace")};v.current=async()=>{const Ke=Se.find(st=>st.key===j.current),He=(Ke==null?void 0:Ke.workspacePath)??null,Xe=(Ke==null?void 0:Ke.workspaceId)??null;if(B.kind==="ide"&&B.providerType){await R.handleLaunchIde(B.providerType,He?{workspace:He}:void 0);return}if((B.kind==="cli"||B.kind==="acp")&&B.providerType){await R.runLaunchCliCore({cliType:B.providerType,dir:Xe?void 0:He||"",workspaceId:Xe||void 0,model:B.kind==="acp"&&vc(B.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:B.providerSessionId});return}await De()},j.current=Me,$(Me),I({title:B.kind==="ide"?os("restart-ide",B.label):B.providerSessionId?co(B.label):os("start-fresh",B.label),description:B.kind==="ide"?is("restart-ide"):B.providerSessionId?lo():is("start-fresh"),confirmLabel:B.kind==="ide"?Ds("restart-ide"):B.providerSessionId?cn(!0):Ds("start-fresh"),busyLabel:B.kind==="ide"?Es("restart-ide"):B.providerSessionId?oo(!0):Es("start-fresh"),workspaceOptions:Se,details:[{label:"Mode",value:B.kind.toUpperCase()},...B.providerType?[{label:"Provider",value:B.providerType}]:[]]})},[R,_]);if(o.useEffect(()=>{p(ie)},[ce,ie,t]),o.useEffect(()=>{he&&S(he)},[he,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:U,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 me=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Mt,{size:14})," Workspace"]}),count:E.length+F.length+Y.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Yt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(hn,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(pu,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(uu,{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:U,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:B=>R.setNicknameInput(B.target.value),onKeyDown:B=>{B.key==="Enter"&&R.handleSaveNickname(),B.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}),C?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:me.map(B=>s.jsxs("button",{onClick:()=>p(B.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${y===B.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[B.label,B.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${y===B.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:B.count})]},B.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[y==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(xy,{machineEntry:u,providers:k,recentLaunches:de,currentConversations:ke,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",Cl(u))}catch{}},onOpenRecent:Z,onOpenConversation:fe}),s.jsx(vy,{machine:_,machineId:t,providers:k,ideSessions:E,cliSessions:F,acpSessions:Y,actions:R,getIcon:W,initialCategory:N,initialWorkspaceId:je,initialWorkspacePath:Q,sendDaemonCommand:a,onOpenGitDialog:h})]}),y==="providers"&&s.jsx(Cg,{machineId:t,providers:k,sendDaemonCommand:a}),y==="overview"&&s.jsx(bg,{machineId:t,machine:_,ideSessions:E,cliSessions:F,acpSessions:Y,actions:R,sendDaemonCommand:a}),y==="session-host"&&s.jsx(py,{machineId:t,cliSessions:F,sendDaemonCommand:a}),y==="logs"&&s.jsx(iy,{machineId:t,sendDaemonCommand:a})]})})}),R.launchPick&&_&&s.jsx(hy,{machine:_,launchPick:R.launchPick,actions:R}),M&&s.jsx(wo,{title:M.title,description:M.description,details:M.details,workspaceOptions:M.workspaceOptions,selectedWorkspaceKey:w,onWorkspaceChange:B=>{j.current=B,$(B)},confirmLabel:M.confirmLabel,busyLabel:M.busyLabel,busy:P,onConfirm:xe,onCancel:()=>{v.current=null,I(null)}}),g&&s.jsx(ed,{daemonId:g.daemonId,workspace:g.workspace,onClose:()=>b(null)}),s.jsx(Zc,{toasts:l.toasts||[],onDismiss:B=>l.setToasts(Se=>Se.filter(Me=>Me.id!==B)),onClickToast:B=>{B.targetKey&&r(Jt(B.targetKey))}}),s.jsx("style",{children:`
|
|
90
|
+
@keyframes toast-in {
|
|
91
|
+
from { opacity: 0; transform: translateX(40px); }
|
|
92
|
+
to { opacity: 1; transform: translateX(0); }
|
|
93
|
+
}
|
|
94
|
+
`})]})}const zi="hermes-cli, claude-cli, codex-cli, gemini-cli",rd=new Set(["hermes-cli","claude-cli","codex-cli","gemini-cli"]);function jy(e){const t=new Set;return e.split(",").map(r=>r.trim()).filter(r=>r&&rd.has(r)).filter(r=>t.has(r)?!1:(t.add(r),!0))}function ky(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(a=>a&&rd.has(a)).filter(a=>r.has(a)?!1:(r.add(a),!0))}function Sy({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=Ml(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(kt,{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(Ql,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function Ny(){const{sendCommand:e}=gt(),{ides:t}=Qt(),r=t.find(R=>R.daemonMode||R.type==="adhdev-daemon"),n=(r==null?void 0:r.id)||"",a=[];if(r){const R=r.availableProviders||[];for(const k of R)k.category==="cli"&&a.push({id:k.type||k.id,name:k.displayName||k.name||k.type,meshCoordinator:k.meshCoordinator})}const[i,c]=o.useState([]),[l,d]=o.useState(null),[m,u]=o.useState(!0),[f,x]=o.useState(null),[C,y]=o.useState(!1),[p,g]=o.useState(""),[b,h]=o.useState(""),[N,S]=o.useState(!1),[v,M]=o.useState(""),[I,j]=o.useState(zi),w=i.find(R=>R.id===l)||null,$=o.useCallback(async()=>{if(n){u(!0);try{const R=await e(n,"list_meshes");R!=null&&R.success?(c(R.meshes||[]),x(null)):x((R==null?void 0:R.error)||"Failed to load meshes")}catch(R){x((R==null?void 0:R.message)||"Failed to load meshes")}finally{u(!1)}}},[n,e]);o.useEffect(()=>{$()},[$]);async function P(){var R;if(!(!n||!p.trim()))try{const k=await e(n,"create_mesh",{name:p.trim(),repoIdentity:b.trim()||void 0});k!=null&&k.success?(y(!1),g(""),h(""),await $(),d(((R=k.mesh)==null?void 0:R.id)||null)):x((k==null?void 0:k.error)||"Create failed")}catch(k){x((k==null?void 0:k.message)||"Create failed")}}async function T(R){if(!(!n||!confirm("Delete this mesh?")))try{await e(n,"delete_mesh",{meshId:R}),d(null),await $()}catch(k){x((k==null?void 0:k.message)||"Delete failed")}}async function O(){if(!(!n||!l||!v.trim()))try{const R=await e(n,"add_mesh_node",{meshId:l,workspace:v.trim(),providerPriority:jy(I)});R!=null&&R.success?(S(!1),M(""),j(zi),await $()):x((R==null?void 0:R.error)||"Add node failed")}catch(R){x((R==null?void 0:R.message)||"Add node failed")}}async function U(R){if(!(!n||!l))try{await e(n,"remove_mesh_node",{meshId:l,nodeId:R}),await $()}catch(k){x((k==null?void 0:k.message)||"Remove node failed")}}return n?w?s.jsxs(sr,{icon:s.jsx(jr,{}),title:w.name,subtitle:w.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:()=>T(w.id),children:"Delete"})]}),children:[f&&s.jsx(Ns,{variant:"error",className:"mb-4",children:f}),s.jsxs(kt,{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:()=>S(!0),children:"+ Add Node"})}),N&&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:()=>S(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(vt,{size:16})})]}),s.jsx(Ar,{label:"Workspace Path",children:s.jsx(Rr,{value:v,onChange:R=>M(R.target.value),placeholder:"/Users/dev/projects/myapp",autoFocus:!0})}),s.jsx(Ar,{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(Rr,{value:I,onChange:R=>j(R.target.value),placeholder:"hermes-cli, claude-cli, codex-cli, gemini-cli",onKeyDown:R=>{R.key==="Enter"&&O()}})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:O,disabled:!v.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>S(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),w.nodes.length===0?s.jsx(ln,{icon:s.jsx(fs,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:w.nodes.map(R=>{const k=ky(R);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:R.workspace.split("/").pop()}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:R.workspace}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-1 font-mono",children:["providerPriority: ",k.length?k.join(" → "):"not configured"]})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:()=>U(R.id),children:s.jsx(vt,{size:14})})]},R.id)})})]}),s.jsx(Sy,{meshId:w.id,availableCliAgents:a})]}):s.jsxs(sr,{icon:s.jsx(jr,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>y(!0),children:"+ Create Mesh"}),children:[f&&s.jsx(Ns,{variant:"error",className:"mb-4",children:f}),C&&s.jsx(kt,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Ar,{label:"Name",children:s.jsx(Rr,{value:p,onChange:R=>g(R.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(Ar,{label:"Repo Identity (optional)",children:s.jsx(Rr,{value:b,onChange:R=>h(R.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:P,disabled:!p.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(!1),children:"Cancel"})]})]})}),m?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):i.length===0?s.jsx(ln,{icon:s.jsx(jr,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(R=>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(R.id),children:[s.jsx("div",{className:"font-semibold text-sm",children:R.name}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:R.repoIdentity||"No repo identity"}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[R.nodes.length," node(s)"]})]},R.id))})]}):s.jsx(sr,{icon:s.jsx(jr,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})})}function Mo(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Cy(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=Mo();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 Et(e,t){return await fetch(Cy(e),{credentials:"same-origin",...t})}function nd(){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 Ty{constructor(){Je(this,"adapters",new Map);Je(this,"states",new Map);Je(this,"runtimeListeners",new Map);Je(this,"screenshotCallbacks",new Map);Je(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 Et(`${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 Ty;function My(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Mo();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Or=My(),Vi=3e3,Iy=3e4;let Pt=null,Ay=0;const pn=new Map;let es=null,ar=null;function Gi(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Ys(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function Ry(e){return e==="connected"?"connected":e}async function Xr(e,t,r){const n=sl(e,r||{}),a=Pt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++Ay}_${Date.now()}`;return new Promise((c,l)=>{const d=setTimeout(()=>{pn.delete(i),l(new Error(`WS command timeout: ${t}`))},3e4);pn.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 $a(e,t){const r=Pt;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 Ly(e,t,r){const n=Pt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=sl(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 Py{constructor(t){Je(this,"daemonId");Je(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Pt==null?void 0:Pt.readyState)===WebSocket.OPEN}get connectionState(){return(Pt==null?void 0:Pt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Xr(this.daemonId,t,r)}async sendInput(t,r){return Xr(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,es&&(clearInterval(es),es=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Xr(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(),es=setInterval(r,2e3)}stopScreenshots(t){es&&(clearInterval(es),es=null)}}let At=null;function _y(e){return(!At||At.daemonId!==e)&&(At=new Py(e)),At}function Dy({children:e}){const t=o.useRef(ir()),r=ir();t.current=r;const{setUserName:n}=Qt(),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),ar==null||ar(p,g)},[]),m=o.useRef(null),u=o.useRef(),f=o.useRef(Vi),x=o.useRef(!0),C=o.useRef(!1),y=o.useRef("initial_connect");return o.useEffect(()=>{x.current=!0,C.current=!1;function p(){var h,N;if(!x.current||((h=m.current)==null?void 0:h.readyState)===WebSocket.OPEN||((N=m.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Or}...`),Ys("connect_attempt",{url:Or,reason:y.current,delayMs:f.current});let b;try{b=new WebSocket(Or)}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=Vi,Ys("open",{url:Or,reason:y.current}),Ht.resubscribeAll({sendData:$a}),console.log("[Standalone WS] Connected")},Pt=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=pn.get(I.requestId);j&&(pn.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&&Ht.publish(j);return}if(I.type==="status"||I.type==="initial_state"){const j=I.data;if(!j)return;const{injectEntries:w,markLoaded:$,getIdes:P}=t.current,T=j.instanceId||"standalone",O=P().find(k=>k.id===T),U=_y(T);Wt.register(T,U),Wt.setState(T,"connected"),d("connected",T),Wt.emitStatus(T,j);const R=on(j,{daemonId:T,existingDaemon:O,existingEntries:P()});Gi("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}))}),Gi("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]}),$(),c.current!==T&&((M=i.current)==null||M.call(i),c.current=T,i.current=Ht.subscribe({sendData:$a},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(),W=A.find(E=>E.id===T),_=on(k.status,{daemonId:T,existingDaemon:W,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&&(At==null||At.stopScreenshots(),At&&Wt.setState(At.daemonId,"disconnected"),d("disconnected"),m.current=null,y.current=`close:${S.code}${S.wasClean?":clean":":unclean"}`,Ys("close",{code:S.code,reason:S.reason||"",wasClean:S.wasClean}),g())},b.onerror=S=>{C.current||!x.current||(y.current="error",Ys("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...`),Ys("schedule_reconnect",{reason:y.current,delayMs:b}),u.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,Iy),p()},b)}return p(),()=>{var b;x.current=!1,C.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,Pt=null),At&&(At.stopScreenshots(),Wt.unregister(At.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function Ey({children:e}){const[t,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(ar=(c,l)=>{r(c),l&&a(l)},()=>{ar=null}),[]);const i=o.useMemo(()=>{const c=t==="connected",l=Ry(t),d={};return n&&(d[n]=l),d.standalone=l,{wsStatus:t,isConnected:c,connectionStates:d}},[t,n]);return s.jsx(eu,{connectionOverrides:i,children:s.jsx(Dy,{children:e})})}const ad="adhdev_standalone_font_preferences",ms={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},In=[{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"}],dr=[{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"}],$y=new Set(In.map(e=>e.id)),By=new Set(dr.map(e=>e.id));function Bt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Jr("chat",t.chat),code:Jr("code",t.code),terminal:Jr("terminal",t.terminal)}}function Jr(e,t){const r=ms[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"?$y:By).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function Qr(e,t){var a;const r=Jr(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?In:dr;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function Ky(e){const t=Bt(e),r=Qr("chat",t.chat),n=Qr("code",t.code),a=Qr("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function ss(e,t=document.documentElement){const r=Bt(e),n=Ky(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))t.style.setProperty(a,i);return r}function Ba(e){const t=Bt(e);try{localStorage.setItem(ad,JSON.stringify(t))}catch{}return t}function Wy(){try{const e=localStorage.getItem(ad);if(e)return Bt(JSON.parse(e))}catch{}return ms}function Oy(){return ss(Wy())}function Xs(e,t){var n;const r=e==="chat"?In:dr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const Fy=[{id:"dashboard",path:"/dashboard",icon:s.jsx(rc,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(Yt,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(Rs,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(hn,{}),label:"Settings"}];function Hy({children:e}){const t=Bs(),r=Wa(),n=o.useMemo(()=>Fy.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(ac,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(oc,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(qp,{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 Uy=[{icon:s.jsx(Yt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ut,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(ic,{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(Rs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(ac,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],zy=[{icon:s.jsx(xu,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(rc,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(xn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(du,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(nc,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(mu,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Vy=[{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 Gy(){return s.jsxs(sr,{icon:s.jsx(oc,{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(kt,{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(kt,{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:Uy.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(kt,{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:rl.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:al.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:nl.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(kt,{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:zy.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(kt,{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:Vy.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(ln,{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(Cu,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function fa(e,t,r){return{...e,[t]:r}}function pa({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:Qr(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(pa,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:In,onChange:u=>i(fa(e,"chat",u))}),s.jsx(pa,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:dr,onChange:u=>i(fa(e,"code",u))}),s.jsx(pa,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:dr,onChange:u=>i(fa(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: ",Xs("chat",e.chat.preset)," · Code: ",Xs("code",e.code.preset)," · Terminal: ",Xs("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Xs("chat",ms.chat.preset)," / ",Xs("code",ms.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 Yy(){const{ides:e}=Qt(),t=e.find(Q=>Q.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=gt(),{userName:a}=Qt(),[i,c]=o.useState(a||""),[l,d]=o.useState(null),[m,u]=o.useState(null),[f,x]=o.useState(ms),[C,y]=o.useState(!1),[p,g]=o.useState(""),[b,h]=o.useState(""),[N,S]=o.useState("127.0.0.1"),[v,M]=o.useState(""),[I,j]=o.useState(""),[w,$]=o.useState(""),[P,T]=o.useState(""),[O,U]=o.useState(""),[R,k]=o.useState(!1),A=async()=>{const ie=await(await Et("/auth/session")).json();d(ie)},W=async()=>{const ie=await(await Et("/api/v1/standalone/preferences")).json();u(ie),S(ie.standaloneBindHost);const he=Bt(ie.standaloneFontPreferences);x(he),ss(he),Ba(he)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([A(),W()]).catch(Q=>{T(Q instanceof Error?Q.message:String(Q))})},[]),o.useEffect(()=>{ss(f)},[f]);const _=Q=>{const ie=Q.target.value.trim();t!=null&&t.id&&ie!==a&&n(t.id,"set_user_name",{userName:ie}).catch(console.error)},[E,F]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),Y=Q=>{F(Q);try{localStorage.setItem("adhdev_sound",Q?"1":"0")}catch{}},be=async()=>{g(""),h(""),y(!0);try{const Q=Bt(f),ie=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:Q})}),he=await ie.json();if(!ie.ok)throw new Error((he==null?void 0:he.error)||"Failed to save standalone font preferences");const se=Bt(he.standaloneFontPreferences);u(he),x(se),ss(se),Ba(se),h("Standalone chat fonts saved for this self-hosted dashboard.")}catch(Q){g(Q instanceof Error?Q.message:String(Q))}finally{y(!1)}},ce=()=>{const Q=Bt(m==null?void 0:m.standaloneFontPreferences);g(""),h(""),x(Q),ss(Q)},ee=()=>{g(""),h(""),x(ms),ss(ms)},ye=async()=>{T(""),U(""),k(!0);try{const Q=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:N})}),ie=await Q.json();if(!Q.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to save standalone network preference");u(ie),S(ie.standaloneBindHost),U(ie.standaloneBindHost==="0.0.0.0"?"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.":"Default standalone network mode set to localhost only. Restart standalone to apply it.")}catch(Q){T(Q instanceof Error?Q.message:String(Q))}finally{k(!1)}},we=async()=>{if(T(""),U(""),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 Q=await Et("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:I})}),ie=await Q.json();if(!Q.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to save password");d(ie),await W(),M(""),j(""),$(""),U(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),nd()}catch(Q){T(Q instanceof Error?Q.message:String(Q))}finally{k(!1)}},je=async()=>{T(""),U(""),k(!0);try{const Q=await Et("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),ie=await Q.json();if(!Q.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to clear password");d(ie),await W(),M(""),j(""),$(""),U("Standalone password disabled.")}catch(Q){T(Q instanceof Error?Q.message:String(Q))}finally{k(!1)}};return s.jsxs(sr,{icon:s.jsx(hn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Ns,{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(Ns,{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(kt,{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(kt,{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:N==="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:N==="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:()=>{ye()},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(kt,{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(Ns,{variant:"error",children:P}),O&&s.jsx(Ns,{variant:"success",children:O}),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:Q=>M(Q.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:I,onChange:Q=>j(Q.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:w,onChange:Q=>$(Q.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{we()},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:()=>{je()},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(kt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(Q=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${Q.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:Q.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:Q.type})]},Q.type))})}),s.jsx(kt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(rh,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(kt,{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(ih,{})]}),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(hh,{})]}),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:Bt(m==null?void 0:m.standaloneFontPreferences),saving:C,error:p,notice:b,onChange:x,onSave:()=>{be()},onResetToSaved:ce,onResetToDefaults:ee})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),s.jsx(gh,{})]})]})}),s.jsx(kt,{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(eh,{}),s.jsx(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Nu,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:Y})]})}),s.jsx(kt,{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(lu,{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:Q=>c(Q.target.value),onBlur:_,onKeyDown:Q=>{Q.key==="Enter"&&Q.currentTarget.blur()}})]})})})]})}Vp();fh();Oy();const Xy=tc({baseUrl:"",getToken:Mo});function Jy({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 Et("/auth/session")).json();r(y)}catch(C){d(C instanceof Error?C.message:String(C))}finally{a(!1)}};o.useEffect(()=>{f()},[]),o.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let C=!1;return(async()=>{try{const y=await Et("/api/v1/standalone/preferences");if(!y.ok)return;const p=await y.json();if(C)return;const g=Bt(p.standaloneFontPreferences);ss(g),Ba(g)}catch{}})(),()=>{C=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const x=async C=>{C.preventDefault(),u(!0),d("");try{const y=await Et("/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(""),nd()}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:C=>c(C.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}=Qt();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(ba,{to:`/machines/${r.id}`,replace:!0}):s.jsx(ba,{to:"/dashboard",replace:!0})}function Qy(){const e=o.useMemo(()=>({sendCommand:Xr,sendData:$a,sendPtyInput:Ly}),[]);return s.jsx($d,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(ru,{client:Xy,children:s.jsx(Jy,{children:s.jsx(Ey,{children:s.jsx(au,{value:e,children:s.jsx(Hy,{children:s.jsxs(Bd,{children:[s.jsx(Gt,{path:"/dashboard",element:s.jsx(hg,{})}),s.jsx(Gt,{path:"/machine",element:s.jsx(qi,{})}),s.jsx(Gt,{path:"/machines/:id",element:s.jsx(wy,{})}),s.jsx(Gt,{path:"/machines",element:s.jsx(qi,{})}),s.jsx(Gt,{path:"/about",element:s.jsx(Gy,{})}),s.jsx(Gt,{path:"/settings",element:s.jsx(Yy,{})}),s.jsx(Gt,{path:"/mesh",element:s.jsx(Ny,{})}),s.jsx(Gt,{path:"*",element:s.jsx(ba,{to:"/dashboard",replace:!0})})]})})})})})})})}ip({connectionManager:Wt});Kd(document.getElementById("root")).render(s.jsx(Qy,{}));
|