@adhdev/daemon-standalone 0.8.98 → 0.8.100

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,77 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-0pG_vku6.js","assets/vendor-BRZ4K-AC.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
+ var td=Object.defineProperty;var sd=(e,s,r)=>s in e?td(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var qe=(e,s,r)=>sd(e,typeof s!="symbol"?s+"":s,r);import{r as a,j as t,M as Na,a as Ca,b as Ai,c as Mi,u as Os,R as ot,d as nr,t as rd,e as nd,D as ad,f as aa,g as oa,h as Ia,i as od,k as id,B as cd,l as ld,m as is,N as ia,n as dd}from"./vendor-BRZ4K-AC.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))n(o);new MutationObserver(o=>{for(const i of o)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(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(o){if(o.ep)return;o.ep=!0;const i=r(o);fetch(o.href,i)}})();function ud(e={}){const s=Math.max(1,Math.floor(e.capacity||200)),r=[];return{record(n){const o={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(o),r.length>s&&r.splice(0,r.length-s),o},list(n={}){const o=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(-o).map(i=>({...i,payload:i.payload?{...i.payload}:{}}))},clear(){r.splice(0,r.length)}}}const Ps=ud();function ko(e){const s={};for(const r of e)r.transport&&(s[r.transport]=(s[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:s}}function md(e,s){return typeof e=="string"&&e.trim().length>0&&e!==s}function ca(e,s){if(!e)return s??null;if(!s)return e??null;const r=Array.isArray(e.messages)?e.messages:[],n=Array.isArray(s.messages)?s.messages:[],o=r.length>0?r:n,i=e.activeModal||(e.status==="waiting_approval"?s.activeModal:null);return{...s,...e,messages:o,activeModal:i,inputContent:e.inputContent??s.inputContent}}function Qs(e,s){const r=md(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(s==null?void 0:s.parentSessionId)??null,providerSessionId:e.providerSessionId??(s==null?void 0:s.providerSessionId),providerName:r??(s==null?void 0:s.providerName)??(s==null?void 0:s.cliName)??(s==null?void 0:s.type)??e.providerName??e.providerType,title:e.title??(s==null?void 0:s.title)??r??(s==null?void 0:s.providerName)??e.providerName??e.providerType,workspace:e.workspace??(s==null?void 0:s.workspace)??null,mode:e.mode??(s==null?void 0:s.mode),capabilities:e.capabilities??(s==null?void 0:s.sessionCapabilities)??(s==null?void 0:s.capabilities)??[],cdpConnected:e.cdpConnected??(s==null?void 0:s.cdpConnected),activeChat:ca(e.activeChat,s==null?void 0:s.activeChat),controlValues:e.controlValues??(s==null?void 0:s.controlValues),providerControls:e.providerControls??(s==null?void 0:s.providerControls),summaryMetadata:e.summaryMetadata??(s==null?void 0:s.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(s==null?void 0:s.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(s==null?void 0:s.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(s==null?void 0:s.lastMessagePreview),lastMessageRole:e.lastMessageRole??(s==null?void 0:s.lastMessageRole),lastMessageAt:e.lastMessageAt??(s==null?void 0:s.lastMessageAt),lastMessageHash:e.lastMessageHash??(s==null?void 0:s.lastMessageHash),unread:e.unread??(s==null?void 0:s.unread),lastSeenAt:e.lastSeenAt??(s==null?void 0:s.lastSeenAt),inboxBucket:e.inboxBucket??(s==null?void 0:s.inboxBucket),completionMarker:e.completionMarker??(s==null?void 0:s.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(s==null?void 0:s.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(s==null?void 0:s.surfaceHidden),resume:e.resume??(s==null?void 0:s.resume),runtimeKey:e.runtimeKey??(s==null?void 0:s.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(s==null?void 0:s.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(s==null?void 0:s.runtimeWorkspaceLabel)}}function So(e,s){if(!(s!=null&&s.length))return e;if(!(e!=null&&e.length))return s;const r=new Map(e.map(n=>[n.id,n]));return s.map(n=>{const o=r.get(n.id);return o?Qs(n,o):n})}const Ti=a.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}),Li=a.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function No(e){var r,n;let s=0;return e.activeChat!==void 0&&(s+=4),(r=e.childSessions)!=null&&r.length&&(s+=2),e.workspace&&(s+=1),e.machine&&(s+=1),(n=e.agents)!=null&&n.length&&(s+=1),s}function An(e,s,r){if(r.type!=="adhdev-daemon")return r;const n={...r},o=s.version??r.version??e.version,i=s.serverVersion??e.serverVersion??r.serverVersion,c=s.versionMismatch===!0||e.versionMismatch===!0,l=s.versionUpdateRequired===!0||e.versionUpdateRequired===!0,u=s.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return o&&(n.version=o),i&&(n.serverVersion=i),u&&(n.versionUpdateReason=u),o&&i&&o===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((s.versionMismatch===!0||c&&o&&i&&o!==i)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function tn(e){return Array.isArray(e)?e.map(tn):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([s])=>s!=="timestamp"&&s!=="_lastUpdate").sort(([s],[r])=>s.localeCompare(r)).map(([s,r])=>[s,tn(r)]))}function fd(e,s){try{return JSON.stringify(tn(e))===JSON.stringify(tn(s))}catch{return!1}}function Sr(e,s,r){return fd(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function pd(e,s,r){var m,d,g,p,w,I,b;const n=Date.now(),o=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return e.map(f=>({...f,_lastUpdate:n}));const i=new Map;for(const f of s)i.set(f.id,f);for(const f of e){const x=i.get(f.id);if(!x){i.set(f.id,{...f,_lastUpdate:n});continue}const y=No(f),k=No(x);if(y>k){const T=(m=f.chats)!=null&&m.length?f.chats:x.chats,v=So(x.childSessions,f.childSessions),R=ca(f.activeChat,x.activeChat),j=An(x,f,{...x,...f,chats:T,childSessions:v,activeChat:R,_lastUpdate:n});i.set(f.id,Sr(x,j,n))}else if(y<k){const T={};if(f.status&&f.status!==x.status&&(T.status=f.status),f.cdpConnected!==void 0&&(T.cdpConnected=f.cdpConnected),(d=f.chats)!=null&&d.length&&!((g=x.chats)!=null&&g.length)&&(T.chats=f.chats),f.title!==void 0&&(T.title=f.title),f.workspace!==void 0&&(T.workspace=f.workspace),f.providerSessionId!==void 0&&(T.providerSessionId=f.providerSessionId),f.parentSessionId!==void 0&&(T.parentSessionId=f.parentSessionId),f.sessionKind!==void 0&&(T.sessionKind=f.sessionKind),f.sessionCapabilities!==void 0&&(T.sessionCapabilities=f.sessionCapabilities),f.controlValues!==void 0&&(T.controlValues=f.controlValues),f.providerControls!==void 0&&(T.providerControls=f.providerControls),f.summaryMetadata!==void 0&&(T.summaryMetadata=f.summaryMetadata),f.lastMessagePreview!==void 0&&(T.lastMessagePreview=f.lastMessagePreview),f.lastMessageRole!==void 0&&(T.lastMessageRole=f.lastMessageRole),f.lastMessageAt!==void 0&&(T.lastMessageAt=f.lastMessageAt),f.lastMessageHash!==void 0&&(T.lastMessageHash=f.lastMessageHash),f.lastUpdated!==void 0&&(T.lastUpdated=f.lastUpdated),f.unread!==void 0&&(T.unread=f.unread),f.lastSeenAt!==void 0&&(T.lastSeenAt=f.lastSeenAt),f.inboxBucket!==void 0&&(T.inboxBucket=f.inboxBucket),f.completionMarker!==void 0&&(T.completionMarker=f.completionMarker),f.seenCompletionMarker!==void 0&&(T.seenCompletionMarker=f.seenCompletionMarker),f.surfaceHidden!==void 0&&(T.surfaceHidden=f.surfaceHidden),f.runtimeKey!==void 0&&(T.runtimeKey=f.runtimeKey),f.runtimeDisplayName!==void 0&&(T.runtimeDisplayName=f.runtimeDisplayName),f.runtimeWorkspaceLabel!==void 0&&(T.runtimeWorkspaceLabel=f.runtimeWorkspaceLabel),f.runtimeWriteOwner!==void 0&&(T.runtimeWriteOwner=f.runtimeWriteOwner),f.runtimeAttachedClients!==void 0&&(T.runtimeAttachedClients=f.runtimeAttachedClients),f.machineNickname!==void 0&&f.machineNickname!==x.machineNickname&&(T.machineNickname=f.machineNickname),f.version!==void 0&&(T.version=f.version),f.serverVersion!==void 0&&(T.serverVersion=f.serverVersion),f.versionMismatch===!0&&(T.versionMismatch=!0),Object.keys(T).length>0){const v=An(x,f,{...x,...T,_lastUpdate:n});i.set(f.id,Sr(x,v,n))}else Sr(x,{...x,_lastUpdate:n},n)}else{const T=f.timestamp||n,v=x._lastUpdate||x.timestamp||0;if(T>=v){const R=(p=f.chats)!=null&&p.length?f.chats:x.chats,j=So(x.childSessions,f.childSessions),S=ca(f.activeChat,x.activeChat),h=An(x,f,{...x,...f,chats:R,childSessions:j,activeChat:S,_lastUpdate:n});i.set(f.id,Sr(x,h,n))}else(w=f.chats)!=null&&w.length&&!((I=x.chats)!=null&&I.length)&&i.set(f.id,{...x,chats:f.chats})}}const c=new Set(e.map(f=>f.id)),l=new Set,u=new Set;for(const f of e){const x=f.daemonId||((b=f.id)==null?void 0:b.split(":")[0]);x&&l.add(x),x&&f.type!=="adhdev-daemon"&&u.add(x)}for(const[f,x]of i){const y=x.daemonId||f.split(":")[0];if(!l.has(y))continue;if(o.has(y)&&!c.has(f)){i.delete(f);continue}const k=n-(x._lastUpdate||x.timestamp||0);(x.transport==="pty"&&u.has(y)&&!c.has(f)&&k>1e4||x.transport==="acp"&&u.has(y)&&!c.has(f)&&k>1e4||x.transport==="cdp-page"&&u.has(y)&&!c.has(f)&&k>3e4)&&i.delete(f)}for(const[f,x]of i){const y=x.daemonId||f.split(":")[0];if(l.has(y)&&x.transport&&!u.has(y))continue;n-(x._lastUpdate||x.timestamp||0)>3e5&&x.status!=="online"&&i.delete(f)}return Array.from(i.values())}function hd(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==s[r])return!1;return!0}function xd({children:e,connectionOverrides:s}){const[r,n]=a.useState([]),[o,i]=a.useState(!1),[c,l]=a.useState([]),[u,m]=a.useState(void 0),d=a.useRef(r);a.useEffect(()=>{d.current=r},[r]);const g=a.useCallback((x,y)=>{n(k=>{let T=!1;const v=k.map(R=>R.id!==x||R.chats===y?R:(T=!0,{...R,chats:y}));return T?v:k})},[]),p=a.useCallback((x,y)=>{n(k=>{const T=k.length===0?x:pd(x,k,y),v=!hd(k,T);return v&&Ps.record({kind:"dashboard.entries_applied",payload:{incoming:ko(x),next:ko(T)}}),v?T:k})},[]),w=a.useCallback(()=>i(!0),[]),I=a.useMemo(()=>({injectEntries:p,markLoaded:w,getIdes:()=>d.current}),[p,w]),b=s,f=a.useMemo(()=>({ides:r,updateRouteChats:g,initialLoaded:o,toasts:c,setToasts:l,wsStatus:(b==null?void 0:b.wsStatus)??"connected",isConnected:(b==null?void 0:b.isConnected)??!0,connectionStates:(b==null?void 0:b.connectionStates)??{},connectionTransports:(b==null?void 0:b.connectionTransports)??{},showReconnected:(b==null?void 0:b.showReconnected)??!1,retryConnection:b==null?void 0:b.retryConnection,retryServerConnection:b==null?void 0:b.retryServerConnection,isP2PActive:(b==null?void 0:b.isP2PActive)??!1,p2pStates:(b==null?void 0:b.p2pStates)??{},userRole:b==null?void 0:b.userRole,userName:u,setUserName:m}),[r,g,o,c,b==null?void 0:b.wsStatus,b==null?void 0:b.isConnected,b==null?void 0:b.connectionStates,b==null?void 0:b.connectionTransports,b==null?void 0:b.showReconnected,b==null?void 0:b.retryConnection,b==null?void 0:b.retryServerConnection,b==null?void 0:b.isP2PActive,b==null?void 0:b.p2pStates,b==null?void 0:b.userRole,u]);return t.jsx(Li.Provider,{value:I,children:t.jsx(Ti.Provider,{value:f,children:e})})}function vs(){return a.useContext(Ti)}function ar(){return a.useContext(Li)}function Ri(e){const{baseUrl:s,getToken:r,onUnauthorized:n}=e;function o(l){return l.startsWith("http")?l:`${s}${l.startsWith("/")?"":"/"}${l}`}function i(l){const u=r==null?void 0:r(),m=o(l),d=l.startsWith("http")?new URL(m):new URL(m,typeof window<"u"?window.location.origin:"http://localhost");return u&&d.searchParams.set("token",u),!l.startsWith("http")&&!s?`${d.pathname}${d.search}${d.hash}`:d.toString()}async function c(l,u={}){const m={"Content-Type":"application/json",...u.headers||{}},d=r==null?void 0:r();d&&(m.Authorization=`Bearer ${d}`);const g=o(l),p=new AbortController,w=setTimeout(()=>p.abort(),15e3);try{const I=await fetch(g,{...u,headers:m,signal:p.signal});if(I.status===401)throw n==null||n(),new Error("Unauthorized");if(!I.ok){const b=await I.json().catch(()=>({error:I.statusText}));throw new Error(b.error||`API Error: ${I.status}`)}return I.json()}finally{clearTimeout(w)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,u,m={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:u,payload:m})}),execTerminal:(l,u,m)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:m})}),sendAgentMessage:(l,u,m)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:m})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,u,m)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:u,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,u,m={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:m})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const bd=Ri({baseUrl:"http://localhost:3847"}),gd=a.createContext(bd);function yd({client:e,children:s}){return t.jsx(gd.Provider,{value:e,children:s})}const vd={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Pi=a.createContext(vd);function wd({value:e,children:s}){return t.jsx(Pi.Provider,{value:e,children:s})}function Tt(){return a.useContext(Pi)}function jd(e){let s=2166136261;for(const r of e){const n=String(r||"");for(let o=0;o<n.length;o+=1)s^=n.charCodeAt(o),s=Math.imul(s,16777619)>>>0;s^=255,s=Math.imul(s,16777619)>>>0}return s.toString(16).padStart(8,"0")}function kd(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function _i(e){return e?jd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),kd(e.content)]):""}const He={size:18};function Di({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function Aa({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polyline",{points:"15 18 9 12 15 6"})})}function ws({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),t.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),t.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),t.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function Ei({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"9",cy:"7",r:"4"}),t.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),t.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Sd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Nd({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function $i({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),t.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),t.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),t.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function Cd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),t.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),t.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),t.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),t.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function mn({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"3"}),t.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Bi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),t.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Id({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function es({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Rt({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Ma({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),t.jsx("polyline",{points:"14 2 14 8 20 8"}),t.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),t.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Ad({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"11",cy:"11",r:"8"}),t.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function _s({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function fr({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"23 4 23 10 17 10"}),t.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function or({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),t.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),t.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function ir({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M12 22v-5"}),t.jsx("path",{d:"M9 8V2"}),t.jsx("path",{d:"M15 8V2"}),t.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function Ki({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),t.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Oi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),t.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),t.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),t.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Wi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function Md({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),t.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),t.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function Ta({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"4 17 10 11 4 5"}),t.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Td({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function La({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Hi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function Mt({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Ld({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),t.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),t.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),t.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function Rd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),t.jsx("path",{d:"M12 2v6"}),t.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Pd({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function _d({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),t.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function fn({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),t.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function Dd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"5"}),t.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),t.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),t.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),t.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),t.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),t.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),t.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),t.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function Ed({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function $d({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Bd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),t.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Kd({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function Od({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),t.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function Wd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),t.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),t.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function Hd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),t.jsx("path",{d:"M13 2h9v9"}),t.jsx("path",{d:"M22 2L13 11"})]})}function Fd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"9 14 4 9 9 4"}),t.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function Ud({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),t.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),t.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),t.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),t.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),t.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),t.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),t.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),t.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),t.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function zd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),t.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function Vd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),t.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),t.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}function Co(e){return!!e&&typeof e=="object"&&"text"in e}function Ra(e,s){const r=(s==null?void 0:s.joiner)??" ",n=(s==null?void 0:s.normalizeWhitespace)??!1;let o="";return typeof e=="string"?o=e:Array.isArray(e)?o=e.map(i=>typeof i=="string"?i:Co(i)?String(i.text||""):"").join(r):Co(e)?o=String(e.text||""):o=String(e||""),n?o.replace(/\s+/g," ").trim():o}function Pa(e){return Ra(e,{normalizeWhitespace:!0})}const Mn=new Map;function Io(e,s){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(s||""):!0}function Gd(e){if(!Array.isArray(e)||e.length===0)return"0:empty";const s=e[e.length-1];return`${e.length}:${_i(s)}`}function Ao(e,s){const r=Math.max(0,e.scrollHeight-e.clientHeight-s.fromBottom);e.scrollTop=Number.isFinite(r)?r:s.top}function Fi(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function qd(e,s,r){return Number(e.receivedAt||r[sn(e,s)]||0)||0}function Ui(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Yd(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function Nr(e,s){if(!e)return s;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||s}catch{return e.split(/[\\/]/).filter(Boolean).pop()||s}}function Tn(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 Mo(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):Ui(e)?t.jsx(Na,{remarkPlugins:[Ca,Ai,Mi],children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function Cr({parts:e,renderAsPreformatted:s}){return t.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return t.jsx("div",{children:Mo(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const o=Tn(r);return o?t.jsx("img",{src:o,alt:Nr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const o=Tn(r);return o?t.jsx("audio",{controls:!0,src:o,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const o=Tn(r);return o?t.jsx("video",{controls:!0,src:o,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"},`video-${n}`):r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:Nr(r.uri,"video")},`video-link-${n}`):null}if(r.type==="resource_link")return r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:r.name||Nr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const o=Nr(r.resource.uri,"resource");if(r.resource.text)return t.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[t.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:o}),Mo(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return t.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:o},`resource-uri-${n}`)}return null})})}function sn(e,s){const r=e,n=Ra(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:${s}`].filter(Boolean).join("|")}const Xd=a.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(Na,{remarkPlugins:[Ca],children:s.text}),t.jsx("span",{className:"action-time",children:Fi(s.timestamp)})]})},(e,s)=>e.log===s.log),Jd=a.memo(function({message:s,receivedAt:r,agentName:n,userName:o,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var R,j,S;const u=(s.role||"").toLowerCase(),m=u==="user"||u==="human",d=s.kind||(u==="tool"?"tool":"standard"),g=Yd(s.content)?s.content:null,p=!!(g!=null&&g.some(h=>h.type!=="text")),w=Ra(s.content,{joiner:`
4
+ `});if(d==="thought"){const h=typeof((R=s.meta)==null?void 0:R.label)=="string"?s.meta.label:"Thought";return t.jsxs("div",{className:"self-start chat-msg-thought",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx(Pd,{size:13}),t.jsx("span",{children:h})]}),t.jsx("div",{className:"chat-msg-body",children:w})]})}if(d==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),p&&g?t.jsx("div",{className:"tool-text w-full",children:t.jsx(Cr,{parts:g,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:w})]});if(d==="terminal"){const h=(j=s.meta)!=null&&j.isRunning?"⏳":"✅",E=typeof((S=s.meta)==null?void 0:S.label)=="string"?s.meta.label:"Ran command";return t.jsxs("div",{className:"self-start chat-msg-terminal",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx("span",{children:h}),t.jsx("span",{children:E})]}),p&&g?t.jsx("div",{className:"chat-msg-body",children:t.jsx(Cr,{parts:g,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:w})]})}if(d==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:p&&g?t.jsx(Cr,{parts:g,renderAsPreformatted:!1}):w.slice(0,100)});const I=s.meta,f=(typeof(I==null?void 0:I.renderMode)=="string"?I.renderMode.trim():"")==="preformatted",x=w,y=!1,k=x,T=f,v=!T&&Ui(k);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${m?"self-end":"self-start"}`,children:(x||p||m)&&t.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${x||p?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:m?o||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:Fi(r)})]}),(x||p)&&t.jsx("div",{className:"chat-markdown",children:p&&g?t.jsx(Cr,{parts:g,renderAsPreformatted:T}):T?t.jsx("pre",{className:"chat-preformatted",children:k}):v?t.jsx(Na,{remarkPlugins:[Ca,Ai,Mi],children:k}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:k})}),y]})})},(e,s)=>e.message===s.message&&e.receivedAt===s.receivedAt&&e.agentName===s.agentName&&e.userName===s.userName&&e.isCliMode===s.isCliMode&&e.isTextExpanded===s.isTextExpanded),Qd=a.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:o,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:u={},emptyState:m,onLoadMore:d,isLoadingMore:g,hasMoreHistory:p,hiddenLiveCount:w=0,loadError:I,scrollToBottomRequestNonce:b},f){const x=a.useRef(null),y=a.useRef(null),k=a.useRef(null),T=a.useRef(0),v=a.useRef(""),R=a.useRef(!1),j=a.useRef(null),S=a.useRef(!1),h=a.useRef(null),E=a.useRef(!1),[C,A]=a.useState(new Set),P=a.useRef(!1),B=a.useRef(!1),q=()=>{const z=x.current;return z?z.scrollHeight-z.scrollTop-z.clientHeight<200:!0},N=a.useCallback((z="auto")=>{const xe=x.current;xe&&xe.scrollTo({top:xe.scrollHeight,behavior:z})},[]),L=a.useCallback(()=>{var Y;const z=x.current,xe=(Y=window.getSelection)==null?void 0:Y.call(window);if(!z||!xe||xe.rangeCount===0||xe.isCollapsed){E.current=!1;return}const D=xe.anchorNode,W=xe.focusNode;E.current=!!(D&&W&&z.contains(D)&&z.contains(W))},[]),U=Gd(s),$=a.useCallback(()=>{const z=x.current;!z||!l||Mn.set(l,{top:z.scrollTop,fromBottom:Math.max(0,z.scrollHeight-z.scrollTop-z.clientHeight),messageFingerprint:U})},[l,U]),K=a.useCallback((z="auto")=>{j.current!=null&&cancelAnimationFrame(j.current),j.current=requestAnimationFrame(()=>{j.current=null,N(z)})},[N]);a.useEffect(()=>{const z=!R.current,xe=v.current!==l;if(v.current=l,z||xe){if(R.current=!0,P.current=!1,S.current=!0,!E.current){const W=l?Mn.get(l):null;W&&Io(W,U)?requestAnimationFrame(()=>{const Y=x.current;Y&&(Ao(Y,W),B.current=!0)}):K("auto")}T.current=s.length;return}s.length>T.current?!P.current&&!E.current&&K("auto"):q()&&!P.current&&!E.current&&K("auto"),T.current=s.length},[U,l,c,s.length,K]),a.useEffect(()=>{b&&(P.current=!1,S.current=!0,B.current=!0,h.current!=null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>{S.current=!1,h.current=null},180),E.current||K("auto"))},[K,b]),a.useEffect(()=>()=>{$(),j.current!=null&&cancelAnimationFrame(j.current),h.current!=null&&window.clearTimeout(h.current)},[$]),a.useEffect(()=>{const z=y.current;if(!z)return;const xe=()=>{h.current!=null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>{S.current=!1,h.current=null},180)},D=new ResizeObserver(()=>{S.current&&(E.current||(K("auto"),xe()))});return D.observe(z),()=>{D.disconnect(),h.current!=null&&(window.clearTimeout(h.current),h.current=null)}},[K,l]),a.useImperativeHandle(f,()=>({scrollToBottom:(z="smooth")=>{N(z)}}),[N]),a.useEffect(()=>{const z=x.current;if(!z)return;let xe;const D=()=>{clearTimeout(xe),xe=setTimeout(()=>{P.current=!q(),$()},50)};return z.addEventListener("scroll",D,{passive:!0}),()=>{z.removeEventListener("scroll",D),clearTimeout(xe)}},[$]),a.useEffect(()=>(document.addEventListener("selectionchange",L),()=>document.removeEventListener("selectionchange",L)),[L]);const X=a.useRef(0),te=a.useRef(!1);a.useEffect(()=>{const z=x.current;if(!z||!te.current||X.current===0)return;const xe=z.scrollHeight-X.current;xe>0&&(z.scrollTop=xe),$(),X.current=0,te.current=!1},[s.length,$]),a.useEffect(()=>{if(B.current||!l)return;const z=Mn.get(l),xe=x.current;if(!(!z||!xe)){if(!Io(z,U)){N("auto"),B.current=!0;return}Ao(xe,z),B.current=!0}},[l,U,s.length,N]);const le=()=>{const z=x.current;z&&(X.current=z.scrollHeight),te.current=!0,d==null||d()},he=a.useMemo(()=>{const z=s.map((Y,ae)=>({type:"message",data:Y,index:ae,ts:qd(Y,ae,u)}));if(!r||r.length===0)return z;const xe=[...r].sort((Y,ae)=>Y.timestamp-ae.timestamp).map((Y,ae)=>({type:"action",data:Y,index:ae,ts:Y.timestamp})),D=[];let W=0;for(const Y of z){for(;W<xe.length&&Y.ts>0&&xe[W].ts<Y.ts;)D.push(xe[W++]);D.push(Y)}for(;W<xe.length;)D.push(xe[W++]);return D},[s,r,u]),Ce=w>0||!!p,ke=w>0?`↑ Show ${Math.min(w,80)} earlier messages${w>80?` (${w} hidden)`:""}`:I?`↻ ${I}`:"↑ Load older messages";return t.jsx("div",{ref:x,"data-chat-scroll":!0,className:"chat-container",children:t.jsxs("div",{ref:y,className:"chat-container-content",children:[g&&t.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),Ce&&!g&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{onClick:le,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${I&&w===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:ke})}),he.length===0&&!Ce&&(m||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),he.map(z=>{if(z.type==="action"){const Se=z.data;return t.jsx(Xd,{log:Se},`action-${z.index}`)}const xe=z.data,D=z.index,W=sn(xe,D),Y=xe.receivedAt||u[W],ae=`${l}-${W}`,ce=C.has(ae);return t.jsx(Jd,{message:xe,receivedAt:Y,agentName:n,userName:o,isCliMode:i,isTextExpanded:ce,onToggleTextExpanded:()=>A(Se=>{const oe=new Set(Se);return ce?oe.delete(ae):oe.add(ae),oe})},`msg-${W}`)}),c&&t.jsx("div",{className:"self-start chat-typing-wrapper",children:t.jsxs("div",{className:"typing-indicator",children:[t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),t.jsx("div",{className:"min-h-10",ref:k})]})})}),Zd=a.memo(Qd,(e,s)=>e.messages===s.messages&&e.actionLogs===s.actionLogs&&e.agentName===s.agentName&&e.userName===s.userName&&e.isCliMode===s.isCliMode&&e.isWorking===s.isWorking&&e.contextKey===s.contextKey&&e.receivedAtMap===s.receivedAtMap&&e.emptyState===s.emptyState&&e.onLoadMore===s.onLoadMore&&e.isLoadingMore===s.isLoadingMore&&e.hasMoreHistory===s.hasMoreHistory&&e.hiddenLiveCount===s.hiddenLiveCount&&e.loadError===s.loadError&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce),eu="modulepreload",tu=function(e){return"/"+e},To={},su=function(s,r,n){let o=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"));o=Promise.allSettled(r.map(u=>{if(u=tu(u),u in To)return;To[u]=!0;const m=u.endsWith(".css"),d=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const g=document.createElement("link");if(g.rel=m?"stylesheet":eu,m||(g.as="script"),g.crossOrigin="",g.href=u,l&&g.setAttribute("nonce",l),document.head.appendChild(g),m)return new Promise((p,w)=>{g.addEventListener("load",p),g.addEventListener("error",()=>w(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return o.then(c=>{for(const l of c||[])l.status==="rejected"&&i(l.reason);return s().catch(i)})};let Lo=!1;const zi=a.forwardRef(({onInput:e,onViewportMetrics:s,fontSize:r=13,readOnly:n=!1,sizingMode:o="measured"},i)=>{const c=a.useRef(null),[l,u]=a.useState(null),m=a.useRef([]),d=a.useRef(!1),g=a.useRef(!1),p=a.useRef(!1),w=()=>{const I=c.current;if(I){d.current&&(I.clear(),d.current=!1);for(const b of m.current)I.write(b);m.current=[],g.current&&(I.fit(),g.current=!1),p.current&&(I.bumpResize(),p.current=!1)}};return a.useImperativeHandle(i,()=>({write:I=>{c.current?c.current.write(I):m.current.push(I)},clear:()=>{c.current?c.current.clear():(m.current=[],d.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(m.current=[],d.current=!0)},resize:(I,b)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(I,b)},fit:()=>{c.current?c.current.fit():g.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():p.current=!0}}),[]),a.useEffect(()=>{if(!l)return;const I=requestAnimationFrame(()=>{w()});return()=>cancelAnimationFrame(I)},[l]),a.useEffect(()=>{let I=!1;return su(()=>import("./terminal-0pG_vku6.js"),__vite__mapDeps([0,1,2])).then(b=>{Lo||(Lo=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),I||u(()=>b.GhosttyTerminalView)}).catch(b=>{console.error("[CliTerminal] failed to load terminal renderer",b)}),()=>{I=!0}},[]),l?t.jsx(l,{ref:c,onInput:e,onViewportMetrics:s,fontSize:r,readOnly:n,sizingMode:o,className:"w-full h-full rounded-lg overflow-hidden"}):t.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});zi.displayName="CliTerminal";function Ir({label:e,value:s,sub:r,icon:n}){return t.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[t.jsx("span",{className:"text-base flex items-center",children:n}),t.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),t.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:s}),r&&t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function Ro({value:e,max:s,label:r,color:n="#8b5cf6",detail:o,compact:i=!1}){const c=s>0?Math.min(Math.round(e/s*100),100):0,l=c>85?"#ef4444":c>60?"var(--status-warning)":n;return i?t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex justify-between mb-0.5",children:[t.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),t.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[c,"%"]})]}),t.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:t.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${c}%`,background:l}})})]}):t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex justify-between mb-1.5",children:[t.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),t.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[c,"%"]})]}),t.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:t.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${c}%`,background:`linear-gradient(90deg, ${l}, ${l}cc)`}})}),o&&t.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:o})]})}function ru({cursorPos:e,viewportRef:s,imgRef:r}){var y;if(!e||!r.current)return null;const n=r.current,o=n.getBoundingClientRect(),i=(y=s.current)==null?void 0:y.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||o.width,l=n.naturalHeight||o.height,u=c/l,m=o.width/o.height;let d,g,p,w;u>m?(d=o.width,g=o.width/u,p=0,w=(o.height-g)/2):(g=o.height,d=o.height*u,p=(o.width-d)/2,w=0);const I=o.left-i.left+p+d*e.nx,b=o.top-i.top+w+g*e.ny,f=Math.max(8,Math.min(i.width-8,I)),x=Math.max(8,Math.min(i.height-8,b));return t.jsxs("div",{style:{position:"absolute",left:f-8,top:x-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[t.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),t.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),t.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function nu({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:o,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:u,isConnActive:m,zoom:d,isMobile:g,mobileFillZoom:p,onZoomOut:w,onZoomReset:I,onZoomIn:b,transportType:f,screenshotUsage:x,lastActionStatus:y}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:k=>k.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[t.jsxs("div",{onClick:s,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[t.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),t.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),t.jsxs("div",{className:"relative",children:[t.jsx("div",{onClick:()=>{n(k=>!k),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:t.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&t.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:t.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:k=>k.stopPropagation(),onChange:k=>l(k.target.value),onKeyDown:k=>{u(k)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),t.jsx("div",{className:"relative",children:t.jsx("div",{onClick:()=>{i(k=>!k),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${o?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⚙️"})})}),t.jsx("div",{className:"w-px h-[18px] bg-white/10"}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:m?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[t.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:m?"#22c55e":"#eab308",boxShadow:m?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:m?"#22c55e":"#eab308"},children:m?"Connected":"WS"})]}),d>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),f==="direct"&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),f==="relay"&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),x&&x.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:x.budgetExhausted?"#ef4444":"#c4b5fd",background:x.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:x.budgetExhausted?"TURN blocked":`TURN ${x.dailyUsedMinutes}/${x.dailyBudgetMinutes}m`}),y&&t.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:y})]})]}),o&&t.jsxs("div",{onTouchStart:k=>k.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[t.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",d<=(g?p:1)+.01?g?"FILL":"FIT":`${Math.round(d*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:k=>{k.stopPropagation(),w()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),t.jsx("button",{onClick:k=>{k.stopPropagation(),I()},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:g?"FILL":"FIT"}),t.jsx("button",{onClick:k=>{k.stopPropagation(),b()},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 au({waitingLabel:e,waitingHint:s,transportType:r}){return t.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[t.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-white/10 bg-white/[0.04] shadow-[0_10px_30px_rgba(0,0,0,0.35)]",style:{animation:"remote-float 2.8s ease-in-out infinite"},children:t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),t.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),t.jsx("div",{className:"text-[11px] text-white/40",children:s}),r==="relay"&&t.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function ou(){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 Po(e){return e==null||typeof e=="number"||typeof e=="boolean"?e:typeof e=="string"?e.length>64?`${e.slice(0,61)}...`:e:Array.isArray(e)?`Array(${e.length})`:typeof e=="object"?"Object":typeof e}function pr(e,s){const r=a.useRef(null),n=a.useRef(0);a.useEffect(()=>{if(!ou())return;n.current+=1;const o=r.current;if(!o){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(s).map(([c,l])=>[c,Po(l)]))}),r.current=s;return}const i=Object.keys({...o,...s}).filter(c=>!Object.is(o[c],s[c]));i.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:i,snapshot:Object.fromEntries(i.map(c=>[c,Po(s[c])]))}),r.current=s})}function iu({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:o,minZoom:i,zoomRef:c,panXRef:l,panYRef:u,setPanX:m,setPanY:d,setZoom:g,lastWheelTimeRef:p,onAction:w,setLastActionStatus:I,spawnRippleFromNormalized:b,clampPan:f,isMobile:x,mobileFillZoom:y}){const[k,T]=a.useState(null),v=a.useRef(null),R=a.useRef(null),j=a.useRef(null),S=a.useRef(!1),h=a.useRef(null),E=a.useRef(0),C=a.useRef(null),A=a.useRef(1),P=a.useRef({x:0,y:0}),B=a.useRef(!1),q=a.useRef(n),N=a.useRef(w),L=30,U=550,$=18,K=60,X=400,te=12,le=()=>{if(v.current)return;const ke={nx:.5,ny:.5};v.current=ke,T(ke)};return a.useEffect(()=>{q.current=n,n==="mouse"&&le()},[n]),a.useEffect(()=>{N.current=w},[w]),a.useEffect(()=>{const ke=e.current;if(!ke)return;const z=ce=>{if(!r.current)return null;const Se=r.current.getBoundingClientRect();return!Se.width||!Se.height?null:{nx:Math.max(0,Math.min(1,(ce.clientX-Se.left)/Se.width)),ny:Math.max(0,Math.min(1,(ce.clientY-Se.top)/Se.height))}},xe=(ce,Se)=>{if(!r.current)return{dnx:0,dny:0};const oe=r.current,de=oe.getBoundingClientRect(),ee=oe.naturalWidth||de.width,ue=oe.naturalHeight||de.height,se=ee/ue,je=de.width/de.height;let we,Re;return se>je?(we=de.width,Re=de.width/se):(Re=de.height,we=de.height*se),{dnx:ce/we,dny:Se/Re}},D=(ce,Se,oe)=>{if(oe<=1.05)return;const de=-(ce-.5)*100,ee=-(Se-.5)*100,ue=f(de,ee,oe);(Math.abs(ue.x-l.current)>.1||Math.abs(ue.y-u.current)>.1)&&(m(ue.x),d(ue.y),l.current=ue.x,u.current=ue.y)},W=ce=>{const Se=s.current;if(Se&&ce.target instanceof Node&&Se.contains(ce.target))ce.preventDefault();else return;if(ce.touches.length===1){const oe=ce.touches[0];R.current={x:oe.clientX,y:oe.clientY,time:Date.now()},j.current={x:oe.clientX,y:oe.clientY},B.current||(S.current=!1),h.current=setTimeout(()=>{if(!S.current&&!B.current)if(S.current=!0,q.current==="mouse"){const de=v.current||{nx:.5,ny:.5};I("Right Click"),b(de.nx,de.ny,"right"),N.current("input_click",{...de,button:"right"}).catch(()=>{})}else{const de=z(oe);de&&(I("Right Click"),b(de.nx,de.ny,"right"),N.current("input_click",{...de,button:"right"}).catch(()=>{}))}},500);return}if(ce.touches.length===2){h.current&&clearTimeout(h.current),S.current=!0,B.current=!0;const oe=ce.touches[1].clientX-ce.touches[0].clientX,de=ce.touches[1].clientY-ce.touches[0].clientY;C.current=Math.sqrt(oe*oe+de*de),A.current=c.current,P.current={x:(ce.touches[0].clientX+ce.touches[1].clientX)/2,y:(ce.touches[0].clientY+ce.touches[1].clientY)/2}}},Y=ce=>{const Se=s.current;if(Se&&ce.target instanceof Node&&Se.contains(ce.target)&&ce.preventDefault(),ce.touches.length===1&&j.current){const oe=ce.touches[0],de=oe.clientX-j.current.x,ee=oe.clientY-j.current.y;if(!S.current&&R.current){const ue=oe.clientX-R.current.x,se=oe.clientY-R.current.y;Math.sqrt(ue*ue+se*se)>8&&(S.current=!0,h.current&&clearTimeout(h.current))}if(S.current)if(q.current==="mouse"){const ue=xe(de,ee),se=v.current||{nx:.5,ny:.5},je=Math.max(0,Math.min(1,se.nx+ue.dnx)),we=Math.max(0,Math.min(1,se.ny+ue.dny));v.current={nx:je,ny:we},T({nx:je,ny:we}),I(`Cursor: ${Math.round(je*100)}%, ${Math.round(we*100)}%`),D(je,we,c.current);const Re=Date.now();Re-p.current>=30&&(p.current=Re,N.current("input_mouseMoved",{nx:je,ny:we}).catch(()=>{}))}else if(c.current>1){const ue=s.current;if(ue){const se=ue.clientWidth,je=ue.clientHeight,we=l.current+de/se*100,Re=u.current+ee/je*100,M=f(we,Re,c.current);m(M.x),d(M.y),l.current=M.x,u.current=M.y}}else{const ue=z(oe);if(ue){const se=Date.now();se-p.current>=40&&(p.current=se,I("Scroll"),N.current("input_wheel",{nx:ue.nx,ny:ue.ny,deltaX:Math.round(-de*2.5),deltaY:Math.round(-ee*2.5)}).catch(()=>{}))}}j.current={x:oe.clientX,y:oe.clientY};return}if(ce.touches.length===2&&C.current!==null){const oe=ce.touches[1].clientX-ce.touches[0].clientX,de=ce.touches[1].clientY-ce.touches[0].clientY,ue=Math.sqrt(oe*oe+de*de)/C.current,se=(ce.touches[0].clientX+ce.touches[1].clientX)/2,je=(ce.touches[0].clientY+ce.touches[1].clientY)/2,we=se-P.current.x,Re=je-P.current.y,M=Math.abs(ue-1)>.03;if(q.current==="mouse"){if(M){const me=Math.max(i,Math.min(5,A.current*ue));g(me),c.current=me}else if(Math.abs(we)>2||Math.abs(Re)>2){const me=v.current||{nx:.5,ny:.5},ge=Date.now();ge-p.current>=30&&(p.current=ge,I("Scroll"),N.current("input_wheel",{nx:me.nx,ny:me.ny,deltaX:Math.round(-we*3),deltaY:Math.round(-Re*3)}).catch(()=>{}))}}else{const me=Math.max(i,Math.min(5,A.current*ue));g(me),c.current=me;const ge=s.current;if(ge&&me>1){const Z=ge.clientWidth,ye=ge.clientHeight,Ae=l.current+we/Z*100,We=u.current+Re/ye*100,De=f(Ae,We,me);m(De.x),d(De.y),l.current=De.x,u.current=De.y}}P.current={x:se,y:je}}},ae=ce=>{var Se;if(h.current&&clearTimeout(h.current),C.current=null,ce.touches.length===1&&B.current){const oe=ce.touches[0];R.current={x:oe.clientX,y:oe.clientY,time:Date.now()},j.current={x:oe.clientX,y:oe.clientY},S.current=!0;return}if(ce.touches.length===0){if(B.current){B.current=!1,S.current=!1;return}if(ce.changedTouches.length===1){const oe=ce.changedTouches[0],de=Date.now(),ee=de-(((Se=R.current)==null?void 0:Se.time)||0),ue=R.current?oe.clientX-R.current.x:0,se=R.current?oe.clientY-R.current.y:0,je=Math.sqrt(ue*ue+se*se);if(q.current==="mouse"){if(ee<L||ee>U||je>$){S.current=!1;return}const we=v.current||z(oe);we&&(I(`Click: ${Math.round(we.nx*100)}%, ${Math.round(we.ny*100)}%`),b(we.nx,we.ny,"left"),N.current("input_click",{...we}).catch(()=>{}))}else{if(S.current){S.current=!1;return}if(ee<K||ee>X||je>te){S.current=!1;return}const we=z(oe);if(!we)return;de-E.current<300?(I("Double tap"),b(we.nx,we.ny,"double"),N.current("input_click",{...we,clickCount:2}).catch(()=>{}),E.current=0):(I(`Tap: ${Math.round(we.nx*100)}%, ${Math.round(we.ny*100)}%`),b(we.nx,we.ny,"left"),N.current("input_click",{...we}).catch(()=>{}),E.current=de)}}S.current=!1}};return ke.addEventListener("touchstart",W,{passive:!1}),ke.addEventListener("touchmove",Y,{passive:!1}),ke.addEventListener("touchend",ae,{passive:!1}),()=>{ke.removeEventListener("touchstart",W),ke.removeEventListener("touchmove",Y),ke.removeEventListener("touchend",ae),h.current&&clearTimeout(h.current)}},[e,s,r,i,c,l,u,m,d,g,p,I,b,f]),{cursorPos:k,cursorPosRef:v,handleToggleInputMode:()=>{o(ke=>{const z=ke==="touch"?"mouse":"touch";return z==="mouse"&&le(),z})},handleZoomReset:()=>{const ke=x?y:1;g(ke),c.current=ke,m(0),d(0),l.current=0,u.current=0}}}function Vi({onAction:e,addLog:s,connState:r,connScreenshot:n,screenshotUsage:o,transportType:i}){const c=a.useRef(null),l=a.useRef(null),u=a.useRef(null),[m,d]=a.useState(null),[g,p]=a.useState(""),[,w]=a.useState(!1),[I,b]=a.useState([]),f=a.useRef(0),[x,y]=a.useState(!1),[k,T]=a.useState(!1),v=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[R,j]=a.useState(v?"mouse":"touch"),[S,h]=a.useState(1),E=a.useRef(!1),[C,A]=a.useState(1),[P,B]=a.useState(0),[q,N]=a.useState(0);pr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:R,zoom:C,panX:P,panY:q,isMenuOpen:x,isImeOpen:k});const L=a.useRef(0),U=a.useRef(C),$=a.useRef(P),K=a.useRef(q);a.useEffect(()=>{U.current=C},[C]),a.useEffect(()=>{$.current=P},[P]),a.useEffect(()=>{K.current=q},[q]),a.useEffect(()=>{var ee;(ee=c.current)==null||ee.focus()},[]);const X=r==="connected",te=n,le=X?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",he=X?"The remote stream is warming up":"Waiting for the remote stream to catch up";a.useEffect(()=>{if(!v||E.current||!te)return;const ee=u.current,ue=l.current;if(!ee||!ue)return;const se=()=>{const je=ue.clientWidth,we=ue.clientHeight,Re=ee.naturalWidth,M=ee.naturalHeight;if(!Re||!M||!je||!we)return;const me=Math.min(je/Re,we/M),Z=Math.max(je/Re,we/M)/me;Z>1.01&&(h(Z),A(Z),U.current=Z),E.current=!0};ee.complete&&ee.naturalWidth?se():ee.addEventListener("load",se,{once:!0})},[te,v]);const Ce=.5;a.useEffect(()=>{C<=Ce&&(B(0),N(0))},[C,Ce]);const ke=(ee,ue,se)=>{if(se<=Ce)return{x:0,y:0};const je=(se-1)/(2*se)*100,we=(se-1)/(2*se)*100;return{x:Math.max(-je,Math.min(je,ee)),y:Math.max(-we,Math.min(we,ue))}},z=(ee,ue)=>{if(!u.current)return null;const se=u.current.getBoundingClientRect();return!se.width||!se.height?null:{nx:Math.max(0,Math.min(1,(ee-se.left)/se.width)),ny:Math.max(0,Math.min(1,(ue-se.top)/se.height))}},xe=(ee,ue,se)=>{const je=l.current;if(!je)return;const we=je.getBoundingClientRect(),Re=++f.current;b(M=>[...M,{id:Re,x:ee-we.left,y:ue-we.top,type:se}]),setTimeout(()=>b(M=>M.filter(me=>me.id!==Re)),600)},D=(ee,ue,se)=>{const je=u.current,we=l.current;if(!je||!we)return;const Re=je.getBoundingClientRect(),M=we.getBoundingClientRect(),me=je.naturalWidth||Re.width,ge=je.naturalHeight||Re.height,Z=me/ge,ye=Re.width/Re.height;let Ae,We,De,Fe;Z>ye?(Ae=Re.width,We=Re.width/Z,De=0,Fe=(Re.height-We)/2):(We=Re.height,Ae=Re.height*Z,De=(Re.width-Ae)/2,Fe=0);const Je=Re.left-M.left+De+Ae*ee,bt=Re.top-M.top+Fe+We*ue,rt=++f.current;b(ut=>[...ut,{id:rt,x:Je,y:bt,type:se}]),setTimeout(()=>b(ut=>ut.filter(ht=>ht.id!==rt)),600)},W=async ee=>{var se;const ue=z(ee.clientX,ee.clientY);if(ue){d(`Click: ${Math.round(ue.nx*100)}%, ${Math.round(ue.ny*100)}%`),xe(ee.clientX,ee.clientY,"left"),(se=c.current)==null||se.focus();try{const je=await e("input_click",{nx:ue.nx,ny:ue.ny});je!=null&&je.success||s(`❌ Click failed: ${je==null?void 0:je.error}`)}catch(je){s(`❌ Click error: ${je.message||je}`)}}},Y=async(ee,ue,se,je=0)=>{try{await e("input_key",{type:se?"char":"keyDown",key:ee,code:ue,text:se?ee:void 0,unmodifiedText:se?ee:void 0,modifiers:je})}catch(we){s(`❌ Key error: ${we.message||we}`)}},ae=async ee=>{if(ee.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ee.key)&&ee.preventDefault();let se=0;ee.altKey&&(se|=1),ee.ctrlKey&&(se|=2),ee.metaKey&&(se|=4),ee.shiftKey&&(se|=8),d(`Key: ${ee.key}`),await Y(ee.key,ee.code,ee.key.length===1,se)},ce=async ee=>{if(ee.key==="Enter"){if(ee.nativeEvent.isComposing)return;if(g){const ue=g;p(""),d(`IME Sent: ${ue}`);try{const se=await e("input_type",{text:ue});se!=null&&se.success||s(`❌ IME error: ${se==null?void 0:se.error}`)}catch(se){s(`❌ IME error: ${se.message}`)}}else d("Key: Enter"),await Y("Enter","Enter",!1)}};a.useEffect(()=>{const ee=c.current;if(!ee)return;const ue=se=>{var je;if((je=u.current)!=null&&je.contains(se.target)){se.preventDefault();const we=Date.now();if(we-L.current<40)return;L.current=we;const Re=z(se.clientX,se.clientY);if(!Re)return;d(`Scroll: ${Math.round(se.deltaY)}`),e("input_wheel",{nx:Re.nx,ny:Re.ny,deltaX:Math.round(se.deltaX),deltaY:Math.round(se.deltaY)}).catch(()=>{})}};return ee.addEventListener("wheel",ue,{passive:!1}),()=>ee.removeEventListener("wheel",ue)},[e]);const{cursorPos:Se,handleToggleInputMode:oe,handleZoomReset:de}=iu({containerRef:c,viewportRef:l,imgRef:u,inputMode:R,setInputMode:j,minZoom:Ce,zoomRef:U,panXRef:$,panYRef:K,setPanX:B,setPanY:N,setZoom:A,lastWheelTimeRef:L,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:D,clampPan:ke,isMobile:v,mobileFillZoom:S});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ae,onContextMenu:ee=>ee.preventDefault(),onFocus:()=>w(!0),onBlur:()=>w(!1),tabIndex:0,children:[t.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[te?t.jsx("img",{ref:u,src:te,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${C}) translate(${P}%, ${q}%)`,transformOrigin:"center center",cursor:R==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:W,onContextMenu:ee=>ee.preventDefault(),onDragStart:ee=>ee.preventDefault()}):t.jsx(au,{waitingLabel:le,waitingHint:he,transportType:i}),R==="mouse"&&te&&t.jsx(ru,{cursorPos:Se,viewportRef:l,imgRef:u}),I.map(ee=>{const se={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ee.type];return t.jsxs("div",{style:{position:"absolute",left:ee.x,top:ee.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${se}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),t.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${se}, 0.9)`,boxShadow:`0 0 12px rgba(${se}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ee.id)})]}),t.jsx(nu,{inputMode:R,onToggleInputMode:oe,isImeOpen:k,setIsImeOpen:T,isMenuOpen:x,setIsMenuOpen:y,imeText:g,setImeText:p,handleImeSubmit:ce,isConnActive:X,zoom:C,isMobile:v,mobileFillZoom:S,onZoomOut:()=>A(ee=>Math.max(.5,ee-.25)),onZoomReset:de,onZoomIn:()=>A(ee=>Math.min(5,ee+.25)),transportType:i,screenshotUsage:o,lastActionStatus:m}),t.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 jt(e){return(typeof e=="string"?e.trim():"")||void 0}function Zt(e,s){const r=jt(s);return r?`${e}:${r}`:void 0}function ts(e,s,r){const n=Zt(s,r),o=jt(r);n&&e.push(n),o&&e.push(o)}function Ms(e){const s=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),s.push(n));return s}function Gi(e){return jt(e.providerSessionId)||jt(e.sessionId)||jt(e.tabKey)||jt(e.routeId)}function _a(e){return Ms([jt(e.providerSessionId),jt(e.sessionId)])}function ss(e){const s=[];return ts(s,"provider",e.providerSessionId),ts(s,"session",e.sessionId),ts(s,"tab",e.tabKey),ts(s,"route",e.routeId),Ms(s)}function cu(e){const s=[];return jt(e.providerSessionId)?(ts(s,"provider",e.providerSessionId),Ms(s)):jt(e.sessionId)?(ts(s,"session",e.sessionId),Ms(s)):jt(e.tabKey)?(ts(s,"tab",e.tabKey),Ms(s)):jt(e.routeId)?(ts(s,"route",e.routeId),Ms(s)):[]}function Da(e){return Zt("provider",e.providerSessionId)||Zt("session",e.sessionId)||Zt("tab",e.tabKey)||Zt("route",e.routeId)||"unknown:"}function hr(e){return _a(e)[0]}function qi(e){const s=jt(e.providerSessionId),r=jt(e.sessionId),n=jt(e.tabKey),o=jt(e.routeId),i=[Zt("provider",s),Zt("session",r),Zt("tab",n),Zt("route",o)].filter(u=>typeof u=="string"),c=ss({providerSessionId:s,sessionId:r,tabKey:n,routeId:o}),l=Da({providerSessionId:s,sessionId:r,tabKey:n,routeId:o});return{providerSessionId:s,sessionId:r,tabKey:n,routeId:o,canonicalKey:l,targetKey:l,targetValue:Gi({providerSessionId:s,sessionId:r,tabKey:n,routeId:o}),historySessionId:hr({providerSessionId:s,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function cr(e,s){const r=qi(e);return cu(s).some(n=>r.lookupKeys.includes(n))}function pn(e,s={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:o=60}=s,i=Date.now()-e,c=Math.floor(i/1e3);if(c<o)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const u=Math.floor(l/60);if(u<24)return`${u}h${r}`;const m=Math.floor(u/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const Yi=e=>pn(e);function lu(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden,completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function Ws(e){const s=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",o=e.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:o}}function du(e){const s=new Map,r=(n,o)=>{n&&s.set(n,{sessionId:n,...lu(o)})};for(const n of e)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const o of n.childSessions||[])r(o.id,o)}return s}function rn(e,s){if(e.sessionId){const r=s.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,completionMarker:"",seenCompletionMarker:""}}function hn(e,s,r){const n=rn(e,s),o=Ws(e),i=ss(e).map(I=>{var b;return(b=r==null?void 0:r.notificationStateBySessionId)==null?void 0:b.get(I)}).find(I=>!!I),c=o.isReconnecting,l=o.isConnecting,u=o.isGenerating,m=o.isWaiting,d=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||m,g=n.inboxBucket==="working"||u,w=!!(n.inboxBucket==="task_complete"&&(i?i.unreadCount>0:n.unread)&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:w,requiresAction:d,isWorking:g,isReconnecting:c,isConnecting:l,isGenerating:u,isWaiting:m,inboxBucket:d?"needs_attention":g?"working":w?"task_complete":"idle"}}function uu(e,s,r){return hn(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation,notificationStateBySessionId:r==null?void 0:r.notificationStateBySessionId}).unread}function Xi({activeConv:e,onModalButton:s}){const[r,n]=a.useState(null);if(a.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Ws(e).isWaiting||!e.modalButtons)return null;const i=l=>{r||(n(l),s(l))},c=l=>l.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return t.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&t.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[t.jsx(or,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,u)=>{const m=c(l).toLowerCase(),d=/^(run|approve|accept|yes|allow|always)/.test(m),g=/^(reject|deny|delete|remove|abort)/.test(m),p=r===l,w=r!==null;return t.jsx("button",{onClick:()=>i(l),disabled:w,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${d?"font-extrabold":g?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${w&&!p?"opacity-40":"opacity-100"} ${w?"cursor-not-allowed":"cursor-pointer"}`,style:d?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:g?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:p?"⏳ ...":c(l)},u)})})]})]})}const Ea="adhdev_controls_bar_visible",la="adhdev:controlsbarvisibilitychange";function Ln(e){if(!e)return!1;try{return e.getItem(Ea)==="1"}catch{return!1}}function _o(e,s){if(s)try{s.setItem(Ea,e?"1":"0")}catch{}}function Do(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(la,{detail:{visible:e}}))}function Ji(){const[e,s]=a.useState(()=>typeof window>"u"?!1:Ln(window.localStorage));a.useEffect(()=>{const o=c=>{const l=c.detail;if(typeof(l==null?void 0:l.visible)=="boolean"){s(l.visible);return}s(Ln(window.localStorage))},i=c=>{c.key===Ea&&s(Ln(window.localStorage))};return window.addEventListener(la,o),window.addEventListener("storage",i),()=>{window.removeEventListener(la,o),window.removeEventListener("storage",i)}},[]);const r=a.useCallback(o=>{s(o),typeof window<"u"&&_o(o,window.localStorage),Do(o)},[]),n=a.useCallback(()=>{s(o=>{const i=!o;return typeof window<"u"&&_o(i,window.localStorage),Do(i),i})},[]);return{isVisible:e,setVisibility:r,toggleVisibility:n}}var mu=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function fu(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function wt(e,s){if(fu(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":mu.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 Qi(e){return wt(e)==="generating"}function it(e){return e?e.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" "):"IDE"}function pu(e){if(e<60)return`${Math.round(e)}s`;const s=Math.floor(e/60);if(s<60)return`${s}m`;const r=Math.floor(s/60),n=s%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const o=Math.floor(r/24),i=r%24;return`${o}d ${i}h`}function Rn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function xn(e,s){const r=typeof s=="string"?s.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const o=n.replace(/[\\/]+$/,""),i=o.split(/[\\/]/).filter(Boolean);return i[i.length-1]||o}function hu(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const s=e.split("_"),r=s[s.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function xu(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function bu(e){return hu(e.trim().replace(/\.local$/i,""))}function gu(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function Zi(e,s={}){var o,i;const r=[e.hostname,(o=e.machine)==null?void 0:o.hostname,(i=e.system)==null?void 0:i.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!xu(c));if(r&&r!=="Unknown")return bu(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function $t(e,s={}){return gu(e)||Zi(e,s)}function ec(e){return!e||!Array.isArray(e.items)?[]:e.items.map(s=>String((s==null?void 0:s.value)||(s==null?void 0:s.shortValue)||"").trim()).filter(Boolean)}function tc(e,s,r={}){const n=String(s).trim();if(!e||!Array.isArray(e.items)||!n)return"";const o=e.items.find(i=>String((i==null?void 0:i.id)||"").trim()===n);return o?String(r.preferShortValue?o.shortValue||o.value||"":o.value||o.shortValue||"").trim():""}function js(e,s){return ec(e).join(" · ")}function lr(e){return e.transport==="pty"}function Ts(e){return e.transport==="acp"}function yu(e,s){var r,n;return(r=s==null?void 0:s.providerLabels)!=null&&r[e]?s.providerLabels[e]:(n=s==null?void 0:s.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?s.providerLabels[e.toLowerCase()]:s!=null&&s.agentName&&s.agentName!==e?s.agentName:it(e)}function Eo(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const o=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=it(r||"").trim().toLowerCase();return n===o||n===i||n===c}function vu(e){return wt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function wu(e){if(!Array.isArray(e)||e.length<=1)return e;const s=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const o=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),i=s.get(o),c=wt(n.status);if(!i){s.set(o,{...n,status:c});continue}const l=r.indexOf(i.status||"idle"),u=r.indexOf(c||"idle");u>=0&&(l<0||u<l)&&s.set(o,{...n,status:c})}return Array.from(s.values())}function ju(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function ku(e){var r,n;const s=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return s&&ju(s.receivedAt)||0}function Su(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function da(e){return Math.max(Su(e),ku(e.activeChat))}function Nu(e,s,r,n,o,i){const c=s-e;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:o.localeCompare(i)}function $a(e,s){return Nu(da(e),da(s),$t(e,{fallbackId:e.id}),$t(s,{fallbackId:s.id}),e.id,s.id)}const sc="adhdev_notification_prefs",$o={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Cu(){try{const e=localStorage.getItem(sc);if(e){const s=JSON.parse(e);return{...$o,...s}}}catch{}return{...$o}}function Iu(e){try{localStorage.setItem(sc,JSON.stringify(e))}catch{}}let Qt=Cu(),zr=[];function Au(){zr.forEach(e=>e())}function Mu(e){Qt={...Qt,...e},Iu(Qt),Au()}function Tu(){const[,e]=a.useState(0);a.useEffect(()=>{const r=()=>e(n=>n+1);return zr.push(r),()=>{zr=zr.filter(n=>n!==r)}},[]);const s=a.useCallback(r=>{Mu(r)},[]);return[{...Qt},s]}function Zs(e){if(!Qt.globalEnabled)return!1;switch(e){case"disconnect":return Qt.disconnectAlert;case"completion":return Qt.completionAlert;case"approval":return Qt.approvalAlert;case"browser":return Qt.browserNotifications;default:return!0}}const Lu={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function rc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function nc(){return"Notification"in window&&Notification.permission==="granted"}let cs=null;async function Ru(){if(cs!==null)return cs;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return cs=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(cs=!!await e.pushManager.getSubscription(),cs):(cs=!1,!1)}catch{return cs=!1,!1}}function ua(e,s,r){if(nc())try{const n=new Notification(e,{body:s,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function Pu(e,s={}){const r={...Lu,...s},n=a.useRef(new Map),o=a.useRef(0),i=a.useRef(null);a.useEffect(()=>{Ru().then(l=>{i.current=l})},[]);const c=a.useCallback((l,u,m)=>{const d=Date.now();d-o.current<r.throttleMs||(o.current=d,ua(l,u,m))},[r.throttleMs]);a.useEffect(()=>{var l;if(!(!r.enabled||!nc())&&Zs("browser")&&i.current!==!0){if(document.hasFocus()){for(const u of e)n.current.set(u.id,wt(u.status,{activeModal:u.activeModal}));return}for(const u of e){const m=n.current.get(u.id),d=wt(u.status,{activeModal:u.activeModal}),g=u.name||u.id;if(r.onApproval&&Zs("approval")&&d==="waiting_approval"&&m!=="waiting_approval"){const p=((l=u.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${g} — Approval needed`,p.slice(0,120),`approval-${u.id}`)}r.onComplete&&Zs("completion")&&Qi(m)&&d==="idle"&&c(`✅ ${g} — Task complete`,"Agent has finished generating",`complete-${u.id}`),r.onError&&d==="error"&&m!=="error"&&c(`⚠️ ${g} — Error`,"Agent encountered an error",`error-${u.id}`),n.current.set(u.id,d)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const _u=/^(run|approve|accept|yes|allow|always)/,Du=/^(run|approve|accept|yes|allow|always|proceed|save)/,Eu=/^(reject|deny|delete|remove|abort|cancel|no)/;function Ba(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function $u(e){const s=Ba(e).toLowerCase();return _u.test(s)?"primary":Eu.test(s)?"danger":"default"}function Bu(e){return Du.test(Ba(e).toLowerCase())?"approve":"reject"}function Ku(e){return e.map((s,r)=>({label:Ba(s),variant:$u(s),action:Bu(s),button:s,buttonIndex:r}))}function Ou(e,s){const r=e||"Approval requested",n=s!=null&&s.length?s.map(o=>`[${o}]`).join(" "):"[Approve] [Reject]";return`⚡ Approval requested: ${r}
28
+ ${n}`}function Wu(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Hu(e,s,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,s,"approve").catch(o=>n==null?void 0:n("approve",o))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,s,"reject").catch(o=>n==null?void 0:n("reject",o))}}]}class Fu{constructor(){qe(this,"dedupMap",new Map);qe(this,"DEDUP_WINDOW_MS",5e3);qe(this,"DEDUP_MAX_SIZE",50);qe(this,"DEDUP_CLEANUP_AGE_MS",1e4);qe(this,"toastCallbacks",[]);qe(this,"systemMessageCallbacks",[]);qe(this,"clearSystemMessageCallbacks",[]);qe(this,"resolveActionFn",null);qe(this,"viewRequestRespondFn",null);qe(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==s)}}onSystemMessage(s){return this.systemMessageCallbacks.push(s),()=>{this.systemMessageCallbacks=this.systemMessageCallbacks.filter(r=>r!==s)}}onClearSystemMessage(s){return this.clearSystemMessageCallbacks.push(s),()=>{this.clearSystemMessageCallbacks=this.clearSystemMessageCallbacks.filter(r=>r!==s)}}setResolveAction(s){this.resolveActionFn=s}setIdes(s){this.ides=s}setViewRequestRespond(s){this.viewRequestRespondFn=s}emitToast(s){for(const r of this.toastCallbacks)r(s)}showToast(s,r="info",n){const o=(n==null?void 0:n.id)||Date.now();this.emitToast({id:o,message:s,type:r,timestamp:o,duration:5e3,...n})}emitSystemMessage(s,r){for(const n of this.systemMessageCallbacks)n(s,r)}isDuplicate(s){const r=Date.now(),n=this.dedupMap.get(s)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(s,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[o,i]of this.dedupMap)r-i>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(o);return!1}resolveOwningDaemon(s){if(s.daemonId){const o=this.ides.find(i=>i.id===s.daemonId&&i.type==="adhdev-daemon");if(o)return o}const r=s.targetSessionId&&this.findOwningSession(s.targetSessionId)||void 0;if(r){const o=r.daemonId;if(o){const i=this.ides.find(c=>c.id===o&&c.type==="adhdev-daemon");if(i)return i}}const n=this.ides.filter(o=>o.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(s){for(const r of this.ides)if(r.id===s||r.sessionId===s||(Array.isArray(r.childSessions)?r.childSessions:[]).some(o=>(o==null?void 0:o.id)===s))return r;return null}resolveActionRouteTarget(s){if(s.targetSessionId){const r=this.findOwningSession(s.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return s.daemonId||null}resolveConversationKey(s){return s.targetSessionId?s.targetSessionId:s.daemonId?s.daemonId:null}handleRawEvent(s,r){var I,b;const n=this.resolveConversationKey(s),o=Number.isFinite(s.timestamp)?Number(s.timestamp):Date.now(),i=n||s.daemonId||"",c=s.requestId||s.targetName||s.requesterName||s.modalMessage||String(o),l=`${i}:${s.event}:${c}`;if(this.isDuplicate(l))return;const u=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,m=(u==null?void 0:u.type)||"";let d=it(m);const g=this.resolveOwningDaemon(s);if(g){const f=$t(g,{fallbackId:g.id});f&&(d=!m||m==="adhdev-daemon"?f:`${f}/${d}`)}let p="",w="info";if(s.event==="agent:generating_completed"){const f=s.duration?` (${s.duration}s)`:"";p=`✅ ${d} agent task completed${f}`,w="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(s.event!=="agent:generating_started")if(s.event==="agent:waiting_approval"){if(p=`⚡ ${d} approval needed`,w="warning",n&&!((I=s.modalButtons)!=null&&I.length)&&this.emitSystemMessage(n,{role:"system",timestamp:o,content:Ou(s.modalMessage,s.modalButtons),_localId:`sys_approval_${o}`}),(b=s.modalButtons)!=null&&b.length&&this.resolveActionFn){const f=this.resolveActionRouteTarget(s);if(!f)return;const x=this.resolveActionFn,y=Ku(s.modalButtons).map(v=>({label:v.label,variant:v.variant,onClick:()=>{x(f,"resolve_action",{action:v.action,button:v.button,buttonIndex:v.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),k=Wu(d,s.modalMessage,p),T=Date.now();this.emitToast({id:T,message:k,type:w,timestamp:T,targetKey:n||f,actions:y,duration:15e3}),p=""}}else if(s.event==="monitor:long_generating"){const f=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";p=`⚠️ ${d} agent is taking a long time${f}`,w="warning",Zs("browser")&&!document.hasFocus()&&ua(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${f.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const f=s.requesterName||"A team member",x=s.requestId,y=s.orgId;if(p=`👁️ ${f} wants to view your session`,w="warning",x&&y&&this.viewRequestRespondFn){const k=Date.now(),T=Hu(y,x,this.viewRequestRespondFn,(v,R)=>console.error(`[EventManager] ${v} view request failed:`,R));this.emitToast({id:k,message:p,type:w,timestamp:k,actions:T,duration:3e4}),p=""}Zs("browser")&&!document.hasFocus()&&ua("👁️ View Request",`${f} wants to view your session`,`view-request-${x}`)}else s.event==="team:view_request_approved"?(p="✅ View request approved",w="success"):s.event==="team:view_request_rejected"&&(p=`❌ ${s.targetName||"Team member"} declined your view request`,w="warning");if(p){const f=Date.now();this.emitToast({id:f,message:p,type:w,timestamp:f,targetKey:n||s.daemonId,duration:5e3})}}}const dt=new Fu,Bo=new Map;function Ds(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ls(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Uu(e){return!Ds(e)||!Ds(e.controlResult)||!Array.isArray(e.controlResult.options)?null:e.controlResult}function Ar(e){return!Ds(e)||!Ds(e.controlResult)||typeof e.controlResult.ok!="boolean"?null:e.controlResult}function zs(e){if(!(!Ds(e)||typeof e.error!="string"||!e.error.trim()))return e.error}function Mr(e){return Ds(e)&&e.success===!1}function zu(e){var s,r;for(const n of e||[]){if(n.type==="toast"&&((s=n.toast)!=null&&s.message)){const o=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";dt.showToast(n.toast.message,o);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const o=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";dt.showToast(n.notification.body,o)}}}function Vu(e,s){return e&&Ls(e.currentValue)?e.currentValue:s}function Gu(e,s){return Ls(s)?Ls(e)?typeof e=="string"&&e.trim()==="":!0:!1}function qu(e,s){var i,c;if((s.now??Date.now())<s.localOverrideUntil){const l=s.localValues[e];if(Ls(l))return l}const n=(i=s.controlValues)==null?void 0:i[e];if(Ls(n))return n;const o=(c=s.defaultValues)==null?void 0:c[e];return Ls(o)?o:void 0}function Vr(e,s){return e.options||s[e.id]||[]}const Yu={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 Xu(e,s,r){var n;return((n=Yu[s])==null?void 0:n.has(r.id))===!0}function Ka(e,s){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Xu(s.hostIdeType,s.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function Pn(e,s){return{value:s}}function Ju(e,s,r){var o;return r?((o=Vr(e,s).find(i=>i.value===r))==null?void 0:o.label)||r:""}const Qu={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Zu({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,controls:i,controlValues:c}){const{sendCommand:l}=Tt(),u=`${e}:${s||n}`,m=Qu[n]||"#94a3b8",[d,g]=a.useState({}),p=a.useRef({}),w=a.useRef(c);p.current=d,w.current=c;const I=a.useRef(0),b={};for(const L of i||[])L.defaultValue!==void 0&&(b[L.id]=L.defaultValue);const f={...b,...c||{},...Date.now()<I.current?d:{}};a.useEffect(()=>{c&&Date.now()>I.current&&g({})},[c]);const[x,y]=a.useState(Bo.get(u)||{}),[k,T]=a.useState(null),[v,R]=a.useState(null),j=a.useCallback(async(L,U={})=>{const $={...U,...s&&{targetSessionId:s}};return await l(e,L,$)},[e,s,l]),S=a.useCallback(async(L,U={})=>{const $=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await j("invoke_provider_script",{...$,scriptName:L,...U})},[j,n,r,s]),h=a.useCallback((L,U,$)=>{const K=Vu($,U);g(X=>({...X,[L.id]:K})),zu($==null?void 0:$.effects)},[]),E=a.useCallback((L,U)=>{g($=>{const K={...$};return U===void 0?delete K[L.id]:K[L.id]=U,K}),I.current=0},[]);if(!i||i.length===0)return null;const C=Ka(i,{hostIdeType:r,providerType:n});if(C.length===0)return null;const A=async L=>{if(k===L.id){T(null);return}if(Vr(L,x).length>0){T(L.id);return}if(L.dynamic&&L.listScript){R(L.id);try{const $=await S(L.listScript,{}),K=Uu($);if(!K){const le=zs($);le&&dt.showToast(le,"warning");return}const X=K.options;y(le=>{const he={...le,[L.id]:X};return Bo.set(u,he),he});const te=qu(L.id,{localOverrideUntil:I.current,localValues:p.current,controlValues:w.current,defaultValues:b});if(Gu(te,K.currentValue)){const le=K.currentValue;g(he=>({...he,[L.id]:le}))}T(L.id)}catch($){const K=$ instanceof Error?$.message:`Could not load ${L.label}`;dt.showToast(K,"warning")}finally{R(null)}}},P=async(L,U)=>{T(null);const $=(c==null?void 0:c[L.id])??b[L.id];g(K=>({...K,[L.id]:U})),I.current=Date.now()+5e3;try{if(!L.setScript)return;const K=await S(L.setScript,Pn(L,U)),X=Ar(K);if(X&&!X.ok||Mr(K))throw new Error((X==null?void 0:X.error)||zs(K)||`Could not update ${L.label}`);h(L,U,X)}catch(K){E(L,$);const X=K instanceof Error?K.message:`Could not update ${L.label}`;dt.showToast(X,"warning")}},B=async L=>{const U=Vr(L,x).map(he=>he.value);if(U.length===0)return;const $=String(f[L.id]||""),X=(U.indexOf($)+1)%U.length,te=U[X];if(typeof te!="string")return;const le=(c==null?void 0:c[L.id])??b[L.id];g(he=>({...he,[L.id]:te})),I.current=Date.now()+5e3;try{if(!L.setScript)return;const he=await S(L.setScript,Pn(L,te)),Ce=Ar(he);if(Ce&&!Ce.ok||Mr(he))throw new Error((Ce==null?void 0:Ce.error)||zs(he)||`Could not update ${L.label}`);h(L,te,Ce)}catch(he){E(L,le);const Ce=he instanceof Error?he.message:`Could not update ${L.label}`;dt.showToast(Ce,"warning")}},q=async L=>{const $=!f[L.id],K=(c==null?void 0:c[L.id])??b[L.id];g(X=>({...X,[L.id]:$})),I.current=Date.now()+5e3;try{if(!L.setScript)return;const X=await S(L.setScript,Pn(L,$)),te=Ar(X);if(te&&!te.ok||Mr(X))throw new Error((te==null?void 0:te.error)||zs(X)||`Could not update ${L.label}`);h(L,$,te)}catch(X){E(L,K);const te=X instanceof Error?X.message:`Could not update ${L.label}`;dt.showToast(te,"warning")}},N=async L=>{if(!L.invokeScript)return;if(L.confirmMessage){const $=[L.confirmTitle,L.confirmMessage,L.confirmLabel].filter(X=>typeof X=="string"&&X.trim().length>0);if(!window.confirm($.join(`
29
+
30
+ `)))return}const U=(c==null?void 0:c[L.id])??b[L.id];try{const $=await S(L.invokeScript),K=Ar($);if(K&&!K.ok||Mr($))throw new Error((K==null?void 0:K.error)||zs($)||`Could not run ${L.label}`);K&&h(L,U??!0,K)}catch($){E(L,U);const K=$ instanceof Error?$.message:`Could not run ${L.label}`;dt.showToast(K,"warning")}};return t.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${m}33`,background:`${m}12`,color:m},children:o}),C.map(L=>{const U=String(f[L.id]||""),$=Ju(L,x,U),K=k===L.id,X=v===L.id,te=Vr(L,x),le="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(L.type){case"select":return t.jsxs("div",{className:"relative max-w-full",children:[t.jsxs("button",{type:"button",className:`${le} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:K?`${m}55`:"var(--border-default)",background:K?`${m}10`:"var(--surface-tertiary)",color:U?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void A(L),title:L.label,children:[L.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:X?"Loading…":$||L.label}),t.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),K&&te.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>T(null)}),t.jsxs("div",{className:"absolute bottom-full left-0 z-[60] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[t.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:L.label}),te.map(he=>t.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-[12px] transition-colors",style:{background:he.value===U?`${m}14`:"transparent",color:he.value===U?"var(--text-primary)":"var(--text-secondary)",borderLeft:he.value===U?`2px solid ${m}`:"2px solid transparent"},title:he.description||he.label,onMouseEnter:Ce=>{Ce.currentTarget.style.background=`${m}10`},onMouseLeave:Ce=>{Ce.currentTarget.style.background=he.value===U?`${m}14`:"transparent"},onClick:()=>void P(L,he.value),children:[t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:he.label}),he.value===U&&t.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},he.value))]})]})]},L.id);case"cycle":return t.jsxs("button",{type:"button",className:`${le} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:U?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void B(L),title:`Click to cycle: ${te.map(he=>he.label).join(" → ")}`,children:[L.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:$||L.label}),t.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},L.id);case"toggle":return t.jsxs("button",{type:"button",className:`${le} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:U?`${m}44`:"var(--border-default)",background:U?`${m}14`:"var(--surface-tertiary)",color:U?m:"var(--text-muted)"},onClick:()=>void q(L),"aria-pressed":!!U,children:[L.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),L.label]},L.id);case"action":return t.jsxs("button",{type:"button",className:`${le} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void N(L),children:[L.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:L.resultDisplay==="inline"&&U?`${L.label}: ${U}`:L.label})]},L.id);case"display":return t.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:U?"var(--text-primary)":"var(--text-muted)"},children:[L.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:U?`${L.label}: ${U}`:L.label})]},L.id);default:return null}})]})})}function em({isActive:e=!0,isCliTerminal:s=!1,routeId:r,sessionId:n,hostIdeType:o,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:m}=Ji(),d=Ka(l,{hostIdeType:o,providerType:i});return!e||s||d.length===0||!m?null:t.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:t.jsx(Zu,{routeId:r,sessionId:n,hostIdeType:o,providerType:i,displayLabel:c,controls:d,controlValues:u})})}function tm({hasDraft:e,isBusy:s=!1}){return!e||s}const ac=a.memo(function({contextKey:s,panelLabel:r,isSending:n,isBusy:o=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:u=!1}){const m=a.useRef(null),[d,g]=a.useState(""),{isVisible:p,toggleVisibility:w}=Ji();a.useEffect(()=>{g("")},[s]),a.useEffect(()=>{var b;l&&((b=m.current)==null||b.focus())},[s,l]);const I=async()=>{const b=d.trim();if(!b||o)return;await c(b)!==!1&&g("")};return t.jsxs("div",{className:"dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden transition-all duration-200 ease-out",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:[t.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[u&&t.jsx("button",{type:"button",onClick:w,"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:t.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[t.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),t.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),t.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:m,type:"text",placeholder:i||`Send message to ${r}...`,value:d,onChange:b=>g(b.target.value),onPaste:b=>{const f=b.clipboardData.getData("text");f&&g(x=>x+f),b.preventDefault()},onKeyDown:b=>{if(b.key==="Enter"){if(b.nativeEvent.isComposing){b.preventDefault();return}b.preventDefault(),I()}},onBlur:b=>{if(window.innerWidth<768){const f=b.relatedTarget;if((f==null?void 0:f.tagName)==="BUTTON")return;setTimeout(()=>{document.documentElement.scrollTop=0},300)}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:()=>{I()},disabled:tm({hasDraft:!!d.trim(),isBusy:o}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${d.trim()&&!o?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:d.trim()&&!o?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:t.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:d.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),i&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),st=e=>e.transport==="pty",Es=(e,s)=>st(e)?e.mode||"terminal":"chat",oc=(e,s)=>st(e)&&Es(e)==="terminal",Qe=e=>e.transport==="acp";function rs(e){return e.streamSource!=="agent-stream"}function os(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function ic(e){return e.machineName||""}function xr(e){return os(e)}function Wt(e){return e.agentType||""}function nn(e){return e.hostIdeType||""}function Oa(e){return e.displayPrimary||e.agentName||"Agent"}function cc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function sm(e){return e.lastMessagePreview||e.displaySecondary||""}function lc(e){return[e.displaySecondary,ic(e)].filter(Boolean)}function $s(e){return e.agentName||it(Wt(e))}function rm(e){var s,r;if(!rs(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return it(nn(e)||Wt(e))}function dc(e){return rs(e)?e.sessionId:e.nativeSessionId}function Ko(e){return rs(e)?"native":e.tabKey}function nm(e){return e.sessionId}function am(e,s){if(s)return rs(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function om(e,s){const r=Wt(e),n=rs(e),o=st(e)||Qe(e),i=n?o?$s(e)||(s==null?void 0:s.cliName)||it(nn(e)||r):s!=null&&s.type?it(s.type):it(nn(e)||r):$s(e);return{isNativeConversation:n,isCli:st(e),isAcp:Qe(e),isCliTerminal:oc(e),providerType:r,displayLabel:i,targetEntry:am(e,s)}}function im(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function ms(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||im(s==null?void 0:s.receivedAt)||0}function ma(e,s=0){return ms(e)||e.lastUpdated||s||0}function uc(e){return ms(e)||e.lastUpdated||0}function mc(e,s,r=uc){const n=r(s)-r(e);if(n!==0)return n;const o=(e.machineName||"").localeCompare(s.machineName||"");if(o!==0)return o;const i=e.displayPrimary.localeCompare(s.displayPrimary);if(i!==0)return i;const c=e.displaySecondary.localeCompare(s.displaySecondary);return c!==0?c:e.tabKey.localeCompare(s.tabKey)}function fa(e){var r;const s=wt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function cm(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!fa(e)&&!e.title.trim()}function lm(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(fa(r))-Number(fa(s));if(n!==0)return n;const o=r.messages.length-s.messages.length;return o!==0?o:mc(s,r)})[0]||null}function Ft(e,s){const r=e.filter(c=>c.routeId===s);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,o=r.filter(c=>c.streamSource==="agent-stream"),i=lm(o);return n?i&&cm(n)?i:n:i||r[0]||null}function ns(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Wa(e){return hr(e)||e.tabKey||e.routeId||null}function fc(e){const s=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(s)return s;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 o=Ft(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return o?Wa(o):null}function pc({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:o=!0}){const i=Os(),c=os(e),l=ic(e),u=e.transport==="cdp-page"||e.transport==="cdp-webview",m=e.streamSource==="agent-stream"&&!!e.agentName,d=!m&&(e.transport==="pty"||e.transport==="acp"),g=$s(e),p=rm(e),w=a.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),I=a.useCallback(()=>{if(r){r();return}const b=Wa(e);b&&i(ns(b))},[e,i,r]);return t.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[u&&(o?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:I,title:p,children:[t.jsx(Rt,{size:12}),t.jsx("span",{children:p})]}):t.jsxs("span",{className:"conversation-meta-chip",title:p,children:[t.jsx(Rt,{size:12}),t.jsx("span",{children:p})]})),m&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[t.jsx(ir,{size:12}),t.jsx("span",{children:g})]}),d&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[t.jsx(ir,{size:12}),t.jsx("span",{children:g})]}),l&&(o?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:w,title:l,children:[t.jsx(ws,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(ws,{size:12}),t.jsx("span",{children:l})]}))]})}function _n(e,s){return`${e}:${s}`}function dm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Tr(e,s){dm()&&console.debug(`[subscription-manager] ${e}`,s)}class um{constructor(){qe(this,"active",new Map)}subscribe(s,r,n,o){var m;const i=_n(n.topic,n.key),c=this.active.get(i);let l=!0;if(c)c.handlers.add(o),c.lastUpdate&&o(c.lastUpdate);else{const d={daemonId:r,request:n,handlers:new Set([o])};this.active.set(i,d),Tr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((m=s.sendData)==null?void 0:m.call(s,r,n))??!1}const u=()=>{var p;const d=this.active.get(i);if(!d||(d.handlers.delete(o),d.handlers.size>0))return;this.active.delete(i);const g={type:"unsubscribe",topic:n.topic,key:n.key};Tr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(p=s.sendData)==null||p.call(s,r,g)};return u.initialSendAccepted=l,u}publish(s){const r=_n(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,Ps.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.publish",topic:s.topic,payload:{key:s.key}}),n.handlers.forEach(o=>{o(s),Ps.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.handler_invoked",topic:s.topic,payload:{key:s.key}})}))}updateParams(s,r,n){const o=_n(s,r),i=this.active.get(o);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(s){var r;Tr("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=s.sendData)==null||r.call(s,n.daemonId,n.request)}resubscribeForDaemon(s,r){var o;const n=Array.from(this.active.values()).filter(i=>i.daemonId===s);Tr("resubscribe_daemon",{daemonId:s,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(o=r.sendData)==null||o.call(r,i.daemonId,i.request)}}const as=new um;function mm(e,s){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===s&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,mode:n.mode,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash,completionMarker:n.completionMarker,seenCompletionMarker:n.seenCompletionMarker});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 fm(e){const s=[],r=new Map;for(const n of e)if(n.parentId){const o=r.get(n.parentId)||[];o.push(n),r.set(n.parentId,o)}else s.push(n);return{topLevel:s,childrenByParent:r}}function an(e,s){const r=[],{daemonId:n,existingDaemon:o,existingEntries:i,timestamp:c}=s,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:m,childrenByParent:d}=fm(u),g=mm(i,n),p=e.machine?{...(o==null?void 0:o.machine)||{},...e.machine}:o==null?void 0:o.machine,w=m.filter(f=>f.kind==="workspace"&&f.transport==="cdp-page"),I=m.filter(f=>f.kind==="agent"&&f.transport==="pty"),b=m.filter(f=>f.kind==="agent"&&f.transport==="acp");r.push({...o||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...p&&{machine:p,platform:p.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},cdpConnected:w.some(f=>!!f.cdpConnected)});for(const f of w){const x=g.get(f.id),y=Qs(f,x),k=(d.get(f.id)||[]).map(T=>Qs(T,g.get(T.id)));r.push({id:`${n}:ide:${f.id}`,sessionId:f.id,providerSessionId:f.providerSessionId??(x==null?void 0:x.providerSessionId),parentSessionId:y.parentId,sessionKind:y.kind,transport:y.transport,sessionCapabilities:y.capabilities,type:y.providerType,status:y.cdpConnected?"online":"detected",daemonId:n,instanceId:f.id,workspace:y.workspace,terminals:0,childSessions:k,agents:k.map(T=>({id:T.id,name:T.providerName||T.providerType,type:T.providerType,status:T.status})),activeChat:y.activeChat,chats:[],cdpConnected:y.cdpConnected,...y.lastMessagePreview!==void 0&&{lastMessagePreview:y.lastMessagePreview},...y.lastMessageRole!==void 0&&{lastMessageRole:y.lastMessageRole},...y.lastMessageAt!==void 0&&{lastMessageAt:y.lastMessageAt},...y.lastMessageHash!==void 0&&{lastMessageHash:y.lastMessageHash},lastUpdated:y.lastUpdated,unread:y.unread,lastSeenAt:y.lastSeenAt,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,seenCompletionMarker:y.seenCompletionMarker,surfaceHidden:y.surfaceHidden,...y.controlValues!==void 0&&{controlValues:y.controlValues},...y.providerControls!==void 0&&{providerControls:y.providerControls},...y.summaryMetadata!==void 0&&{summaryMetadata:y.summaryMetadata},timestamp:l})}for(const f of I){const x=g.get(f.id),y=Qs(f,x);r.push({id:`${n}:cli:${f.id}`,sessionId:f.id,providerSessionId:f.providerSessionId??(x==null?void 0:x.providerSessionId),parentSessionId:y.parentId,sessionKind:y.kind,transport:y.transport,sessionCapabilities:y.capabilities,type:y.providerType,agentType:y.providerType,status:y.status||"running",daemonId:n,instanceId:f.id,cliName:y.providerName||y.providerType,mode:y.mode||(x==null?void 0:x.mode)||"terminal",workspace:y.workspace||"",activeChat:y.activeChat,...y.resume!==void 0&&{resume:y.resume},...y.runtimeKey!==void 0&&{runtimeKey:y.runtimeKey},...y.runtimeDisplayName!==void 0&&{runtimeDisplayName:y.runtimeDisplayName},...y.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:y.runtimeWorkspaceLabel},...y.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:y.runtimeWriteOwner},...y.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:y.runtimeAttachedClients},...y.lastMessagePreview!==void 0&&{lastMessagePreview:y.lastMessagePreview},...y.lastMessageRole!==void 0&&{lastMessageRole:y.lastMessageRole},...y.lastMessageAt!==void 0&&{lastMessageAt:y.lastMessageAt},...y.lastMessageHash!==void 0&&{lastMessageHash:y.lastMessageHash},lastUpdated:y.lastUpdated,unread:y.unread,lastSeenAt:y.lastSeenAt,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,seenCompletionMarker:y.seenCompletionMarker,surfaceHidden:y.surfaceHidden,...y.controlValues!==void 0&&{controlValues:y.controlValues},...y.providerControls!==void 0&&{providerControls:y.providerControls},...y.summaryMetadata!==void 0&&{summaryMetadata:y.summaryMetadata},timestamp:l,_isCli:!0})}for(const f of b){const x=g.get(f.id),y=Qs(f,x);r.push({id:`${n}:acp:${f.id}`,sessionId:f.id,providerSessionId:f.providerSessionId??(x==null?void 0:x.providerSessionId),parentSessionId:y.parentId,sessionKind:y.kind,transport:y.transport,sessionCapabilities:y.capabilities,type:y.providerType,agentType:y.providerType,status:y.status||"running",daemonId:n,instanceId:f.id,cliName:y.providerName||y.providerType,mode:"chat",workspace:y.workspace||"",activeChat:y.activeChat,...y.runtimeKey!==void 0&&{runtimeKey:y.runtimeKey},...y.runtimeDisplayName!==void 0&&{runtimeDisplayName:y.runtimeDisplayName},...y.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:y.runtimeWorkspaceLabel},...y.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:y.runtimeWriteOwner},...y.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:y.runtimeAttachedClients},...y.lastMessagePreview!==void 0&&{lastMessagePreview:y.lastMessagePreview},...y.lastMessageRole!==void 0&&{lastMessageRole:y.lastMessageRole},...y.lastMessageAt!==void 0&&{lastMessageAt:y.lastMessageAt},...y.lastMessageHash!==void 0&&{lastMessageHash:y.lastMessageHash},lastUpdated:y.lastUpdated,unread:y.unread,lastSeenAt:y.lastSeenAt,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,seenCompletionMarker:y.seenCompletionMarker,surfaceHidden:y.surfaceHidden,...y.controlValues!==void 0&&{controlValues:y.controlValues},...y.providerControls!==void 0&&{providerControls:y.providerControls},...y.summaryMetadata!==void 0&&{summaryMetadata:y.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const pm=15e3,hm=15e3,xm=6e4,bm=1200,Oo=12,gm=8e3,ym=4e3,Dn=new Map,En=new Map,Lr=new Set,er=new Map;function vm(e){if(!e||typeof e!="object")return null;const s=e,r=s.status;if(r&&typeof r=="object")return r;const n=s.result;if(n&&typeof n=="object"&&"status"in n){const o=n.status;if(o&&typeof o=="object")return o}return s}function Wo(e,s){const r=er.get(e);!r||r.size===0||(er.delete(e),r.forEach(n=>n(s)))}function wm(e,s){return new Promise(r=>{const n=er.get(e)||new Set;er.set(e,n);const o=c=>{clearTimeout(i),n.delete(o),n.size===0&&er.delete(e),r(c)},i=setTimeout(()=>o(!1),s);n.add(o)})}function br(){const{sendCommand:e,sendData:s}=Tt(),{injectEntries:r,getIdes:n}=ar();return a.useCallback(async(o,i)=>{if(!o)return;const c=(i==null?void 0:i.minFreshMs)??xm,l=En.get(o)||0;if(!(i!=null&&i.force)&&Lr.has(o)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=Dn.get(o);if(u)return u;const m=(async()=>{if(s&&!Lr.has(o)){const b=as.subscribe({sendData:s},o,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${o}`,params:{includeSessions:!0}},f=>{const x=n(),y=x.find(T=>T.id===o),k=an(f.status,{daemonId:o,existingDaemon:y,existingEntries:x,timestamp:f.timestamp});k.length>0&&r(k),En.set(o,Date.now()),Wo(o,!0)});if(b.initialSendAccepted?Lr.add(o):Lr.delete(o),!(i!=null&&i.force)&&b.initialSendAccepted&&await wm(o,bm))return}const d=await e(o,"get_status_metadata"),g=vm(d);if(!g)return;const p=n(),w=p.find(b=>b.id===o),I=an(g,{daemonId:o,existingDaemon:w,existingEntries:p,timestamp:g.timestamp||Date.now()});I.length>0&&r(I,{authoritativeDaemonIds:[o]}),En.set(o,Date.now()),Wo(o,!0)})().finally(()=>{Dn.delete(o)});return Dn.set(o,m),m},[n,r,e,s])}function jm(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function Rs(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:st(e)||Qe(e)?{agentType:Wt(e)}:e.streamSource==="agent-stream"?{agentType:Wt(e)}:s}function dr(e){return e?xr(e):""}function Vs(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Ha(e){if(!e)return null;if(Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return"Resolve the pending approval prompt before sending another message.";switch(e.status){case"waiting_approval":case"waiting_for_user_input":return"Resolve the pending approval prompt before sending another message.";default:return null}}function km(e){const s=e instanceof Error?e.message:String(e||""),r=s.toLowerCase();return r.includes("still processing the previous prompt")?"Wait for the current reply to finish before sending another message.":r.includes("awaiting confirmation")?"Resolve the pending approval prompt before sending another message.":r.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":r.includes("not running")?"Runtime is not available right now.":s||"Unable to send message right now."}const Sm=60,Nm=1e3;function hc(e={}){return e.isCliLike?Nm:Sm}function Cm(e={}){return hc(e)}const gr=60,Im=1e3,Fa=12e4,Am=new Set(["generating","waiting_approval","starting","streaming","working"]),Ho=new Map;function xc(e,s){return`${e}::${s}`}function pa(e=gr){return{liveMessages:[],cursor:gc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function bc(e){return _i(e)}function gc(e,s=gr){return{knownMessageCount:e.length,lastMessageSignature:bc(e[e.length-1]),tailLimit:s}}function Rr(e,s){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function Mm(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return[...e,...r];case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return[...e.slice(0,n),...r]}case"full":return r;default:return r}}class Tm{constructor(s){qe(this,"manager");qe(this,"sendData");qe(this,"daemonId");qe(this,"sessionId");qe(this,"historySessionId");qe(this,"subscriptionKey");qe(this,"snapshot");qe(this,"transportSubscription",null);qe(this,"listeners",new Set);qe(this,"retainCount",0);qe(this,"loadHistoryPromise",null);qe(this,"pendingDisconnectTimer",null);qe(this,"pendingSubscribeRetryTimer",null);this.manager=s.manager||as,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.snapshot=pa(Math.max(0,s.tailLimit??gr))}updateOptions(s){if(s.manager&&(this.manager=s.manager),s.sendData&&(this.sendData=s.sendData),s.historySessionId&&(this.historySessionId=s.historySessionId),s.tailLimit!==void 0){const r=Math.max(0,s.tailLimit);if(r!==this.snapshot.cursor.tailLimit){const n=Math.min(this.snapshot.cursor.knownMessageCount,this.snapshot.liveMessages.length);this.snapshot={...this.snapshot,cursor:{...this.snapshot.cursor,knownMessageCount:n,tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect())}}}getSnapshot(){return this.snapshot}hydrateLiveMessages(s){const r=Array.isArray(s)?s:[];if(r.length===0)return;const n=r,o=gc(n,this.snapshot.cursor.tailLimit);Rr(this.snapshot.liveMessages)===Rr(n)&&this.snapshot.cursor.knownMessageCount===o.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===o.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:o},this.emit())}subscribe(s){return this.listeners.add(s),s(this.snapshot),()=>{this.listeners.delete(s)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(s){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await s(),o=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...o,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+o.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}:{},knownMessageCount:this.snapshot.cursor.knownMessageCount,lastMessageSignature:this.snapshot.cursor.lastMessageSignature,...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}clearPendingSubscribeRetry(){this.pendingSubscribeRetryTimer&&(clearTimeout(this.pendingSubscribeRetryTimer),this.pendingSubscribeRetryTimer=null)}scheduleSubscribeRetry(){this.pendingSubscribeRetryTimer||!this.sendData||!this.daemonId||!this.sessionId||this.retainCount===0||(this.pendingSubscribeRetryTimer=setTimeout(()=>{if(this.pendingSubscribeRetryTimer=null,!this.sendData||!this.daemonId||!this.sessionId||this.retainCount===0)return;this.sendData(this.daemonId,this.buildSubscribeRequest())||this.scheduleSubscribeRetry()},Im))}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),s=>{this.handleUpdate(s)}),this.transportSubscription.initialSendAccepted||this.scheduleSubscribeRetry())}disconnect(){var s;this.clearPendingSubscribeRetry(),(s=this.transportSubscription)==null||s.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(s=>s(this.snapshot))}handleUpdate(s){this.clearPendingSubscribeRetry();const r=Mm(this.snapshot.liveMessages,s),n={knownMessageCount:r.length,lastMessageSignature:typeof s.lastMessageSignature=="string"?s.lastMessageSignature:bc(r[r.length-1]),tailLimit:this.snapshot.cursor.tailLimit};Rr(this.snapshot.liveMessages)===Rr(r)&&this.snapshot.cursor.knownMessageCount===n.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===n.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:r,cursor:n},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:n.knownMessageCount,lastMessageSignature:n.lastMessageSignature}),this.emit())}}function yc(e){const s=xc(e.daemonId,e.sessionId),r=Ho.get(s);if(r)return r.updateOptions(e),r;const n=new Tm(e);return Ho.set(s,n),n}function Lm(e,s){return{...e,loadHistoryPage:s}}function Rm(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function Pm(e,s={}){const r=String(e.status||"").trim().toLowerCase();if(Am.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=s.now??Date.now(),o=Math.max(0,Number(s.recentActivityMs??Fa)),i=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return i>0?n-i<=o:Array.isArray(e.messages)&&e.messages.length>0}function _m(e=Fa){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Dm(e,s={}){const r=new Set,n=[];for(const o of e){if(!Pm(o,s))continue;const i=xr(o),c=o.sessionId||"";if(!i||!c)continue;const l=xc(i,c);if(r.has(l))continue;r.add(l);const u=hr(o);n.push({daemonId:i,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(Rm),{descriptors:n,signature:n.map(o=>`${o.subscriptionKey}|${o.historySessionId}`).join("||")}}function Em(e,s){const{sendData:r,sendCommand:n}=Tt(),o=(s==null?void 0:s.enabled)!==!1,i=xr(e),c=e.sessionId||"",l=hr(e)||c,u=`daemon:${i}:session:${c}`,m=Math.max(0,(s==null?void 0:s.tailLimit)??gr),d=a.useMemo(()=>!o||!i||!c?null:yc({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:m}),[i,o,l,r,c,u,m]),[g,p]=a.useState(()=>(d==null?void 0:d.getSnapshot())||pa(m));a.useEffect(()=>{if(!d){p(pa(m));return}d.retain(),p(d.getSnapshot());const I=d.subscribe(b=>{p(b)});return()=>{I(),d.release()}},[d,m]),a.useEffect(()=>{d&&(d.hydrateLiveMessages(e.messages),p(d.getSnapshot()))},[e.messages,d]);const w=a.useCallback(async()=>{!d||!i||!c||await d.loadHistoryPage(async()=>{const I=e.agentType,b=await n(i,"chat_history",{agentType:I,offset:d.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),f=b&&typeof b=="object"&&"result"in b?b.result||{}:b||{};return{messages:Array.isArray(f.messages)?f.messages:[],hasMore:f.hasMore===!0}})},[e.agentType,d,i,l,n,c]);return a.useMemo(()=>Lm(g,w),[w,g])}function $m(e,s){const{sendData:r}=Tt(),n=(s==null?void 0:s.enabled)!==!1,o=Math.max(0,(s==null?void 0:s.tailLimit)??gr),i=Math.max(0,Number((s==null?void 0:s.recentActivityMs)??Fa)),c=_m(i),[l,u]=a.useState(0);a.useEffect(()=>{if(!n||e.length===0)return;const d=setInterval(()=>{u(g=>g+1)},c);return()=>{clearInterval(d)}},[e.length,n,c]);const m=a.useMemo(()=>Dm(e,{recentActivityMs:i}),[e,i,l]);a.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const d=m.descriptors.map(g=>yc({...g,sendData:r,tailLimit:o}));return d.forEach(g=>g.retain()),()=>{d.forEach(g=>g.release())}},[m.signature,n,r,o])}function Bm(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function Km(e){return Bm(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Om=60;function ha({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:o=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:m=!1,scrollToBottomRequestNonce:d,isInputActive:g=!0}){var Ce,ke,z,xe,D;const p=a.useRef(new Map),w=br();pr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const I=ot.useMemo(()=>Ws(e),[e.status,e.connectionState]),b=a.useMemo(()=>om(e,s),[e,s]),f=a.useMemo(()=>{var W;return Ka((W=b.targetEntry)==null?void 0:W.providerControls,{hostIdeType:e.hostIdeType,providerType:b.providerType})},[e.hostIdeType,b.providerType,(Ce=b.targetEntry)==null?void 0:Ce.providerControls]),x=hc({isCliLike:b.isCli||b.isAcp}),y=Cm({isCliLike:b.isCli||b.isAcp}),k=Em(e,{enabled:!!e.sessionId,tailLimit:y}),[T,v]=a.useState(x),R=e.tabKey,j=k.historyMessages,S=k.hasMoreHistory,h=k.historyError,E=k.liveMessages.length>0?k.liveMessages:e.messages;a.useEffect(()=>{v(x)},[x,R]);const C=Math.max(0,E.length-T),A=Oa(e),P=xr(e),B=Km(e),q=Ha(e),N=o||q,L=!!q,[U,$]=a.useState(!1);a.useEffect(()=>{const W=b.targetEntry;P&&(!W||W.providerControls===void 0||W.controlValues===void 0)&&w(P,{minFreshMs:3e4}).catch(()=>{})},[P,b.isAcp,(ke=b.targetEntry)==null?void 0:ke.providerControls,(z=b.targetEntry)==null?void 0:z.controlValues,w]);const K=a.useCallback(async()=>{if(!U){if(E.length>T){v(W=>Math.min(E.length,W+Om));return}$(!0);try{await k.loadHistoryPage()}finally{$(!1)}}},[k,U,E.length,T]),{allMessages:X,receivedAtMap:te}=a.useMemo(()=>{const W=C>0?E.slice(-T):E,Y=j.length===0?W:[...j,...W],ae={};return Y.forEach((ce,Se)=>{const oe=`${e.tabKey}:${sn(ce,Se)}`;let de=jm(ce)||p.current.get(oe)||0;de||(de=Date.now(),p.current.set(oe,de)),ae[sn(ce,Se)]=de}),{allMessages:Y,receivedAtMap:ae}},[e.tabKey,C,j,E,T]),le=a.useMemo(()=>l.filter(W=>W.routeId===e.tabKey).sort((W,Y)=>W.timestamp-Y.timestamp),[l,e.tabKey]),he=a.useMemo(()=>{if(E.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[t.jsx("div",{className:"connecting-logo-float",children:t.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),t.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[t.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",t.jsx("span",{className:"connecting-dots"})]}),t.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((I.isGenerating||e.status==="streaming")&&$(!1),e.status==="not_monitored"&&B)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(ir,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(_s,{size:14})," Open ",A," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&B)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(Ki,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(_s,{size:14})," Open ",A," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!U)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),t.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,B,i,c,U,E.length,A,I.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[m&&t.jsx(pc,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(Zd,{messages:X,actionLogs:le,agentName:$s(e)||A||"Agent",userName:u,isCliMode:b.isCli||b.isAcp,isWorking:I.isGenerating,contextKey:e.tabKey,receivedAtMap:te,onLoadMore:K,isLoadingMore:U,hasMoreHistory:S,hiddenLiveCount:C,loadError:h??void 0,emptyState:he,scrollToBottomRequestNonce:d}),t.jsx(em,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:b.providerType,displayLabel:b.displayLabel,controls:(xe=b.targetEntry)==null?void 0:xe.providerControls,controlValues:(D=b.targetEntry)==null?void 0:D.controlValues,isActive:g,isCliTerminal:b.isCliTerminal}),!b.isCliTerminal&&t.jsx(ac,{contextKey:e.tabKey,panelLabel:A,isSending:n,isBusy:L,statusMessage:N,onSend:r,isActive:g,showControlsToggle:f.length>0})]})}let vc=vs;function wc(){return vc()}class Wm{constructor(){qe(this,"listeners",new Map)}send(s){}isConnected(){return!1}on(s,r){return this.listeners.has(s)||this.listeners.set(s,new Set),this.listeners.get(s).add(r),()=>{var n;(n=this.listeners.get(s))==null||n.delete(r)}}emit(s,...r){var n;(n=this.listeners.get(s))==null||n.forEach(o=>o(...r))}}let jc=new Wm;class Hm{sendPtyInput(s,r,n){return!1}retryConnection(s){}getState(s){return"disconnected"}sendData(s,r){return!1}get(s){}onScreenshot(s,r){return()=>{}}onRuntimeEvent(s,r){return()=>{}}requestRuntimeSnapshot(s,r){return Promise.resolve()}}let et=new Hm;function Fm(e){e.dashboardWS&&(jc=e.dashboardWS),e.connectionManager&&(et=e.connectionManager),e.useDaemonsHook&&(vc=e.useDaemonsHook)}const Um=.5,zm=1.15;function ct(e){return Oa(e)}function ks(e){return lc(e).join(" · ")}function kc(e){if(e.lastMessagePreview)return e.lastMessagePreview;const s=[...e.messages].reverse().find(n=>!(n!=null&&n._localId))||e.messages[e.messages.length-1],r=Pa(s==null?void 0:s.content);return r||(e.title?e.title:ks(e)||"No messages yet")}function Sc(e,s){const{isReconnecting:r,isConnecting:n}=Ws(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function Vm(e,s){const r=["Chat",...lc(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function fs(e){return Sc(e)||ks(e)}function Gm(e){return`${ct(e)} · ${kc(e)}`}function qm(e){const s=nn(e),r=s?it(s):$s(e);return`${ct(e)} — ${r||"Agent"}`}function Ym(e){return $s(e)||"CLI"}function Nc(e){return cc(e)}function Cc(e){return e?`Remote · ${ct(e)||e.workspaceName||"Session"}`:"Remote"}function Xm({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:o=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var xe;vs();const{sendData:u}=Tt(),[m,d]=a.useState(!1),[g,p]=a.useState(1),[w,I]=a.useState({width:0,height:0}),[b,f]=a.useState({width:0,height:0}),x=a.useRef(null),y=a.useRef(null),k=a.useRef(!1),T=a.useRef(0),v=a.useRef(!1),R=a.useRef(""),j=a.useRef(null),S=a.useRef(!1),h=a.useRef(null),E=e.tabKey,C=e.sessionId||"",A=e.daemonId||((xe=e.routeId)==null?void 0:xe.split(":")[0])||e.routeId||"",P=Ha(e),B=m?i||P:"Runtime terminal unavailable",q=Um,N=zm,L=()=>{const D=b.width,W=b.height;if(!Number.isFinite(w.width)||w.width<=0||!Number.isFinite(w.height)||w.height<=0||!Number.isFinite(D)||D<=0||!Number.isFinite(W)||W<=0)return 1;const Y=w.width/D,ae=w.height/W;return Number(Math.min(N,Math.max(q,Math.min(Y,ae))).toFixed(2))},U=L(),$=k.current&&g>U,K=Number.isFinite(b.width)&&b.width>0?Math.max(w.width,Math.round(b.width*g)):w.width,X=Number.isFinite(b.height)&&b.height>0?Math.max(w.height,Math.round(b.height*g)):w.height,te=()=>{requestAnimationFrame(()=>{const D=y.current;D&&(D.scrollLeft=0,D.scrollTop=D.scrollHeight-D.clientHeight)})},le=()=>{var D,W;T.current=0,v.current=!1,R.current="",j.current=null,S.current=!1,h.current!==null&&(cancelAnimationFrame(h.current),h.current=null),d(!1),(W=(D=r.current)==null?void 0:D.reset)==null||W.call(D)},he=()=>{var D,W;T.current=0,v.current=!1,R.current="",j.current=null,S.current=!1,h.current!==null&&(cancelAnimationFrame(h.current),h.current=null),d(!0),(W=(D=r.current)==null?void 0:D.reset)==null||W.call(D)},Ce=()=>{var W;if(h.current=null,!c)return;const D=R.current;D&&(R.current="",(W=r.current)==null||W.write(D))},ke=D=>{D&&(R.current+=D,c&&h.current===null&&(h.current=requestAnimationFrame(Ce)))},z=(D,W=0,Y,ae)=>{var ce,Se,oe,de,ee;W>0&&T.current>=W||W===0&&v.current||(T.current=W,d(!0),typeof Y=="number"&&typeof ae=="number"&&Y>0&&ae>0&&((Se=(ce=r.current)==null?void 0:ce.resize)==null||Se.call(ce,Y,ae)),(de=(oe=r.current)==null?void 0:oe.reset)==null||de.call(oe),D&&((ee=r.current)==null||ee.write(D)))};return a.useEffect(()=>{le()},[C]),a.useEffect(()=>{var W;if(!C)return;const D=((W=et.onRuntimeEvent)==null?void 0:W.call(et,C,Y=>{if(!(!Y||Y.sessionId!==C)){if(Y.type==="runtime_snapshot"){if(!c){j.current={text:Y.text||"",seq:Y.seq||0,cols:Y.cols,rows:Y.rows};return}z(Y.text||"",Y.seq||0,Y.cols,Y.rows);return}if(Y.type==="session_output"){v.current=!0,typeof Y.seq=="number"&&(T.current=Math.max(T.current,Y.seq)),m||d(!0),typeof Y.data=="string"&&ke(Y.data);return}if(Y.type==="session_cleared"){if(!c){S.current=!0,R.current="",j.current=null;return}he()}}}))||(()=>{});return()=>{D()}},[A,C,r,c,m]),a.useEffect(()=>{var W,Y,ae;if(!C)return;A&&((W=et.getState)==null?void 0:W.call(et,A))==="connected"&&(d(!0),(Y=et.requestRuntimeSnapshot)==null||Y.call(et,A,C).catch(()=>{}));const D=(ae=et.onStateChange)==null?void 0:ae.call(et,(ce,Se)=>{var oe;ce!==A||Se!=="connected"||(d(!0),(oe=et.requestRuntimeSnapshot)==null||oe.call(et,A,C).catch(()=>{}))});return()=>{D==null||D()}},[A,C,r]),a.useEffect(()=>{s&&le()},[s,E,r]),a.useEffect(()=>{const D=x.current;if(!D||typeof ResizeObserver>"u")return;const W=new ResizeObserver(Y=>{const ae=Y[0];if(!ae)return;const{width:ce,height:Se}=ae.contentRect;I(oe=>{const de=Math.round(ce),ee=Math.round(Se);return oe.width===de&&oe.height===ee?oe:{width:de,height:ee}})});return W.observe(D),()=>W.disconnect()},[]),a.useEffect(()=>{(()=>{k.current||p(L())})()},[b.height,b.width,w.height,w.width]),a.useEffect(()=>{var W,Y;if(!c)return;S.current&&(S.current=!1,he());const D=j.current;D&&(j.current=null,z(D.text,D.seq,D.cols,D.rows)),A&&C&&((W=et.getState)==null?void 0:W.call(et,A))==="connected"&&((Y=et.requestRuntimeSnapshot)==null||Y.call(et,A,C).catch(()=>{})),R.current&&h.current===null&&(h.current=requestAnimationFrame(Ce)),requestAnimationFrame(()=>{var ae;(ae=r.current)==null||ae.bumpResize()})},[A,c,C]),a.useEffect(()=>()=>{h.current!==null&&(cancelAnimationFrame(h.current),h.current=null)},[]),a.useEffect(()=>{const D=W=>{var ae;const Y=W.detail;Y!=null&&Y.sessionId&&Y.sessionId!==C||m&&((ae=r.current)==null||ae.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",D),()=>{window.removeEventListener("adhdev:fit-cli-terminal",D)}},[m,C,r]),t.jsxs(t.Fragment,{children:[t.jsxs("div",{ref:x,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[t.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[t.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{k.current=!0,p(D=>{const W=Math.max(q,Number((D-.1).toFixed(2)));return W>U&&te(),W})},title:"Shrink terminal viewport",children:"-"}),t.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{k.current=!0,p(D=>{const W=Math.min(N,Number((D+.1).toFixed(2)));return W>U&&te(),W})},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{ref:y,className:$?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:t.jsx("div",{style:{width:K>0?`${K}px`:"100%",height:X>0?`${X}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:t.jsx("div",{style:{width:b.width>0?`${b.width}px`:"100%",height:b.height>0?`${b.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:g},children:t.jsx(zi,{ref:r,readOnly:!m||!c,sizingMode:"measured",onViewportMetrics:f,onInput:D=>{m&&(u==null||u(A,{type:"pty_input",sessionId:C,targetSessionId:C,data:D}))}})})})}),!m&&t.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:"Runtime terminal unavailable"})]}),t.jsx(ac,{contextKey:e.tabKey,panelLabel:ct(e),isSending:o,isBusy:!m||!!P,statusMessage:B,onSend:async D=>!m||P?!1:n(D),isActive:l&&c,showControlsToggle:!1})]})}function Jm({wsStatus:e,showReconnected:s,loginUrl:r,onReconnect:n}){const o=e==="disconnected"||e==="reconnecting"||e==="offline"||e==="auth_failed",i=e==="auth_failed"?"red":e==="offline"?"orange":"accent",c={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))"},l={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)"},u={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"};return t.jsxs(t.Fragment,{children:[o&&t.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5 justify-center",style:{background:c[i],borderBottom:l[i],color:u[i]},children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5",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}}),e==="offline"&&"Network offline — waiting for connection...",e==="disconnected"&&"Reconnecting to server...",e==="reconnecting"&&"Reconnecting to server...",e==="auth_failed"&&(r?t.jsxs(t.Fragment,{children:["Session expired."," ",t.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — please restart the server."),n&&e!=="auth_failed"&&t.jsx("button",{type:"button",className:"ml-3 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,disabled:e==="offline",children:"Reconnect now"})]}),s&&e==="connected"&&t.jsxs("div",{className:"py-2 px-4 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-b border-green-500/15 animate-[fadeIn_0.3s_ease]",children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})]})}function Qm({terminalBackend:e,isStandalone:s=!1,machineLabel:r,machineKey:n}){const o=a.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,c]=a.useState(!1);if(a.useEffect(()=>{if(!o){c(!1);return}try{c(localStorage.getItem(o)==="1")}catch{c(!1)}},[o]),!s||!e||e.backend!=="xterm"||i)return null;const l=(r==null?void 0:r.trim())||"This machine",u=()=>{if(o)try{localStorage.setItem(o,"1")}catch{}c(!0)};return t.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[t.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[t.jsxs("span",{children:[l," is using `xterm` fallback."]}),t.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),t.jsx("button",{type:"button",onClick:u,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 Ua({mode:e,onChange:s,compact:r=!1}){const n=r?14:15;return t.jsx("button",{type:"button",onClick:()=>s(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?t.jsx(Ta,{size:n}):t.jsx(es,{size:n})})}const qt="New session",Ic="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 Zm({wsStatus:e,isConnected:s,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const o=Object.values(n),i=o.filter(l=>l==="connected").length,c=o.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..."}:s?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function Fo({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Uo({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:o,onDelete:i}){const c=pn(e.updatedAt),l=!e.readAt;return t.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[t.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[s?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",s]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",c].filter(Boolean).join(" · ")]}),e.preview?t.jsx("span",{className:"dashboard-header-inbox-item-meta",children:e.preview}):null]}),t.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),n()},children:"Mark read"}):t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),o()},children:"Mark unread"}),t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),i()},children:"Delete"})]})]})}function ef({activeConv:e,wsStatus:s,isConnected:r,conversations:n,onOpenHistory:o,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:u,onHideConversation:m,hiddenConversations:d=[],onShowConversation:g,onShowAllHidden:p,onResetPanelsToMain:w,inboxOpen:I,onInboxOpenChange:b,hiddenOpen:f,onHiddenOpenChange:x,onOpenNewSession:y,actionShortcuts:k,notifications:T,notificationUnreadCount:v,onOpenNotification:R,onMarkNotificationRead:j,onMarkNotificationUnread:S,onDeleteNotification:h}){const{ides:E,p2pStates:C={}}=vs(),A=!!e&&st(e)&&!Qe(e),P=!!e&&Qe(e),B=l||(e?oc(e)?"terminal":"chat":null),[q,N]=a.useState(!1),L=a.useRef(null),U=a.useRef(null),$=E.filter(D=>D.type==="adhdev-daemon"),K=Zm({wsStatus:s,isConnected:r,daemonCount:$.length,p2pStates:C}),X=K.subtitle,te=K.tone==="connected"?"#22c55e":K.tone==="limited"?"#eab308":"#ef4444",le=K.tone==="connected"?"0 0 4px #22c55e80":K.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",he=a.useMemo(()=>T.filter(D=>!D.readAt),[T]),Ce=a.useMemo(()=>T.filter(D=>!!D.readAt),[T]),ke=a.useMemo(()=>he.slice(0,9),[he]),z=v;a.useEffect(()=>{if(!I)return;const D=W=>{var Y;(Y=L.current)!=null&&Y.contains(W.target)||b(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[I,b]),a.useEffect(()=>{if(!f)return;const D=W=>{var Y;(Y=U.current)!=null&&Y.contains(W.target)||x(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[f,x]),a.useEffect(()=>{if(!f&&!I)return;const D=W=>{if(!W.altKey)return;const Y=W.code.match(/^Digit([1-9])$/);if(!Y)return;const ae=Number(Y[1])-1,ce=f?d[ae]:void 0,Se=I?ke[ae]:void 0;if(!(!ce&&!Se)){if(W.preventDefault(),W.stopPropagation(),ce){g==null||g(ce),x(!1);return}Se&&(R(Se),b(!1))}};return window.addEventListener("keydown",D,!0),()=>window.removeEventListener("keydown",D,!0)},[d,f,I,ke,x,b,R,g]);const xe=D=>{if(!D)return;const W=n.find(Y=>Y.tabKey===D);W&&(m==null||m(W))};return t.jsxs("div",{className:"dashboard-header",children:[t.jsx("div",{className:"flex items-center gap-3",children:t.jsx("div",{className:"header-title-block",children:t.jsxs("div",{className:"header-title-row",children:[t.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[t.jsx(es,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?ct(e):"Dashboard"}),t.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:t.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:te,boxShadow:le}})})]}),t.jsxs("div",{className:"header-subtitle flex items-center",children:[t.jsx("span",{title:K.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:te,boxShadow:le}}),X&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",X]}),y&&t.jsx("button",{type:"button",onClick:y,className:"btn btn-secondary btn-sm ml-2",title:qt,"aria-label":qt,children:t.jsx(Hi,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(A||P||!Qe(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:ks(e)||ct(e),children:ct(e)}),(A||P)&&c&&t.jsxs(t.Fragment,{children:[A&&u&&B&&t.jsx(Ua,{mode:B,onChange:u,compact:!0}),t.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:P?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(Mt,{size:14})})]}),!Qe(e)&&t.jsx("button",{onClick:()=>o(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(Ma,{size:14})}),!A&&!Qe(e)&&t.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(Rt,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:L,children:[t.jsxs("div",{className:`dashboard-header-hidden${q?" is-drop-target":""}`,ref:U,onDragEnter:D=>{D.dataTransfer.types.includes("text/tab-key")&&(D.preventDefault(),N(!0))},onDragOver:D=>{D.dataTransfer.types.includes("text/tab-key")&&(D.preventDefault(),D.dataTransfer.dropEffect="move",N(!0))},onDragLeave:D=>{D.currentTarget.contains(D.relatedTarget)||N(!1)},onDrop:D=>{const W=D.dataTransfer.getData("text/tab-key");D.preventDefault(),N(!1),xe(W)},children:[t.jsxs("button",{type:"button",onClick:()=>x(!f),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${k!=null&&k.toggleHiddenTabs?` (${k.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(Oi,{size:16}),d.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:d.length})]}),f&&t.jsxs("div",{className:"dashboard-header-hidden-popover",children:[t.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),t.jsx(Fo,{value:k==null?void 0:k.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[w&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:w,children:"Reset panels"}),d.length>0&&p&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{p(),x(!1)},children:"Restore all"})]})]}),e&&m&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[t.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[t.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),t.jsx(Fo,{value:k==null?void 0:k.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:ct(e)})]}),d.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(D=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{g==null||g(D),x(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:ct(D)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(D)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(D)+1]}):null,ks(D)]})]},D.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>b(!I),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(fn,{size:16}),z>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:z})]}),I&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[he.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),he.map(D=>t.jsx(Uo,{notification:D,shortcutIndex:ke.indexOf(D)>=0?ke.indexOf(D)+1:void 0,onOpen:()=>R(D),onMarkRead:()=>j(D.id),onMarkUnread:()=>S(D.id),onDelete:()=>h(D.id)},D.id))]}),Ce.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),Ce.map(D=>t.jsx(Uo,{notification:D,onOpen:()=>R(D),onMarkRead:()=>j(D.id),onMarkUnread:()=>S(D.id),onDelete:()=>h(D.id)},D.id))]}),T.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function yt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function tf(e,s){return String(e||"")!==String(s||"")}function sf(e,s={}){const r=String(s.textQuery||"").trim().toLowerCase(),n=String(s.workspaceQuery||"").trim().toLowerCase(),o=String(s.modelQuery||"").trim().toLowerCase(),i=!!s.resumableOnly;return!r&&!n&&!o&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(u=>String(u||"").toLowerCase()).join(`
31
+ `).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||o&&!ec(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
32
+ `).includes(o)))}function rf(e,s="recent"){const r=e.slice();return r.sort((n,o)=>{if(s==="oldest")return(Number(n.lastMessageAt)||0)-(Number(o.lastMessageAt)||0);if(s==="messages"){const i=(Number(o.messageCount)||0)-(Number(n.messageCount)||0);if(i!==0)return i}return(Number(o.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function Ac(e,s={}){return rf(sf(e,s),s.sortMode||"recent")}function on(e){return e?"Resume saved history":"Start fresh"}function za(e){return e?"Resuming saved history…":"Starting fresh…"}function nf(){return"Start fresh"}function Mc(e,s=!1){return e==="cli"?on(s):e==="ide"?"Start IDE":"Start ACP session"}function Tc(e,s=!1){return e==="cli"?za(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function af(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function of(){return"Open saved history"}function cf(){return"Saved History"}function Va(){return"Use saved history when you want continuity in the same provider conversation."}function lf(){return"No saved history found yet."}function df(){return"Refresh saved history"}function uf(){return"Refreshing saved history…"}function ps(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function hs(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 Bs(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ks(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Ga(e){return`Resume saved history with ${e}?`}function qa(){return"Review or change the target workspace before resuming saved history."}function mf(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 Ya({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:o=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:m,onNewChat:d,onSwitchSession:g,onRefreshHistory:p,onResumeSavedSession:w}){var S;const I=s.find(h=>h.id===e.routeId),b=(I==null?void 0:I.chats)||[],f=(S=I==null?void 0:I.activeChat)==null?void 0:S.id,x=st(e)&&!Qe(e),[y,k]=a.useState(()=>yt()),T=l||y,v=h=>{if(u){u(h);return}k(h)},R=a.useMemo(()=>Ac(o,{textQuery:T.textQuery,workspaceQuery:T.workspaceQuery,modelQuery:T.modelQuery,resumableOnly:T.resumableOnly,sortMode:T.sortMode}),[T.modelQuery,T.resumableOnly,T.sortMode,T.textQuery,T.workspaceQuery,o]),j=t.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[t.jsx("div",{onClick:m,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[t.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"m-0 text-lg font-extrabold",children:x?cf():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:qm(e)}),x&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Va()})]}),t.jsx("button",{onClick:m,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:t.jsx(Mt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!x&&t.jsx("button",{onClick:d,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),x?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[t.jsx("input",{type:"text",value:T.textQuery,onChange:h=>v({...T,textQuery:h.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("input",{type:"text",value:T.workspaceQuery,onChange:h=>v({...T,workspaceQuery:h.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("input",{type:"text",value:T.modelQuery,onChange:h=>v({...T,modelQuery:h.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsxs("select",{value:T.sortMode,onChange:h=>v({...T,sortMode:h.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:T.resumableOnly,onChange:h=>v({...T,resumableOnly:h.target.checked})}),"Resume-ready only"]})]}),R.map(h=>{const E=e.providerSessionId===h.providerSessionId,C=E||!h.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{C||!w||w(h)},disabled:C,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${E?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${C?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:`font-bold text-sm mb-1 truncate ${E?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:h.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:h.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:mf(h.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:h.preview||"No saved preview yet"}),t.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[t.jsxs("div",{className:"truncate",children:[h.workspace||"Workspace unknown",js(h.summaryMetadata)?` · ${js(h.summaryMetadata)}`:"",h.messageCount>0?` · ${h.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:E?"ACTIVE":h.canResume?c===h.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},h.id)})]}):b.map(h=>t.jsxs("div",{onClick:()=>{g(e.routeId,h.id),m()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${f===h.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[t.jsx("div",{className:`font-bold text-sm mb-1 ${f===h.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:h.title||"Untitled Session"}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[h.id.substring(0,12),"..."]}),f===h.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},h.id)),(x&&!i&&R.length===0||!x&&b.length===0)&&t.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[t.jsx("div",{className:"text-3xl mb-3 opacity-60",children:t.jsx(_d,{size:32})}),t.jsx("div",{className:"text-[13px]",children:x?o.length>0?"No saved history matches these filters.":lf():"No recent chat sessions found."})]}),x&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:uf()})})]}),t.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:t.jsx("button",{onClick:p,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(fr,{size:13})," ",x?df():"Refresh History"]})})})]})]});return typeof document>"u"?j:nr.createPortal(j,document.body)}const zo={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 Lc({toasts:e,onDismiss:s,onClickToast:r}){return t.jsx("div",{className:"fixed right-4 z-[9999] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const o=zo[n.type]||zo.info;return t.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=n.actions)!=null&&i.length||r&&r(n)},children:[t.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${o.accent}, color-mix(in srgb, ${o.accent} 55%, transparent))`}}),t.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),s(n.id)},"aria-label":"Dismiss",children:t.jsx(Mt,{size:14})}),t.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[t.jsx("div",{className:"flex items-center gap-2 pr-8",children:t.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:o.chipBg,color:o.chipText,border:`1px solid color-mix(in srgb, ${o.accent} 22%, transparent)`},children:o.label})}),t.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&t.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>t.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(),s(n.id)},children:i.label},c))})]})]},n.id)})})}const ff=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function pf(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function hf(e){return e.sessionId||e.instanceId||e.agentType}function $n(e,s){return e||s}function Rc(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=$t(r,{fallbackId:r.id}));return s}function Pc(e,s={}){var n,o;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((o=s.machineNames)==null?void 0:o[e.daemonId])||void 0,connectionState:s.connectionStates?s.connectionStates[r]||s.defaultConnectionState||"new":s.defaultConnectionState}}function Xa(e,s,r={}){return xf(e,s,Pc(e,r))}function xf(e,s,r={}){var g,p,w,I,b,f;const n=[],o=r.machineName,i=r.connectionState,c=pf(e),l=yu(e.type,{agentName:e.cliName}),u=st(e)||Qe(e)?l:it(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var y,k;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||it(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((y=x.activeChat)==null?void 0:y.messages)||[],activeModal:((k=x.activeChat)==null?void 0:k.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,surfaceHidden:x.surfaceHidden}}):[],d=ff(e);if(d){const x=e.sessionId||e.instanceId,y=l,k=(g=e.activeChat)==null?void 0:g.activeModal,T=k&&Array.isArray(k.buttons)&&k.buttons.length>0,v=wt((p=e.activeChat)==null?void 0:p.status,{activeModal:(w=e.activeChat)==null?void 0:w.activeModal})||wt((b=(I=e.agents)==null?void 0:I[0])==null?void 0:b.status)||"idle",R=e.activeChat||{title:"",messages:[]};let j=R.title&&String(R.title).trim()?String(R.title).trim():"";const S=(f=e.activeChat)==null?void 0:f.id,h=e.chats;if(S&&Array.isArray(h)&&h.length>0){const P=h.find(B=>B.id===S||B.id&&String(B.id)===String(S));P!=null&&P.title&&String(P.title).trim()&&(j=String(P.title).trim())}const E=(st(e)||Qe(e),e.type),C=(st(e)||Qe(e))&&Eo(j,y,E)?"":j,A=R.messages||[];n.push({routeId:e.id,sessionId:x,providerSessionId:e.providerSessionId,nativeSessionId:x,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:st(e)?e.mode||"terminal":"chat",agentName:y,agentType:E,status:v,title:C,messages:A,resume:e.resume,hostIdeType:!st(e)&&!Qe(e)?e.type:void 0,workspaceName:c,displayPrimary:C||c||(st(e)?e.mode==="chat"?y:"Terminal":y),displaySecondary:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:T?k.buttons:void 0,modalMessage:T?k.message:void 0,streamSource:"native",tabKey:$n(x,e.id),machineName:o,connectionState:i})}if(d&&(st(e)||Qe(e)))return n;for(const x of m){const y=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,k=vu(x),T=hf(x),v=`${e.id}:${T}`,R=x.title&&String(x.title).trim()||"",j=Eo(R,x.agentName,x.agentType)?"":R,S=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||S.length>0||y||j||!["idle","panel_hidden","disconnected","not_monitored"].includes(k))&&n.push({routeId:e.id,sessionId:x.sessionId||x.instanceId,providerSessionId:x.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:x.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:x.sessionCapabilities,mode:"chat",agentName:x.agentName,agentType:x.agentType,status:k,title:j,messages:S,hostIdeType:e.type,workspaceName:c,displayPrimary:j||c||x.agentName||u,displaySecondary:`${u} · ${x.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,lastUpdated:x.lastUpdated||e.lastUpdated,modalButtons:y?x.activeModal.buttons:void 0,modalMessage:y?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:$n(x.sessionId||x.instanceId,v),machineName:o,connectionState:i})}return n.length===0&&n.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:c,displayPrimary:c||u,displaySecondary:u,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:$n(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function bf(e){const s=e.split(":");return s.length>=3&&(s[1]==="ide"||s[1]==="cli"||s[1]==="acp")?{daemonId:s[0],targetSessionId:s.slice(2).join(":")||void 0}:{daemonId:e}}function gf(e,s){const r=bf(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const _c=[{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:"🏄"}],Dc=[{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:"🧩"}],Ec=[{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:"🟠"}],yf=_c,vf=Dc,wf=Ec;function Ss(...e){return rd(nd(e))}function jf({icon:e,title:s,subtitle:r,badge:n,actions:o,className:i}){return t.jsxs("div",{className:Ss("dashboard-header",i),children:[t.jsxs("div",{children:[t.jsxs("h1",{className:"header-title flex items-center gap-2",children:[t.jsx("span",{className:"flex items-center text-lg",children:e})," ",s,n&&t.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&t.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),o&&t.jsx("div",{className:"flex gap-2",children:o})]})}function $c({icon:e,title:s,subtitle:r,badge:n,actions:o,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsx(jf,{icon:e,title:s,subtitle:r,badge:n,actions:o}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:Ss("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Lt({title:e,icon:s,description:r,accentColor:n,className:o,children:i}){return t.jsxs("div",{className:Ss("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]",o),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&t.jsxs("div",{className:"mb-4",children:[e&&t.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[s&&t.jsx("span",{className:"mr-1.5",children:s}),e]}),r&&t.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function Bc({icon:e,title:s,description:r,action:n,className:o}){return t.jsxs("div",{className:Ss("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",o),children:[t.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),t.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:s}),t.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const kf={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"},Sf={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Pr({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:Ss("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",kf[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:Sf[e]}),t.jsx("span",{children:s})]}),r&&t.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const Nf={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"},Cf={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function If({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:Ss("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Nf[e],r),children:[t.jsx("span",{className:Ss("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Cf[e])}),n]})}const xa="adhdev:themechange";function Af(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Is(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function As(e){return e==="system"?Af():e}function Kc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Gr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(xa,{detail:{preference:e,theme:s}}))}function Mf(){const e=Is(),s=As(e);Kc(s),Gr(e,s)}function Ja(){const[e,s]=a.useState(Is),[r,n]=a.useState(()=>As(Is()));a.useEffect(()=>{Kc(r)},[r]),a.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const m=u.matches?"light":"dark";n(m),Gr("system",m)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),a.useEffect(()=>{const c=u=>{const m=u.detail||{},d=m.preference,g=m.theme;s(d==="dark"||d==="light"||d==="system"?d:Is()),n(g==="dark"||g==="light"?g:As(Is()))},l=u=>{if(u.key!=="theme")return;const m=Is(),d=As(m);s(m),n(d)};return window.addEventListener(xa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(xa,c),window.removeEventListener("storage",l)}},[]);const o=a.useCallback(c=>{const l=As(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}Gr(c,l)},[]),i=a.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=As(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Gr(l,u),l})},[]);return{theme:r,preference:e,setPreference:o,cycleTheme:i,isDark:r==="dark"}}const Vo={dark:"Dark",light:"Light",system:"System"};function Tf({collapsed:e}){const{preference:s,cycleTheme:r}=Ja(),n=s==="dark"?t.jsx(Ed,{size:16}):s==="light"?t.jsx(Dd,{size:16}):t.jsx($d,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Vo[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:Vo[s]})]})}function ds({label:e,description:s,checked:r,disabled:n,onChange:o,extra:i}){return t.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[t.jsxs("div",{className:"pr-4",children:[t.jsx("div",{className:"font-medium text-sm",children:e}),t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:s})]}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,t.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>o(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[t.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),t.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function Lf({onPrefChange:e}){const[s,r]=Tu(),[n,o]=a.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);a.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){o("unsupported");return}o(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 t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(fn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:c=>i("globalEnabled",c)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Rt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:c=>i("browserNotifications",c)}),s.globalEnabled&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&t.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[t.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),t.jsx("button",{onClick:()=>{rc().then(o)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&t.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&t.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),s.globalEnabled&&s.browserNotifications&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Bd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:c=>i("completionAlert",c)}),t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Kd,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:c=>i("approvalAlert",c)}),t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(ir,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!s.globalEnabled&&t.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function cn(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Rf(e,s){const r=cn(e),n=cn(s);if(!r||!n)return e.localeCompare(s);for(let o=0;o<3;o+=1){if(r[o]<n[o])return-1;if(r[o]>n[o])return 1}return 0}function Oc(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function tr(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Rf(r,s)>=0)return!1;const n=cn(r),o=cn(s);return!n||!o?!1:n[0]!==o[0]||n[1]!==o[1]}function Pf(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Bn(e,s){return e instanceof Error?e.message:s}function _f({ides:e,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?t.jsx(Bc,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:s||"Install ADHDev on a machine and sign in to connect it here."}):t.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>t.jsx(Ef,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o},c.id))})}function Go({title:e,message:s,confirmLabel:r,confirmColor:n,onConfirm:o,onCancel:i}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return nr.createPortal(t.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:l=>l.stopPropagation(),children:[t.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),t.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:s}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.jsx("button",{onClick: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"}),t.jsx("button",{onClick:o,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 Df(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...yf,...vf,...wf].find(o=>o.id===s||s.includes(o.id)||o.id.includes(s));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function Ef({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){var B,q;const[i,c]=a.useState("idle"),[l,u]=a.useState(""),[m,d]=a.useState(null),[g,p]=a.useState("idle"),[w,I]=a.useState(""),b=e.version||null,f=((B=e.machine)==null?void 0:B.platform)||((q=e.system)==null?void 0:q.platform)||"",x=$t(e,{fallbackId:e.id}),y=f==="win32"?"🪟":f==="darwin"?"🍎":"🐧",k=s.filter(N=>N.daemonId===e.id&&N.transport==="cdp-page"),T=s.filter(N=>N.daemonId===e.id&&N.transport==="pty"),v=s.filter(N=>N.daemonId===e.id&&N.transport==="acp"),R=e.p2p,j=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const N=Pf(await r(e.id,"daemon_upgrade",{}));N.alreadyLatest?(c("done"),u(`Already on v${N.version||"latest"}.`)):N.upgraded||N.success?(c("done"),u(`Upgrade to v${N.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(N.error||"Upgrade failed"))}catch(N){c("error"),u(Bn(N,"Connection lost during upgrade"))}}},S=async()=>{if(d(null),!!n){p("loading");try{await n(e.id),p("done"),I("Machine disconnected.")}catch(N){p("error"),I(Bn(N,"Failed to disconnect"))}}},h=async()=>{if(d(null),!!o){p("loading");try{await o(e.id),p("done"),I("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(N){p("error"),I(Bn(N,"Failed to revoke token"))}}},E="0.8.100",C=Oc(e,E),A=tr(e,E),P=k.length+T.length+v.length;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("span",{className:"text-xl",children:y}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:x}),t.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[t.jsxs("span",{children:[e.id.substring(0,12),"…"]}),b&&t.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${C?"":"bg-bg-secondary"}`,style:C?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",b,!C&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&C&&t.jsx("button",{onClick:j,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${E}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${A?"↑ Update now":`↑ Update${` to v${E}`}`}`}),n&&t.jsx("button",{onClick:()=>d("disconnect"),disabled:g==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),o&&t.jsx("button",{onClick:()=>d("revoke"),disabled:g==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(If,{status:e.status==="online"?"online":"error"})]})]}),t.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[R&&t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${R.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${R.state==="connecting"||R.state==="new"?"animate-pulse":""}`,style:R.state==="connecting"||R.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",R.state==="connected"?"connected":R.state==="connecting"||R.state==="new"?"connecting...":R.state||"off"]}),R.peers!==void 0&&R.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",R.peers," peer",R.peers!==1?"s":"",")"]})]}),R&&P>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),P>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[k.map(N=>{const L=Df(N.type),U=N.cdpConnected;return t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:L.icon}),t.jsx("span",{children:L.name}),U!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${U?"bg-green-400":"animate-pulse"}`,style:U?void 0:{background:"var(--status-warning)"},title:U?"CDP connected":"CDP connecting..."})]},N.id)}),T.map(N=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"⌨️"}),t.jsx("span",{children:N.cliName||"CLI"})]},N.id)),v.map(N=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"🔗"}),t.jsx("span",{children:N.cliName||"ACP"})]},N.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||w)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||g==="error"?"text-red-400":i==="done"||g==="done"?"text-green-400":"text-text-muted"}`,children:w||l})]}),m==="disconnect"&&t.jsx(Go,{title:"🔌 Disconnect Machine",message:`Disconnect "${x}" from ADHDev?
33
+
34
+ This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
35
+
36
+ Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:S,onCancel:()=>d(null)}),m==="revoke"&&t.jsx(Go,{title:"⚠️ Remove Machine",message:`Remove "${x}" from your dashboard?
37
+
38
+ This will:
39
+ • Immediately disconnect the machine
40
+ • Delete the machine registration
41
+ • Require restarting ADHDev on that machine
42
+
43
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:h,onCancel:()=>d(null)})]})}const $f=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Bf(){const{preference:e,setPreference:s}=Ja();return t.jsx("div",{className:"flex gap-2",children:$f.map(r=>t.jsxs("button",{onClick:()=>s(r.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[t.jsx("span",{children:r.icon}),r.label]},r.id))})}function Kf(e){const s=e.trim();return/^#[0-9a-fA-F]{6}$/.test(s)?s:/^#[0-9a-fA-F]{3}$/.test(s)?`#${s[1]}${s[1]}${s[2]}${s[2]}${s[3]}${s[3]}`:null}function Of(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Kn(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function qo(e){const{r:s,g:r,b:n}=Of(e);return .2126*Kn(s)+.7152*Kn(r)+.0722*Kn(n)}function Yo(e,s){const r=qo(e),n=qo(s),o=Math.max(r,n),i=Math.min(r,n);return(o+.05)/(i+.05)}function Wc(e){const s=Kf(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return Yo(s,r)>=Yo(s,n)?r:n}const ba={bgPrimary:"#0a0e1a",bgSecondary:"#0f1320",surfacePrimary:"#111726",textPrimary:"#f0f0f5",textSecondary:"#9ca3af",textMuted:"#6b7280",borderSubtle:"#1d2536",borderDefault:"#313c52",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#111726",assistantText:"#f0f0f5",containerBg:"#0f1320",sendButton:"#d97706",inputBorder:"#313c52",bubbleRadius:16},ga={bgPrimary:"#fff8ee",bgSecondary:"#fff1de",surfacePrimary:"#ffffff",textPrimary:"#24160f",textSecondary:"#6f6255",textMuted:"#938374",borderSubtle:"#e7d3ba",borderDefault:"#d7b892",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#fffaf4",assistantText:"#24160f",containerBg:"#fff8ee",sendButton:"#d97706",inputBorder:"#d7b892",bubbleRadius:16},Wf=[{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"}}}],Hc="adhdev-chat-theme",Fc="adhdev-chat-theme-custom";function qr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Hc)||"ember"}catch{return"ember"}}function Ht(e){try{const s=localStorage.getItem(Fc);if(s){const r=JSON.parse(s);return{...e==="dark"?ba:ga,...r[e]}}}catch{}return e==="dark"?ba:ga}function _r(e,s){try{localStorage.setItem(Fc,JSON.stringify({dark:e,light:s}))}catch{}}function Dt(e,s){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${o}, ${s})`}function ln(e,s){const r=Math.min(255,parseInt(e.slice(1,3),16)+s),n=Math.min(255,parseInt(e.slice(3,5),16)+s),o=Math.min(255,parseInt(e.slice(5,7),16)+s);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`}const Hf={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function sr(e,s){var o;const r=(o=Hf[e])==null?void 0:o[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",ln(r,24)),n.style.setProperty("--accent-on-primary",Wc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${ln(r,18)})`),n.style.setProperty("--border-accent",Dt(r,.35)),n.style.setProperty("--nav-active-bg",Dt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Dt(r,.06)}`)}function xs(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Dt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Dt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Dt(e.borderSubtle,.25)),s.style.setProperty("--text-primary",e.textPrimary),s.style.setProperty("--text-secondary",e.textSecondary),s.style.setProperty("--text-muted",e.textMuted),s.style.setProperty("--border-subtle",Dt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Dt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",ln(e.accentColor,30)),s.style.setProperty("--accent-on-primary",Wc(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${ln(e.accentColor,40)})`),s.style.setProperty("--border-accent",Dt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Dt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Dt(e.accentColor,.06)}`),s.style.setProperty("--chat-user-bg",e.userBubble),s.style.setProperty("--chat-user-color",e.userText),s.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),s.style.setProperty("--chat-assistant-bg",e.assistantBubble),s.style.setProperty("--chat-assistant-color",e.assistantText),s.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),s.style.setProperty("--chat-assistant-border",`1px solid ${Dt(e.accentColor,.12)}`),s.style.setProperty("--chat-container-bg",e.containerBg),s.style.setProperty("--dashboard-pane-bg",e.containerBg),s.style.setProperty("--chat-thought-accent",e.accentColor),s.style.setProperty("--chat-tool-accent",e.accentColor),s.style.setProperty("--chat-action-color",e.accentColor),s.style.setProperty("--chat-send-bg",e.sendButton),s.style.setProperty("--chat-input-border",e.inputBorder)}function Qa(){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 Ff(e){try{localStorage.setItem(Hc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=bs()?"dark":"light";xs(Ht(s))}else Qa(),sr(e,bs()?"dark":"light")}function Uf(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=qr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=bs()?"dark":"light";xs(Ht(s))}else Qa(),sr(e,bs()?"dark":"light")}function bs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function vt({label:e,value:s,onChange:r}){return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[t.jsx("input",{type:"color",value:s,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),t.jsx("input",{type:"text",value:s,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function Gs({title:e,children:s}){return t.jsxs("div",{style:{marginBottom:14},children:[t.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function zf({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,o]=a.useState(()=>Ht(r));a.useEffect(()=>{o(Ht(r))},[r]);const i=a.useCallback((c,l)=>{o(u=>{const m={...u,[c]:l},g=Ht(r==="dark"?"light":"dark");return r==="dark"?_r(m,g):_r(g,m),xs(m),s(m),m})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",t.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(Gs,{title:"App Background",children:[t.jsx(vt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(vt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(vt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs(Gs,{title:"App Text",children:[t.jsx(vt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(vt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(vt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs(Gs,{title:"Borders & Accent",children:[t.jsx(vt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(vt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(vt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs(Gs,{title:"Chat Bubbles",children:[t.jsx(vt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(vt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(vt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(vt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs(Gs,{title:"Chat Layout",children:[t.jsx(vt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(vt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(vt,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[t.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),t.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),t.jsx("button",{onClick:()=>{const c=e?ba:ga,u=Ht(e?"light":"dark");e?_r(c,u):_r(u,c),o(c),xs(c),s(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 Vf(){const[e,s]=a.useState(qr),[r,n]=a.useState(!0),[o,i]=a.useState(()=>Ht("dark"));a.useEffect(()=>{n(bs());const u=new MutationObserver(()=>{const g=bs();n(g);const p=qr();p==="custom"?xs(Ht(g?"dark":"light")):sr(p,g?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const g=bs();n(g);const p=qr();p==="custom"?xs(Ht(g?"dark":"light")):sr(p,g?"dark":"light")};return m.addEventListener("change",d),()=>{u.disconnect(),m.removeEventListener("change",d)}},[]),a.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?xs(Ht(r?"dark":"light")):(Qa(),sr(e,r?"dark":"light"))},[e,r]),a.useEffect(()=>{i(Ht(r?"dark":"light"))},[r]);const c=u=>{s(u),Ff(u)},l=[...Wf,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText},light:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText}}}];return t.jsxs("div",{children:[t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(u=>{const m=e===u.id,d=r?u.preview.dark:u.preview.light,g=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?o.userText:"#fff";return t.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:m?"var(--bg-glass-hover)":"var(--bg-glass)",border:m?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:m?1:.75},children:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:d.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"Hello! How can I help?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.userBubble,color:g},children:"Fix the bug please"}),t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[m&&t.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?"🎨 Custom":u.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&t.jsx(zf,{dark:r,onColorsChange:u=>i(u)})]})}const Za="adhdev_mobileDashboardMode_v1",ya="adhdev:mobile-dashboard-mode-change";function eo(){try{return localStorage.getItem(Za)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Gf(e){if(typeof window>"u")return()=>{};const s=o=>{e(o??eo())},r=o=>{const i=o.detail;s(i)},n=o=>{o.key&&o.key!==Za||s()};return window.addEventListener(ya,r),window.addEventListener("storage",n),()=>{window.removeEventListener(ya,r),window.removeEventListener("storage",n)}}function qf(e){try{localStorage.setItem(Za,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ya,{detail:e}))}function Yf(){const[e,s]=a.useState(!0);return a.useEffect(()=>{s(eo()==="chat")},[]),t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(es,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{s(r),qf(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const On=new Map,Xo=new Map;function Xf(e){if(!e||typeof e!="object")return null;const s=e,r=s.machine;return!r||typeof r!="object"?null:{machine:r,timestamp:typeof s.timestamp=="number"?s.timestamp:void 0}}function Jf(e,s,r,n){return{...e||{},id:s,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n,platform:r.platform,machine:r}}function Uc(){const{sendCommand:e}=Tt(),{injectEntries:s,getIdes:r}=ar();return a.useCallback(async(n,o)=>{if(!n)return;const i=(o==null?void 0:o.minFreshMs)??hm,c=Xo.get(n)||0;if(!(o!=null&&o.force)&&c>0&&Date.now()-c<i)return;const l=On.get(n);if(l)return l;const u=(async()=>{const m=await e(n,"get_machine_runtime_stats"),d=Xf(m);if(!d)return;const g=r().find(w=>w.id===n),p=Jf(g,n,d.machine,d.timestamp||Date.now());s([p]),Xo.set(n,Date.now())})().finally(()=>{On.delete(n)});return On.set(n,u),u},[r,s,e])}function Qf(e,s,r){return{...e||{},id:s,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r.timestamp,platform:r.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...r.machine}}}function Zf(e,s){const{sendData:r}=Tt(),{injectEntries:n,getIdes:o}=ar(),i=Array.from(new Set(e.filter(Boolean))).join("|");a.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(u=>as.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:s==null?void 0:s.intervalMs}},d=>{const g=o().find(w=>w.id===u),p=Qf(g,u,d);n([p])}));return()=>{l.forEach(u=>u())}},[i,o,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}function ep(e,s){const{sendData:r}=Tt(),[n,o]=a.useState(null),[i,c]=a.useState(!1);return a.useEffect(()=>{if(!e){o(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}o(null),c(!0);let l=null;const u=as.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},m=>{l&&(clearTimeout(l),l=null),o(m.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},ym):c(!1),()=>{l&&clearTimeout(l),u()}},[e,s==null?void 0:s.enabled,s==null?void 0:s.includeSessions,s==null?void 0:s.intervalMs,s==null?void 0:s.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:o}}function tp(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function zc(e){const{sendData:s}=Tt(),[r,n]=a.useState({});return a.useEffect(()=>{const o=tp(e);if(!o||!e.sessionId||!s){n({});return}const i=as.subscribe({sendData:s},o,{type:"subscribe",topic:"session.modal",key:`daemon:${o}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),Ps.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,s]),r}const Vc="adhdev_hiddenTabs";function sp(){try{const e=localStorage.getItem(Vc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function Ns(e){try{localStorage.setItem(Vc,JSON.stringify([...e]))}catch{}}function Dr(e){return Da(e)}function to(e,s){return ss(s).some(r=>e.has(r))}function rp(){const[e,s]=a.useState(sp),r=a.useCallback(m=>{s(d=>{const g=new Set(d);return g.has(m)?g.delete(m):g.add(m),Ns(g),g})},[]),n=a.useCallback(m=>{s(d=>{if(d.has(m))return d;const g=new Set(d);return g.add(m),Ns(g),g})},[]),o=a.useCallback(m=>{s(d=>{if(!d.has(m))return d;const g=new Set(d);return g.delete(m),Ns(g),g})},[]),i=a.useCallback(()=>{s(m=>{if(m.size===0)return m;const d=new Set;return Ns(d),d})},[]),c=a.useCallback((m,d)=>{s(g=>{const p=new Set(g);for(const w of d)p.add(w);return Ns(p),p})},[]),l=a.useCallback((m,d)=>{s(g=>{const p=new Set(g);for(const w of d)p.delete(w);return Ns(p),p})},[]),u=a.useCallback(m=>to(e,m),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:o,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function Gc(e){return e instanceof Error?e.message:String(e||"")}function so(e){const s=Gc(e);return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("P2P channel not open")||s.includes("P2P not available")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function ro(e){const s=Gc(e);return s.includes("P2P command timeout")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function Jo(e,s){const r=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!r||e.transport!=="pty")return e;const n=s[r];return!n||e.mode===n?e:{...e,mode:n}}function np(e,s){if(!Array.isArray(e)||e.length===0||!s||Object.keys(s).length===0)return e;let r=!1;const n=e.map(o=>{const i=Jo(o,s),c=Array.isArray(o.childSessions)?o.childSessions.map(u=>Jo(u,s)):o.childSessions,l=c!==o.childSessions;return i!==o||l?(r=!0,{...i,...l?{childSessions:c}:{}}):o});return r?n:e}function qc(e,s){if(!s)return null;for(const r of e){if(r.sessionId===s&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===s&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function ap(e,s){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[o,i]of Object.entries(e))qc(s,o)===i&&(delete n[o],r=!0);return r?n:e}function op({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){a.useEffect(()=>{rc()},[]);const o=a.useMemo(()=>e.map(i=>({id:i.tabKey,name:Nc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Pu(o),a.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),m={};for(const[d,g]of Object.entries(l))u-g<5e3&&(m[d]=g);return Object.keys(m).length===Object.keys(l).length?l:m})},5500);return()=>clearTimeout(c)},[s,r]),a.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const u=l.filter(m=>m.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(i)},[n]),null}function ip(e){const s=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of s){const o=r.get(n.id);if(!o){r.set(n.id,n);continue}const i=(o.workspace?1:0)+(o.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(o.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function Wn(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==s[r])return!1;return!0}function cp(e){let s=2166136261;for(let r=0;r<e.length;r+=1)s^=e.charCodeAt(r),s=Math.imul(s,16777619)>>>0;return s.toString(16).padStart(8,"0")}function Qo(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?cp(Pa(r.content)):"";return[e.id||"",e.title||"",e.status||"",s.length,String((r==null?void 0:r.id)||""),String((r==null?void 0:r.index)??""),String((r==null?void 0:r.receivedAt)??(r==null?void 0:r.timestamp)??""),n].join(":")}function lp(e){const s=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastUpdated||""),Qo(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),Qo(r.activeChat)].join(":"))].join("|")}function dp(e,s){const r=Date.now();return e.map(n=>{const o=s[n.tabKey];return o&&r-o<5e3?{...n,messages:[],title:""}:n})}function up(e,s){const r=[],n=e.sessionId||e.instanceId;r.push({key:e.id,ref:s[e.id]}),n&&r.push({key:n,ref:s[n]});for(const o of e.childSessions||[]){const i=o.id||o.providerType,c=`${e.id}:${i}`;r.push({key:c,ref:s[c]}),r.push({key:o.id,ref:s[o.id]})}return r}function mp(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r].key!==s[r].key||e[r].ref!==s[r].ref)return!1;return!0}function fp(e,s){const r=new Map;for(const n of e){const o=s.get(n.routeId)||n;for(const i of ss({routeId:n.routeId}))r.set(i,o);for(const i of ss({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?o:n);for(const i of ss({tabKey:n.tabKey}))r.set(i,n)}return r}function pp(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function hp(e){const s=pp(e);if(!s)return`empty:${e.messages.length}`;if(s.id)return`id:${String(s.id)}`;if(s._localId)return`local:${String(s._localId)}`;const r=String(s.role||""),n=Pa(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function xp({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:o}){const i=a.useMemo(()=>ip(e),[e]),c=a.useMemo(()=>Rc(e),[e]),l=a.useRef([]),u=a.useRef([]),m=a.useRef([]),d=a.useRef(new Map),g=a.useRef(new Map),p=a.useMemo(()=>{const v=new Map,R=[];for(const E of i){const{connectionState:C="new",machineName:A}=Pc(E,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),P=up(E,r),B=lp(E),q=d.current.get(E.id);if(q&&q.ide===E&&q.sourceSignature===B&&q.connectionState===C&&q.machineName===A&&mp(q.localRefs,P)){v.set(E.id,q),R.push(...q.conversations);continue}const N=Xa(E,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),L={ide:E,sourceSignature:B,connectionState:C,machineName:A,localRefs:P,conversations:N};v.set(E.id,L),R.push(...N)}d.current=v;const j=new Map,S=E=>{const C=hp(E),A=g.current.get(E.tabKey);if(A&&A.signature===C)return j.set(E.tabKey,A),A.timestamp;const P={signature:C,timestamp:uc(E)||(A==null?void 0:A.timestamp)||0};return j.set(E.tabKey,P),P.timestamp},h=[...R].sort((E,C)=>mc(E,C,S));return g.current=j,h},[i,r,s,c]),w=a.useMemo(()=>{const v=dp(p,n);return Wn(l.current,v)?l.current:(l.current=v,v)},[p,n]),I=a.useMemo(()=>{const v=new Map,R=Array.from(new Set(w.map(j=>j.routeId)));for(const j of R){const S=Ft(w,j);S&&v.set(j,S)}return v},[w]),b=a.useMemo(()=>{const v=new Map;for(const R of w){const j=I.get(R.routeId),S=R.streamSource==="native"&&j?j:R;for(const h of ss({providerSessionId:R.providerSessionId,sessionId:R.sessionId}))v.set(h,S)}return v},[w,I]),f=a.useMemo(()=>fp(w,I),[w,I]),x=a.useCallback(v=>{if(v)return b.get(v)},[b]),y=a.useCallback(v=>{if(v)return f.get(v)},[f]),k=a.useMemo(()=>{const v=w.filter(R=>!to(o,R));return Wn(u.current,v)?u.current:(u.current=v,v)},[w,o]),T=a.useMemo(()=>{const v=k.map(R=>R.tabKey);return Wn(m.current,v)?m.current:(m.current=v,v)},[k]);return{chatIdes:i,conversations:w,visibleConversations:k,visibleTabKeys:T,resolveConversationBySessionId:x,resolveConversationByTarget:y}}function bp({isMobile:e,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const o=a.useMemo(()=>{var l;return e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),i=a.useMemo(()=>{var l;return!e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),c=a.useCallback(()=>{s&&n(l=>{const u=new URLSearchParams(l);return u.delete("activeTab"),u},{replace:!0})},[n,s]);return{requestedDesktopTabKey:o,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function gp({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:o}){a.useEffect(()=>{dt.setIdes(e)},[e]),a.useEffect(()=>{dt.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),a.useEffect(()=>{const i=dt.onToast(u=>{r(d=>d.some(p=>p.message===u.message&&u.timestamp-p.timestamp<3e3)?d:[...d.slice(-4),{id:u.id,message:u.message,type:u.type,timestamp:u.timestamp,targetKey:u.targetKey,actions:u.actions}]);const m=u.duration||5e3;setTimeout(()=>r(d=>d.filter(g=>g.id!==u.id)),m)}),c=dt.onSystemMessage((u,m)=>{var w,I;const d=o(u),g=(w=m._localId)==null?void 0:w.startsWith("sys_approval_"),p=!!(d&&(d.status==="waiting_approval"||(I=d.modalButtons)!=null&&I.length||d.modalMessage));g&&p||n(b=>({...b,[u]:[...b[u]||[],m]}))}),l=dt.onClearSystemMessage((u,m)=>{n(d=>{var g;return(g=d[u])!=null&&g.length?{...d,[u]:d[u].filter(p=>{var w;return!(p.role==="system"&&((w=p._localId)!=null&&w.startsWith(m)))})}:d})});return()=>{i(),c(),l()}},[r,n]),a.useEffect(()=>{const i=jc.on("status_event",c=>{dt.handleRawEvent(c,"ws")});return()=>{i()}},[]),a.useEffect(()=>{var c;const i=l=>{var f;const u=l.data;if((u==null?void 0:u.type)!=="notification_action"||typeof u.action!="string"||!u.action.startsWith("approval_")||!(u.daemonId||u.targetSessionId||u.targetKey))return;const m=u.targetSessionId||u.targetKey||u.daemonId,d=o(m),g=(d==null?void 0:d.routeId)||u.daemonId;if(!g)return;const p=Number(u.buttonIndex),w=u.button||((f=d==null?void 0:d.modalButtons)==null?void 0:f[p])||"Approve",I=String(w).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),b=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(I);s(g,"resolve_action",{action:b?"approve":"reject",button:w,...Number.isFinite(p)&&{buttonIndex:p},...(d==null?void 0:d.sessionId)&&{targetSessionId:d.sessionId},...u.targetSessionId&&{targetSessionId:u.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};return(c=navigator.serviceWorker)==null||c.addEventListener("message",i),()=>{var l;return(l=navigator.serviceWorker)==null?void 0:l.removeEventListener("message",i)}},[o,s])}const yp="adhdev_dashboardLayout_v1",vp="adhdev_dashboardDockview_v1",wp="adhdev_dashboardDockviewHiddenRestore_v1",qs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function no(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function Yc(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Xc(e){return`${yp}:${e}`}function jp(e){const s=Xc(e);return no(s,null)}function kp(e,s){try{const r=s.groupAssignments.length===0&&s.focusedGroup===0&&Object.keys(s.groupActiveTabIds).length===0&&Object.keys(s.groupTabOrders).length===0&&s.groupSizes.length===0,n=Xc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function Jc(e){return`${vp}:${e}`}function Sp(e){const s=Jc(e);return no(s,null)}function Np(e,s){try{const r=Jc(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Qc(e){return`${wp}:${e}`}function Cp(e){const s=Qc(e);return no(s,{})}function Ip(e,s){try{const r=Qc(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Ap(){return{groupAssignments:[...qs.groupAssignments],focusedGroup:qs.focusedGroup,groupActiveTabIds:{...qs.groupActiveTabIds},groupTabOrders:{...qs.groupTabOrders},groupSizes:[...qs.groupSizes]}}function Mp(){const[e]=a.useState(()=>Yc(typeof window<"u"?window.innerWidth:1280)),[s,r]=a.useState(()=>new Map),[n,o]=a.useState(0),[i,c]=a.useState({}),[l,u]=a.useState({}),[m,d]=a.useState([]),[g,p]=a.useState(()=>typeof window<"u"&&window.innerWidth<768),[w,I]=a.useState(!1),b=a.useCallback(()=>{if(w)return;const f=jp(e)??Ap();r(new Map(f.groupAssignments)),o(f.focusedGroup),c(f.groupActiveTabIds),u(f.groupTabOrders),d(f.groupSizes),I(!0)},[w,e]);return a.useEffect(()=>{w&&kp(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:m})},[w,e,s,n,i,l,m]),a.useEffect(()=>{const f=window.matchMedia("(max-width: 767px)"),x=y=>p(y.matches);return f.addEventListener("change",x),()=>f.removeEventListener("change",x)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:o,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:u,groupSizes:m,setGroupSizes:d,isMobile:g,hasHydratedStoredLayout:w,hydrateStoredLayout:b}}function Tp(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=_a(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Lp({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:o,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:l,setSearchParams:u,historyModalOpen:m,activeConv:d,isRefreshingHistory:g,ides:p,handleRefreshHistory:w}){const I=a.useRef(!1),b=a.useRef(!1),f=a.useRef(null),x=a.useRef(!1);a.useEffect(()=>{if(!e||I.current||s.length===0)return;if(!o){i();return}const y=r(e);if(!y)return;const k=n.get(y.tabKey)??0;c(T=>({...T,[k]:y.tabKey})),l(k),I.current=!0,b.current=!0,f.current!=null&&(window.clearTimeout(f.current),f.current=null),u(T=>{const v=new URLSearchParams(T);return v.delete("activeTab"),v},{replace:!0})},[e,s,r,n,o,i,c,l,u]),a.useEffect(()=>{if(!(b.current||o)&&s.length!==0){if(!e){i(),b.current=!0;return}if(I.current){b.current=!0;return}if(f.current==null)return f.current=window.setTimeout(()=>{f.current=null,!(b.current||o)&&(i(),b.current=!0)},1500),()=>{f.current!=null&&(window.clearTimeout(f.current),f.current=null)}}},[e,s.length,o,i]),a.useEffect(()=>{if(!m){x.current=!1;return}if(!d||x.current||g)return;const y=p.find(k=>k.id===d.routeId);y&&(!y.chats||y.chats.length===0||Tp(y.chats,d))&&(x.current=!0,w())},[m,d,g,p,w]),a.useEffect(()=>{if(!d)return;let y=null,k=0,T=-1,v=0;const R=()=>{y=null;const j=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(h=>h.offsetParent!==null);if(j.length===0){k<18&&(k+=1,y=requestAnimationFrame(R));return}let S=0;for(const h of j)h.scrollTop=h.scrollHeight,S+=h.scrollHeight;S===T?v+=1:(v=0,T=S),k+=1,!(v>=2||k>=18)&&(y=requestAnimationFrame(R))};return y=requestAnimationFrame(R),()=>{y!=null&&cancelAnimationFrame(y)}},[d==null?void 0:d.tabKey])}function Rp({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:o,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,m]=a.useState(null),[d,g]=a.useState(null),p=a.useMemo(()=>{if(e||!n)return null;const x=l(n);return x&&!st(x)&&!Qe(x)?x:null},[e,n,l]),w=a.useMemo(()=>{const x=u==null?void 0:u.routeId;if(!x)return null;const y=u!=null&&u.tabKey?i.find(k=>k.tabKey===u.tabKey):o?i.find(k=>k.tabKey===o):null;return(y==null?void 0:y.routeId)===x?y:Ft(i,x)},[i,u,o]),I=a.useMemo(()=>{if(w)return c.find(x=>x.id===w.routeId)},[c,w]);a.useEffect(()=>{p&&(m({routeId:p.routeId,tabKey:Ko(p)}),g(p),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,p]);const b=a.useCallback(x=>{x&&(m({routeId:x.routeId,tabKey:Ko(x)}),g(x))},[]),f=a.useCallback(()=>{m(null),g(null)},[]);return{remoteDialogConv:w,remoteDialogIdeEntry:I,remoteDialogActiveConv:d,setRemoteDialogActiveConv:g,openRemoteDialog:b,closeRemoteDialog:f}}function Hn(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=_a(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Zo({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:o,setLocalUserMessages:i,setClearedTabs:c}){const[l,u]=a.useState(!1),[m,d]=a.useState(!1),g=a.useCallback(async b=>{try{await e("standalone","launch_ide",{ideType:b,enableCdp:!0})}catch(f){console.error("Launch failed",f)}},[e]),p=a.useCallback(async(b,f)=>{try{const x=b||(s==null?void 0:s.daemonId)||"",y=await e(x,"switch_chat",{id:f,sessionId:f,...Rs(s)}),k=y==null?void 0:y.result;if((y==null?void 0:y.success)===!0||k==="switched"||k==="switched-by-title")return;k===!1||k==="not_found"?Vs(o,"⚠️ Session tab not found — try refreshing history"):typeof k=="string"&&k.startsWith("error:")?Vs(o,`⚠️ Switch error: ${k}`):Vs(o,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),Vs(o,`❌ Switch failed: ${x.message||"connection error"}`)}},[s,e,o]),w=a.useCallback(async()=>{if(!(!s||l)){u(!0);try{const b=dr(s);await e(b,"new_chat",{...Rs(s)}),c(f=>({...f,[s.tabKey]:Date.now()})),i(f=>({...f,[s.tabKey]:[]}))}catch(b){console.error("New chat failed",b)}finally{u(!1)}}},[s,l,e,c,i]),I=a.useCallback(async()=>{var b,f;if(!(!s||m)){d(!0);try{const x=dr(s),y=async()=>e(x,"list_chats",{forceExpand:!0,...Rs(s)});let k=await y(),T=(k==null?void 0:k.chats)||((b=k==null?void 0:k.result)==null?void 0:b.chats);Hn(T,s)&&(await new Promise(v=>setTimeout(v,450)),k=await y(),T=(k==null?void 0:k.chats)||((f=k==null?void 0:k.result)==null?void 0:f.chats)),k!=null&&k.success&&Array.isArray(T)&&(n(s.routeId,T),Hn(T,s)&&!Hn(r,s)&&Vs(o,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{d(!1)}}},[s,r,m,e,n,o]);return{isCreatingChat:l,isRefreshingHistory:m,handleLaunchIde:g,handleSwitchSession:p,handleNewChat:w,handleRefreshHistory:I}}function Pp(e,s){if(e.size!==s.size)return!1;for(const[r,n]of e)if(s.get(r)!==n)return!1;return!0}function _p(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function ei(e,s){const r=Object.keys(e),n=Object.keys(s);return r.length!==n.length?!1:r.every(o=>s[Number(o)]===e[Number(o)])}function Er(e,s){const r=new Set(s),n=s.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 o={};n.forEach((c,l)=>{o[c]=l}),n.length===0&&(o[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const u=o[l];typeof u=="number"&&u>0&&i.set(c,u)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:o,usedGroups:n}}function ti(e,s){const r={};for(const[n,o]of Object.entries(e)){const i=s[Number(n)];typeof i=="number"&&(r[i]=o)}return r}function Dp(e,s,r){if(s.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...s].reverse().find(o=>o<e)??s[0];return r[n]??0}function Ep(e,s,r){if(s.length<=1)return[];const n=s.map(c=>e[c]).filter(c=>Number.isFinite(c)),o=n.length===s.length?n:Array(r).fill(100/r),i=o.reduce((c,l)=>c+l,0);return i>0?o.map(c=>c/i*100):Array(r).fill(100/r)}function si(e,s){const r={};for(const[n,o]of Object.entries(e)){const i=Number(n);r[i>=s?i+1:i]=o}return r}function ri(e){return Array(e).fill(100/e)}function $p({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:o,groupSizes:i,setGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:m}){const d=a.useRef(null),g=a.useMemo(()=>Er(e,m),[e,m]),p=g.assignments,w=a.useMemo(()=>l?1:g.groupCount,[g.groupCount,l]),I=w>1,b=a.useCallback((v,R)=>{s(j=>{const S=new Map(Er(j,m).assignments);return R===0?S.delete(v):S.set(v,R),S}),n(j=>({...j,[R]:v})),r(R)},[s,m,n,r]),f=a.useCallback(v=>{s(R=>{const j=Er(R,m).assignments,S=new Map;for(const[h,E]of j)E!==v&&(E>v?S.set(h,E-1):S.set(h,E));return S}),c(R=>{if(R.length<=1)return[];const j=[...R];j.splice(v,1);const S=j.reduce((h,E)=>h+E,0);return S>0?j.map(h=>h/S*100):[]}),r(0)},[s,m,c,r]),x=a.useCallback((v,R)=>{R.preventDefault();const j=d.current;if(!j)return;const S=R.clientX,h=j.offsetWidth,E=i.length===w?[...i]:ri(w),C=P=>{const q=(P.clientX-S)/h*100,N=[...E];N[v]=Math.max(15,E[v]+q),N[v+1]=Math.max(15,E[v+1]-q),c(N)},A=()=>{document.removeEventListener("mousemove",C),document.removeEventListener("mouseup",A),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",C),document.addEventListener("mouseup",A)},[i,w,c]),y=a.useCallback((v,R,j)=>{if(w>=4)return;const S=j==="left"?R:R+1;s(h=>{const E=Er(h,m).assignments,C=new Map;for(const A of u){const P=E.get(A.tabKey)??0,B=P>=S?P+1:P;B>0&&C.set(A.tabKey,B)}return S>0&&C.set(v,S),C}),c(h=>{const E=h.length===w?[...h]:ri(w),C=E[R]??100/w,A=Math.max(15,C/2),P=Math.max(15,C/2),B=[...E];B[R]=A,B.splice(S,0,P);const q=B.reduce((N,L)=>N+L,0);return B.map(N=>N/q*100)}),n(h=>{const E=si(h,S);return E[S]=v,E}),o(h=>{const E=si(h,S);return E[S]=[v],E}),r(S)},[w,s,m,u,c,n,o,r]);a.useEffect(()=>{Pp(e,p)||s(p)},[e,p,s]),a.useEffect(()=>{const{mapping:v,usedGroups:R}=g;n(j=>{const S=ti(j,v);return ei(j,S)?j:S}),o(j=>{const S=ti(j,v);return ei(j,S)?j:S}),r(j=>{const S=l?0:Dp(j,R,v);return j===S?j:S}),c(j=>{const S=l?[]:Ep(j,R,g.groupCount);return _p(j,S)?j:S})},[g,l,n,o,r,c]);const k=a.useMemo(()=>{const v=Array.from({length:w},()=>[]);for(const R of u){const j=p.get(R.tabKey)??0,S=Math.min(j,w-1);v[S].push(R)}return v},[u,p,w]),T=a.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:d,normalizedGroupAssignments:p,numGroups:w,isSplitMode:I,groupedConvs:k,moveTabToGroup:b,closeGroup:f,handleResizeStart:x,splitTabRelative:y,clearAllSplits:T}}function Bp({ides:e,sendDaemonCommand:s}){const r="0.8.100",n=a.useMemo(()=>e.filter(d=>d.type!=="adhdev-daemon"?!1:Oc(d,r)).sort((d,g)=>Number(tr(g,r))-Number(tr(d,r))),[r,e]),o=a.useMemo(()=>n.some(d=>tr(d,r)),[r,n]),[i,c]=a.useState(!1),[l,u]=a.useState({}),m=a.useCallback(async d=>{var g,p;u(w=>({...w,[d]:"upgrading"}));try{const w=await s(d,"daemon_upgrade",{});(g=w==null?void 0:w.result)!=null&&g.upgraded||(p=w==null?void 0:w.result)!=null&&p.success?u(I=>({...I,[d]:"done"})):u(I=>({...I,[d]:"error"}))}catch{u(w=>({...w,[d]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:o,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:m}}const va="adhdev_dashboard_notifications_v2",wa="adhdev_dashboard_notifications_v1",yr=80;function Yr(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function ao(e){return{...e,createdAt:Yr(e.createdAt),updatedAt:Yr(e.updatedAt,e.createdAt),lastEventAt:Yr(e.lastEventAt,e.updatedAt||e.createdAt)}}function Kp(e){const s=Da(e);return s==="unknown:"?e.id:s}function ni(e){return[e.type,Gi(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Op(e,s,r,n){var c;const o=Date.now(),i=[];for(const l of e){const u=l.sessionId?s.get(l.sessionId):void 0;if(u!=null&&u.surfaceHidden)continue;const m=ni({type:"task_complete",sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,lastMessageHash:l.lastMessageHash,lastMessageAt:l.lastMessageAt,lastUpdated:(u==null?void 0:u.lastUpdated)||l.lastUpdated}),d=!!((c=n==null?void 0:n.get(m))!=null&&c.forceUnread),g=hn(l,s,{notificationStateBySessionId:r}),p=g.inboxBucket==="needs_attention"?"needs_attention":g.inboxBucket==="task_complete"&&g.unread||(u==null?void 0:u.inboxBucket)==="task_complete"&&d?"task_complete":null;if(!p)continue;const w=Yr(l.lastMessageAt||(u==null?void 0:u.lastUpdated)||l.lastUpdated,o),I=p==="task_complete"?m:ni({type:p,sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,lastMessageHash:l.lastMessageHash,lastMessageAt:l.lastMessageAt,lastUpdated:(u==null?void 0:u.lastUpdated)||l.lastUpdated});i.push(ao({id:I,dedupKey:I,type:p,routeId:l.routeId,machineId:l.daemonId||l.routeId,sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,title:cc(l),preview:sm(l),createdAt:w,updatedAt:w,lastEventAt:w}))}return i.sort((l,u)=>u.updatedAt-l.updatedAt)}function Wp(e,s=yr){const r=new Map;for(const n of e){if(n.deletedAt)continue;const o=Kp(n),i=r.get(o);if(!i){r.set(o,n);continue}(n.updatedAt>i.updatedAt||n.updatedAt===i.updatedAt&&n.createdAt>i.createdAt)&&r.set(o,n)}return Array.from(r.values()).sort((n,o)=>{const i=o.updatedAt-n.updatedAt;return i!==0?i:o.createdAt-n.createdAt}).slice(0,Math.max(0,s))}function Hp(e){return e.filter(s=>typeof s.readAt=="number"||typeof s.deletedAt=="number").map(s=>({id:s.id,...typeof s.readAt=="number"?{readAt:s.readAt}:{},...typeof s.deletedAt=="number"?{deletedAt:s.deletedAt}:{}}))}function Fp(e){return new Map(e.map(s=>[s.id,s]))}function Zc(e,s,r=yr){const n=new Map;for(const i of s)n.set(i.id,i);const o=e.map(i=>{const c=ao(i),l=n.get(c.id);return{...c,...typeof(l==null?void 0:l.readAt)=="number"?{readAt:l.readAt}:{},...typeof(l==null?void 0:l.deletedAt)=="number"?{deletedAt:l.deletedAt}:{}}});return Wp(o,r)}function Up(e,s,r=yr){const n=new Set(Zc(s,[],r).map(o=>o.id));return e.filter(o=>n.has(o.id)).slice(0,Math.max(0,r))}function zp(e,s,r=Date.now()){const n=e.filter(o=>o.id!==s);return n.push({id:s,readAt:r}),n}function Vp(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,forceUnread:!0}),r}function Gp(e,s,r,n=Date.now()){const o=e.filter(i=>{const c=s.find(l=>l.id===i.id);return!c||!cr(c,r)});for(const i of s)cr(i,r)&&o.push({id:i.id,readAt:n});return o}function qp(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,deletedAt:Date.now()}),r}function Yp(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function Xp(e){const s=new Map;for(const r of e){if(r.deletedAt)continue;const n=ss(r);if(n.length===0)continue;const o=r.readAt?0:1;for(const i of n){const c=s.get(i);if(!c){s.set(i,{unreadCount:o,latestNotificationAt:r.updatedAt,latestRecordId:r.id});continue}s.set(i,{unreadCount:c.unreadCount+o,latestNotificationAt:Math.max(c.latestNotificationAt,r.updatedAt),latestRecordId:c.latestNotificationAt>=r.updatedAt?c.latestRecordId:r.id})}}return s}function Jp(){if(typeof window>"u")return[];const e=s=>{if(!s||typeof s!="object")return null;const r=s;if(typeof r.id!="string"||r.id.length===0)return null;const n=typeof r.readAt=="number"&&Number.isFinite(r.readAt)?r.readAt:void 0,o=typeof r.deletedAt=="number"&&Number.isFinite(r.deletedAt)?r.deletedAt:void 0,i=r.forceUnread===!0;return typeof n!="number"&&typeof o!="number"&&!i?null:{id:r.id,...typeof n=="number"?{readAt:n}:{},...typeof o=="number"?{deletedAt:o}:{},...i?{forceUnread:!0}:{}}};try{const s=window.localStorage.getItem(va),r=s?JSON.parse(s):[];if(Array.isArray(r))return r.map(e).filter(n=>!!n)}catch{}try{const s=window.localStorage.getItem(wa),r=s?JSON.parse(s):[];return Array.isArray(r)?Hp(r.map(n=>ao(n)).filter(n=>!n.deletedAt)):[]}catch{return[]}}function Qp(e){if(!(typeof window>"u"))try{const s=e.filter(r=>typeof r.readAt=="number"||typeof r.deletedAt=="number"||r.forceUnread===!0).slice(0,yr);if(s.length===0){window.localStorage.removeItem(va),window.localStorage.removeItem(wa);return}window.localStorage.setItem(va,JSON.stringify(s)),window.localStorage.removeItem(wa)}catch{}}function Zp(e,s){return e===s?!0:e.length!==s.length?!1:e.every((r,n)=>{const o=s[n];return o?r.id===o.id&&r.readAt===o.readAt&&r.deletedAt===o.deletedAt&&r.forceUnread===o.forceUnread:!1})}function eh(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=yr}=e,[o,i]=a.useState(()=>Jp()),c=a.useMemo(()=>Fp(o),[o]),l=a.useMemo(()=>Op(s,r,void 0,c),[s,r,c]),u=a.useMemo(()=>Zc(l,o,n),[l,o,n]),m=a.useMemo(()=>Xp(u),[u]);a.useEffect(()=>{i(b=>{const f=Up(b,l,n);return Zp(b,f)?b:f})},[l,n]),a.useEffect(()=>{Qp(o)},[o]);const d=a.useMemo(()=>Yp(u),[u]),g=a.useCallback((b,f)=>{i(x=>zp(x,b,f))},[]),p=a.useCallback(b=>{i(f=>Vp(f,b))},[]),w=a.useCallback((b,f)=>{i(x=>Gp(x,u,b,f))},[u]),I=a.useCallback(b=>{i(f=>qp(f,b))},[]);return{notifications:u,unreadCount:d,notificationStateBySessionId:m,markRead:g,markUnread:p,markTargetRead:w,deleteNotification:I}}function el(){return"select_session"}function th(){return"open_panel"}function sh({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function rh(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function ai(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function oi(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function oo(e){return e instanceof Error?e.message:String(e||"")}function ii(e){const s=oo(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function ci(e,s){const r=oo(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function bn({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:o}){const[i,c]=a.useState(!1),[l,u]=a.useState(!1),[m,d]=a.useState(null),g=a.useRef(!1),p=a.useRef(null);a.useEffect(()=>{d(null)},[s==null?void 0:s.tabKey]);const w=a.useCallback(async x=>{if(!s)return!1;const y=x.trim(),k=Ha(s);if(sh({hasMessage:!!y,blockedMessage:k,sendInFlight:g.current}))return k&&d(k),!1;const T=Date.now(),v={tabKey:s.tabKey,message:y,timestamp:T};if(rh(p.current,v))return d(null),!0;g.current=!0,u(!0),d(null),p.current=v;const R=`${T}-${Math.random().toString(36).slice(2,8)}`,j={role:"user",content:y,timestamp:T,_localId:R},S=!0;r(h=>({...h,[v.tabKey]:[...h[v.tabKey]||[],j]}));try{const h=dr(s);if(!h)return p.current=ai(p.current,v),S&&r(A=>({...A,[v.tabKey]:(A[v.tabKey]||[]).filter(P=>P._localId!==R)})),d("Unable to send message right now."),!1;const E=await e(h,"send_chat",{message:y,...Rs(s)}),C=oi(E);if(S&&(C!=null&&C.deduplicated))return r(A=>({...A,[v.tabKey]:(A[v.tabKey]||[]).filter(P=>P._localId!==R)})),d(null),!0;if((C==null?void 0:C.sent)===!1)throw new Error((C==null?void 0:C.error)||"Send failed");if((C==null?void 0:C.success)===!1)throw new Error((C==null?void 0:C.error)||"Send failed");return setTimeout(()=>{const A=Date.now()-6e4;r(P=>{const B=P[v.tabKey];if(!B)return P;const q=B.filter(N=>N.timestamp>A);return q.length===B.length?P:{...P,[v.tabKey]:q}})},6e4),d(null),!0}catch(h){const E=oo(h);return E.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",E):console.warn("Send blocked/failed",h),p.current=ai(p.current,v),r(C=>({...C,[v.tabKey]:(C[v.tabKey]||[]).filter(A=>A._localId!==R)})),d(km(h)),!1}finally{g.current=!1,u(!1)}},[s,e,n,r]),I=a.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(x){console.error("Relaunch failed",x)}},[s,e]),b=a.useCallback(async x=>{if(s)try{const k=(s.modalButtons||[]).indexOf(x),T=x.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),v=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(T),R=dr(s);if(!R)return;const j=await e(R,"resolve_action",{button:x,action:v?"approve":"reject",...k>=0&&{buttonIndex:k},...Rs(s)}),S=oi(j);S.success||n(h=>[...h,{routeId:s.tabKey,text:ci(x,S==null?void 0:S.error),timestamp:Date.now()}])}catch(y){ii(y)||console.error("[ModalButton] Error:",y),n(k=>[...k,{routeId:s.tabKey,text:ii(y)?ci(x,y):`❌ **${x}** error`,timestamp:Date.now()}])}},[s,e,n]),f=a.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,th(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(x){console.error("Focus agent failed",x)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,sendFeedbackMessage:m,isFocusingAgent:i,handleSendChat:w,handleRelaunch:I,handleModalButton:b,handleFocusAgent:f}}const io=a.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:o,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d=null,handleFocusAgent:g,isFocusingAgent:p,actionLogs:w,userName:I,scrollToBottomRequestNonce:b,isInputActive:f=!0}){const x=zc(s),y=x.status||x.modalMessage||x.modalButtons?{...s,...x.status?{status:x.status}:{},...x.modalMessage!==void 0?{modalMessage:x.modalMessage}:{},...x.modalButtons!==void 0?{modalButtons:x.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(Xi,{activeConv:y,onModalButton:c}),y.transport!=="pty"&&y.transport!=="acp"&&y.cdpConnected===!1?t.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:t.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[t.jsx("span",{className:"text-sm",children:t.jsx(or,{size:14})}),t.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),t.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:l,children:"Relaunch with CDP"})]})}):null,y.transport==="pty"?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{display:n?"flex":"none",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(Xm,{activeConv:y,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,isVisible:n,isInputActive:f})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(ha,{activeConv:y,ideEntry:o,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,handleFocusAgent:g,isFocusingAgent:p,actionLogs:w,userName:I,scrollToBottomRequestNonce:b,isInputActive:f})})]}):t.jsx(ha,{activeConv:y,ideEntry:o,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,handleFocusAgent:g,isFocusingAgent:p,actionLogs:w,userName:I,scrollToBottomRequestNonce:b,isInputActive:f})]})},(e,s)=>e.activeConv===s.activeConv&&e.isCliTerminal===s.isCliTerminal&&e.ideEntry===s.ideEntry&&e.terminalRef===s.terminalRef&&e.handleModalButton===s.handleModalButton&&e.handleRelaunch===s.handleRelaunch&&e.handleSendChat===s.handleSendChat&&e.isSendingChat===s.isSendingChat&&e.sendFeedbackMessage===s.sendFeedbackMessage&&e.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive);function nh({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:o,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:m,onOpenNativeConversation:d,onOpenMachine:g,onOpenHistory:p,onOpenRemote:w,onHideConversation:I,onStopCli:b,cliViewMode:f,onSetCliViewMode:x,handleSendChat:y,handleFocusAgent:k,handleModalButton:T,handleRelaunch:v}){const R=a.useRef(null),j=st(e)&&!s,S=j&&f==="terminal",h=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`flex items-center justify-between gap-3 ${h} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:t.jsx(Aa,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:ct(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(pc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>g(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[j&&f&&t.jsx(Ua,{mode:f,onChange:x,compact:!0}),j&&b&&t.jsx("button",{onClick:()=>{b(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(Mt,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>p(e),type:"button",children:t.jsx(Ma,{size:14})}),!s&&!j&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:t.jsx(Rt,{size:14})}),I&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>I(e),type:"button",title:"Close chat",children:t.jsx(Mt,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(io,{activeConv:e,clearToken:0,isCliTerminal:S,ideEntry:n,terminalRef:R,handleModalButton:T,handleRelaunch:v,handleSendChat:y,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:k,isFocusingAgent:u,actionLogs:o,userName:i})})]})}const Fn={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 ah(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function tl(){const[e,s]=a.useState("unix"),[r,n]=a.useState("powershell"),[o,i]=a.useState(!1),c=e==="unix"?"unix":r;a.useEffect(()=>{s(ah())},[]);const l=a.useCallback(()=>{navigator.clipboard.writeText(Fn[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return t.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>s("unix"),children:"🍎🐧 macOS / Linux"}),t.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>s("windows"),children:"🪟 Windows"})]}),e==="windows"&&t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),t.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),t.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[t.jsx("span",{className:"text-text-muted select-none",children:Fn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:Fn[c].cmd}),t.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:o?"✓":"📋"})]}),t.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",t.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function sl({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Rt},{key:"chats",label:"Chats",icon:es}];return t.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:t.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:o,icon:i})=>{const c=e===n;return t.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${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:()=>s(n),type:"button","aria-pressed":c,children:[t.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:t.jsx(i,{size:15})}),t.jsx("span",{children:o})]},n)})})})}function $r({title:e,className:s=""}){return t.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:t.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function Cs({children:e,className:s=""}){return t.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${s}`,children:e})}function Ys({icon:e,title:s,subtitle:r,children:n}){return t.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[t.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),t.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function Br({item:e,type:s,getAvatarText:r,onOpenConversation:n}){const o=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",l=s==="task_complete",{isReconnecting:u,isConnecting:m}=Ws(e.conversation),d=ct(e.conversation),g=ks(e.conversation),p=Sc(e.conversation,{requiresAction:s==="needs_attention"}),w=o?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",I=o?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"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=c?"text-text-secondary":"text-text-primary",f=c?"text-text-muted":"text-text-secondary",x=c?"text-text-secondary opacity-80":"text-text-muted",y=c?"text-text-muted opacity-80":"text-text-muted",k="text-[color:var(--status-warning)]";return t.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${w}`,onClick:()=>n(e.conversation),type:"button",children:[o||i?t.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,t.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${I}`,style:o?{color:"var(--accent-on-primary)"}:void 0,children:r(d)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${b}`,children:d}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${y}`,children:Yi(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${f}`,children:[g,u?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${k} animate-pulse`,children:"Reconnecting…"})]}):m?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):p==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:k,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${x}`,children:e.preview})]}),o&&!l&&t.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),l&&t.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),i&&t.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]},e.conversation.tabKey)}function li({size:e=32,label:s}){return t.jsxs("div",{className:"flex flex-col items-center gap-2.5",children:[t.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}}),s&&t.jsx("div",{className:"text-xs font-semibold text-accent-primary-light tracking-tight",children:s})]})}function oh({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:o,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:m,onShowAllHidden:d,onOpenNewSession:g,onOpenMachine:p,onOpenSettings:w,onSectionChange:I,wsStatus:b="connected",isStandalone:f=!1}){const x=b==="disconnected"||b==="reconnecting"||b==="offline"||b==="auth_failed",y=c.length>0,k=s.length>0||r.length>0||n.length>0||o.length>0,T=e==="machines"?"Machines":"Chats",v=f?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",R=f?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return t.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[t.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${v}`,children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:T}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(s.length>0||r.length>0)&&t.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[t.jsx(fn,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:w,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:t.jsx(mn,{size:18})})]})]})}),t.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${R}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:x?t.jsx(Ys,{icon:t.jsx(li,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:b==="offline"?"Your device appears to be offline. Waiting for network…":b==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?t.jsx(Ys,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:f?"Waiting for your daemon":"Connect your machines",subtitle:f?"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:!f&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(tl,{})})}):t.jsx(Cs,{children:c.map((j,S)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${S>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(j.id),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(j.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:j.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:j.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[j.unread," new"]}):j.total>0?`${j.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:j.subtitle}),j.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[j.total," chat",j.total!==1?"s":"",j.unread>0?` · ${j.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},j.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx($r,{title:"Needs attention",className:"mb-0"}),t.jsx(Cs,{children:s.map((j,S)=>t.jsx("div",{className:S>0?"border-t border-border-subtle/70":"",children:t.jsx(Br,{item:j,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx($r,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(Cs,{children:r.map((j,S)=>t.jsx("div",{className:S>0?"border-t border-border-subtle/70":"",children:t.jsx(Br,{item:j,type:"task_complete",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx($r,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(Cs,{children:n.map((j,S)=>t.jsx("div",{className:S>0?"border-t border-border-subtle/70":"",children:t.jsx(Br,{item:j,type:"working",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[o.length>0&&t.jsx($r,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?t.jsx(Cs,{children:o.map((j,S)=>t.jsx("div",{className:S>0?"border-t border-border-subtle/70":"",children:t.jsx(Br,{item:j,type:"earlier",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))}):k?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):x?t.jsx(Ys,{icon:t.jsx(li,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):y?t.jsx(Ys,{icon:t.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:t.jsx(es,{size:20})}),title:"No conversations yet",subtitle:Ic,children:g&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:g,"aria-label":qt,title:qt,children:[t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),t.jsx("span",{children:qt})]})}):t.jsx(Ys,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[t.jsx("span",{children:"Hidden"}),t.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:d,children:"Restore all"})]}),t.jsx(Cs,{className:"bg-bg-secondary/25",children:i.map((j,S)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] opacity-50 saturate-0 ${S>0?"border-t border-border-subtle/70":""}`,onClick:()=>m(j),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:l(ct(j))}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:ct(j)}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:ks(j)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},j.tabKey))})]})]}),e==="chats"&&g&&k&&t.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:g,"aria-label":qt,title:qt,children:t.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),t.jsx(sl,{section:e,onSectionChange:I})]})}function ih(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 rl(e){const s=[e.workspace||"Workspace unknown"],r=js(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=ih(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function gn(...e){const s=new Set,r=[],n=o=>{const i=typeof o=="string"?o.trim():"";if(!i)return;const c=i.toLowerCase();s.has(c)||(s.add(c),r.push(i))};for(const o of e){if(Array.isArray(o)){for(const i of o)n(i);continue}n(o)}return r}function ch(e){const s=e.trim();if(!s)return null;if(s.startsWith("~"))return s;if(/^[A-Za-z]:$/.test(s))return`${s[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(s))return`${s[0].toUpperCase()}:${s.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(s))return`${s[0].toUpperCase()}:\\${s.slice(2).replace(/[\\/]+/g,"\\")}`;const r=s.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),o=(r[2]||"").replace(/[\\/]+/g,"\\");return o?`${n}:\\${o}`:`${n}:\\`}return null}function yn(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=ch(r);if(n)return n}return"C:\\"}for(const r of s){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function lh(e){const s=e.replace(/[\\/]+$/,"");if(!s||s==="/"||/^[A-Za-z]:$/.test(s))return null;const r=s.includes("\\")?"\\":"/",n=s.split(/[\\/]/);return/^[A-Za-z]:$/.test(n[0]||"")?n.length<=2?`${n[0]}\\`:n.slice(0,-1).join("\\"):n.length<=2?r:n.slice(0,-1).join(r)||r}function dh(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function vn(e,s,r){const n=await e(s,"file_list_browse",{path:r}),o=dh(n);if(!(o!=null&&o.success))throw new Error((o==null?void 0:o.error)||(n==null?void 0:n.error)||"Could not browse folder");const i=typeof(o==null?void 0:o.path)=="string"?o.path:r,c=i.includes("\\")?"\\":"/",l=(m,d)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${d}`:m==="/"||m==="\\"?`${c}${d}`:`${m.replace(/[\\/]+$/,"")}${c}${d}`,u=Array.isArray(o==null?void 0:o.files)?o.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,d)=>m.name.localeCompare(d.name)):[];return{path:i,directories:u}}function wn({title:e,description:s,currentPath:r,directories:n,busy:o=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:m}){const[d,g]=a.useState(r);a.useEffect(()=>{g(r)},[r]);const p=lh(r),w=d.trim();return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:t.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:l,"aria-label":"Close folder browser",children:t.jsx(Mt,{size:16})})]}),t.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[t.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!p||o||u(p)},disabled:!p||o,children:[t.jsx(Aa,{size:15}),"Parent"]}),t.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"text",value:d,onChange:I=>g(I.target.value),onKeyDown:I=>{I.key!=="Enter"||!w||o||(I.preventDefault(),u(w))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!w||o||u(w)},disabled:!w||o,children:"Go"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:o?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?t.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):t.jsx("div",{className:"p-3",children:n.map(I=>t.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(I.path),children:[t.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(_s,{size:17})}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:I.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:I.path})]})]},I.path))})}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(w||r),disabled:!w&&!r||o,children:c})]})]})})}function co({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:o,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:m,argsValue:d,onArgsChange:g,showModelInput:p,modelValue:w,onModelChange:I,historyProviderNode:b,onConfirm:f,onCancel:x}){const y=n==null?void 0:n.find(k=>k.key===o);return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:t.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:x,"aria-label":"Close launch confirmation",children:t.jsx(Mt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),t.jsx("select",{value:o||"",onChange:k=>i(k.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:n.map(k=>t.jsx("option",{value:k.key,children:k.label},k.key))}),(y==null?void 0:y.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:y.description})]}),b,r.map(k=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:k.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:k.value})]},`${k.label}:${k.value}`)),p&&I&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),t.jsx("input",{type:"text",value:w||"",onChange:k=>I(k.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:u})]}),m&&g&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),t.jsx("input",{type:"text",value:d||"",onChange:k=>g(k.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:u})]})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:x,disabled:u,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:f,disabled:u,children:[t.jsx(La,{size:14}),u?l:c]})]})]})})}function di(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function gs(e){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:o=!0}=e,i=[];o&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of s.workspaces||[])i.push({key:`saved:${u.id}`,label:`${u.id===s.defaultWorkspaceId?"⭐ ":""}${di(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const c=(r==null?void 0:r.trim())||"",l=c?(s.workspaces||[]).find(u=>u.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:di(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(m=>m.key===u))return{options:i,selectedKey:u}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function uh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function mh(e){return[uh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function fh(e){return e.lastLaunchedAt?pn(e.lastLaunchedAt):""}function nl(e){return{metaText:mh(e),updatedLabel:fh(e)}}function Un(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function ph({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:o,onListSavedSessions:i}){var ht,kt,ft,nt;const c=br(),[l,u]=a.useState(!1),m=(((ht=e.detectedIdes)==null?void 0:ht.length)||0)>0,d=a.useMemo(()=>(e.workspaces||[]).map(Me=>({id:Me.id,path:Me.path,label:Me.label})),[e]),g=e.defaultWorkspaceId||null,[p,w]=a.useState(g||((kt=d[0])==null?void 0:kt.id)||""),[I,b]=a.useState(""),[f,x]=a.useState(""),[y,k]=a.useState([]),[T,v]=a.useState(!1),[R,j]=a.useState(""),[S,h]=a.useState(!1),[E,C]=a.useState(Un(m,s.length,r.length)),A=a.useRef(null),[P,B]=a.useState(null),q=a.useRef("__home__"),[N,L]=a.useState("__home__"),[U,$]=a.useState(""),[K,X]=a.useState(""),[te,le]=a.useState(""),[he,Ce]=a.useState([]),[ke,z]=a.useState(()=>yt().textQuery),[xe,D]=a.useState(()=>yt().workspaceQuery),[W,Y]=a.useState(()=>yt().modelQuery),[ae,ce]=a.useState(()=>yt().resumableOnly),[Se,oe]=a.useState(()=>yt().sortMode),[de,ee]=a.useState(!1),[ue,se]=a.useState(!1),je=a.useRef(null),we=a.useRef(null);a.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const Re=p==="__custom__"?I.trim():((ft=d.find(Me=>Me.id===p))==null?void 0:ft.path)||"",M=p==="__custom__"&&!!Re&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),me=p!=="__custom__"&&((nt=d.find(Me=>Me.id===p))==null?void 0:nt.path)||"",ge=a.useMemo(()=>(e.recentLaunches||[]).map(Me=>Me.workspace),[e]),Z=a.useCallback(async Me=>{v(!0),j("");try{const Ye=await o(Me);x(Ye.path),b(Ye.path),k(Ye.directories)}catch(Ye){j(Ye instanceof Error?Ye.message:"Could not load folder")}finally{v(!1)}},[o]),ye=a.useCallback(()=>{var Ye;w("__custom__"),h(!0);const Me=yn(e.platform,gn(I.trim(),me,ge,e.defaultWorkspacePath,(Ye=d.find(Ue=>Ue.id===g))==null?void 0:Ye.path,d.map(Ue=>Ue.path)));Z(Me)},[I,g,Z,ge,me,e.platform,d]),Ae=a.useCallback(Me=>{if(Me!=null&&Me.workspaceId){w(Me.workspaceId),b("");return}if(Me!=null&&Me.workspacePath){w("__custom__"),b(Me.workspacePath);return}w(""),b("")},[]),We=a.useCallback(Me=>{if(w(Me),Me==="__custom__"){ye();return}b("")},[ye]),De=a.useCallback(Me=>{w("__custom__"),b(Me)},[]),Fe=a.useCallback((Me,Ye)=>{A.current=Ye,q.current=Me.selectedWorkspaceKey||"__home__",L(Me.selectedWorkspaceKey||"__home__"),$(Me.initialArgs||""),X(Me.initialModel||""),le(""),Ce([]);const Ue=Me.providerType?`${e.id}:${Me.providerType}`:null;if(tf(we.current,Ue)){const Ve=yt();z(Ve.textQuery),D(Ve.workspaceQuery),Y(Ve.modelQuery),ce(Ve.resumableOnly),oe(Ve.sortMode)}we.current=Ue,B(Me),Me.providerType&&i&&(ee(!0),i(Me.providerType).then(Ve=>Ce(Ve||[])).catch(Ve=>console.warn("Failed to load saved sessions",Ve)).finally(()=>ee(!1)))},[i,e.id]),Je=a.useMemo(()=>Ac(he,{textQuery:ke,workspaceQuery:xe,modelQuery:W,resumableOnly:ae,sortMode:Se}),[W,ae,he,Se,ke,xe]);a.useEffect(()=>{te&&(Je.some(Me=>Me.providerSessionId===te)||le(""))},[Je,te]);const bt=a.useCallback(()=>{A.current&&(se(!0),A.current().finally(()=>{A.current=null,se(!1),B(null)}))},[]),rt=a.useCallback(()=>{A.current=null,B(null)},[]),ut=a.useCallback(Me=>{q.current=Me,L(Me)},[]);return a.useEffect(()=>{var Me;je.current!==e.id&&(je.current=e.id,w(g||((Me=d[0])==null?void 0:Me.id)||"__custom__"),b(""),x(""),k([]),j(""),h(!1),z(yt().textQuery),D(yt().workspaceQuery),Y(yt().modelQuery),ce(yt().resumableOnly),oe(yt().sortMode),we.current=null,C(Un(m,s.length,r.length)))},[r.length,s.length,g,m,e.id,d]),a.useEffect(()=>{var Me;p!=="__custom__"&&(p&&d.some(Ye=>Ye.id===p)||w(g||((Me=d[0])==null?void 0:Me.id)||"__custom__"))},[g,p,d]),a.useEffect(()=>{E==="ide"&&m||E==="cli"&&s.length>0||E==="acp"&&r.length>0||C(Un(m,s.length,r.length))},[E,r.length,s.length,m]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:m,workspaceRows:d,defaultWorkspaceId:g,workspaceChoice:p,customWorkspacePath:I,browseCurrentPath:f,browseDirectories:y,browseBusy:T,browseError:R,browseDialogOpen:S,activeLauncherKind:E,launchConfirm:P,launchConfirmWorkspaceKeyRef:q,launchConfirmWorkspaceKey:N,launchConfirmArgs:U,launchConfirmModel:K,launchConfirmResumeId:te,launchConfirmSavedSessions:he,launchConfirmTextFilter:ke,launchConfirmWorkspaceFilter:xe,launchConfirmModelFilter:W,launchConfirmResumableOnly:ae,launchConfirmSortMode:Se,filteredLaunchConfirmSavedSessions:Je,launchConfirmSessionsLoading:de,launchConfirmBusy:ue,resolvedWorkspacePath:Re,canCreateMissingWorkspace:M,openBrowseDialog:ye,loadBrowsePath:Z,handleWorkspaceChoiceChange:We,chooseCustomWorkspacePath:De,setCustomWorkspacePath:b,setBrowseDialogOpen:h,setActiveLauncherKind:C,openLaunchConfirm:Fe,handleConfirmLaunch:bt,closeLaunchConfirm:rt,setWorkspaceSelectionFromOption:Ae,setLaunchConfirmWorkspaceKeyAndSync:ut,setLaunchConfirmArgs:$,setLaunchConfirmModel:X,setLaunchConfirmResumeId:le,setLaunchConfirmTextFilter:z,setLaunchConfirmWorkspaceFilter:D,setLaunchConfirmModelFilter:Y,setLaunchConfirmResumableOnly:ce,setLaunchConfirmSortMode:oe}}function hh({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:o,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:m,showBottomNav:d,onBack:g,onSectionChange:p,onOpenConversation:w,onOpenRecent:I,onOpenMachineDetails:b,onMachineUpgrade:f,onLaunchDetectedIde:x,onAddWorkspace:y,onBrowseDirectory:k,onLaunchWorkspaceProvider:T,onListSavedSessions:v}){const R=N=>N==="ide"?"IDE":N==="cli"?"CLI":"ACP",j=r.slice(0,4),S=s.slice(0,3),h=ph({selectedMachineEntry:e,cliProviders:n,acpProviders:o,machineAction:l,onBrowseDirectory:k,onListSavedSessions:v}),E=a.useMemo(()=>j.map(N=>{const{metaText:L,updatedLabel:U}=nl(N);return{key:`recent-launch:${N.id}`,primary:N.label,secondary:L,updatedLabel:U,onClick:()=>{const{options:$,selectedKey:K}=gs({machine:{workspaces:h.workspaceRows,defaultWorkspaceId:h.defaultWorkspaceId},currentWorkspacePath:N.workspace});h.openLaunchConfirm({title:N.kind==="ide"?ps("restart-ide",N.label):N.providerSessionId?Ga(N.label):ps("start-fresh",N.label),description:N.kind==="ide"?hs("restart-ide"):N.providerSessionId?qa():hs("start-fresh"),confirmLabel:N.kind==="ide"?Bs("restart-ide"):N.providerSessionId?on(!0):Bs("start-fresh"),busyLabel:N.kind==="ide"?Ks("restart-ide"):N.providerSessionId?za(!0):Ks("start-fresh"),workspaceOptions:$,selectedWorkspaceKey:K,details:[{label:"Mode",value:R(N.kind)},...N.providerType?[{label:"Provider",value:N.providerType}]:[]]},async()=>{const X=$.find(te=>te.key===h.launchConfirmWorkspaceKeyRef.current);h.setWorkspaceSelectionFromOption(X),await I({...N,workspace:(X==null?void 0:X.workspacePath)??null})})}}}),[h,I,j]),C=a.useMemo(()=>S.map(N=>({key:`recent-chat:${N.conversation.tabKey}`,primary:ct(N.conversation),secondary:Vm(N.conversation,{timestampLabel:N.timestamp?Yi(N.timestamp):null}),unread:N.unread,onClick:()=>w(N.conversation)})),[w,S]),A=h.showAllRecent?E:E.slice(0,4),P=E.length>0,B=C.length>0,q=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:`flex items-center justify-between gap-3 ${q} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:g,type:"button","aria-label":"Back",children:t.jsx(Aa,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:$t(e,{fallbackId:e.id})}),t.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[B&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:C.map(N=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${N.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:N.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:N.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))})]}),P&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:A.map(N=>t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:N.onClick,children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:N.primary}),N.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:N.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))}),E.length>4&&t.jsx("div",{className:"flex justify-center px-4 pt-2",children:t.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>h.setShowAllRecent(N=>!N),children:h.showAllRecent?"Show fewer":`Show ${E.length-4} more`})})]}),(h.hasIdeOptions||n.length>0||o.length>0)&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:t.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),t.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),t.jsx("select",{value:h.workspaceChoice,onChange:N=>h.handleWorkspaceChoiceChange(N.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:h.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[h.workspaceRows.map(N=>t.jsxs("option",{value:N.id,children:[N.id===h.defaultWorkspaceId?"⭐ ":"",xn(N.path,N.label)||N.path]},N.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),h.workspaceChoice==="__custom__"&&t.jsxs("div",{className:"flex flex-col gap-2.5",children:[t.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start gap-3",children:[t.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(_s,{size:17})}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),t.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:h.resolvedWorkspacePath||h.browseCurrentPath||"No folder selected yet."})]})]})}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:h.openBrowseDialog,children:"Select workspace…"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{h.resolvedWorkspacePath&&y(h.resolvedWorkspacePath)},disabled:!h.resolvedWorkspacePath||h.browseBusy,children:"Save as workspace"})]})]}),h.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:h.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[h.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${h.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:()=>h.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${h.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:()=>h.setActiveLauncherKind("cli"),children:"CLI"}),o.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${h.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:()=>h.setActiveLauncherKind("acp"),children:"ACP"})]}),h.activeLauncherKind&&t.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[t.jsx("div",{className:"text-xs font-bold text-text-secondary",children:h.activeLauncherKind==="ide"?"Choose an IDE":h.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:h.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(N=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:L,selectedKey:U}=gs({machine:{workspaces:h.workspaceRows,defaultWorkspaceId:h.defaultWorkspaceId},currentWorkspaceId:h.workspaceChoice!=="__custom__"?h.workspaceChoice:null,currentWorkspacePath:h.resolvedWorkspacePath});h.openLaunchConfirm({title:`Launch ${N.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:L,selectedWorkspaceKey:U,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:N.name}]},async()=>{const $=L.find(K=>K.key===h.launchConfirmWorkspaceKeyRef.current);h.setWorkspaceSelectionFromOption($),x(N.type,{workspacePath:($==null?void 0:$.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:N.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:h.resolvedWorkspacePath||"Use selected workspace"})]},N.type)):(h.activeLauncherKind==="cli"?n:o).map(N=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const L=h.activeLauncherKind==="cli"?"cli":"acp",{options:U,selectedKey:$}=gs({machine:{workspaces:h.workspaceRows,defaultWorkspaceId:h.defaultWorkspaceId},currentWorkspaceId:h.workspaceChoice!=="__custom__"?h.workspaceChoice:null,currentWorkspacePath:h.resolvedWorkspacePath});h.openLaunchConfirm({title:`Launch ${N.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${L.toUpperCase()}`,workspaceOptions:U,selectedWorkspaceKey:$,details:[{label:"Mode",value:L.toUpperCase()},{label:"Provider",value:N.displayName}],showArgsInput:!0,showModelInput:L==="acp",initialArgs:"",initialModel:"",providerType:N.type},async()=>{const K=U.find(X=>X.key===h.launchConfirmWorkspaceKeyRef.current);h.setWorkspaceSelectionFromOption(K),T(L,N.type,{workspaceId:(K==null?void 0:K.workspaceId)??null,workspacePath:(K==null?void 0:K.workspacePath)??null,args:h.launchConfirmArgs,model:h.launchConfirmModel,resumeSessionId:h.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[N.icon?`${N.icon} `:"",N.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:h.resolvedWorkspacePath||"Use selected workspace"})]},N.type))})]}),l.message&&t.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,h.canCreateMissingWorkspace&&t.jsx("div",{className:"mt-2",children:t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>y(h.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:f,children:[t.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:b,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),h.browseDialogOpen&&t.jsx(wn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:h.browseCurrentPath,directories:h.browseDirectories,busy:h.browseBusy,error:h.browseError,confirmLabel:"Use this folder",onClose:()=>h.setBrowseDialogOpen(!1),onNavigate:N=>{h.loadBrowsePath(N)},onConfirm:N=>{h.chooseCustomWorkspacePath(N),h.setBrowseDialogOpen(!1)}}),h.launchConfirm&&t.jsx(co,{title:h.launchConfirm.title,description:h.launchConfirm.description,details:h.launchConfirm.details,workspaceOptions:h.launchConfirm.workspaceOptions,selectedWorkspaceKey:h.launchConfirmWorkspaceKey,onWorkspaceChange:h.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:h.launchConfirm.providerType?on(!!h.launchConfirmResumeId):h.launchConfirm.confirmLabel,busyLabel:h.launchConfirm.providerType?void 0:h.launchConfirm.busyLabel,busy:h.launchConfirmBusy,showArgsInput:h.launchConfirm.showArgsInput,argsValue:h.launchConfirmArgs,onArgsChange:h.setLaunchConfirmArgs,showModelInput:h.launchConfirm.showModelInput,modelValue:h.launchConfirmModel,onModelChange:h.setLaunchConfirmModel,historyProviderNode:h.launchConfirm.providerType&&(h.launchConfirmSessionsLoading||h.launchConfirmSavedSessions.length>0)&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),h.launchConfirmSessionsLoading&&t.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:Va()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:h.launchConfirmTextFilter,onChange:N=>h.setLaunchConfirmTextFilter(N.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:h.launchConfirmBusy||h.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:h.launchConfirmWorkspaceFilter,onChange:N=>h.setLaunchConfirmWorkspaceFilter(N.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:h.launchConfirmBusy||h.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:h.launchConfirmModelFilter,onChange:N=>h.setLaunchConfirmModelFilter(N.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:h.launchConfirmBusy||h.launchConfirmSessionsLoading}),t.jsxs("select",{value:h.launchConfirmSortMode,onChange:N=>h.setLaunchConfirmSortMode(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:h.launchConfirmBusy||h.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:h.launchConfirmResumableOnly,onChange:N=>h.setLaunchConfirmResumableOnly(N.target.checked),disabled:h.launchConfirmBusy||h.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:h.launchConfirmResumeId,onChange:N=>h.setLaunchConfirmResumeId(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:h.launchConfirmBusy||h.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:nf()}),h.filteredLaunchConfirmSavedSessions.map(N=>t.jsxs("option",{value:N.providerSessionId,disabled:!N.canResume,children:[N.title||N.providerSessionId," ",N.canResume?"":"(workspace missing)"]},N.providerSessionId))]}),!h.launchConfirmSessionsLoading&&h.launchConfirmSavedSessions.length>0&&h.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),h.launchConfirmResumeId&&(()=>{const N=h.filteredLaunchConfirmSavedSessions.find(U=>U.providerSessionId===h.launchConfirmResumeId);if(!N)return null;const L=rl(N);return t.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[t.jsx("div",{className:"font-semibold text-text-primary truncate",children:L.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:L.providerSessionId}),t.jsx("div",{className:"mt-1",children:L.metaLine}),L.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:L.updatedLabel}),L.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:L.preview})]})})()]}),onConfirm:h.handleConfirmLaunch,onCancel:h.closeLaunchConfirm}),d&&t.jsx(sl,{section:m,onSectionChange:p})]})}function xh(e){var r;const s=((r=e.p2p)==null?void 0:r.state)||"";return s==="connected"?"Connected":s==="connecting"||s==="new"||s==="checking"?"Connecting":"Offline"}function bh(e,s){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:js(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):s.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,u,m,d;const o=lr(n)?"cli":Ts(n)?"acp":"ide",i=js(n.summaryMetadata);return{id:`${o}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(lr(n)?n.cliName||n.type:Ts(n)&&n.cliName||n.type),kind:o,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ts(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((d=(m=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:m.call(u,-1))==null?void 0:d.timestamp)||0}}).sort((n,o)=>o.timestamp-n.timestamp).map(({timestamp:n,...o})=>o)}function gh(e,s){const r=new Map;for(const n of s){const o=os(n.conversation),i=r.get(o);i?i.push(n):r.set(o,[n])}return e.map(n=>{const o=r.get(n.id)||[],i=[...o].sort((g,p)=>p.timestamp-g.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=da(n),u=o.filter(g=>g.unread||g.requiresAction).length,m=xh(n),d=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:$t(n,{fallbackId:n.id}),subtitle:d.join(" · "),unread:u,total:o.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?Gm(c):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,o)=>{const i=n.latestTimestamp||n.fallbackActivityAt||0,c=o.latestTimestamp||o.fallbackActivityAt||0;return c!==i?c-i:n.label.localeCompare(o.label)})}function Kr(e,s){var r;if(!(typeof window>"u"))try{if(!(!!((r=import.meta.env)!=null&&r.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,s)}catch{}}function yh({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:o,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:g,requestedMobileSection:p,onRequestedMobileSectionConsumed:w,setSelectedTabKey:I,setScreen:b,setSelectedMachineId:f,setSection:x,setMachineBackTarget:y,resetMachineAction:k,markNotificationTargetRead:T}){const v=a.useRef(null),R=a.useCallback(j=>{if(!(j!=null&&j.sessionId))return;const S=rn(j,c),h=Math.max(Date.now(),ms(j),S.lastUpdated||0);Kr("mark_read:start",{tabKey:j.tabKey,sessionId:j.sessionId,displayPrimary:ct(j),inboxBucket:S.inboxBucket,unread:S.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:ms(j),readAt:h}),T({sessionId:j.sessionId,providerSessionId:j.providerSessionId,tabKey:j.tabKey,routeId:j.routeId},h),l(os(j)||j.routeId,"mark_session_seen",{sessionId:j.sessionId,seenAt:h}).then(E=>{Kr("mark_read:result",{tabKey:j.tabKey,sessionId:j.sessionId,result:E})}).catch(E=>{Kr("mark_read:error",{tabKey:j.tabKey,sessionId:j.sessionId,error:E instanceof Error?E.message:String(E)})})},[c,l]);return a.useEffect(()=>{var S;if(!n){b("inbox"),I(((S=e[0])==null?void 0:S.tabKey)||null),v.current=null;return}if(i!=="chat"){v.current=null;return}const j=`${n.tabKey}:${n.sessionId||""}`;v.current!==j&&(v.current=j,R(n))},[e,R,i,n,b,I]),a.useEffect(()=>{if(!u)return;const j=e.find(S=>S.tabKey===u);j&&(I(j.tabKey),b("chat"),m==null||m())},[e,m,u,b,I]),a.useEffect(()=>{if(!d)return;const j=s.find(S=>S.id===d);j&&(f(j.id),k(),x("machines"),y("inbox"),b("machine"),g==null||g())},[s,g,d,k,y,b,x,f]),a.useEffect(()=>{p&&(x(p),b("inbox"),w==null||w())},[w,p,b,x]),a.useEffect(()=>{const j=r.filter(S=>S.inboxBucket==="task_complete"||S.unread);j.length!==0&&Kr("inbox_state",{screen:i,selectedTabKey:o,items:j.map(S=>{const h=rn(S.conversation,c);return{liveState:h,tabKey:S.conversation.tabKey,sessionId:S.conversation.sessionId,displayPrimary:ct(S.conversation),serverBucket:h.inboxBucket,computedBucket:S.inboxBucket,serverUnread:h.unread,computedUnread:S.unread,lastSeenAt:h.lastSeenAt,lastUpdated:h.lastUpdated,activityAt:ms(S.conversation)}})})},[r,c,i,o]),{markConversationRead:R}}function vh(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function ui(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function wh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function jh({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[o,i]=a.useState("idle"),[c,l]=a.useState(""),[u,m]=a.useState(null),d=a.useCallback(()=>{i("idle"),l(""),m(null)},[]),g=a.useCallback(async(y,k,T)=>{var v;try{i("loading"),l(`Launching ${k}…`);const R={ideType:k,enableCdp:!0};(v=T==null?void 0:T.workspacePath)!=null&&v.trim()&&(R.workspace=T.workspacePath.trim()),await e(y,"launch_ide",R),i("done"),l(`${k} launch requested`)}catch(R){i("error"),l(R instanceof Error?R.message:"Launch IDE failed"),console.error("Launch IDE failed",R)}},[e]),p=a.useCallback(async(y,k,T)=>{if(k.trim())try{i("loading"),l(T!=null&&T.createIfMissing?"Creating folder…":"Saving workspace…");const v=await e(y,"workspace_add",{path:k.trim(),createIfMissing:(T==null?void 0:T.createIfMissing)===!0});if(v!=null&&v.success){i("done"),l(T!=null&&T.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]),w=a.useCallback(async y=>{var k,T,v,R,j,S;try{i("loading"),l("Starting daemon upgrade…");const h=await e(y,"daemon_upgrade",{});if((k=h==null?void 0:h.result)!=null&&k.alreadyLatest){i("done"),l(`Already on v${((T=h==null?void 0:h.result)==null?void 0:T.version)||"latest"}.`);return}if((v=h==null?void 0:h.result)!=null&&v.upgraded||(R=h==null?void 0:h.result)!=null&&R.success){i("done"),l(`Upgrade to v${((j=h==null?void 0:h.result)==null?void 0:j.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((S=h==null?void 0:h.result)==null?void 0:S.error)||"Upgrade failed")}catch(h){i("error"),l(h instanceof Error?h.message:"Upgrade failed")}},[e]),I=a.useCallback(async(y,k,T,v)=>{var S,h,E;const R=Date.now(),j={machineId:y,kind:k,providerType:T,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:R};try{i("loading"),l(`Launching ${T}…`),m(j);const C={cliType:T};(S=v==null?void 0:v.workspacePath)!=null&&S.trim()?C.dir=v.workspacePath.trim():v!=null&&v.workspaceId&&(C.workspaceId=v.workspaceId),v!=null&&v.resumeSessionId&&(C.resumeSessionId=v.resumeSessionId),(h=v==null?void 0:v.args)!=null&&h.trim()&&(C.cliArgs=v.args.trim().split(/\s+/).filter(Boolean)),(E=v==null?void 0:v.model)!=null&&E.trim()&&(C.initialModel=v.model.trim());const A=await e(y,"launch_cli",C),P=(A==null?void 0:A.result)||A,B=(P==null?void 0:P.sessionId)||(P==null?void 0:P.id);if(A!=null&&A.success&&B){m(null),i("done"),l(`${T} launched`),s(ns(B));return}if(A!=null&&A.success){i("loading"),l(`${T} launch requested — waiting for session…`);return}m(null),i("error"),l((A==null?void 0:A.error)||(P==null?void 0:P.error)||`Could not launch ${k.toUpperCase()} workspace`)}catch(C){if(wh(C)){i("loading"),l(`${T} launch requested — waiting for session…`);return}m(null),i("error"),l(C instanceof Error?C.message:`Could not launch ${k.toUpperCase()} workspace`)}},[s,e]),b=a.useCallback(async(y,k)=>{try{const T=await e(y,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),v=(T==null?void 0:T.result)??T;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(T){return console.error("Failed to list saved sessions on mobile:",T),[]}},[e]),f=a.useCallback(async(y,k)=>vn(e,y,k),[e]);a.useEffect(()=>{if(!u)return;const y=ui(u.workspacePath),k=r.find(v=>{var C,A,P,B;if(!v||v.type==="adhdev-daemon"||vh(v.daemonId||v.id)!==u.machineId||(v.transport==="acp"?"acp":v.transport==="pty"?"cli":null)!==u.kind||String(v.agentType||v.type||"")!==u.providerType)return!1;const h=String(v.providerSessionId||"");if(u.resumeSessionId&&h)return h===u.resumeSessionId;if(y){const q=ui(v.workspace||v.runtimeWorkspaceLabel);return q?q===y:!1}return Number(v.lastUpdated||v._lastUpdate||v.timestamp||((B=(P=(A=(C=v.activeChat)==null?void 0:C.messages)==null?void 0:A.at)==null?void 0:P.call(A,-1))==null?void 0:B.timestamp)||0)>=u.startedAt-5e3});if(!k)return;const T=fc({entrySessionId:k.sessionId,entryInstanceId:k.instanceId,entryRouteId:k.id,conversations:n});T&&(m(null),i("done"),l(`${u.providerType} launched`),s(ns(T)))},[n,r,s,u]),a.useEffect(()=>{if(!u)return;const y=window.setTimeout(()=>{m(k=>!k||k.startedAt!==u.startedAt?k:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(y)},[u]);const x=a.useCallback(async(y,k)=>{if(k.kind==="ide"&&k.providerType){await g(y,k.providerType,{workspacePath:k.workspace||null});return}(k.kind==="cli"||k.kind==="acp")&&k.providerType&&await I(y,k.kind,k.providerType,{workspacePath:k.workspace||null,resumeSessionId:k.providerSessionId||null})},[g,I]);return{machineAction:{state:o,message:c},resetMachineAction:d,handleLaunchDetectedIde:g,handleAddWorkspace:p,handleMachineUpgrade:w,handleLaunchWorkspaceProvider:I,handleListSavedSessions:b,handleBrowseDirectory:f,handleOpenRecent:x}}function kh({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:o,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:m}){const d=a.useCallback(x=>{i(x.tabKey),c("chat"),n(x)},[n,c,i]),g=a.useCallback(x=>{const y=e.find(k=>k.routeId===x.routeId&&k.streamSource==="native");y&&(i(y.tabKey),c("chat"),n(y))},[e,n,c,i]),p=a.useCallback(()=>{n(s),c("inbox")},[n,s,c]),w=a.useCallback((x,y="inbox")=>{l(x),o(),u("machines"),m(y),c("machine")},[o,m,c,u,l]),I=a.useCallback(x=>{const y=os(x);y&&w(y,"chat")},[w]),b=a.useCallback(()=>{o(),c(r)},[r,o,c]),f=a.useCallback(x=>{u(x),c("inbox")},[c,u]);return{openConversation:d,openNativeConversation:g,backFromConversation:p,openMachine:w,openConversationMachine:I,backFromMachine:b,changeMachineSection:f}}function Sh(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Or(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Nh({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,userName:u,requestedActiveTabKey:m,onRequestedActiveTabConsumed:d,requestedMachineId:g,onRequestedMachineConsumed:p,requestedMobileSection:w,onRequestedMobileSectionConsumed:I,onOpenHistory:b,onOpenRemote:f,onStopCli:x,wsStatus:y,isConnected:k,onShowHiddenConversation:T,onShowAllHiddenConversations:v,onHideConversation:R,onOpenNewSession:j,notificationStateBySessionId:S,liveSessionInboxState:h,onMarkNotificationTargetRead:E}){const[C,A]=a.useState(()=>{var Z;return((Z=e[0])==null?void 0:Z.tabKey)||null}),[P,B]=a.useState(()=>e[0]?"chat":"inbox"),[q,N]=a.useState("chats"),[L,U]=a.useState(null),[$,K]=a.useState("inbox"),X=Os(),te="0.8.100",le=a.useMemo(()=>e.find(Z=>Z.tabKey===C)||e[0]||null,[e,C]),he=a.useMemo(()=>le?r.find(Z=>Z.id===le.routeId):void 0,[r,le]),Ce=a.useMemo(()=>!le||Qe(le)||!st(le)?null:Es(le),[le]),ke=a.useMemo(()=>r.filter(Z=>Z.type==="adhdev-daemon").sort($a),[r]),z=a.useMemo(()=>ke.find(Z=>Z.id===L)||null,[ke,L]),xe=bn({sendDaemonCommand:o,activeConv:le||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),D=jh({sendDaemonCommand:o,navigate:X,ides:r,conversations:e}),W=a.useMemo(()=>e.map(Z=>{const ye=P==="chat"&&(le==null?void 0:le.tabKey)===Z.tabKey,Ae=hn(Z,h,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ye,notificationStateBySessionId:S}),We=ms(Z),De=kc(Z);return{conversation:Z,timestamp:We,preview:De,unread:Ae.unread,requiresAction:Ae.requiresAction,isWorking:Ae.isWorking,inboxBucket:Ae.inboxBucket}}),[e,h,S,P,le]),{markConversationRead:Y}=yh({conversations:e,machineEntries:ke,items:W,selectedConversation:le,selectedTabKey:C,screen:P,liveSessionInboxState:h,sendDaemonCommand:o,requestedActiveTabKey:m,onRequestedActiveTabConsumed:d,requestedMachineId:g,onRequestedMachineConsumed:p,requestedMobileSection:w,onRequestedMobileSectionConsumed:I,setSelectedTabKey:A,setScreen:B,setSelectedMachineId:U,setSection:N,setMachineBackTarget:K,resetMachineAction:D.resetMachineAction,markNotificationTargetRead:E}),ae=kh({conversations:e,selectedConversation:le,machineBackTarget:$,markConversationRead:Y,resetMachineAction:D.resetMachineAction,setSelectedTabKey:A,setScreen:B,setSelectedMachineId:U,setSection:N,setMachineBackTarget:K}),ce=a.useMemo(()=>Or(W.filter(Z=>Z.requiresAction)),[W]),Se=a.useMemo(()=>Or(W.filter(Z=>Z.unread&&!Z.requiresAction)),[W]),oe=a.useMemo(()=>Or(W.filter(Z=>!Z.unread&&!Z.requiresAction&&Z.isWorking)),[W]),de=a.useMemo(()=>Or(W.filter(Z=>!Z.unread&&!Z.requiresAction&&!Z.isWorking)),[W]),ee=a.useMemo(()=>z?W.filter(Z=>os(Z.conversation)===z.id):[],[W,z]),ue=a.useMemo(()=>bh(z,r),[r,z]),se=(z==null?void 0:z.version)||null,je=!!z&&!!se&&!0&&se!==te,we=a.useMemo(()=>(z==null?void 0:z.availableProviders)||[],[z]),Re=a.useMemo(()=>we.filter(Z=>Z.category==="cli"&&Z.installed!==!1).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[we]),M=a.useMemo(()=>we.filter(Z=>Z.category==="acp"&&Z.installed!==!1).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[we]),me=a.useMemo(()=>gh(ke,W),[W,ke]),ge=a.useCallback(async Z=>{z&&await D.handleOpenRecent(z.id,Z)},[D,z]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:P==="chat"&&le?t.jsx(nh,{selectedConversation:le,isAcp:Qe(le),isStandalone:l,selectedIdeEntry:he,actionLogs:n,userName:u,isSendingChat:xe.isSendingChat,sendFeedbackMessage:xe.sendFeedbackMessage,isFocusingAgent:xe.isFocusingAgent,handleModalButton:xe.handleModalButton,handleRelaunch:xe.handleRelaunch,onBack:ae.backFromConversation,onOpenNativeConversation:ae.openNativeConversation,onOpenMachine:ae.openConversationMachine,onHideConversation:R,onOpenHistory:b,onOpenRemote:f,onStopCli:x,cliViewMode:Ce,onSetCliViewMode:async Z=>{if(le&&Ce!==Z)try{await o(os(le)||le.routeId,"set_cli_view_mode",{targetSessionId:le.sessionId,cliType:Wt(le),mode:Z})}catch(ye){const Ae=ro(ye);so(ye)?console.warn(Ae?"CLI view mode result was lost after send; keeping optimistic mobile mode override:":"Skipped CLI view mode switch:",ye instanceof Error?ye.message:String(ye)):console.error("Failed to switch CLI view mode:",ye)}},handleSendChat:xe.handleSendChat,handleFocusAgent:xe.handleFocusAgent}):P==="machine"&&z?t.jsx(hh,{selectedMachineEntry:z,selectedMachineConversations:ee,selectedMachineRecentLaunches:ue,cliProviders:Re,acpProviders:M,selectedMachineNeedsUpgrade:je,appVersion:te,machineAction:D.machineAction,isStandalone:l,section:q,showBottomNav:$==="inbox",onBack:ae.backFromMachine,onSectionChange:ae.changeMachineSection,onOpenConversation:ae.openConversation,onOpenRecent:ge,onOpenMachineDetails:()=>X(`/machines/${z.id}`),onMachineUpgrade:()=>D.handleMachineUpgrade(z.id),onLaunchDetectedIde:(Z,ye)=>D.handleLaunchDetectedIde(z.id,Z,ye),onAddWorkspace:(Z,ye)=>D.handleAddWorkspace(z.id,Z,ye),onBrowseDirectory:Z=>D.handleBrowseDirectory(z.id,Z),onLaunchWorkspaceProvider:(Z,ye,Ae)=>D.handleLaunchWorkspaceProvider(z.id,Z,ye,Ae),onListSavedSessions:Z=>D.handleListSavedSessions(z.id,Z)}):t.jsx(oh,{section:q,attentionItems:ce,unreadItems:Se,workingItems:oe,completedItems:de,hiddenConversations:s,machineCards:me,getAvatarText:Sh,onOpenConversation:ae.openConversation,onShowConversation:T,onShowAllHidden:v,onOpenNewSession:j,onOpenMachine:ae.openMachine,onOpenSettings:()=>X("/settings"),onSectionChange:N,wsStatus:y,isConnected:k,isStandalone:l})})}function zn(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function Ch({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:o,onClearPreviewOrder:i}){const c=a.useRef(0),[l,u]=a.useState(!1),[m,d]=a.useState(null),g=a.useCallback(()=>{c.current=0,u(!1),d(null)},[]);a.useEffect(()=>(window.addEventListener("dragend",g),window.addEventListener("drop",g),()=>{window.removeEventListener("dragend",g),window.removeEventListener("drop",g)}),[g]);const p=a.useCallback(f=>{f.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),w=a.useCallback(f=>{if(!f.dataTransfer.types.includes("text/tab-key"))return;if(f.preventDefault(),!zn(s,r)){d("merge");return}const x=f.currentTarget.getBoundingClientRect(),y=f.clientX-x.left,k=x.width/3;y<k?d("split-left"):y>k*2?d("split-right"):d("merge")},[s,r]),I=a.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),d(null))},[]),b=a.useCallback(f=>{c.current=0,u(!1);const x=f.dataTransfer.getData("text/tab-key"),y=x?e.some(T=>T.tabKey===x):!1,k=m;if(d(null),i(),!!x){if(f.preventDefault(),k==="split-left"&&zn(s,r)){r==null||r(x,"split-left");return}if(k==="split-right"&&zn(s,r)){r==null||r(x,"split-right");return}if(y){o(x);return}n==null||n(x)}},[e,m,s,r,n,o,i]);return{dragOver:l,dropAction:m,resetDragState:g,handleDragEnter:p,handleDragOver:w,handleDragLeave:I,handleDrop:b}}function Ih(e,s){const r=new Set(s.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),o=s.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...o]}function Ah({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:o}){const[i,c]=a.useState(s??null),[l,u]=a.useState(r??[]),[m,d]=a.useState(null),g=a.useRef(null),p=a.useRef(null),w=a.useRef(n),I=a.useRef(o);a.useEffect(()=>{w.current=n},[n]),a.useEffect(()=>{I.current=o},[o]),a.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),a.useEffect(()=>{u(j=>{const S=Ih(j,e);return S.length===j.length&&S.every((h,E)=>h===j[E])?j:S})},[e]);const b=a.useMemo(()=>{const j=m??l;if(j.length===0)return e;const S=new Map(j.map((h,E)=>[h,E]));return[...e].sort((h,E)=>{const C=S.get(h.tabKey)??999,A=S.get(E.tabKey)??999;return C-A})},[e,m,l]);a.useEffect(()=>{var S,h;if(b.length===0){i!==null&&(c(null),(S=w.current)==null||S.call(w,null));return}if(i&&b.some(E=>E.tabKey===i))return;const j=b[0].tabKey;j!==i&&(c(j),(h=w.current)==null||h.call(w,j))},[b,i]);const f=a.useMemo(()=>b.find(j=>j.tabKey===i),[b,i]),x=a.useCallback(j=>{var S;c(j),(S=w.current)==null||S.call(w,j)},[]),y=a.useCallback((j,S,h)=>{u(E=>{var B;const C=E.filter(q=>q!==j),A=C.indexOf(S);if(A<0)return E;const P=h==="left"?A:A+1;return C.splice(P,0,j),(B=I.current)==null||B.call(I,C),C}),d(null)},[]),k=a.useCallback((j,S,h)=>{const C=(l.length>0?l:e.map(B=>B.tabKey)).filter(B=>B!==j),A=C.indexOf(S);if(A<0)return;const P=h==="left"?A:A+1;C.splice(P,0,j),g.current=C,d(C)},[l,e]),T=a.useCallback(()=>{var S;const j=g.current;j&&(u(j),(S=I.current)==null||S.call(I,j))},[]),v=a.useCallback(()=>{g.current=null,d(null)},[]),R=a.useCallback(j=>{u(S=>{var E;const h=S.filter(C=>C!==j);return h.push(j),(E=I.current)==null||E.call(I,h),h})},[]);return{activeTabId:i,activeConv:f,sortedConversations:b,previewOrderRef:g,draggingTabRef:p,selectTab:x,handleTabReorder:y,updatePreviewOrder:k,commitPreviewOrder:T,clearPreviewOrder:v,moveTabToEnd:R,setDraggingTabKey:j=>{p.current=j}}}function Mh({dropAction:e,canSplit:s}){return t.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[t.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:s?1:.45},children:t.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),t.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:t.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),t.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:s?1:.45},children:t.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function lo({conversationsCount:e,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:o=!1,onOpenNewSession:i}){if(o)return t.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,u=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?Ic:r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!s?t.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[t.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),t.jsxs("div",{className:"text-center max-w-lg",children:[t.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:u}),t.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),l&&t.jsx("div",{className:"flex items-center justify-center mb-4",children:t.jsxs("button",{type:"button",onClick:i,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:qt,"aria-label":qt,children:[t.jsx(Hi,{size:14}),t.jsx("span",{children:qt})]})}),c&&t.jsx(tl,{}),c&&t.jsx("div",{className:"mt-8",children:t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):t.jsx("div",{className:"text-sm text-text-muted opacity-50",children:s?"Move a tab here to view":"No active agent"})}const al="adhdev-tab-shortcuts";function ol(){try{return JSON.parse(localStorage.getItem(al)||"{}")}catch{return{}}}function il({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=a.useState(()=>ol()),[l,u]=a.useState(null),m=a.useCallback(g=>{const p=[];return g.metaKey&&p.push(o?"⌘":"Meta"),g.ctrlKey&&p.push("Ctrl"),g.altKey&&p.push(o?"⌥":"Alt"),g.shiftKey&&p.push(o?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(g.key)?null:(p.push(g.key.length===1?g.key.toUpperCase():g.key),p.join("+"))},[o]),d=a.useCallback(g=>{c(g);try{localStorage.setItem(al,JSON.stringify(g))}catch{}},[]);return a.useEffect(()=>{if(!e||!l)return;const g=p=>{if(p.preventDefault(),p.stopPropagation(),p.key==="Escape"){u(null);return}const w=m(p);if(!w)return;const I={...i};for(const[b,f]of Object.entries(I))f===w&&delete I[b];I[l]=w,d(I),u(null)};return window.addEventListener("keydown",g,!0),()=>window.removeEventListener("keydown",g,!0)},[e,l,i,d,m]),a.useEffect(()=>{if(!e)return;const g=p=>{if(!(!p.ctrlKey&&!p.metaKey&&!p.altKey)){for(const[w,I]of Object.entries(i))if(s.includes(w)&&m(p)===I){p.preventDefault(),r(),n(w);return}}};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[e,i,s,r,n,m]),{isMac:o,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:d}}const Th=a.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:o,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:m,onConversationActivated:d,onPreviewReorder:g,onReorderTab:p,onCommitPreviewOrder:w,onClearPreviewOrder:I,onDragStateReset:b,onDragTabKeyChange:f,onReceiveTab:x,onOpenContextMenu:y,longPressTimer:k,isGroupActive:T}){const v=Ws(s),R=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",j=v.isReconnecting,S=a.useCallback(L=>{l.current=s.tabKey,f(s.tabKey),L.dataTransfer.setData("text/tab-key",s.tabKey),L.dataTransfer.effectAllowed="move"},[s.tabKey,l,f]),h=a.useCallback(()=>{l.current=null,f(null),w(),I(),b()},[l,f,w,I,b]),E=a.useCallback(L=>{const U=l.current;if(!(!U||U===s.tabKey)&&L.dataTransfer.types.includes("text/tab-key")){L.preventDefault(),L.stopPropagation();const $=L.currentTarget.getBoundingClientRect(),K=L.clientX<$.left+$.width/2?"left":"right";g(U,s.tabKey,K)}},[s.tabKey,l,g]),C=a.useCallback(L=>{L.preventDefault(),L.stopPropagation();const U=L.dataTransfer.getData("text/tab-key");if(U&&U!==s.tabKey){const $=L.currentTarget.getBoundingClientRect(),K=L.clientX<$.left+$.width/2?"left":"right";c.includes(U)?p(U,s.tabKey,K):x&&x(U)}I()},[s.tabKey,c,p,x,I]),A=a.useCallback(L=>{L.stopPropagation(),u(),m(s.tabKey),d(s)},[s,d,u,m]),P=a.useCallback(L=>{L.preventDefault(),y(L.clientX,L.clientY,s.tabKey)},[s.tabKey,y]),B=a.useCallback(L=>{const U=L.touches[0];k.current=setTimeout(()=>{y(U.clientX,U.clientY,s.tabKey)},600)},[s.tabKey,k,y]),q=a.useCallback(()=>{k.current&&clearTimeout(k.current)},[k]),N=["adhdev-dockview-tab",R,r&&"is-active",T&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:N,draggable:!0,onDragStart:S,onDragEnd:h,onDragOver:E,onDrop:C,onClick:A,onContextMenu:P,onTouchStart:B,onTouchEnd:q,onTouchMove:q,style:{cursor:"pointer",opacity:n?.4:void 0},children:[o&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status",children:v.isGenerating?t.jsx("div",{className:"tab-spinner"}):v.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?t.jsx("div",{className:"tab-connecting-spinner"}):s.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("span",{className:"adhdev-dockview-tab-primary",title:ct(s),children:ct(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:fs(s)}):v.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[fs(s),t.jsx("span",{className:"connecting-dots"})]}):fs(s)})]}),i&&t.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,s)=>e.conv===s.conv&&e.isActive===s.isActive&&e.isDraggedTab===s.isDraggedTab&&e.isTaskCompleteUnread===s.isTaskCompleteUnread&&e.shortcut===s.shortcut&&e.conversationKeys===s.conversationKeys&&e.isGroupActive===s.isGroupActive);function Lh({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:m,onCommitPreviewOrder:d,onClearPreviewOrder:g,onDragStateReset:p,onDragTabKeyChange:w,onReceiveTab:I,onHideTab:b,isGroupActive:f,allowTabShortcuts:x=!0}){const[y,k]=a.useState(null),T=a.useRef(null),v=a.useRef(null),R=a.useMemo(()=>e.map(P=>P.tabKey),[e]);pr("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(y==null?void 0:y.tabKey)||null});const{isMac:j,tabShortcuts:S,shortcutListening:h,setShortcutListening:E,saveShortcuts:C}=il({enabled:x,sortedTabKeys:e.map(P=>P.tabKey),onFocus:i,onSelectTab:c});a.useEffect(()=>{if(!y)return;const P=B=>{const q=document.querySelector("[data-pane-context-menu]");q&&q.contains(B.target)||k(null)};return window.addEventListener("mousedown",P,!0),()=>window.removeEventListener("mousedown",P,!0)},[y]),a.useEffect(()=>{const P=v.current;if(!P)return;const B=q=>{Math.abs(q.deltaY)<=Math.abs(q.deltaX)||(q.preventDefault(),P.scrollLeft+=q.deltaY)};return P.addEventListener("wheel",B,{passive:!1}),()=>P.removeEventListener("wheel",B)},[]);const A=a.useCallback((P,B,q)=>{k({x:P,y:B,tabKey:q})},[]);return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:t.jsxs("div",{ref:v,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(P=>t.jsx(Th,{conv:P,isActive:s===P.tabKey,isDraggedTab:o.current===P.tabKey,isTaskCompleteUnread:n.has(P.tabKey),shortcut:x?S[P.tabKey]:void 0,conversationKeys:R,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:m,onCommitPreviewOrder:d,onClearPreviewOrder:g,onDragStateReset:p,onDragTabKeyChange:w,onReceiveTab:I,onOpenContextMenu:A,longPressTimer:T,isGroupActive:f},P.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),y&&t.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:y.x,top:y.y},children:[x&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:P=>{P.stopPropagation(),E(y.tabKey),k(null)},children:["⌨ ",S[y.tabKey]?`Change shortcut (${S[y.tabKey]})`:"Set shortcut"]}),S[y.tabKey]&&t.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onClick:()=>{const P={...S};delete P[y.tabKey],C(P),k(null)},children:"✕ Remove shortcut"})]}),b&&t.jsxs(t.Fragment,{children:[x&&t.jsx("div",{className:"border-t border-border-subtle my-1"}),t.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{b(y.tabKey),k(null)},children:"🚫 Hide from Dashboard"})]})]}),x&&h&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>E(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:P=>P.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",j?"⌘+1":"Ctrl+1",", ",j?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Rh({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,userName:m,groupIndex:d,onFocus:g,isSplitMode:p,numGroups:w,onMoveTab:I,onReceiveTab:b,style:f,onActiveTabChange:x,initialActiveTabId:y,initialTabOrder:k,onTabOrderChange:T,onHideTab:v,isFocused:R,allowTabShortcuts:j=!0,onOpenNewSession:S,notificationStateBySessionId:h,liveSessionInboxState:E}){const{sendCommand:C}=Tt(),A=a.useRef(null),{activeTabId:P,activeConv:B,sortedConversations:q,draggingTabRef:N,selectTab:L,handleTabReorder:U,updatePreviewOrder:$,commitPreviewOrder:K,clearPreviewOrder:X,moveTabToEnd:te,setDraggingTabKey:le}=Ah({conversations:e,initialActiveTabId:y,initialTabOrder:k,onActiveTabChange:x,onTabOrderChange:T}),he=bn({sendDaemonCommand:o,activeConv:B,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:Ce,dropAction:ke,resetDragState:z,handleDragEnter:xe,handleDragOver:D,handleDragLeave:W,handleDrop:Y}=Ch({conversations:e,numGroups:w,onMoveTab:I,onReceiveTab:b,onOwnTabDrop:te,onClearPreviewOrder:X}),ae=B&&!Qe(B)&&Es(B)==="terminal",ce=a.useMemo(()=>B?s.find(ee=>ee.id===B.routeId):void 0,[s,B]),Se=a.useMemo(()=>B?n.filter(ee=>ee.routeId===B.tabKey):[],[n,B]),oe=a.useMemo(()=>new Set(q.filter(ee=>uu(ee,E,{isOpenConversation:ee.tabKey===P,notificationStateBySessionId:h})).map(ee=>ee.tabKey)),[P,E,q]);pr("PaneGroup",{groupIndex:d,conversationCount:e.length,activeTabId:P,dragOver:Ce});const de=a.useCallback(ee=>{ee.streamSource==="agent-stream"&&ee.agentType&&C(ee.routeId,el(),{agentType:ee.agentType,...ee.sessionId&&{targetSessionId:ee.sessionId}}).catch(()=>{})},[C]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:g,style:{...f,outline:Ce?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(Lh,{conversations:q,activeTabId:P,groupIndex:d,numGroups:w,unreadTabKeys:oe,draggingTabRef:N,onFocus:g,onSelectTab:L,onConversationActivated:de,onPreviewReorder:$,onReorderTab:U,onCommitPreviewOrder:K,onClearPreviewOrder:X,onDragStateReset:z,onDragTabKeyChange:le,onMoveTab:I,onReceiveTab:b,onHideTab:v,isGroupActive:R??!1,allowTabShortcuts:j}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:xe,onDragOver:D,onDragLeave:W,onDrop:Y,children:[Ce&&t.jsx(Mh,{dropAction:ke,canSplit:!!(w<4&&I)}),B?t.jsx(io,{activeConv:B,clearToken:r[B.tabKey]||0,isCliTerminal:!!ae,ideEntry:ce,terminalRef:A,handleModalButton:he.handleModalButton,handleRelaunch:he.handleRelaunch,handleSendChat:he.handleSendChat,isSendingChat:he.isSendingChat,sendFeedbackMessage:he.sendFeedbackMessage,handleFocusAgent:he.handleFocusAgent,isFocusingAgent:he.isFocusingAgent,actionLogs:Se,userName:m,isInputActive:!p||!!R}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(lo,{conversationsCount:e.length,isSplitMode:p,isStandalone:l,hasRegisteredMachines:u,onOpenNewSession:S})})]})]})}function Ph({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:o,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:m,setActionLogs:d,isStandalone:g,hasRegisteredMachines:p,userName:w,focusedGroup:I,setFocusedGroup:b,moveTabToGroup:f,splitTabRelative:x,closeGroup:y,handleResizeStart:k,groupActiveTabIds:T,setGroupActiveTabIds:v,groupTabOrders:R,setGroupTabOrders:j,toggleHiddenTab:S,onOpenNewSession:h,allowTabShortcuts:E=!0,notificationStateBySessionId:C,liveSessionInboxState:A}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:o.map((P,B)=>{const q=s&&n.length===r?`${n[B]}%`:void 0;return t.jsxs(ot.Fragment,{children:[s&&B>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:N=>k(B-1,N),onDoubleClick:()=>y(B),title:"Drag to resize · Double-click to merge",children:t.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),t.jsx(Rh,{style:s?{flexBasis:q??`${100/r}%`,flexGrow:q?0:1,flexShrink:q?0:1}:void 0,conversations:P,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:m,setActionLogs:d,isStandalone:g,hasRegisteredMachines:p,userName:w,groupIndex:B,isFocused:s&&I===B,onFocus:()=>b(B),isSplitMode:s,numGroups:r,onMoveTab:(N,L)=>{L==="left"&&B>0?f(N,B-1):L==="right"&&B<r-1?f(N,B+1):L==="split-left"&&r<4?x(N,B,"left"):L==="split-right"&&r<4&&x(N,B,"right")},onReceiveTab:N=>f(N,B),onActiveTabChange:N=>v(L=>(L[B]??null)===(N??null)?L:{...L,[B]:N}),initialActiveTabId:T[B],initialTabOrder:R[B],onTabOrderChange:N=>j(L=>{const U=L[B]||[];return U.length===N.length&&U.every(($,K)=>$===N[K])?L:{...L,[B]:N}}),onHideTab:S,onOpenNewSession:h,allowTabShortcuts:E,notificationStateBySessionId:C,liveSessionInboxState:A})]},B)})})}function cl({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[o,i]=a.useState(null),[c,l]=a.useState(null);a.useEffect(()=>e?et.onScreenshot("ide-page",(d,g)=>{if(d!==e)return;const p=new FileReader;p.onload=()=>i(p.result),p.readAsDataURL(g)}):void 0,[e]),a.useEffect(()=>{r!=="connected"&&i(null)},[r]),a.useEffect(()=>{var d;return e?((d=et.onStatus)==null?void 0:d.call(et,(g,p)=>{g===e&&p!=null&&p.screenshotUsage&&l(p.screenshotUsage)}))||(()=>{}):void 0},[e]),a.useEffect(()=>{i(null)},[e,s]),a.useEffect(()=>{const m=e?et.get(e):null;if(!(!m||r!=="connected"))return n!=="chat"&&s?m.startScreenshots(s):m.stopScreenshots(s),()=>{m.stopScreenshots(s)}},[n,r,s,e]);const u=a.useCallback(async(m,d)=>{const g=e?et.get(e):null;return!g||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):g.sendInput(m,d,s)},[e,r,s]);return{connScreenshot:o,screenshotUsage:c,handleRemoteAction:u}}const ll="adhdev-dashboard-action-shortcuts",_h=1200,Dh={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Eh(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function at(e,s){switch(e){case"openShortcutHelp":return"?";case"hideCurrentTab":return s?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return s?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return s?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return s?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return s?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return s?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return s?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return s?"⌘+⌥+=":"Ctrl+Alt+\\";case"splitActiveTabDown":return s?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return s?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return s?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return s?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return s?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return s?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return s?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return s?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return s?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";case"triggerPrimaryApprovalAction":return s?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return s?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return s?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return s?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return s?"⌥+[":"Ctrl+Alt+[";case"selectNextGroupTab":return s?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return s?"⌥+T":"Ctrl+Alt+T"}}function dl(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:at("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:at("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:at("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:at("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:at("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:at("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:at("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:at("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:at("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:at("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:at("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:at("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:at("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:at("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:at("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:at("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:at("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:at("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:at("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:at("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:at("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:at("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:at("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:at("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:at("toggleCliView",e)}]}function ja(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function dn(e){const s=Object.fromEntries(dl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(ll)||"{}"),n={...s,...r};for(const[o,i]of Object.entries(Dh))n[o]===i&&(n[o]=s[o]);return n}catch{return s}}function ul(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function $h({enabled:e=!0,onTrigger:s}){const r=Eh(),[n,o]=a.useState(()=>dn(r)),[i,c]=a.useState(null),[l,u]=a.useState([]),m=a.useRef({parts:[],timer:null}),d=a.useCallback(b=>{const f=[];return b.metaKey&&f.push(r?"⌘":"Meta"),b.ctrlKey&&f.push("Ctrl"),b.altKey&&f.push(r?"⌥":"Alt"),b.shiftKey&&b.key.length!==1&&f.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(b.key)?null:(f.push(ul(b.key)),f.join("+"))},[r]),g=a.useCallback(b=>{o(b);try{localStorage.setItem(ll,JSON.stringify(b))}catch{}},[]);a.useEffect(()=>{const b=dn(r),f=Object.entries(n),x=Object.entries(b);f.length===x.length&&f.every(([y,k])=>b[y]===k)||g(b)},[n,r,g]);const p=a.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),w=a.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},_h))},[]);a.useEffect(()=>{if(!i)return;const b=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){c(null),u([]);return}const x=d(f);if(!x)return;const k=!(f.metaKey||f.ctrlKey||f.altKey)&&/^[A-Z0-9]$/.test(x);if(l.length===0&&k){u([x]);return}const v=[...l,x].slice(0,2).join(" "),R={...n};for(const[j,S]of Object.entries(R))S===v&&delete R[j];R[i]=v,g(R),c(null),u([])};return window.addEventListener("keydown",b,!0),()=>window.removeEventListener("keydown",b,!0)},[n,d,g,i,l]),a.useEffect(()=>{if(!e||i)return;const b=f=>{if(f.defaultPrevented)return;const x=d(f);if(!x)return;const y=f.metaKey||f.ctrlKey||f.altKey;if(ja(f.target)&&!y)return;const k=m.current.parts,T=y?[x]:[...k.slice(-1),x].slice(-2),v=T.join(" "),R=T[T.length-1],j=Object.entries(n).filter(([,A])=>!!A),S=j.find(([,A])=>A===v);if(S){f.preventDefault(),p(),s(S[0]);return}if(j.some(([,A])=>A.startsWith(`${v} `))){f.preventDefault(),m.current.parts=T,w();return}const E=j.find(([,A])=>A===R);if(E){f.preventDefault(),p(),s(E[0]);return}if(j.some(([,A])=>A.startsWith(`${R} `))){f.preventDefault(),m.current.parts=[R],w();return}p()};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[n,w,e,d,s,p,i]),a.useEffect(()=>()=>p(),[p]);const I=a.useMemo(()=>dl(r),[r]);return{isMac:r,actionDefinitions:I,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:g}}function Bh({isTabInPopout:e,isTabFloating:s,tabShortcut:r,actionShortcuts:n}){const o=[];return e?(s&&o.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),o.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):s?o.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):o.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),o.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:r?`Change shortcut (${r})`:"Set shortcut",shortcut:n.setActiveTabShortcut}),r&&o.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),o.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:n.hideCurrentTab,tone:"muted"}),o}function ml(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function mi({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!ml(n):!0}function Kh({previousVisibleConversationCount:e,visibleConversationCount:s,ides:r}){return s>0||e<=0?!1:ml(r)}const fl=a.createContext(null);function jn(){const e=a.useContext(fl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Xr(e){return ct(e)||e.tabKey}function Oh(e){return`remote:${e}`}function Ot(e){return e.startsWith("remote:")}function fi(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Vn(e){var r,n,o,i,c;const s=e==null?void 0:e.defaultView;if(s)try{s.focus(),(n=(r=e==null?void 0:e.body)==null?void 0:r.focus)==null||n.call(r),(i=(o=e==null?void 0:e.documentElement)==null?void 0:o.focus)==null||i.call(o),(c=s.requestAnimationFrame)==null||c.call(s,()=>{var l,u;try{s.focus(),(u=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||u.call(l)}catch{}})}catch{}}function Wr(e,s){e.classList.remove(aa.className,oa.className),e.classList.add(s==="light"?aa.className:oa.className)}function pi(e){return e?Array.from(new Set(e.groups.map(s=>{var r,n;return(n=(r=s.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(s=>!!s&&s!==window))):[]}function Wh(e){const[,s]=a.useState(0);a.useEffect(()=>{const r=()=>s(o=>o+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const o of n)o.dispose()}},[e.api,e.containerApi])}function Hh(e,s,r){var c;const n=[s];let o;for(const l of n){let u;for(const m of l){const d=e.addPanel({id:m.tabKey,component:"conversation",title:Xr(m),params:{kind:"conversation",tabKey:m.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:o?{position:{referencePanel:o,direction:"right"},inactive:!0}:{}});u||(u=d.id)}o=u??o}return r??((c=s[0])==null?void 0:c.tabKey)??null}function hi(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Ot(n.id)||r.has(n.id)||e.removePanel(n);for(const n of s){const o=e.getPanel(n.tabKey);if(o){o.update({params:{tabKey:n.tabKey}}),o.title!==Xr(n)&&o.api.setTitle(Xr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Xr(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 xi(e,s,r){var u,m;const n=r?Oh(r):null;for(const d of[...e.panels])Ot(d.id)&&(!n||d.id!==n)&&e.removePanel(d);if(!r||!n)return;const o=Ft(s,r);if(!o&&e.totalPanels===0)return;const i=e.getPanel(n),c=Cc(o);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(o==null?void 0:o.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((m=e.panels.find(d=>!Ot(d.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 Fh({params:e,api:s}){var g;const r=jn(),n=a.useRef(null),[o,i]=a.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=bn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});a.useEffect(()=>{i(s.isActive);const p=[s.onDidActiveChange(w=>i(w.isActive)),s.onDidActiveGroupChange(w=>{if(!s.isActive&&!w.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const w of p)w.dispose()}},[s]);const u=a.useMemo(()=>c?r.ides.find(p=>p.id===c.routeId):void 0,[r.ides,c]),m=a.useMemo(()=>c?r.actionLogs.filter(p=>p.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:t.jsx(lo,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const d=!Qe(c)&&Es(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(io,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:d,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:m,userName:r.userName,scrollToBottomRequestNonce:((g=r.scrollToBottomRequest)==null?void 0:g.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:o})})}function Uh({params:e}){var u;const s=jn(),r=a.useMemo(()=>Ft([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=a.useMemo(()=>s.ides.find(m=>m.id===e.routeId),[s.ides,e.routeId]),o=(r==null?void 0:r.daemonId)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=cl({doId:o,targetSessionId:r?dc(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:t.jsx(Vi,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:l})}):t.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function zh(){const e=jn();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(lo,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Vh(e){var w,I;Wh(e);const s=jn(),r=a.useCallback(b=>{"button"in b&&b.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const b=Ft([...s.conversationsByTabKey.values()],e.params.routeId),f=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,x=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${f?" is-active":""}${x?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(b==null?void 0:b.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:b!=null&&b.machineName?t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Live remote view"}),t.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),t.jsx("span",{className:"adhdev-dockview-tab-machine",children:b.machineName})]}):t.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(e.params.tabKey);if(!n)return t.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:t.jsx("div",{className:"adhdev-dockview-tab-copy",children:t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const o=((I=e.api.group.activePanel)==null?void 0:I.id)===e.api.id,i=e.api.isGroupActive,c=hn(n,s.liveSessionInboxState,{isOpenConversation:o,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,u=c.isConnecting,m=c.isGenerating,d=c.isWaiting,g=c.unread,p=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${o?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:ct(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:b=>{var f;b.preventDefault(),r(b),s.openTabContextMenu({x:b.clientX,y:b.clientY,tabKey:n.tabKey,sourceDocument:((f=b.target)==null?void 0:f.ownerDocument)??document})},children:[g&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:m?t.jsx("div",{className:"tab-spinner"}):d?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):u?t.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:ct(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:fs(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:fs(n)}):t.jsx("span",{children:fs(n)})})]}),p&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:p,children:p})]})}function Gh({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,initialDataLoaded:m,userName:d,toggleHiddenTab:g,actionShortcuts:p,registerActionHandlers:w,onActiveTabChange:I,onOpenNewSession:b,onRequestScrollToBottom:f,requestedActiveTabKey:x,requestedRemoteIdeId:y,onRequestedActiveTabConsumed:k,scrollToBottomRequest:T,notificationStateBySessionId:v,liveSessionInboxState:R}){var Kt,It,At;const{theme:j}=Ja(),{sendCommand:S}=Tt(),h=a.useRef(null),E=a.useRef(null),C=a.useRef(!1),A=a.useRef(!1),P=a.useRef(!1),B=a.useRef(null),q=a.useRef([]),[N,L]=a.useState(null),[U,$]=a.useState(!1),[K,X]=a.useState(!1),[te,le]=a.useState(0),he=a.useRef(null),Ce=a.useMemo(()=>Yc(typeof window<"u"?window.innerWidth:1280),[]),ke=a.useRef(typeof window>"u"?{}:Cp(Ce)),z=a.useMemo(()=>new Map(e.map(O=>[O.tabKey,O])),[e]),xe=a.useMemo(()=>{const O=h.current;return O?O.groups.some(H=>{try{const F=H.model.location.type;return F!=="floating"&&F!=="popout"?!1:H.panels.some(V=>z.has(V.id))}catch{return!1}}):!1},[z,te,e]),D=a.useCallback(()=>{var O;(O=h.current)==null||O.focus()},[]),W=a.useCallback((O,H)=>{f==null||f(O,H)},[f]),Y=a.useCallback(O=>{const H=document,F=O.document;for(const Le of H.querySelectorAll('link[rel="stylesheet"]')){const Ke=F.createElement("link");Ke.rel="stylesheet",Ke.href=Le.href,Le.crossOrigin&&(Ke.crossOrigin=Le.crossOrigin),F.head.appendChild(Ke)}for(const Le of H.querySelectorAll("style")){const Ke=F.createElement("style");Ke.textContent=Le.textContent,F.head.appendChild(Ke)}const V=[];for(const Le of H.styleSheets)try{for(const Ke of Le.cssRules)Ke instanceof CSSStyleRule&&(Ke.selectorText===":root"||Ke.selectorText==="html")&&V.push(Ke.cssText)}catch{}if(V.length>0){const Le=F.createElement("style");Le.textContent=V.join(`
44
+ `),F.head.appendChild(Le)}const re=H.documentElement.getAttribute("data-theme");re&&F.documentElement.setAttribute("data-theme",re),F.documentElement.style.colorScheme=re==="light"?"light":"dark",F.body.className=H.body.className;const Ne=H.documentElement.getAttribute("style");Ne&&F.documentElement.setAttribute("style",Ne);const Ie=F.getElementById("dv-popout-window");Ie instanceof HTMLElement&&(Ie.classList.add("adhdev-dockview"),Wr(Ie,j))},[j]),ae=a.useCallback(()=>{var H;const O=h.current;if(O)for(const F of O.groups)try{const V=(H=F.element)==null?void 0:H.ownerDocument;if(!V||V===document)continue;const re=V.getElementById("dv-popout-window");re instanceof HTMLElement&&(re.classList.add("adhdev-dockview"),Wr(re,j));const Ne=document.documentElement.getAttribute("data-theme");Ne&&V.documentElement.setAttribute("data-theme",Ne),V.documentElement.style.colorScheme=Ne==="light"?"light":"dark",V.body.className=document.body.className;const Ie=document.documentElement.getAttribute("style");Ie?V.documentElement.setAttribute("style",Ie):V.documentElement.removeAttribute("style")}catch{}},[j]),ce=a.useCallback(()=>{var H;const O=h.current;if(O)for(const F of O.groups)try{const V=(H=F.element)==null?void 0:H.ownerDocument;if(!V||V===document)continue;const re=V.getElementById("dv-popout-window");if(!(re instanceof HTMLElement))continue;re.classList.add("adhdev-dockview"),Wr(re,j),re.classList.toggle("is-showing-dockview-overlay",K),re.classList.toggle("is-dragging-dockview",U)}catch{}},[U,K,j]),Se=a.useCallback(O=>{const H=h.current;if(!H)return;const F=H.getPanel(O);F&&H.addPopoutGroup(F,{popoutUrl:"/popout.html",onDidOpen:({window:V})=>{Y(V),M();const re=z.get(O);V.document.title=re?`${ct(re)} — ADHDev`:"ADHDev — Popout"}})},[z,Y]),oe=a.useCallback(O=>{const H=h.current,F=H==null?void 0:H.getPanel(O);if(!H||!F)return;const V=H.groups.filter(re=>{var Ne;try{return((Ne=re.element)==null?void 0:Ne.ownerDocument)===document}catch{return!0}});V.length>0?F.api.moveTo({group:V[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),de=a.useCallback(O=>{var V;const H=h.current;if(!H)return!1;const F=H.getPanel(O);if(!F)return!1;try{return((V=F.group.element)==null?void 0:V.ownerDocument)!==document}catch{return!1}},[]),ee=a.useCallback(O=>{de(O)&&oe(O),g(O)},[de,oe,g]),ue=a.useCallback(O=>{const H=h.current,F=H==null?void 0:H.getPanel(O);!H||!F||H.addFloatingGroup(F,{width:600,height:500})},[]),se=a.useCallback(O=>{var F;const H=(F=h.current)==null?void 0:F.getPanel(O);if(!H)return!1;try{return H.group.model.location.type==="floating"}catch{return!1}},[]),je=a.useCallback(()=>{var H,F;const O=(F=(H=h.current)==null?void 0:H.activePanel)==null?void 0:F.id;return!O||Ot(O)?null:z.has(O)?O:null},[z]),we=a.useCallback(O=>{const H=h.current,F=H==null?void 0:H.getPanel(O);if(!H||!F)return;const V=H.groups.filter(re=>{try{return re.model.location.type==="grid"}catch{return!0}});V.length>0?F.api.moveTo({group:V[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),Re=a.useCallback(()=>{var Ne;const O=h.current;if(!O)return;const F=O.groups.filter(Ie=>{var Le;try{return((Le=Ie.element)==null?void 0:Le.ownerDocument)===document&&Ie.model.location.type==="grid"}catch{return!1}})[0]||null,V=[...O.panels];for(const Ie of V){const Le=(Ne=Ie.group.element)==null?void 0:Ne.ownerDocument,Ke=Ie.group.model.location.type;Le===document&&Ke==="grid"||(F&&F.id!==Ie.group.id?Ie.api.moveTo({group:F,position:"center"}):Ie.api.moveTo({position:"center"}))}const re=O.activePanel;re&&(re.group.model.openPanel(re),re.api.setActive()),Vn(document)},[]),M=a.useCallback(()=>{var H,F;const O=h.current;if(O)for(const V of O.groups){const re=(H=V.element)==null?void 0:H.ownerDocument;if(!re||re===document)continue;const Ne=re.getElementById("dv-popout-window");if(!(Ne instanceof HTMLElement))continue;let Ie=null,Le=re.title||"ADHDev",Ke="Popout workspace";const Q=V.activePanel;if(Q)if(Ie=Q.id,Ot(Q.id)){const _=((F=Q.params)==null?void 0:F.routeId)||Q.id.slice(7),G=Ft([...z.values()],_);Le=Cc(G),Ke=G!=null&&G.machineName?`Remote view · ${G.machineName}`:"Remote view"}else{const _=z.get(Q.id);Le=_?ct(_):Q.title||Q.id,Ke=_?fs(_):"Dockview panel"}re.title=`${Le} — ADHDev`;let ve=re.getElementById("adhdev-popout-header");ve instanceof HTMLElement||(ve=re.createElement("div"),ve.id="adhdev-popout-header",re.body.appendChild(ve)),ve.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(";")),ve.innerHTML=`
45
+ <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
46
+ <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
47
+ <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${fi(Le)}</div>
48
+ <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${fi(Ke)}</div>
49
+ </div>
50
+ <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
51
+ <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>
52
+ <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>
53
+ </div>
54
+ `,Ne.style.top="52px",Ne.style.height="calc(100% - 52px)";const Ze=ve.querySelector("[data-adhdev-popout-focus]");Ze&&(Ze.onclick=()=>{window.focus()});const ze=ve.querySelector("[data-adhdev-popout-dock]");ze&&(ze.disabled=!Ie,ze.style.opacity=Ie?"1":"0.5",ze.style.cursor=Ie?"pointer":"default",ze.onclick=()=>{var _;Ie&&oe(Ie),(_=re.defaultView)==null||_.focus()})}},[z,oe]),me=a.useCallback(O=>{var V;const H=h.current,F=H==null?void 0:H.getPanel(O);if(!(!H||!F)){F.group.model.openPanel(F),F.api.setActive(),W(O,"dockview-shortcut");try{const re=F.group.model.location;re.type==="popout"?re.getWindow().focus():Vn((V=F.group.element)==null?void 0:V.ownerDocument)}catch{}}},[W]),ge=a.useCallback(O=>{const H=h.current,F=H==null?void 0:H.activePanel,V=(H==null?void 0:H.activeGroup)||(F==null?void 0:F.group);if(!H||!F||!V)return;const re=V.panels||[];if(re.length<=1)return;const Ne=re.findIndex(Ke=>Ke.id===F.id);if(Ne<0)return;const Ie=(Ne+O+re.length)%re.length,Le=re[Ie];Le&&(Le.group.model.openPanel(Le),Le.api.setActive(),Ot(Le.id)||W(Le.id,"dockview-shortcut"))},[W]),Z=a.useCallback(O=>{var ze;const H=h.current,F=(H==null?void 0:H.activeGroup)||((ze=H==null?void 0:H.activePanel)==null?void 0:ze.group);if(!H||!F)return;const V=H.groups||[],re=V.find(_=>_.id===F.id);if(!re)return;const Ne=re.element.getBoundingClientRect(),Ie=Ne.left+Ne.width/2,Le=Ne.top+Ne.height/2,Ke=(_,G,ie,Ee)=>Math.max(0,Math.min(G,Ee)-Math.max(_,ie)),Q=_=>{const G=_.element.getBoundingClientRect(),ie=G.left+G.width/2,Ee=G.top+G.height/2;let Te=0,Be=0,Ge=0,Pe=!1;if(O==="left"?(Pe=ie<Ie,Te=Math.max(0,Ne.left-G.right),Be=Math.abs(Ee-Le),Ge=Ke(Ne.top,Ne.bottom,G.top,G.bottom)):O==="right"?(Pe=ie>Ie,Te=Math.max(0,G.left-Ne.right),Be=Math.abs(Ee-Le),Ge=Ke(Ne.top,Ne.bottom,G.top,G.bottom)):O==="above"?(Pe=Ee<Le,Te=Math.max(0,Ne.top-G.bottom),Be=Math.abs(ie-Ie),Ge=Ke(Ne.left,Ne.right,G.left,G.right)):(Pe=Ee>Le,Te=Math.max(0,G.top-Ne.bottom),Be=Math.abs(ie-Ie),Ge=Ke(Ne.left,Ne.right,G.left,G.right)),!Pe)return Number.POSITIVE_INFINITY;const Oe=Ge>0?0:120;return Te*3+Be+Oe};let ve=null,Ze=Number.POSITIVE_INFINITY;for(const _ of V){if(_.id===re.id)continue;const G=Q(_);Number.isFinite(G)&&(G>=Ze||(Ze=G,ve=_))}return ve||void 0},[]),ye=a.useCallback(O=>{var V;const H=Z(O);if(!H)return;const F=H.activePanel||H.panels[0];F&&(H.model.openPanel(F),F.api.setActive(),Ot(F.id)||W(F.id,"dockview-focus"),Vn((V=H.element)==null?void 0:V.ownerDocument))},[Z,W]),Ae=a.useCallback((O,H)=>{const F=h.current,V=F==null?void 0:F.activePanel,re=(F==null?void 0:F.activeGroup)||(V==null?void 0:V.group);if(!F||!V||!re)return;let Ne=Z(O);!Ne&&(H!=null&&H.createGroupIfMissing)&&(Ne=F.addGroup({referenceGroup:re,direction:O})),Ne&&(V.api.moveTo({group:Ne,position:"center"}),V.group.model.openPanel(V),V.api.setActive(),Ot(V.id)||W(V.id,H!=null&&H.createGroupIfMissing?"dockview-split":"dockview-move"))},[Z,W]),{isMac:We,tabShortcuts:De,shortcutListening:Fe,setShortcutListening:Je,saveShortcuts:bt}=il({sortedTabKeys:e.map(O=>O.tabKey),onFocus:D,onSelectTab:me}),rt=a.useCallback(()=>{var F;const O=h.current;if(!O)return;const H=O.activePanel;if(H){if(Ot(H.id)){const V=((F=H.params)==null?void 0:F.routeId)||H.id.slice(7),re=Ft(e,V);re!=null&&re.tabKey&&Je(re.tabKey);return}z.has(H.id)&&Je(H.id)}},[z,me,Je,e]),ut=a.useCallback(O=>{const H=[];return O.metaKey&&H.push(We?"⌘":"Meta"),O.ctrlKey&&H.push("Ctrl"),O.altKey&&H.push(We?"⌥":"Alt"),O.shiftKey&&O.key.length!==1&&H.push(We?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(O.key)?null:(H.push(ul(O.key)),H.join("+"))},[We]),ht=a.useCallback(O=>{var H,F;switch(O){case"splitActiveTabRight":Ae("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Ae("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const V=je();V&&ue(V);return}case"popoutActiveTab":{const V=je();V&&Se(V);return}case"dockActiveTab":{const V=je();if(!V)return;de(V)?oe(V):se(V)&&we(V);return}case"focusLeftPane":ye("left");return;case"focusRightPane":ye("right");return;case"focusUpPane":ye("above");return;case"focusDownPane":ye("below");return;case"moveActiveTabToLeftPane":Ae("left");return;case"moveActiveTabToRightPane":Ae("right");return;case"moveActiveTabToUpPane":Ae("above");return;case"moveActiveTabToDownPane":Ae("below");return;case"selectPreviousGroupTab":ge(-1);return;case"selectNextGroupTab":ge(1);return;case"setActiveTabShortcut":rt();return;case"hideCurrentTab":{const V=(F=(H=h.current)==null?void 0:H.activePanel)==null?void 0:F.id;V&&!Ot(V)&&ee(V);return}default:return}},[ge,we,ye,ue,je,ee,se,de,oe,Ae,Se,rt]);a.useEffect(()=>{if(!N)return;const O=N.sourceDocument,H=O.defaultView??window,F=V=>{const re=O.querySelector("[data-dockview-tab-context-menu]");re&&re.contains(V.target)||L(null)};return H.addEventListener("mousedown",F,!0),H!==window&&window.addEventListener("mousedown",()=>L(null),!0),()=>{H.removeEventListener("mousedown",F,!0),H!==window&&window.removeEventListener("mousedown",()=>L(null),!0)}},[N]);const kt=a.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:z,hasDetachedConversationPanels:xe,ides:r,isStandalone:l,hasRegisteredMachines:u,onOpenNewSession:b,liveSessionInboxState:R,notificationStateBySessionId:v,sendDaemonCommand:o,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:ee,userName:d,scrollToBottomRequest:T,tabShortcuts:De,openTabContextMenu:({x:O,y:H,tabKey:F,sourceDocument:V})=>L({x:O,y:H,tabKey:F,sourceDocument:V??document}),popoutTab:Se,moveTabBackToMain:oe,isTabInPopout:de,floatTab:ue,isTabFloating:se}),[n,s,z,xe,r,l,u,b,R,v,o,c,i,ee,d,T,De,Se,oe,de,ue,se]),ft=N?Bh({isTabInPopout:de(N.tabKey),isTabFloating:se(N.tabKey),tabShortcut:De[N.tabKey],actionShortcuts:p}):[],nt=a.useCallback(O=>{var V;const H=h.current;if((((V=H==null?void 0:H.activePanel)==null?void 0:V.id)??null)===O.id){O.group.model.openPanel(O);return}O.group.model.openPanel(O),O.api.setActive()},[]),Me=a.useCallback((O,H="requested-tab")=>{if(!O)return!1;const F=h.current;if(!F)return!1;const V=F.getPanel(O);return V?(nt(V),W(O,H),k==null||k(),!0):!1},[nt,k,W]),Ye=a.useCallback(()=>{if(P.current)return!1;const O=Me(B.current,"stored-layout-restore");return O&&(P.current=!0),O},[Me]),Ue=a.useCallback(()=>{var H;const O=h.current;O&&Np(Ce,{activeTabId:((H=O.activePanel)==null?void 0:H.id)??null,layout:O.toJSON()})},[Ce]),Ve=a.useCallback(()=>{Ip(Ce,ke.current)},[Ce]),St=a.useCallback(O=>{var V,re,Ne,Ie;const H=h.current;if(!H)return{kind:"grid"};const F=H.toJSON();for(const Le of F.floatingGroups||[])if((re=(V=Le.data)==null?void 0:V.views)!=null&&re.includes(O)&&Le.position)return{kind:"floating",position:Le.position};for(const Le of F.popoutGroups||[])if((Ie=(Ne=Le.data)==null?void 0:Ne.views)!=null&&Ie.includes(O))return{kind:"popout",position:Le.position,popoutUrl:Le.url};return{kind:"grid"}},[]),gt=a.useCallback(O=>{const H=h.current;if(!H)return;const F=H.getPanel(O),V=ke.current[O];if(!F||!V||V.kind==="grid")return;if(F.group.model.location.type===V.kind){delete ke.current[O],Ve();return}if(V.kind==="floating"){H.addFloatingGroup(F,{x:V.position.left??24,y:V.position.top??24,width:V.position.width,height:V.position.height}),delete ke.current[O],Ve();return}delete ke.current[O],Ve()},[Ve]);a.useEffect(()=>(w==null||w({setShortcutForActiveTab:rt,restoreHiddenTabToSavedLocation:gt,activateConversationTab:me,resetAllPanelsToMain:Re,activatePreviousTabInGroup:()=>ge(-1),activateNextTabInGroup:()=>ge(1),floatActiveTab:()=>{const O=je();O&&ue(O)},popoutActiveTab:()=>{const O=je();O&&Se(O)},dockActiveTab:()=>{const O=je();O&&(de(O)?oe(O):se(O)&&we(O))},splitActiveTabRight:()=>Ae("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Ae("below",{createGroupIfMissing:!0}),focusLeftPane:()=>ye("left"),focusRightPane:()=>ye("right"),focusUpPane:()=>ye("above"),focusDownPane:()=>ye("below"),moveActiveTabToLeftPane:()=>Ae("left"),moveActiveTabToRightPane:()=>Ae("right"),moveActiveTabToUpPane:()=>Ae("above"),moveActiveTabToDownPane:()=>Ae("below")}),()=>w==null?void 0:w(null)),[ge,we,ue,ye,je,se,de,Ae,oe,Se,w,Re,gt,me,rt]);const J=a.useCallback(()=>{const O=E.current;if(!O)return;const H=O.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const F of H)F.setAttribute("data-adhdev-force-hidden","true")},[]),_e=a.useCallback(()=>{const O=E.current;if(!O)return;const H=O.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const F of H)F.removeAttribute("data-adhdev-force-hidden")},[]),$e=a.useCallback(()=>{const O=E.current;if(!O)return;const H=O.querySelectorAll(".dv-drop-target-container");for(const re of H)re.remove();const F=O.querySelectorAll(".dv-drop-target-dropzone");for(const re of F)re.remove();const V=O.querySelectorAll(".dv-drop-target");for(const re of V)re.classList.remove("dv-drop-target")},[]),tt=a.useCallback(()=>{$(!1),X(!1),_e(),J(),$e(),!(typeof window>"u")&&(he.current!=null&&window.clearTimeout(he.current),window.requestAnimationFrame(()=>{J(),$e()}),he.current=window.setTimeout(()=>{J(),$e(),he.current=null},80))},[_e,J,$e]),Bt=a.useCallback(O=>{var F;h.current=O.api;const H=Sp(Ce);if(B.current=(H==null?void 0:H.activeTabId)??null,H!=null&&H.layout&&O.api.fromJSON(H.layout,{reuseExistingPanels:!1}),A.current=mi({hasStoredLayout:!!(H!=null&&H.layout),initialDataLoaded:m,visibleConversationCount:e.length,ides:r}),A.current||(hi(O.api,e),xi(O.api,e,y)),O.api.totalPanels===0&&e.length>0){const V=Hh(O.api,e,x);if(V){const re=O.api.getPanel(V);re&&nt(re)}}else!A.current&&!Me(x)&&Ye();C.current=!0,O.api.onDidActivePanelChange(V=>{var Ne;if(B.current=(V==null?void 0:V.id)??null,P.current=!0,M(),V&&Ot(V.id)){const Ie=((Ne=V.params)==null?void 0:Ne.routeId)||V.id.slice(7),Le=Ft(e,Ie);I((Le==null?void 0:Le.tabKey)??null),Ue();return}if(I((V==null?void 0:V.id)??null),Ue(),!V)return;const re=z.get(V.id);(re==null?void 0:re.streamSource)==="agent-stream"&&re.agentType&&S(re.routeId,el(),{agentType:re.agentType,...re.sessionId&&{targetSessionId:re.sessionId}}).catch(()=>{})}),O.api.onDidLayoutChange(()=>{Ue(),M(),le(V=>V+1)}),O.api.onWillDragPanel(()=>{$(!0),X(!1),J()}),O.api.onWillDragGroup(()=>{$(!0),X(!1),J()}),O.api.onWillShowOverlay(()=>{_e(),X(!0)}),O.api.onDidMovePanel(tt),O.api.onDidDrop(tt),O.api.onDidAddGroup(V=>{requestAnimationFrame(()=>{var re,Ne;try{const Ie=(re=V.element)==null?void 0:re.ownerDocument;if(!Ie||Ie===document)return;(Ne=Ie.getElementById("dv-popout-window"))==null||Ne.classList.add("adhdev-dockview");const Le=document.documentElement.getAttribute("data-theme");Le&&Ie.documentElement.setAttribute("data-theme",Le),Ie.body.className=document.body.className;const Ke=document.documentElement.getAttribute("style");Ke&&Ie.documentElement.setAttribute("style",Ke)}catch{}M(),le(Ie=>Ie+1)})}),I(((F=O.api.activePanel)==null?void 0:F.id)??null)},[nt,Me,tt,_e,z,r,m,Ce,J,I,Ue,x,y,S,M,e]);a.useLayoutEffect(()=>{const O=h.current;if(!O||!C.current||A.current&&mi({hasStoredLayout:!0,initialDataLoaded:m,visibleConversationCount:e.length,ides:r}))return;A.current&&(A.current=!1);const H=q.current,F=new Set(H),V=e.map(ve=>ve.tabKey),re=new Set(V),Ne=Kh({previousVisibleConversationCount:H.length,visibleConversationCount:e.length,ides:r});let Ie=!1;for(const ve of H)re.has(ve)||Ne||(ke.current[ve]=St(ve),Ie=!0);Ie&&Ve(),Ne||(hi(O,e),xi(O,e,y));const Le=V.filter(ve=>!F.has(ve));let Ke=!1;for(const ve of Le){const Ze=O.getPanel(ve),ze=ke.current[ve];if(!Ze||!ze||ze.kind==="grid")continue;if(Ze.group.model.location.type===ze.kind){delete ke.current[ve],Ke=!0;continue}if(ze.kind==="floating"){O.addFloatingGroup(Ze,{x:ze.position.left??24,y:ze.position.top??24,width:ze.position.width,height:ze.position.height}),delete ke.current[ve],Ke=!0;continue}}if(Ke&&Ve(),q.current=V,x&&Me(x))return;!O.activePanel&&O.panels[0]&&nt(O.panels[0]),!!(O.activePanel&&O.getPanel(O.activePanel.id))||Ye()},[nt,Me,Ye,r,m,Ve,St,x,y,e]),a.useEffect(()=>{C.current&&Me(x)},[Me,x]),a.useEffect(()=>{if(!U||typeof window>"u")return;const O=()=>tt();return window.addEventListener("pointerup",O),window.addEventListener("mouseup",O),window.addEventListener("dragend",O),()=>{window.removeEventListener("pointerup",O),window.removeEventListener("mouseup",O),window.removeEventListener("dragend",O)}},[tt,U]),a.useEffect(()=>()=>{typeof window>"u"||he.current!=null&&window.clearTimeout(he.current)},[]),a.useEffect(()=>{const O=F=>{const V=F.target;if(!V)return;const re=V.querySelector("[data-tab-key]")||V.closest("[data-tab-key]");if(re){const Ne=re.getAttribute("data-tab-key");if(Ne&&F.dataTransfer){const Ie=V.closest(".dv-tab")||re.closest(".dv-tab")||re;F.dataTransfer.effectAllowed="move",F.dataTransfer.setData("text/tab-key",Ne),Ie instanceof HTMLElement&&F.dataTransfer.setDragImage(Ie,Math.max(12,Math.round(Ie.clientWidth/2)),Math.max(10,Math.round(Ie.clientHeight/2)))}}};window.addEventListener("dragstart",O);const H=pi(h.current);for(const F of H)F.addEventListener("dragstart",O);return()=>{window.removeEventListener("dragstart",O);for(const F of H)F.removeEventListener("dragstart",O)}},[te]),a.useEffect(()=>{var H;const O=(H=E.current)==null?void 0:H.querySelector(".adhdev-dockview");O instanceof HTMLElement&&Wr(O,j),ae(),M(),ce()},[M,ce,ae,j]),a.useEffect(()=>{M(),ce()},[M,ce]),a.useEffect(()=>{const O=H=>{if(H.defaultPrevented||Fe)return;const F=ut(H);if(!F)return;const V=H.metaKey||H.ctrlKey||H.altKey;ja(H.target)&&!V||dn(We).setActiveTabShortcut!==F||(H.preventDefault(),H.stopPropagation(),rt())};return window.addEventListener("keydown",O,!0),()=>window.removeEventListener("keydown",O,!0)},[ut,We,Fe,rt]),a.useEffect(()=>{const O=E.current;if(!O)return;const H=F=>{var Le,Ke;if(!F.isTrusted)return;const V=(Ke=(Le=F.target)==null?void 0:Le.closest)==null?void 0:Ke.call(Le,".dv-scrollable");if(!V)return;F.preventDefault(),F.stopPropagation();const re=Math.abs(F.deltaX),Ne=Math.abs(F.deltaY),Ie=re>Ne?F.deltaX:F.deltaY;V.dispatchEvent(new WheelEvent("wheel",{deltaY:Ie,deltaMode:F.deltaMode,bubbles:!1,cancelable:!0}))};return O.addEventListener("wheel",H,{passive:!1,capture:!0}),()=>O.removeEventListener("wheel",H,{capture:!0})},[]),a.useEffect(()=>{const O=pi(h.current);if(O.length===0)return;const H=O.map(F=>{let V=[],re=null;const Ne=()=>{re!=null&&F.clearTimeout(re),re=null,V=[]},Ie=()=>{re!=null&&F.clearTimeout(re),re=F.setTimeout(()=>{re=null,V=[]},1200)},Le=Q=>{if(!Q.ctrlKey&&!Q.metaKey&&!Q.altKey)return;const ve=ut(Q);if(!ve)return;const Ze=ol();for(const[ze,_]of Object.entries(Ze))if(e.some(G=>G.tabKey===ze)&&_===ve){Q.preventDefault(),me(ze);return}},Ke=Q=>{if(Q.defaultPrevented||Fe)return;const ve=ut(Q);if(!ve)return;const Ze=Q.metaKey||Q.ctrlKey||Q.altKey;if(ja(Q.target)&&!Ze)return;const ze=dn(We),_=Object.entries(ze).filter(([Oe,Ut])=>!!Ut&&(Oe==="splitActiveTabRight"||Oe==="splitActiveTabDown"||Oe==="floatActiveTab"||Oe==="popoutActiveTab"||Oe==="dockActiveTab"||Oe==="focusLeftPane"||Oe==="focusRightPane"||Oe==="focusUpPane"||Oe==="focusDownPane"||Oe==="moveActiveTabToLeftPane"||Oe==="moveActiveTabToRightPane"||Oe==="moveActiveTabToUpPane"||Oe==="moveActiveTabToDownPane"||Oe==="selectPreviousGroupTab"||Oe==="selectNextGroupTab"||Oe==="setActiveTabShortcut"||Oe==="hideCurrentTab")),G=Ze?[ve]:[...V.slice(-1),ve].slice(-2),ie=G.join(" "),Ee=G[G.length-1],Te=_.find(([,Oe])=>Oe===ie);if(Te){Q.preventDefault(),Ne(),ht(Te[0]);return}if(_.some(([,Oe])=>Oe.startsWith(`${ie} `))){Q.preventDefault(),V=G,Ie();return}const Ge=_.find(([,Oe])=>Oe===Ee);if(Ge){Q.preventDefault(),Ne(),ht(Ge[0]);return}if(_.some(([,Oe])=>Oe.startsWith(`${Ee} `))){Q.preventDefault(),V=[Ee],Ie();return}Ne()};return F.addEventListener("keydown",Le),F.addEventListener("keydown",Ke),()=>{Ne(),F.removeEventListener("keydown",Le),F.removeEventListener("keydown",Ke)}});return()=>{for(const F of H)F()}},[ut,We,te,me,Fe,ht,e]);const Ct=j==="light"?aa:oa,Nt=((At=(It=(Kt=h.current)==null?void 0:Kt.activePanel)==null?void 0:It.group.element)==null?void 0:At.ownerDocument)??document;return t.jsxs(fl.Provider,{value:kt,children:[t.jsx("div",{ref:E,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(ad,{className:`h-full min-h-0 min-w-0 adhdev-dockview${U?" is-dragging-dockview":""}${K?" is-showing-dockview-overlay":""}`,components:{conversation:Fh,remote:Uh},defaultTabComponent:Vh,watermarkComponent:zh,onReady:Bt,singleTabMode:"default",tabAnimation:"smooth",theme:Ct,popoutUrl:"/popout.html"})}),N&&nr.createPortal(t.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:N.x,top:N.y},children:ft.map(O=>{if(O.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},O.id);let H=t.jsx(Ud,{size:13,className:"shrink-0 opacity-70"}),F=()=>{};switch(O.id){case"dockInWindow":case"dockBackToGrid":H=t.jsx(Vd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{we(N.tabKey),L(null)};break;case"moveBackToMain":H=t.jsx(Fd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{oe(N.tabKey),L(null)};break;case"floatAsPanel":H=t.jsx(zd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ue(N.tabKey),L(null)};break;case"openInNewWindow":H=t.jsx(Hd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{Se(N.tabKey),L(null)};break;case"setShortcut":F=V=>{V.stopPropagation(),Je(N.tabKey),L(null)};break;case"removeShortcut":H=t.jsx(Mt,{size:13,className:"shrink-0 opacity-70"}),F=()=>{const V={...De};delete V[N.tabKey],bt(V),L(null)};break;case"hideTab":H=t.jsx(Oi,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ee(N.tabKey),L(null)};break}return t.jsxs("button",{className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${O.tone==="muted"?"text-text-muted":""}`,onClick:F,children:[H,t.jsx("span",{className:"flex-1 min-w-0",children:O.label}),O.shortcut?t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:O.shortcut}):null]},O.id)})}),N.sourceDocument.body),Fe&&nr.createPortal(t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>Je(null),children:t.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:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",We?"⌘+1":"Ctrl+1",", ",We?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),Nt.body)]})}const pl="adhdev-recent-launch-args-v1",qh=8;function Yh(e){return String(e||"").trim().replace(/\s+/g," ")}function hl(e,s){return`${e.trim()}::${s.trim()}`}function xl(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(pl)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function Xh(e){if(!(typeof window>"u"))try{window.localStorage.setItem(pl,JSON.stringify(e))}catch{}}function bl(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=xl().byKey[hl(r,n)])==null?void 0:i.items)||[]}function gl(e,s,r){var d;const n=String(e||"").trim(),o=String(s||"").trim(),i=Yh(r);if(!n||!o||!i)return;const c=xl(),l=hl(n,o),u=((d=c.byKey[l])==null?void 0:d.items)||[],m=[i,...u.filter(g=>g!==i)].slice(0,qh);c.byKey[l]={items:m},Xh(c)}function yl(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Jr({title:e,description:s,action:r,children:n,className:o="",contentClassName:i=""}){return t.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${o}`.trim(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),s&&t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:s})]}),r?t.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?t.jsx("div",{className:s||r?`mt-3 ${i}`.trim():i,children:n}):null]})}function vl({busy:e,savedSessionsLoading:s,savedSessionsError:r,selectedSession:n,onRefresh:o,onOpenHistory:i,onClearSelection:c}){const l=n?rl(n):null;return t.jsxs(Jr,{title:"Saved history",description:Va(),action:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||s,onClick:o,children:s?"Loading…":"Refresh"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:i,children:of()})]}),children:[l?t.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:t.jsxs("div",{className:"flex items-start justify-between gap-2",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),t.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:l.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:l.providerSessionId}),t.jsx("div",{className:"mt-1",children:l.metaLine}),l.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:l.updatedLabel}),l.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:l.preview})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:c,disabled:e,children:"Clear"})]})}):t.jsx("div",{className:"text-[11px] text-text-muted",children:"Start fresh, or open saved history when you want continuity."}),r&&t.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function Gn(e){var n;if(!e)return null;const s=e.availableProviders||[];return s.some(o=>o.category==="cli"&&o.installed!==!1)?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":s.some(o=>o.category==="acp"&&o.installed!==!1)?"acp":null}function Hr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Jh({machines:e,ides:s,onClose:r,onBrowseDirectory:n,onSaveWorkspace:o,onLaunchIde:i,onLaunchProvider:c,onListSavedSessions:l}){var St,gt;const u=br(),m=a.useMemo(()=>[...e].sort($a),[e]),[d,g]=a.useState(((St=m[0])==null?void 0:St.id)||""),p=a.useMemo(()=>m.find(J=>J.id===d)||m[0],[d,m]),w=a.useMemo(()=>((p==null?void 0:p.workspaces)||[]).map(J=>({id:J.id,path:J.path,label:J.label})),[p]),I=(p==null?void 0:p.defaultWorkspaceId)||null,[b,f]=a.useState(""),[x,y]=a.useState(""),[k,T]=a.useState(Gn(m[0])),[v,R]=a.useState(""),[j,S]=a.useState(""),[h,E]=a.useState([]),[C,A]=a.useState(""),[P,B]=a.useState([]),[q,N]=a.useState(!1),[L,U]=a.useState(!1),[$,K]=a.useState(""),[X,te]=a.useState(!1),[le,he]=a.useState(()=>yt()),[Ce,ke]=a.useState(null),[z,xe]=a.useState(!1),[D,W]=a.useState(""),[Y,ae]=a.useState(!1),[ce,Se]=a.useState(""),[oe,de]=a.useState([]),[ee,ue]=a.useState(!1),[se,je]=a.useState(""),[we,Re]=a.useState(!1),M=a.useRef(null),me=a.useRef(0);a.useEffect(()=>{var J;!d&&((J=m[0])!=null&&J.id)&&g(m[0].id)},[d,m]),a.useEffect(()=>{!p||!(!p.workspaces||!p.availableProviders||!p.detectedIdes||!p.recentLaunches)||u(p.id,{minFreshMs:3e4}).catch(()=>{})},[u,p]);const ge=a.useMemo(()=>((p==null?void 0:p.availableProviders)||[]).filter(J=>J.category==="cli"&&J.installed!==!1),[p]),Z=a.useMemo(()=>((p==null?void 0:p.availableProviders)||[]).filter(J=>J.category==="acp"&&J.installed!==!1),[p]),ye=a.useMemo(()=>((p==null?void 0:p.detectedIdes)||[]).map(J=>({id:J.type,label:J.name||J.type,meta:J.running?"Detected locally":"Available to open"})),[p]),Ae=a.useMemo(()=>k==="cli"?ge.map(J=>({id:J.type,label:J.displayName||J.type,meta:"CLI provider"})):k==="acp"?Z.map(J=>({id:J.type,label:J.displayName||J.type,meta:"ACP provider"})):ye,[Z,k,ge,ye]);a.useEffect(()=>{var _e;if(!p)return;if(M.current!==p.id){M.current=p.id,f(I||((_e=w[0])==null?void 0:_e.id)||"__home__"),y(""),T(Gn(p)),R(""),S(""),A(""),B([]),U(!1),K(""),he(yt()),W("");return}f($e=>{var tt;return $e==="__custom__"||$e==="__home__"||w.some(Bt=>Bt.id===$e)?$e:I||((tt=w[0])==null?void 0:tt.id)||"__home__"}),T($e=>$e==="ide"&&ye.length>0||$e==="cli"&&ge.length>0||$e==="acp"&&Z.length>0?$e:Gn(p))},[Z.length,ge.length,I,ye.length,p,w]),a.useEffect(()=>{var J;k&&(Ae.some(_e=>_e.id===v)||R(((J=Ae[0])==null?void 0:J.id)||""))},[k,Ae,v]);const We=a.useCallback(async(J,_e)=>{const $e=me.current+1;return me.current=$e,N(!0),K(""),l(J,_e).then(tt=>{me.current===$e&&B(tt)}).catch(tt=>{me.current===$e&&(B([]),K(tt instanceof Error?tt.message:"Could not load saved sessions"))}).finally(()=>{me.current===$e&&(N(!1),U(!0))})},[l]),De=a.useCallback((J,_e)=>{E(bl(J,_e))},[]);a.useEffect(()=>{me.current+=1,A(""),he(yt()),!p||!v||k==="ide"?E([]):De(p.id,v),U(!1),B([]),K(""),N(!1)},[k,De,We,p,v]),a.useEffect(()=>{if(!C)return;const J=P.find(_e=>_e.providerSessionId===C);J!=null&&J.canResume||A("")},[P,C]);const Fe=b==="__custom__"?x.trim():b==="__home__"?"":((gt=w.find(J=>J.id===b))==null?void 0:gt.path)||"",Je=a.useMemo(()=>p?s.filter(J=>J.id!==p.id&&J.daemonId===p.id).map(J=>J.workspace):[],[s,p]),bt=a.useMemo(()=>((p==null?void 0:p.recentLaunches)||[]).map(J=>J.workspace),[p]),rt=a.useCallback(J=>{const _e=String(J.workspace||"").trim();if(!_e)return;const $e=w.find(tt=>Hr(tt.path)===Hr(_e));if($e){f($e.id),y("");return}f("__custom__"),y(_e)},[w]),ut=a.useCallback(J=>{const _e=String(J.workspace||"").trim();if(!_e)return{workspaceId:null,workspacePath:null};const $e=w.find(tt=>Hr(tt.path)===Hr(_e));return $e?{workspaceId:$e.id,workspacePath:null}:{workspaceId:null,workspacePath:_e}},[w]),ht=a.useMemo(()=>P.find(J=>J.providerSessionId===C)||null,[P,C]),kt=a.useMemo(()=>{var _e;if(k!=="cli"||!p||!v)return null;const J=((_e=ge.find($e=>$e.type===v))==null?void 0:_e.displayName)||v;return{routeId:p.id,daemonId:p.id,providerSessionId:C||void 0,transport:"pty",mode:"chat",agentName:J,agentType:v,status:"idle",title:J,messages:[],ideType:v,workspaceName:Fe,displayPrimary:J,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${p.id}:${v}`,machineName:$t(p,{fallbackId:p.id})}},[k,ge,Fe,p,C,v]),ft=a.useCallback(()=>{var _e;if(!p)return;f("__custom__"),ae(!0),je("");const J=yn(p.platform,gn(x.trim(),Fe,Je,bt,p.defaultWorkspacePath,(_e=w.find($e=>$e.id===I))==null?void 0:_e.path,w.map($e=>$e.path)));ue(!0),n(p.id,J).then($e=>{Se($e.path),y($e.path),de($e.directories)}).catch($e=>{je($e instanceof Error?$e.message:"Could not load folder")}).finally(()=>ue(!1))},[x,I,bt,Je,n,Fe,p,w]),nt=a.useCallback(J=>{p&&(ue(!0),je(""),n(p.id,J).then(_e=>{Se(_e.path),y(_e.path),de(_e.directories)}).catch(_e=>{je(_e instanceof Error?_e.message:"Could not load folder")}).finally(()=>ue(!1)))},[n,p]),Me=a.useCallback(async()=>{if(!p||!Fe)return;Re(!0),W("");const J=await o(p.id,Fe);if(Re(!1),!J.ok){W(J.error||"Could not save workspace");return}W("Workspace saved. It will appear in the list once the machine state refreshes.")},[o,Fe,p]),Ye=a.useCallback(async()=>{if(!p||!k||!v)return;xe(!0),W("");const J=j.trim()?j.trim().split(/\s+/).filter(Boolean):[],_e=k==="ide"?await i(p.id,v,{workspacePath:Fe||null}):await c(p.id,k,v,{workspaceId:b!=="__home__"&&b!=="__custom__"?b:null,workspacePath:b==="__custom__"&&Fe||null,resumeSessionId:k==="cli"&&C?C:null,cliArgs:J});if(xe(!1),!_e.ok){W(_e.error||"Could not start session");return}k!=="ide"&&j.trim()&&(gl(p.id,v,j),De(p.id,v)),r()},[k,j,De,r,i,c,Fe,p,C,v,b]),Ue=k?Mc(k,k==="cli"&&!!C):"Start",Ve=k?Tc(k,k==="cli"&&!!C):"Starting…";return p?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:t.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:t.jsx(Mt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[t.jsx(Jr,{title:"Machine",children:t.jsx("select",{value:p.id,onChange:J=>g(J.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:z,children:m.map(J=>t.jsx("option",{value:J.id,children:$t(J,{fallbackId:J.id})},J.id))})}),t.jsxs(Jr,{title:"Workspace",description:"Saved workspace is preferred. Home and custom folders are still available.",action:t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ft,disabled:z,children:"Browse…"}),children:[t.jsxs("select",{value:b,onChange:J=>{const _e=J.target.value;f(_e),_e==="__custom__"?ft():W("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:z,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),w.map(J=>t.jsxs("option",{value:J.id,children:[J.id===I?"⭐ ":"",xn(J.path,J.label)||J.path]},J.id)),t.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:b==="__home__"?"Launch without a workspace.":Fe||"Select a workspace folder."}),b==="__custom__"&&Fe&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ft,disabled:z,children:[t.jsx(_s,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Me,disabled:z||we,children:we?"Saving…":"Save workspace"})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:ge.length>0},{id:"ide",label:"IDE",enabled:ye.length>0},{id:"acp",label:"ACP",enabled:Z.length>0}].map(J=>t.jsx("button",{type:"button",className:`btn btn-sm ${k===J.id?"btn-primary":"btn-secondary"}`,onClick:()=>T(J.id),disabled:!J.enabled||z,children:J.label},J.id))})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:k==="ide"?"Choose IDE":k==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Ae.map(J=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${v===J.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>R(J.id),disabled:z,children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:J.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:J.meta})]},J.id)),Ae.length===0&&t.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),k!=="ide"&&t.jsxs(Jr,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:j,onChange:J=>S(J.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:z}),h.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:h.map(J=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>S(J),disabled:z,title:J,children:J},J))})]}),k==="cli"&&t.jsx(vl,{busy:z,savedSessionsLoading:q,savedSessionsError:$,selectedSession:ht,onRefresh:()=>{!p||!v||We(p.id,v)},onOpenHistory:()=>{!p||!v||(te(!0),yl({hasLoadedInitialResults:L,isLoading:q})&&We(p.id,v))},onClearSelection:()=>A("")}),D&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${D.includes("saved")||D.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:D})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:r,disabled:z,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:Ye,disabled:z||!k||!v||b==="__custom__"&&!Fe,children:[t.jsx(La,{size:14}),z?Ve:Ue]})]})]})}),Y&&t.jsx(wn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:ce,directories:oe,busy:ee,error:se,onClose:()=>ae(!1),onNavigate:nt,onConfirm:J=>{y(J),Se(J),f("__custom__"),ae(!1)}}),X&&kt&&t.jsx(Ya,{activeConv:kt,ides:[],isCreatingChat:!1,isRefreshingHistory:q,savedSessions:P,isSavedSessionsLoading:q,isResumingSavedSessionId:Ce,savedHistoryFilters:le,onSavedHistoryFiltersChange:he,onClose:()=>te(!1),onNewChat:()=>{A(""),te(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!p||!v||We(p.id,v)},onResumeSavedSession:J=>{if(!p||!v||Ce||!J.canResume)return;const _e=ut(J);A(J.providerSessionId),rt(J),ke(J.providerSessionId),te(!1),xe(!0),W(""),c(p.id,"cli",v,{workspaceId:_e.workspaceId,workspacePath:_e.workspacePath,resumeSessionId:J.providerSessionId}).then($e=>{if(!$e.ok){W($e.error||"Could not resume session");return}r()}).finally(()=>{xe(!1),ke($e=>$e===J.providerSessionId?null:$e)})}})]}):null}function Qh(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 Zh(e){return e instanceof Error?e.message:String(e||"")}function ex(e){const s=Zh(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function tx({showMobileChatMode:e,isMobile:s,activeConv:r,wsStatus:n,isConnected:o,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetActiveCliViewMode:m,mobileChatConversations:d,hiddenConversations:g,ides:p,actionLogs:w,sendDaemonCommand:I,setLocalUserMessages:b,setActionLogs:f,isStandalone:x,initialDataLoaded:y,userName:k,requestedMobileTabKey:T,onRequestedMobileTabConsumed:v,requestedMachineId:R,onRequestedMachineConsumed:j,requestedMobileSection:S,onRequestedMobileSectionConsumed:h,containerRef:E,isSplitMode:C,numGroups:A,groupSizes:P,groupedConvs:B,clearedTabs:q,focusedGroup:N,setFocusedGroup:L,moveTabToGroup:U,splitTabRelative:$,closeGroup:K,handleResizeStart:X,groupActiveTabIds:te,setGroupActiveTabIds:le,groupTabOrders:he,setGroupTabOrders:Ce,toggleHiddenTab:ke,visibleConversations:z,requestedDesktopTabKey:xe,onRequestedDesktopTabConsumed:D,onDesktopActiveTabChange:W,onRequestScrollToBottom:Y,onHideConversation:ae,onShowHiddenConversation:ce,onShowAllHiddenConversations:Se,scrollToBottomRequest:oe,machineEntries:de,onBrowseMachineDirectory:ee,onSaveMachineWorkspace:ue,onLaunchMachineIde:se,onLaunchMachineProvider:je,onListMachineSavedSessions:we,notifications:Re,notificationUnreadCount:M,notificationStateBySessionId:me,liveSessionInboxState:ge,onMarkNotificationRead:Z,onMarkNotificationUnread:ye,onDeleteNotification:Ae,onMarkNotificationTargetRead:We}){const De=ot.useRef(null),[Fe,Je]=ot.useState(!1),[bt,rt]=ot.useState(!1),[ut,ht]=ot.useState(!1),[kt,ft]=ot.useState(!1),nt=ot.useCallback(Q=>{var ve;nr.flushSync(()=>{ce(Q)}),(ve=De.current)==null||ve.restoreHiddenTabToSavedLocation(Q.tabKey)},[ce]),Me=ot.useCallback(Q=>{var Ze;const ve=d.find(ze=>cr(ze,Q))||g.find(ze=>cr(ze,Q));ve&&(g.some(ze=>ze.tabKey===ve.tabKey)&&nt(ve),W(ve.tabKey),(Ze=De.current)==null||Ze.activateConversationTab(ve.tabKey),Y(ve.tabKey,"notification-open")),Z(Q.id),(Q.sessionId||Q.providerSessionId||Q.tabKey||Q.routeId)&&We({sessionId:Q.sessionId,providerSessionId:Q.providerSessionId,tabKey:Q.tabKey,routeId:Q.routeId}),Je(!1)},[nt,g,d,W,Z,We,Y]),[Ye,Ue]=ot.useState(!1),[Ve,St]=ot.useState("quickstart"),[gt,J]=ot.useState("workspace"),_e=!e&&!s,$e=ot.useCallback(Q=>{Je(Q),Q&&rt(!1)},[]),tt=ot.useCallback(Q=>{rt(Q),Q&&Je(!1)},[]),Bt=ot.useCallback(()=>{var ve;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((ve=De.current)==null||ve.resetAllPanelsToMain(),rt(!1))},[]),Ct=ot.useCallback(()=>{St(z.length===0?"quickstart":"shortcuts"),J("workspace"),ht(!0),Je(!1),rt(!1)},[z.length]),Nt=ot.useCallback(async Q=>{var G;if(!r)return;const ve=(G=r.modalButtons)==null?void 0:G[Q];if(!ve)return;const Ze=dr(r);if(!Ze)return;const ze=ve.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),_=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(ze);try{await I(Ze,"resolve_action",{button:ve,action:_?"approve":"reject",buttonIndex:Q,...Rs(r)})}catch(ie){ex(ie)||console.error("[Shortcut approval] Failed:",ie)}},[r,I]),{isMac:Kt,actionDefinitions:It,actionShortcuts:At,shortcutListening:O,shortcutListeningDraft:H,setShortcutListening:F,setShortcutListeningDraft:V,saveShortcuts:re}=$h({enabled:_e&&!ut,onTrigger:Q=>{var ve,Ze,ze,_,G,ie,Ee,Te,Be,Ge,Pe,Oe,Ut,Hs,Fs,vr;if(Q==="openShortcutHelp"){Ct();return}if(Q==="hideCurrentTab"){r&&ae(r);return}if(Q==="toggleHiddenTabs"){tt(!bt);return}if(Q==="openHistoryForActiveTab"){r&&!Qe(r)&&i(r);return}if(Q==="openRemoteForActiveTab"){r&&!st(r)&&!Qe(r)&&c(r);return}if(Q==="splitActiveTabRight"){(ve=De.current)==null||ve.splitActiveTabRight();return}if(Q==="splitActiveTabDown"){(Ze=De.current)==null||Ze.splitActiveTabDown();return}if(Q==="floatActiveTab"){(ze=De.current)==null||ze.floatActiveTab();return}if(Q==="popoutActiveTab"){(_=De.current)==null||_.popoutActiveTab();return}if(Q==="dockActiveTab"){(G=De.current)==null||G.dockActiveTab();return}if(Q==="focusLeftPane"){(ie=De.current)==null||ie.focusLeftPane();return}if(Q==="focusRightPane"){(Ee=De.current)==null||Ee.focusRightPane();return}if(Q==="focusUpPane"){(Te=De.current)==null||Te.focusUpPane();return}if(Q==="focusDownPane"){(Be=De.current)==null||Be.focusDownPane();return}if(Q==="moveActiveTabToLeftPane"){(Ge=De.current)==null||Ge.moveActiveTabToLeftPane();return}if(Q==="moveActiveTabToRightPane"){(Pe=De.current)==null||Pe.moveActiveTabToRightPane();return}if(Q==="moveActiveTabToUpPane"){(Oe=De.current)==null||Oe.moveActiveTabToUpPane();return}if(Q==="moveActiveTabToDownPane"){(Ut=De.current)==null||Ut.moveActiveTabToDownPane();return}if(Q==="triggerPrimaryApprovalAction"){Nt(0);return}if(Q==="triggerSecondaryApprovalAction"){Nt(1);return}if(Q==="triggerTertiaryApprovalAction"){Nt(2);return}if(Q==="setActiveTabShortcut"){(Hs=De.current)==null||Hs.setShortcutForActiveTab();return}if(Q==="selectPreviousGroupTab"){(Fs=De.current)==null||Fs.activatePreviousTabInGroup();return}if(Q==="selectNextGroupTab"){(vr=De.current)==null||vr.activateNextTabInGroup();return}!r||!st(r)||Qe(r)||Q==="toggleCliView"&&m(u==="chat"?"terminal":"chat")}}),Ne=ot.useCallback(()=>{ht(!1),F(null),V([])},[F,V]),Ie=ot.useMemo(()=>gt==="all"?It:It.filter(Q=>Qh(Q)===gt),[It,gt]),Le=ot.useCallback(()=>{const Q=Object.fromEntries(It.map(ve=>[ve.id,""]));re(Q)},[It,re]),Ke=ot.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const Q=Object.fromEntries(It.map(ve=>[ve.id,ve.defaultShortcut]));re(Q)},[It,re]);return ot.useEffect(()=>{const Q=ve=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?ve.metaKey&&ve.key.toLowerCase()==="w":ve.ctrlKey&&ve.key.toLowerCase()==="w")&&(ve.preventDefault(),r&&ae&&ae(r))};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[r,ae]),ot.useEffect(()=>{if(!ut||O)return;const Q=ve=>{ve.key==="Escape"&&(ve.preventDefault(),Ne())};return window.addEventListener("keydown",Q,!0),()=>window.removeEventListener("keydown",Q,!0)},[Ne,ut,O]),ot.useEffect(()=>{if(!_e){Ue(!1);return}Ue(!0);const Q=window.setTimeout(()=>{Ue(!1)},1e4);return()=>window.clearTimeout(Q)},[_e]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(ef,{activeConv:r,wsStatus:n,isConnected:o,conversations:z,hiddenConversations:g,onOpenHistory:i,onHideConversation:ae,onShowConversation:nt,onShowAllHidden:Se,onResetPanelsToMain:Bt,notifications:Re,notificationUnreadCount:M,onOpenNotification:Me,onMarkNotificationRead:Z,onMarkNotificationUnread:ye,onDeleteNotification:Ae,inboxOpen:Fe,onInboxOpenChange:$e,hiddenOpen:bt,onHiddenOpenChange:tt,onOpenNewSession:s?void 0:()=>ft(!0),actionShortcuts:At,onOpenRemote:()=>{!r||st(r)||Qe(r)||c(r)},onStopCli:l,activeCliViewMode:u,onSetCliViewMode:m}),e?t.jsx(Nh,{conversations:d,hiddenConversations:g,ides:p,actionLogs:w,sendDaemonCommand:I,setLocalUserMessages:b,setActionLogs:f,isStandalone:x,userName:k,requestedActiveTabKey:T,onRequestedActiveTabConsumed:v,requestedMachineId:R,onRequestedMachineConsumed:j,requestedMobileSection:S,onRequestedMobileSectionConsumed:h,onOpenHistory:i,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:o,onShowHiddenConversation:nt,onShowAllHiddenConversations:Se,onOpenNewSession:()=>ft(!0),notificationStateBySessionId:me,liveSessionInboxState:ge,onMarkNotificationTargetRead:We}):s?t.jsx(Ph,{containerRef:E,isSplitMode:C,numGroups:A,groupSizes:P,groupedConvs:B,clearedTabs:q,ides:p,actionLogs:w,sendDaemonCommand:I,setLocalUserMessages:b,setActionLogs:f,isStandalone:x,hasRegisteredMachines:de.length>0,userName:k,focusedGroup:N,setFocusedGroup:L,moveTabToGroup:U,splitTabRelative:$,closeGroup:K,handleResizeStart:X,groupActiveTabIds:te,setGroupActiveTabIds:le,groupTabOrders:he,setGroupTabOrders:Ce,toggleHiddenTab:ke,onOpenNewSession:()=>ft(!0),allowTabShortcuts:!1,notificationStateBySessionId:me,liveSessionInboxState:ge}):t.jsx(Gh,{visibleConversations:z,clearedTabs:q,ides:p,actionLogs:w,sendDaemonCommand:I,setLocalUserMessages:b,setActionLogs:f,isStandalone:x,hasRegisteredMachines:de.length>0,initialDataLoaded:y,userName:k,toggleHiddenTab:ke,actionShortcuts:At,registerActionHandlers:Q=>{De.current=Q},onActiveTabChange:W,requestedActiveTabKey:xe,onRequestedActiveTabConsumed:D,onRequestScrollToBottom:Y,scrollToBottomRequest:oe,onOpenNewSession:()=>ft(!0),notificationStateBySessionId:me,liveSessionInboxState:ge}),kt&&t.jsx(Jh,{machines:de,ides:p,onClose:()=>ft(!1),onBrowseDirectory:ee,onSaveWorkspace:ue,onLaunchIde:se,onLaunchProvider:je,onListSavedSessions:we}),ut&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:Ne,children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",onClick:Q=>Q.stopPropagation(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:Ne,"aria-label":"Close dashboard guide",children:t.jsx(Mt,{size:14})})]}),t.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(Q=>t.jsx("button",{type:"button",className:`btn btn-sm ${Ve===Q.id?"btn-primary":"btn-secondary"}`,onClick:()=>St(Q.id),children:Q.label},Q.id))}),Ve==="overview"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Kt?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Ve==="quickstart"&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),Ve==="shortcuts"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[t.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(Q=>t.jsx("button",{type:"button",className:`btn btn-sm ${gt===Q.id?"btn-primary":"btn-secondary"}`,onClick:()=>J(Q.id),children:Q.label},Q.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Le,children:"Disable all"}),t.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:Ke,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:Ie.map(Q=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${O===Q.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Q.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Q.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:Q.defaultShortcut})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:O===Q.id?H.length>0?`${H.join(" ")} ...`:"Listening...":At[Q.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{F(Q.id),V([])},children:O===Q.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const ve={...At};ve[Q.id]="",re(ve)},children:"Disable"})]})]})},Q.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Kt?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&t.jsxs("button",{type:"button",onClick:Ct,className:`fixed right-4 bottom-24 z-40 hidden md:inline-flex items-center rounded-full border border-border-subtle bg-bg-primary/88 backdrop-blur py-2 text-xs text-text-secondary hover:text-text-primary transition-all ${Ye?"gap-2 px-2.5":"justify-center w-10 px-0"}`,style:{boxShadow:"0 6px 18px rgba(0,0,0,0.12)"},title:"Dashboard guide","aria-label":"Open dashboard guide",children:[t.jsx("span",{className:"inline-flex items-center justify-center w-5 h-5 rounded-full bg-bg-secondary text-[11px] font-semibold text-text-primary shrink-0",children:"?"}),Ye&&t.jsx("span",{children:"Guide"})]})]})}const qn=[{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 sx({onClose:e}){const[s,r]=a.useState(0),n=qn[s],o=s===qn.length-1;return t.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:i=>{i.stopPropagation()},children:[t.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[t.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:t.jsx(Mt,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:qn.map((i,c)=>t.jsx("div",{style:{width:c===s?24:8,height:8,borderRadius:4,background:c===s?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),t.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),t.jsxs("div",{style:{textAlign:"center"},children:[t.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[t.jsx("span",{children:n.icon})," ",n.title]}),t.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&t.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[t.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),o&&t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),t.jsx("div",{className:"flex justify-end items-center mt-6",children:t.jsx("button",{onClick:()=>o?e():r(i=>i+1),className:"btn btn-primary",children:o?"Get Started →":"Next →"})})]}),t.jsx("style",{children:`
55
+ @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
56
+ @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
57
+ `})]})}function rx({hasExtensions:e,ideName:s,activeChatTab:r,extensionTabs:n,onSelectTab:o}){return e?t.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[t.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${r==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>o("native"),children:s}),n.map(i=>{const c=r===i.tabKey,l=i.status==="waiting_approval",u=i.status==="generating";return t.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${c?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>o(i.tabKey),children:[t.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":u?"var(--accent-primary)":"var(--text-muted)",boxShadow:u?"0 0 6px var(--accent-primary)":"none"}}),i.title,l&&t.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},i.tabKey)})]}):null}function nx({ideData:e,allIdes:s,connectionStates:r,localUserMessages:n,ideName:o,preferredTabKey:i}){const[c,l]=a.useState(()=>i||"native"),u=a.useMemo(()=>Rc(s),[s]),m=a.useMemo(()=>e?Xa(e,n,{machineNames:u,connectionStates:r,defaultConnectionState:"new"}):[],[e,n,u,r]),d=a.useMemo(()=>m.find(f=>f.streamSource==="native"),[m]),g=a.useMemo(()=>m.filter(f=>f.streamSource==="agent-stream"),[m]),p=a.useMemo(()=>e?Ft(m,e.id):null,[m,e]);a.useEffect(()=>{i&&l(i)},[i]),a.useEffect(()=>{if(i||!p)return;const f=p.streamSource==="native"?"native":p.tabKey;!f||c===f||c==="native"&&l(f)},[c,p,i]),a.useEffect(()=>{var f;c!=="native"&&(g.some(x=>x.tabKey===c)||l(((f=g[0])==null?void 0:f.tabKey)||"native"))},[c,g]),a.useEffect(()=>{c==="native"&&(d||g[0]&&l(g[0].tabKey))},[c,d,g]);const w=a.useMemo(()=>c==="native"&&d?d:g.find(f=>f.tabKey===c)||p||d||g[0],[c,d,p,g]),I=a.useMemo(()=>g.map(f=>({tabKey:f.tabKey,title:Nc(f)||o,status:f.status})),[g,o]),b=a.useCallback(f=>{if(f)return m.find(x=>cr(x,{sessionId:f,routeId:f,tabKey:f,providerSessionId:f}))},[m]);return{activeChatTab:c,setActiveChatTab:l,activeConv:w,conversations:m,extensionTabs:I,hasExtensions:I.length>0,resolveConversationByTarget:b}}function ax({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:o,localUserMessages:i,sendDaemonCommand:c,setLocalUserMessages:l,setActionLogs:u,isStandalone:m,userName:d,onOpenHistory:g,onConversationChange:p,onClose:w}){const[I,b]=a.useState("split"),[f,x]=a.useState(()=>rs(e)?"native":e.tabKey),y=a.useRef(null),k=a.useMemo(()=>s||r.find($=>$.id===e.routeId),[e.routeId,s,r]),T=a.useMemo(()=>it((k==null?void 0:k.type)||""),[k==null?void 0:k.type]),{conversations:v,extensionTabs:R,hasExtensions:j}=nx({ideData:k,allIdes:r,connectionStates:n,localUserMessages:i,ideName:T||"IDE",preferredTabKey:rs(e)?void 0:e.tabKey}),S=a.useMemo(()=>k?Ft(v,k.id):null,[k,v]);a.useEffect(()=>{const $=y.current,K={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(y.current=K,!($&&$.routeId===K.routeId&&$.tabKey===K.tabKey&&$.streamSource===K.streamSource)){if(rs(e)){x("native");return}x(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),a.useEffect(()=>{if(f==="native"){if(v.some($=>$.streamSource==="native"))return;(S==null?void 0:S.streamSource)==="agent-stream"&&x(S.tabKey);return}if(!v.some($=>$.tabKey===f)){if((S==null?void 0:S.streamSource)==="agent-stream"){x(S.tabKey);return}x("native")}},[v,f,S]);const h=a.useMemo(()=>f==="native"?v.find($=>$.streamSource==="native")||e:v.find($=>$.tabKey===f)||e,[e,v,f]),E=zc(h),C=a.useMemo(()=>E.status||E.modalMessage||E.modalButtons?{...h,...E.status?{status:E.status}:{},...E.modalMessage!==void 0?{modalMessage:E.modalMessage}:{},...E.modalButtons!==void 0?{modalButtons:E.modalButtons}:{}}:h,[h,E]),A=xr(C),P=bn({sendDaemonCommand:c,activeConv:C,setLocalUserMessages:l,setActionLogs:u,isStandalone:m}),{connScreenshot:B,screenshotUsage:q,handleRemoteAction:N}=cl({doId:A,targetSessionId:dc(C),connState:C.connectionState||"new",viewMode:I}),L=a.useMemo(()=>o.filter($=>$.routeId===C.tabKey),[o,C.tabKey]);a.useEffect(()=>{p==null||p(C)},[C,p]),a.useEffect(()=>{const $=K=>{K.key==="Escape"&&w()};return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[w]);const U=a.useCallback($=>{$.stopPropagation()},[]);return t.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:w,children:t.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:U,children:[t.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[t.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[t.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(Rt,{size:16})}),t.jsx("span",{className:"truncate",children:Oa(h)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:w,children:"Close"})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[t.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map($=>{const K=I===$;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${K?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>b($),title:$==="split"?"Split view":"Remote only",children:$==="split"?t.jsx(Td,{size:15}):t.jsx(Rt,{size:15})},$)})}),t.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),t.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>g(h),title:"Chat History",children:[t.jsx(Ma,{size:14,className:"md:mr-1.5"}),t.jsx("span",{className:"hidden md:inline",children:"History"})]}),t.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:w,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${I==="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:[I!=="remote"&&t.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${I==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[t.jsx(rx,{hasExtensions:j,ideName:T||"IDE",activeChatTab:f,extensionTabs:R,onSelectTab:x}),t.jsx(Xi,{activeConv:C,onModalButton:P.handleModalButton}),t.jsx(ha,{activeConv:C,ideEntry:k,showMetaChips:!1,handleSendChat:P.handleSendChat,isSendingChat:P.isSendingChat,sendFeedbackMessage:P.sendFeedbackMessage,handleFocusAgent:P.handleFocusAgent,isFocusingAgent:P.isFocusingAgent,actionLogs:L,userName:d})]}),t.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${I==="split"?"order-1 md:order-2":""}`,children:t.jsx(Vi,{addLog:()=>{},connState:C.connectionState||"new",connScreenshot:B,screenshotUsage:q,transportType:C.transport,onAction:N})})]})]})})}function ox({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:o}){const i=Ym(e);return t.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[t.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[t.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[t.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",i,"?"]}),t.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:s?"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.":"This provider does not support graceful stop. Force Stop will end the runtime immediately."})]}),t.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s&&t.jsx("button",{onClick:o,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),t.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:"Force Stop"}),t.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function ix({historyModalOpen:e,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:o,savedHistorySessions:i,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:l,onCloseHistory:u,onNewHistoryChat:m,onSwitchHistorySession:d,onRefreshHistory:g,onResumeSavedHistorySession:p,remoteDialogConv:w,remoteDialogIdeEntry:I,connectionStates:b,actionLogs:f,localUserMessages:x,sendDaemonCommand:y,setLocalUserMessages:k,setActionLogs:T,isStandalone:v,userName:R,onOpenRemoteHistory:j,onRemoteConversationChange:S,onCloseRemoteDialog:h,cliStopDialogOpen:E,cliStopTargetConv:C,onCancelCliStop:A,onStopCliNow:P,onSaveCliAndStop:B,toasts:q,onDismissToast:N,onClickToast:L,showOnboarding:U,onCloseOnboarding:$}){var te;const[K,X]=ot.useState(()=>yt());return t.jsxs(t.Fragment,{children:[e&&s&&t.jsx(Ya,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:o,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:l,savedHistoryFilters:K,onSavedHistoryFiltersChange:X,onClose:u,onNewChat:m,onSwitchSession:d,onRefreshHistory:g,onResumeSavedSession:p}),w&&t.jsx(ax,{activeConv:w,ideEntry:I,ides:r,connectionStates:b,actionLogs:f,localUserMessages:x,sendDaemonCommand:y,setLocalUserMessages:k,setActionLogs:T,isStandalone:v,userName:R,onOpenHistory:j,onConversationChange:S,onClose:h}),E&&C&&(st(C)||Qe(C))&&t.jsx(ox,{activeConv:C,canSaveAndStop:st(C)&&!Qe(C)&&!!((te=C.resume)!=null&&te.supported),onCancel:A,onStopNow:P,onSaveAndStop:B}),t.jsx(Lc,{toasts:q,onDismiss:N,onClickToast:L}),U&&t.jsx(sx,{onClose:$})]})}function cx({daemons:e,targetVersion:s,required:r=!1,upgradingDaemons:n,onUpgrade:o,onDismiss:i}){return e.length===0?null:t.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:r?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:r?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[t.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:t.jsx(fr,{size:14})}),t.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[t.jsxs("span",{children:[r?"Daemon update required":"Update available",s?t.jsxs(t.Fragment,{children:[": ",t.jsxs("strong",{children:["v",s]})]}):null]}),e.map(c=>{const l=$t(c,{fallbackId:c.id}),u=n[c.id],m=c.version||c.daemonVersion||"unknown",d=c.versionUpdateRequired===!0;return t.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[t.jsx("span",{className:"font-medium text-text-primary",children:l}),t.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),d&&t.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),u==="upgrading"?t.jsx("span",{className:"text-[10px] animate-pulse",style:{color:d?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):u==="done"?t.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):u==="error"?t.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>o(c.id),children:"retry"}):t.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:d?"var(--status-danger)":"var(--status-warning)",background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>o(c.id),children:d?"Update now":"Upgrade"})]},c.id)})]}),!r&&t.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:t.jsx(Mt,{size:16})})]})}function lx(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function dx(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":return!0;case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function ux(e,s,r=Date.now()){return!e||!dx(s)?null:{tabKey:e,nonce:r}}function mx(e){const s=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?s===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:r===e.autoReadKey?r:null}:r===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:r}:{shouldSchedule:!0,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!r,nextPendingKey:null}}function fx(e){const s=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),o=!!e.liveState.unread,i=[e.tabKey,e.historySessionId||"",s,r,n,o?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&o&&s&&s!==r),autoReadKey:i,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function px(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function bi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function hx(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function xx(){var go,yo,vo,wo,jo;const{sendCommand:e}=Tt(),s=br(),r=Uc(),n=Ia(),o=Os(),[i,c]=od(),l=i.get("activeTab"),u=((go=n.state)==null?void 0:go.openRemoteForTabKey)||null,m=((yo=n.state)==null?void 0:yo.openMachineId)||null,d=((vo=n.state)==null?void 0:vo.mobileSection)||null,g=wc(),p=g.ides||[],w=g.initialLoaded??!0,{updateRouteChats:I,setToasts:b}=g,[f,x]=a.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),y=g.toasts||[],k=g.wsStatus||"connected",T=g.isConnected??!0,v=g.connectionStates||{},R=g.showReconnected||!1,{groupAssignments:j,setGroupAssignments:S,focusedGroup:h,setFocusedGroup:E,groupActiveTabIds:C,setGroupActiveTabIds:A,groupTabOrders:P,setGroupTabOrders:B,groupSizes:q,setGroupSizes:N,isMobile:L,hasHydratedStoredLayout:U,hydrateStoredLayout:$}=Mp(),[K,X]=a.useState(!1),[te,le]=a.useState(!1),[he,Ce]=a.useState(null),[ke,z]=a.useState([]),[xe,D]=a.useState(!1),[W,Y]=a.useState(null),[ae,ce]=a.useState(()=>eo());a.useEffect(()=>Gf(ce),[]);const Se=a.useMemo(()=>lx({isMobile:L,mobileViewMode:ae}),[L,ae]),[oe,de]=a.useState([]),[ee,ue]=a.useState({}),[se,je]=a.useState({}),[we,Re]=a.useState({}),[M,me]=a.useState(null),[ge,Z]=a.useState(null),[ye,Ae]=a.useState(null),We=a.useRef(null);pr("Dashboard",{ideCount:p.length,toastCount:y.length,focusedGroup:h,groupCount:Object.keys(j).length,localMessageTabs:Object.keys(ee).length,actionLogCount:oe.length});const De=a.useMemo(()=>p.filter(ne=>ne.type==="adhdev-daemon").sort($a),[p]),Fe=De[0],Je=!!Fe;a.useEffect(()=>{for(const ne of De){(!ne.detectedIdes||!ne.availableProviders||!ne.recentLaunches||!ne.workspaces)&&s(ne.id,{minFreshMs:3e4}).catch(()=>{});const be=ne.machine;(typeof(be==null?void 0:be.cpus)!="number"||typeof(be==null?void 0:be.totalMem)!="number"||typeof(be==null?void 0:be.arch)!="string"||typeof(be==null?void 0:be.release)!="string")&&r(ne.id,{minFreshMs:3e4}).catch(()=>{})}},[s,r,De]);const bt=(Fe==null?void 0:Fe.terminalBackend)||null,rt=Fe?$t(Fe,{fallbackId:Fe.id}):null,ut=(Fe==null?void 0:Fe.id)||null,ht=a.useMemo(()=>np(p,se),[p,se]),{hiddenTabs:kt,hideTab:ft,toggleTab:nt,showTab:Me,showAllTabs:Ye}=rp(),{conversations:Ue,visibleConversations:Ve,visibleTabKeys:St,resolveConversationBySessionId:gt,resolveConversationByTarget:J}=xp({ides:ht,connectionStates:v,localUserMessages:ee,clearedTabs:we,hiddenTabs:kt}),_e=a.useMemo(()=>new Map(Ue.map(ne=>[ne.tabKey,Dr(ne)])),[Ue]),$e=a.useCallback(ne=>{const pe=_e.get(ne)||Dr({tabKey:ne});ft(pe)},[_e,ft]),tt=a.useCallback(ne=>{const pe=_e.get(ne)||Dr({tabKey:ne});nt(pe)},[_e,nt]),Bt=a.useCallback(ne=>{const pe=_e.get(ne)||Dr({tabKey:ne});Me(pe)},[_e,Me]);$m(Ve,Se),a.useEffect(()=>{Object.keys(se).length!==0&&je(ne=>ap(ne,p))},[p,se]);const Ct=a.useMemo(()=>du(p),[p]),{notifications:Nt,unreadCount:Kt,notificationStateBySessionId:It,markRead:At,markUnread:O,markTargetRead:H,deleteNotification:F}=eh({conversations:Ue,liveSessionInboxState:Ct}),V=a.useCallback(ne=>{const pe=Nt.find(fe=>fe.id===ne),be=Math.max(Date.now(),(pe==null?void 0:pe.updatedAt)||0);At(ne,be),pe!=null&&pe.sessionId&&e(pe.machineId||pe.routeId,"mark_session_seen",{sessionId:pe.sessionId,seenAt:be}).catch(()=>{})},[At,Nt,e]),re=a.useCallback(ne=>{const pe=Nt.find(be=>be.id===ne);O(ne),pe!=null&&pe.sessionId&&e(pe.machineId||pe.routeId,"mark_notification_unread",{sessionId:pe.sessionId,notificationId:pe.id}).catch(()=>{})},[O,Nt,e]),Ne=a.useCallback(ne=>{const pe=Nt.find(be=>be.id===ne);F(ne),pe!=null&&pe.sessionId&&e(pe.machineId||pe.routeId,"delete_notification",{sessionId:pe.sessionId,notificationId:pe.id}).catch(()=>{})},[F,Nt,e]),Ie=a.useRef(null),Le=a.useRef(null),Ke=a.useRef(null),Q=a.useRef(null),ve=a.useRef(null),{containerRef:Ze,normalizedGroupAssignments:ze,numGroups:_,isSplitMode:G,groupedConvs:ie,moveTabToGroup:Ee,closeGroup:Te,handleResizeStart:Be,splitTabRelative:Ge}=$p({groupAssignments:j,setGroupAssignments:S,setFocusedGroup:E,setGroupActiveTabIds:A,setGroupTabOrders:B,groupSizes:q,setGroupSizes:N,isMobile:L,visibleConversations:Ve,visibleTabKeys:St}),Pe=a.useMemo(()=>{var pe,be;if(!L){if(M){const fe=Ue.find(Xe=>Xe.tabKey===M);if(fe)return fe}return Ve[0]}const ne=C[h];if(ne){const fe=Ue.find(Xe=>Xe.tabKey===ne);if(fe)return fe}return((pe=ie[h])==null?void 0:pe[0])||((be=ie[0])==null?void 0:be[0])},[M,L,C,h,Ue,ie,Ve]);a.useEffect(()=>{const ne=()=>{Ke.current&&(clearTimeout(Ke.current),Ke.current=null),Q.current&&(clearTimeout(Q.current),Q.current=null),ve.current&&(document.removeEventListener("visibilitychange",ve.current),ve.current=null),Le.current=null};if(L){ne(),Ie.current=null;return}if(!(Pe!=null&&Pe.sessionId)){ne(),Ie.current=null;return}const pe=rn(Pe,Ct),be=fx({tabKey:Pe.tabKey,historySessionId:hr(Pe)||"",lastMessageHash:Pe.lastMessageHash||"",lastMessageAt:Number(Pe.lastMessageAt||0),timestamp:ms(Pe),liveState:pe}),fe=be.autoReadKey,Xe=mx({autoReadKey:fe,shouldMarkSeen:be.shouldMarkSeen,completedKey:Ie.current,pendingKey:Le.current});if(!be.shouldMarkSeen){Xe.shouldCancelPending&&ne(),Ie.current=fe;return}if(!Xe.shouldSchedule)return;Xe.shouldCancelPending&&ne();const mt=qi(Pe),Pt=()=>{if(document.visibilityState!=="visible"||Ie.current===fe)return;Ie.current=fe,Le.current=null,Ke.current=null,Q.current=null,ve.current&&(document.removeEventListener("visibilitychange",ve.current),ve.current=null);const pt=be.readAt;H({...mt},pt),e(Pe.daemonId||Pe.routeId,"mark_session_seen",{sessionId:Pe.sessionId,seenAt:pt}).catch(()=>{})};if(Le.current=Xe.nextPendingKey,document.visibilityState==="visible"){Ke.current=setTimeout(Pt,1500);const pt=()=>{document.visibilityState!=="visible"&&Ke.current&&(clearTimeout(Ke.current),Ke.current=null)};ve.current=pt,document.addEventListener("visibilitychange",pt);return}const Xt=()=>{document.visibilityState==="visible"&&(Q.current&&clearTimeout(Q.current),Q.current=setTimeout(Pt,800),ve.current&&(document.removeEventListener("visibilitychange",ve.current),ve.current=null))};ve.current=Xt,document.addEventListener("visibilitychange",Xt)},[Pe,L,Ct,H,e]),a.useEffect(()=>()=>{Ke.current&&clearTimeout(Ke.current),Q.current&&clearTimeout(Q.current),ve.current&&document.removeEventListener("visibilitychange",ve.current)},[]);const{requestedDesktopTabKey:Oe,requestedMobileTabKey:Ut,consumeRequestedActiveTab:Hs}=bp({isMobile:L,urlActiveTab:l,resolveConversationBySessionId:gt,setSearchParams:c}),{remoteDialogConv:Fs,remoteDialogIdeEntry:vr,remoteDialogActiveConv:Il,setRemoteDialogActiveConv:Nn,openRemoteDialog:Al,closeRemoteDialog:Ml}=Rp({isMobile:L,location:n,navigate:o,requestedRemoteTabTarget:u,requestedDesktopTabKey:Oe,conversations:Ue,ides:p,resolveConversationByTarget:J}),lt=Il||Fs||Pe,zt=!!lt&&st(lt)&&!Qe(lt),wr=a.useMemo(()=>{if(!lt||!zt)return null;const ne=lt.daemonId||lt.routeId||"",pe=Wt(lt);return`${ne}:${pe}`},[lt,zt]),Tl=a.useMemo(()=>Ve,[Ve]),jr=L&&ae==="chat",Ll=a.useMemo(()=>Ue.filter(ne=>to(kt,ne)),[Ue,kt]),kr=a.useCallback(ne=>{const pe=new URLSearchParams(i);pe.set("activeTab",ne),c(pe,{replace:!0})},[i,c]),Rl=a.useCallback(async(ne,pe)=>vn(e,ne,pe),[e]),Pl=a.useCallback(async(ne,pe)=>{if(!pe.trim())return{ok:!1,error:"Choose a workspace path first."};try{const be=await e(ne,"workspace_add",{path:pe.trim()});return be!=null&&be.success?{ok:!0}:{ok:!1,error:(be==null?void 0:be.error)||"Could not save workspace"}}catch(be){return{ok:!1,error:be instanceof Error?be.message:"Could not save workspace"}}},[e]),_l=a.useCallback(async(ne,pe,be)=>{var fe;try{const Xe={ideType:pe,enableCdp:!0};(fe=be==null?void 0:be.workspacePath)!=null&&fe.trim()&&(Xe.workspace=be.workspacePath.trim());const mt=await e(ne,"launch_ide",Xe);return!(mt!=null&&mt.success)&&(mt==null?void 0:mt.success)!==void 0?{ok:!1,error:(mt==null?void 0:mt.error)||"Could not launch IDE"}:(Ae({machineId:ne,kind:"ide",providerType:pe,workspacePath:(be==null?void 0:be.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(Xe){return{ok:!1,error:Xe instanceof Error?Xe.message:"Could not launch IDE"}}},[e]),Dl=a.useCallback(async(ne,pe,be,fe)=>{var mt,Pt,Xt;const Xe=Date.now();try{const pt={cliType:be};(mt=fe==null?void 0:fe.workspacePath)!=null&&mt.trim()?pt.dir=fe.workspacePath.trim():fe!=null&&fe.workspaceId&&(pt.workspaceId=fe.workspaceId),(Pt=fe==null?void 0:fe.resumeSessionId)!=null&&Pt.trim()&&(pt.resumeSessionId=fe.resumeSessionId.trim()),Array.isArray(fe==null?void 0:fe.cliArgs)&&fe.cliArgs.length>0&&(pt.cliArgs=fe.cliArgs),(Xt=fe==null?void 0:fe.initialModel)!=null&&Xt.trim()&&(pt.initialModel=fe.initialModel.trim());const xt=await e(ne,"launch_cli",pt),_t=(xt==null?void 0:xt.result)||xt,Us=(_t==null?void 0:_t.sessionId)||(_t==null?void 0:_t.id);return xt!=null&&xt.success&&Us?(kr(Us),{ok:!0}):xt!=null&&xt.success?(Ae({machineId:ne,kind:pe,providerType:be,workspacePath:(fe==null?void 0:fe.workspacePath)||null,resumeSessionId:(fe==null?void 0:fe.resumeSessionId)||null,startedAt:Xe}),{ok:!0}):{ok:!1,error:(xt==null?void 0:xt.error)||(_t==null?void 0:_t.error)||`Could not launch ${pe.toUpperCase()} session`}}catch(pt){return hx(pt)?(Ae({machineId:ne,kind:pe,providerType:be,workspacePath:(fe==null?void 0:fe.workspacePath)||null,resumeSessionId:(fe==null?void 0:fe.resumeSessionId)||null,startedAt:Xe}),{ok:!0}):{ok:!1,error:pt instanceof Error?pt.message:`Could not launch ${pe.toUpperCase()} session`}}},[kr,e]),El=a.useCallback(async(ne,pe)=>{if(!ne||!pe)return[];try{const be=await e(ne,"list_saved_sessions",{providerType:pe,kind:"cli",limit:30}),fe=(be==null?void 0:be.result)??be;return Array.isArray(fe==null?void 0:fe.sessions)?fe.sessions:[]}catch(be){return console.error("List saved sessions failed",be),[]}},[e]);a.useEffect(()=>{if(!ye)return;const ne=bi(ye.workspacePath),pe=p.find(fe=>{var pt,xt,_t,Us;if(!fe||fe.type==="adhdev-daemon"||px(fe.daemonId||fe.id)!==ye.machineId||(lr(fe)?"cli":Ts(fe)?"acp":"ide")!==ye.kind||String(fe.agentType||fe.type||"")!==ye.providerType)return!1;if(ye.resumeSessionId)return String(fe.providerSessionId||"")===ye.resumeSessionId;if(ne){const In=bi(fe.workspace||fe.runtimeWorkspaceLabel);return In?In===ne:!1}return Number(fe.lastUpdated||fe._lastUpdate||fe.timestamp||((Us=(_t=(xt=(pt=fe.activeChat)==null?void 0:pt.messages)==null?void 0:xt.at)==null?void 0:_t.call(xt,-1))==null?void 0:Us.timestamp)||0)>=ye.startedAt-5e3});if(!pe)return;const be=fc({entrySessionId:pe.sessionId,entryInstanceId:pe.instanceId,entryRouteId:pe.id,conversations:Ue});be&&(Ae(null),kr(be))},[Ue,kr,p,ye]),a.useEffect(()=>{if(!ye)return;const ne=window.setTimeout(()=>{Ae(pe=>!pe||pe.startedAt!==ye.startedAt?pe:null)},45e3);return()=>window.clearTimeout(ne)},[ye]),op({visibleConversations:Ve,clearedTabs:we,setClearedTabs:Re,setActionLogs:de}),gp({ides:p,sendDaemonCommand:e,setToasts:b,setLocalUserMessages:ue,resolveConversationByTarget:J});const{isRefreshingHistory:$l,handleRefreshHistory:Bl}=Zo({sendDaemonCommand:e,activeConv:Pe,chats:(wo=p.find(ne=>ne.id===(Pe==null?void 0:Pe.routeId)))==null?void 0:wo.chats,updateRouteChats:I,setToasts:b,setLocalUserMessages:ue,setClearedTabs:Re}),{isCreatingChat:Kl,isRefreshingHistory:Ol,handleSwitchSession:Wl,handleNewChat:Hl,handleRefreshHistory:Fl}=Zo({sendDaemonCommand:e,activeConv:lt,chats:(jo=p.find(ne=>ne.id===(lt==null?void 0:lt.routeId)))==null?void 0:jo.chats,updateRouteChats:I,setToasts:b,setLocalUserMessages:ue,setClearedTabs:Re}),Cn=a.useCallback(async()=>{if(!(!lt||!zt||xe)){D(!0);try{const ne=lt.daemonId||lt.routeId,pe=Wt(lt),be=await e(ne,"list_saved_sessions",{agentType:pe,providerType:pe,kind:"cli",limit:50}),fe=(be==null?void 0:be.result)??be;z(Array.isArray(fe==null?void 0:fe.sessions)?fe.sessions:[])}catch(ne){console.error("Refresh saved sessions failed",ne),z([])}finally{D(!1)}}},[lt,xe,zt,e]);a.useEffect(()=>{if(!K){We.current=null;return}if(!zt){We.current=null,z([]),D(!1);return}!wr||xe||We.current!==wr&&(We.current=wr,Cn())},[Cn,K,xe,zt,wr]);const Ul=a.useCallback(async ne=>{if(!lt||!zt||!ne.providerSessionId||!ne.workspace)return;const pe=lt.daemonId||lt.routeId,be=Wt(lt);try{Y(ne.providerSessionId);const fe=await e(pe,"launch_cli",{cliType:be,dir:ne.workspace,resumeSessionId:ne.providerSessionId,initialModel:tc(ne.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Xe=(fe==null?void 0:fe.result)??fe,mt=typeof(Xe==null?void 0:Xe.sessionId)=="string"?Xe.sessionId:typeof(Xe==null?void 0:Xe.id)=="string"?Xe.id:"";mt&&c(Pt=>{const Xt=new URLSearchParams(Pt);return Xt.set("activeTab",mt),Xt},{replace:!0}),X(!1)}catch(fe){console.error("Resume saved session failed",fe)}finally{Y(null)}},[lt,zt,e,c]);Lp({urlActiveTab:L&&!jr?l:null,conversations:Ue,resolveConversationBySessionId:gt,normalizedGroupAssignments:ze,hasHydratedStoredLayout:L&&!jr?U:!0,hydrateStoredLayout:L&&!jr?$:()=>{},setGroupActiveTabIds:A,setFocusedGroup:E,setSearchParams:c,historyModalOpen:K,activeConv:Pe,isRefreshingHistory:$l,ides:p,handleRefreshHistory:Bl});const fo=a.useCallback(async(ne,pe)=>{const be=pe||he||Pe;if(!be||!st(be)&&!Qe(be))return;const fe=Wt(be),Xe=be.routeId||be.daemonId||"";try{await e(Xe,"stop_cli",{cliType:fe,targetSessionId:be.sessionId,mode:ne})}catch(mt){console.error("Stop CLI failed:",mt)}},[Pe,he,e]),zl=a.useCallback(async ne=>{const pe=ne||Pe;!pe||!st(pe)&&!Qe(pe)||(Ce(pe),le(!0))},[Pe]),Vl=a.useMemo(()=>!Pe||!st(Pe)||Qe(Pe)?null:Es(Pe),[Pe]),Gl=a.useCallback(async ne=>{if(!Pe||!st(Pe)||Qe(Pe))return;const pe=Es(Pe);if(pe===ne)return;const be=Pe.sessionId;be&&je(fe=>({...fe,[be]:ne}));try{await e(os(Pe)||Pe.routeId,"set_cli_view_mode",{targetSessionId:Pe.sessionId,cliType:Wt(Pe),mode:ne})}catch(fe){const Xe=ro(fe);be&&!Xe&&je(mt=>{const Pt={...mt};return pe===qc(p,be)?delete Pt[be]:Pt[be]=pe,Pt}),so(fe)?console.warn(Xe?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",fe instanceof Error?fe.message:String(fe)):console.error("Failed to switch CLI view mode:",fe)}},[Pe,p,e]),{versionMismatchDaemons:ql,hasRequiredVersionDaemons:po,appVersion:Yl,versionBannerDismissed:Xl,setVersionBannerDismissed:Jl,upgradingDaemons:Ql,handleBannerUpgrade:Zl}=Bp({ides:p,sendDaemonCommand:e}),ho=a.useCallback(ne=>{me(ne.tabKey),c(pe=>{const be=new URLSearchParams(pe),fe=nm(ne);return fe?be.set("activeTab",fe):be.delete("activeTab"),be},{replace:!0})},[c]),xo=a.useCallback(ne=>{Bt(ne.tabKey),ho(ne)},[ho,Bt]),ed=a.useCallback(ne=>{$e(ne.tabKey)},[$e]),bo=a.useCallback((ne,pe)=>{const be=ux(ne,pe);be&&Z(be)},[]);return t.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[t.jsx(Jm,{wsStatus:k,showReconnected:R,onReconnect:g.retryServerConnection}),t.jsx(Qm,{terminalBackend:bt,isStandalone:Je,machineLabel:rt,machineKey:ut}),(!Xl||po)&&t.jsx(cx,{daemons:ql,targetVersion:Yl,required:po,upgradingDaemons:Ql,onUpgrade:Zl,onDismiss:()=>Jl(!0)}),t.jsx(tx,{showMobileChatMode:jr,isMobile:L,activeConv:Pe,wsStatus:k,isConnected:T,onOpenHistory:ne=>{ne&&Nn(ne),X(!0)},onOpenRemote:Al,onStopCli:zl,activeCliViewMode:Vl,onSetActiveCliViewMode:Gl,mobileChatConversations:Tl,ides:p,actionLogs:oe,sendDaemonCommand:e,setLocalUserMessages:ue,setActionLogs:de,isStandalone:Je,initialDataLoaded:w,userName:g.userName,requestedMobileTabKey:Ut,onRequestedMobileTabConsumed:Hs,requestedMachineId:m,onRequestedMachineConsumed:()=>{o(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:d,onRequestedMobileSectionConsumed:()=>{o(n.pathname+n.search,{replace:!0,state:null})},containerRef:Ze,isSplitMode:G,numGroups:_,groupSizes:q,groupedConvs:ie,clearedTabs:we,focusedGroup:h,setFocusedGroup:E,moveTabToGroup:Ee,splitTabRelative:Ge,closeGroup:Te,handleResizeStart:Be,groupActiveTabIds:C,setGroupActiveTabIds:A,groupTabOrders:P,setGroupTabOrders:B,toggleHiddenTab:tt,visibleConversations:Ve,hiddenConversations:Ll,requestedDesktopTabKey:Oe,onRequestedDesktopTabConsumed:Hs,onDesktopActiveTabChange:me,onRequestScrollToBottom:bo,onHideConversation:ed,onShowHiddenConversation:xo,onShowAllHiddenConversations:Ye,scrollToBottomRequest:ge,machineEntries:De,onBrowseMachineDirectory:Rl,onSaveMachineWorkspace:Pl,onLaunchMachineIde:_l,onLaunchMachineProvider:Dl,onListMachineSavedSessions:El,notifications:Nt,notificationUnreadCount:Kt,notificationStateBySessionId:It,liveSessionInboxState:Ct,onMarkNotificationRead:V,onMarkNotificationUnread:re,onDeleteNotification:Ne,onMarkNotificationTargetRead:H}),t.jsx("style",{children:`
58
+ body { overflow: hidden; overscroll-behavior: none; }
59
+ `}),t.jsx(ix,{historyModalOpen:K,historyTargetConv:lt,ides:p,isHistoryCreatingChat:Kl,isHistoryRefreshingHistory:zt?!1:Ol,savedHistorySessions:ke,isSavedHistoryLoading:xe,isResumingSavedHistorySessionId:W,onCloseHistory:()=>X(!1),onNewHistoryChat:Hl,onSwitchHistorySession:Wl,onRefreshHistory:zt?Cn:Fl,onResumeSavedHistorySession:Ul,remoteDialogConv:Fs,remoteDialogIdeEntry:vr,connectionStates:v,actionLogs:oe,localUserMessages:ee,sendDaemonCommand:e,setLocalUserMessages:ue,setActionLogs:de,isStandalone:Je,userName:g.userName,onOpenRemoteHistory:ne=>{ne&&Nn(ne),X(!0)},onRemoteConversationChange:Nn,onCloseRemoteDialog:Ml,cliStopDialogOpen:te,cliStopTargetConv:he,onCancelCliStop:()=>{le(!1),Ce(null)},onStopCliNow:async()=>{le(!1),await fo("hard",he),Ce(null)},onSaveCliAndStop:async()=>{le(!1),await fo("save",he),Ce(null)},toasts:y,onDismissToast:ne=>b(pe=>pe.filter(be=>be.id!==ne)),onClickToast:ne=>{if(ne.targetKey){const pe=J(ne.targetKey);pe&&(E(ze.get(pe.tabKey)??0),xo(pe),bo(pe.tabKey,"toast-open"))}},showOnboarding:f,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}x(!1)}})]})}function bx({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:o}){const[i,c]=a.useState([]),[l,u]=a.useState(null),[m,d]=a.useState(null),[g,p]=a.useState(!1),[w,I]=a.useState(null),[b,f]=a.useState(!1),[x,y]=a.useState(""),k=a.useRef(null),T=a.useCallback($=>{k.current=$},[]),v=a.useCallback(($,K,X=!1)=>{c(te=>[...te.slice(-100),{timestamp:Date.now(),level:$,message:K}]),setTimeout(()=>{var te;return(te=o.current)==null?void 0:te.scrollIntoView({behavior:"smooth"})},100),X&&dt.showToast(K,$==="error"||$==="warn"?"warning":"success")},[o]),R=a.useCallback($=>{const K=$ instanceof Error?$.message:String($||"");return K.includes("P2P command timeout")||K.includes("P2P not connected")||K.includes("P2P not available")},[]),j=a.useCallback(async($,K)=>{var X;if(!e||l)return!1;u($),v("info",`Launching ${it($)}${K!=null&&K.workspace?` in ${K.workspace}`:""}...`);try{const te={ideType:$,enableCdp:!0};(X=K==null?void 0:K.workspace)!=null&&X.trim()?te.workspace=K.workspace.trim():K!=null&&K.useDefaultWorkspace&&(te.useDefaultWorkspace=!0);const le=await r(e,"launch_ide",te);return v(le!=null&&le.success?"info":"error",le!=null&&le.success?`${it($)} launched`:`Failed: ${le==null?void 0:le.error}`,!0),!!(le!=null&&le.success)}catch(te){return v("error",`Launch error: ${te.message}`,!0),!1}finally{u(null)}},[e,l,v,r]),S=a.useCallback(async $=>{if(!e)return{success:!1};const{cliType:K,dir:X,workspaceId:te,useDefaultWorkspace:le,useHome:he,argsStr:Ce,model:ke,resumeSessionId:z}=$;if(!K)return v("warn","Select a CLI or ACP provider first",!0),{success:!1};const xe=Ce?Ce.split(/\s+/).filter(Boolean):void 0,D=(X==null?void 0:X.trim())||(te?"(saved id)":le?"(default workspace)":he?"(home)":"");v("info",`Launching ${K}${D?` in ${D}`:""}${ke?` (model: ${ke})`:""}...`),d(K);try{const W={cliType:K,cliArgs:xe,initialModel:ke||void 0};X!=null&&X.trim()?W.dir=X.trim():te?W.workspaceId=te:le?W.useDefaultWorkspace=!0:he&&(W.useHome=!0),z&&(W.resumeSessionId=z);const Y=await r(e,"launch_cli",W),ae=(Y==null?void 0:Y.result)||Y;return Y!=null&&Y.success?(v("info",`${K} launched`,!0),(ae==null?void 0:ae.launchSource)==="home"?v("info","📂 Running in home directory (explicit choice)"):(ae==null?void 0:ae.launchSource)==="defaultWorkspace"&&v("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ae==null?void 0:ae.sessionId}):(v("error",`Failed: ${(Y==null?void 0:Y.error)||(ae==null?void 0:ae.error)}`,!0),(Y==null?void 0:Y.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&I({cliType:K,argsStr:Ce,model:ke}),{success:!1,sessionId:ae==null?void 0:ae.sessionId})}catch(W){return R(W)?(v("warn",`${K} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(v("error",`Launch error: ${W.message}`,!0),{success:!1})}finally{d(null)}},[e,v,R,r]),h=a.useCallback(async($,K,X,te)=>e?$?K.trim()?S({cliType:$,dir:K,argsStr:X,model:te}):(I({cliType:$,argsStr:X,model:te}),{success:!1}):(v("warn","Select a provider",!0),{success:!1}):{success:!1},[e,v,S]),E=a.useCallback(async($,K,X)=>{if(e&&window.confirm(`Stop ${$}?
60
+ This will terminate the process.`))try{const te=await r(e,"stop_cli",{cliType:$,dir:K,targetSessionId:X});te!=null&&te.success?v("info",`${$} stopped`,!0):v("error",`Stop failed: ${(te==null?void 0:te.error)||"Unknown error"}`,!0)}catch(te){v("error",`Stop failed: ${te.message}`,!0)}},[e,v,r]),C=a.useCallback(async $=>{try{await r($.daemonId,"restart_ide",{ideType:$.type}),v("info",`${it($.type)} restart initiated`,!0)}catch(K){v("error",`Restart failed: ${K.message}`,!0)}},[v,r]),A=a.useCallback(async $=>{if(window.confirm(`Stop ${it($.type)}?
61
+ This will disconnect CDP and optionally kill the process.`))try{const K=await r($.daemonId,"stop_ide",{ideType:$.type,killProcess:!0});K!=null&&K.success?v("info",`${it($.type)} stopped`,!0):v("error",`Stop failed: ${(K==null?void 0:K.error)||"Unknown error"}`,!0)}catch(K){v("error",`Stop failed: ${K.message}`,!0)}},[v,r]),P=a.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]),B=a.useCallback(async $=>{if(!e||!$.trim())return!1;p(!0);try{const K=await r(e,"workspace_add",{path:$.trim()});return K!=null&&K.success?(v("info",`Workspace added: ${$.trim()}`),!0):(v("error",(K==null?void 0:K.error)||"workspace_add failed"),!1)}catch(K){return v("error",K.message),!1}finally{p(!1)}},[e,v,r]),q=a.useCallback(async $=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){p(!0);try{const K=await r(e,"workspace_remove",{id:$});K!=null&&K.success?v("info","Workspace removed",!0):v("error",(K==null?void 0:K.error)||"workspace_remove failed",!0)}catch(K){v("error",K.message,!0)}finally{p(!1)}}},[e,v,r]),N=a.useCallback(async $=>{var K;if(e){p(!0);try{const X=await r(e,"workspace_set_default",$===null?{clear:!0}:{id:$});if(X!=null&&X.success){v("info",$?"Default workspace updated":"Default workspace cleared",!0);const te=typeof X.defaultWorkspacePath=="string"?X.defaultWorkspacePath:"";te&&((K=k.current)==null||K.call(k,te))}else v("error",(X==null?void 0:X.error)||"workspace_set_default failed",!0)}catch(X){v("error",X.message,!0)}finally{p(!1)}}},[e,v,r]),L=a.useCallback(async $=>{var X;if(!e||!$.trim())return;const K=$.trim();p(!0);try{const te=await r(e,"workspace_set_default",{path:K});te!=null&&te.success?(v("info","Default workspace set from history"),(X=k.current)==null||X.call(k,K)):v("error",(te==null?void 0:te.error)||"Could not set default (path missing on disk?)")}catch(te){v("error",te.message)}finally{p(!1)}},[e,v,r]),U=a.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:x}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:x})}catch($){v("warn",`Live nickname updated, but account sync failed: ${$.message}`)}v("info",`Nickname set to "${x||"(cleared)"}"`),f(!1)}catch($){v("error",`Failed: ${$.message}`)}},[e,x,s,v,n,r]);return{logs:i,launchingIde:l,launchingAgentType:m,workspaceBusy:g,launchPick:w,setLaunchPick:I,editingNickname:b,setEditingNickname:f,nicknameInput:x,setNicknameInput:y,addLog:v,handleLaunchIde:j,runLaunchCliCore:S,handleLaunchCli:h,handleStopCli:E,handleRestartIde:C,handleStopIde:A,handleDetectIdes:P,handleWorkspaceAdd:B,handleWorkspaceRemove:q,handleWorkspaceSetDefault:N,handleWorkspaceResumePath:L,handleSaveNickname:U,setOnDefaultWorkspaceChanged:T}}function gx({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:o,actions:i,sendDaemonCommand:c}){var C;const{workspaceBusy:l,handleWorkspaceAdd:u,handleWorkspaceRemove:m,handleWorkspaceSetDefault:d}=i,[g,p]=a.useState(!1),[w,I]=a.useState(""),[b,f]=a.useState([]),[x,y]=a.useState(!1),[k,T]=a.useState(""),v=a.useCallback(async A=>{y(!0),T("");try{const P=await vn(c,e,A);I(P.path),f(P.directories)}catch(P){T(P instanceof Error?P.message:"Could not load folder")}finally{y(!1)}},[e,c]),R=a.useCallback(()=>{p(!0);const A=[...r.map(B=>B.workspace),...n.map(B=>B.workspace),...o.map(B=>B.workspace)],P=yn(s.platform,gn(A,s.defaultWorkspacePath,(s.workspaces||[]).map(B=>B.path)));v(P)},[o,n,r,v,s.defaultWorkspacePath,s.platform,s.workspaces]),j=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,S=s.availableMem??s.freeMem??s.totalMem,h=j&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-S)/s.totalMem*100))):0,E=((C=s.loadavg)==null?void 0:C[0])||0;return t.jsxs("div",{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[t.jsx(Ir,{icon:t.jsx(Wi,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?pu(s.uptime):"Waiting…"}),t.jsx(Ir,{icon:t.jsx(Rt,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(Ir,{icon:t.jsx(Ta,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(Ir,{icon:t.jsx(Rd,{size:16}),label:"ACPs",value:`${o.length}`})]}),t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),t.jsxs("div",{className:"flex gap-6",children:[t.jsx(Ro,{value:j?Math.min(Math.round(E/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:j?`${E.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(Ro,{value:h,max:100,label:"Memory",color:"#3b82f6",detail:j?`${Rn(s.totalMem-S)} / ${Rn(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Rn(s.totalMem)} total`})]})]}),t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[t.jsx(_s,{size:14})," Workspaces"]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[t.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),t.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:l,value:s.defaultWorkspaceId||"",onChange:A=>void d(A.target.value===""?null:A.target.value),children:[t.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(A=>t.jsx("option",{value:A.id,children:A.label||A.path},A.id))]}),s.defaultWorkspacePath&&t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:s.defaultWorkspacePath,children:s.defaultWorkspacePath})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded transition-colors text-xs",disabled:l,onClick:R,children:"Select workspace…"}),t.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(s.workspaces||[]).length>0&&t.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(s.workspaces||[]).map(A=>t.jsxs("li",{className:"flex items-start gap-2 text-[11px] text-text-muted rounded-lg border border-border-subtle bg-bg-primary px-2.5 py-2",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[A.id===s.defaultWorkspaceId&&t.jsx("span",{className:"text-[10px]",children:"⭐"}),t.jsx("span",{className:"font-medium text-text-primary truncate",children:xn(A.path,A.label)})]}),t.jsx("div",{className:"font-mono truncate text-[10px]",title:A.path,children:A.path})]}),t.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void m(A.id),children:"Remove"})]},A.id))})]}),g&&t.jsx(wn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:w,directories:b,busy:x,error:k,confirmLabel:"Add workspace",onClose:()=>p(!1),onNavigate:A=>{v(A)},onConfirm:A=>{(async()=>{if(!A)return;await u(A)&&p(!1)})()}})]})}function yx(e){if(!e||typeof e!="object")return null;const s=e,r=s.result&&typeof s.result=="object"?s.result:s;return!r.settings||typeof r.settings!="object"?null:{settings:r.settings,values:r.values&&typeof r.values=="object"?r.values:{}}}function vx(e,s,r){const n=[];for(const[o,i]of Object.entries(e.settings)){const c=i;if(c.length===0)continue;const l=s.find(u=>u.type===o);n.push({type:o,displayName:(l==null?void 0:l.displayName)||o,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:c,values:e.values[o]||{}})}return n}function Yn(e){if(!e||typeof e!="object")return!1;const s=e;return(s.sourceMode==="normal"||s.sourceMode==="no-upstream")&&typeof s.disableUpstream=="boolean"&&(s.explicitProviderDir===null||typeof s.explicitProviderDir=="string")&&typeof s.userDir=="string"&&typeof s.upstreamDir=="string"&&Array.isArray(s.providerRoots)}function gi(e){if(!e||typeof e!="object")return null;if(Yn(e))return e;const s=e,r=s.result;return Yn(r)?r:Yn(s.sourceConfig)?s.sourceConfig:null}function wx(e){const s=e.trim();return s||null}const yi=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],jx=[{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 kx({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[o,i]=a.useState("config"),[c,l]=a.useState("codex-cli"),[u,m]=a.useState([]),[d,g]=a.useState(""),[p,w]=a.useState([]),[I,b]=a.useState(""),f=a.useRef(null),x=a.useRef(null),y=S=>{m(h=>h.includes(S)?h.filter(E=>E!==S):[...h,S])},k=()=>m([...yi]),T=()=>m([]);a.useEffect(()=>{var S;(S=f.current)==null||S.scrollIntoView({behavior:"smooth"})},[p]),a.useEffect(()=>()=>{x.current&&clearInterval(x.current)},[]);const v=a.useCallback(()=>{x.current&&clearInterval(x.current),x.current=setInterval(async()=>{try{const S=await r(e,"provider_auto_fix_status",{providerType:s.type});(S==null?void 0:S.running)===!1&&o==="running"&&(i("done"),w(h=>[...h,`
62
+ ✅ Auto-fix completed!`]),x.current&&clearInterval(x.current))}catch{}},3e3)},[e,s.type,r,o]),R=async()=>{if(u.length!==0){i("running"),w(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,d?`💬 Comment: ${d}`:"",""]),b("");try{const S=await r(e,"provider_auto_fix",{providerType:s.type,functions:u,agent:c,...d?{comment:d}:{}});S!=null&&S.success&&(S!=null&&S.started||S!=null&&S.running)?(w(h=>[...h,"✅ Agent started. Monitoring progress..."]),v()):(i("error"),b((S==null?void 0:S.error)||"Failed to start auto-fix"))}catch(S){i("error"),b((S==null?void 0:S.message)||"Connection failed")}}},j=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),w(S=>[...S,`
63
+ ⚠️ Auto-fix cancelled.`]),i("done"),x.current&&clearInterval(x.current)}catch{}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:S=>S.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:s.icon||"🔧"}),t.jsxs("div",{children:[t.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",s.displayName]}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),t.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[o==="config"&&t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),t.jsx("div",{className:"flex gap-2",children:jx.map(S=>t.jsxs("button",{onClick:()=>l(S.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===S.value?S.color+"66":"var(--border-subtle)",background:c===S.value?S.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===S.value?S.color:"var(--text-primary)"},children:S.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:S.desc})]},S.value))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:k,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),t.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),t.jsx("button",{onClick:T,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:yi.map(S=>t.jsxs("button",{onClick:()=>y(S),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(S)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(S)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(S)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(S)?"☑ ":"☐ ",S]},S))})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",t.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),t.jsx("textarea",{value:d,onChange:S=>g(S.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"})]})]}),(o==="running"||o==="done"||o==="error")&&t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[p.map((S,h)=>t.jsx("div",{className:S.startsWith("✅")?"text-green-400":"",style:S.startsWith("❌")||S.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:S},h)),o==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:f})]}),I&&t.jsx("div",{className:"mt-2 px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:I})]})]}),t.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[t.jsxs("div",{className:"text-[10px] text-text-muted",children:[o==="config"&&u.length>0&&`${u.length} script(s) selected`,o==="running"&&"Agent is generating...",o==="done"&&"Run `adhdev provider verify` to validate"]}),t.jsxs("div",{className:"flex gap-2",children:[o==="config"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:R,disabled:u.length===0,className:"machine-btn",style:{background:u.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:u.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:u.length>0?"#a78bfa":void 0,opacity:u.length===0?.4:1},children:"🚀 Start Fix"})]}),o==="running"&&t.jsx("button",{onClick:j,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(o==="done"||o==="error")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{i("config"),w([]),b("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Sx({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:o}){var v;const i=s.filter(R=>R.category==="ide"),[c,l]=a.useState(((v=i[0])==null?void 0:v.type)||""),[u,m]=a.useState(""),[d,g]=a.useState(""),[p,w]=a.useState(!1),[I,b]=a.useState(""),[f,x]=a.useState(!1),y=R=>{const j=R.toLowerCase().replace(/[^a-z0-9-]/g,"");m(j),(!d||d===k(u))&&g(k(j))},k=R=>R.split("-").map(j=>j.charAt(0).toUpperCase()+j.slice(1)).join(" "),T=async()=>{if(!(!u||!d||!c)){w(!0),b("");try{const R=await r(e,"provider_clone",{type:u,name:d,category:"ide",location:"user",cloneFrom:c});R!=null&&R.success||R!=null&&R.created?(x(!0),o==null||o(u)):b((R==null?void 0:R.error)||"Failed to create provider")}catch(R){b((R==null?void 0:R.message)||"Connection failed")}w(!1)}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:R=>R.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[t.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:f?t.jsxs("div",{className:"text-center py-6",children:[t.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),t.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[t.jsx("code",{className:"text-violet-400",children:u})," has been created at ",t.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",u,"/"]})]}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",t.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",u]})," or use Auto-Fix to implement scripts."]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(R=>t.jsxs("button",{onClick:()=>l(R.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===R.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===R.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:R.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===R.type?"#a78bfa":"var(--text-secondary)"},children:R.displayName})]},R.type))})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),t.jsx("input",{value:u,onChange:R=>y(R.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),t.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",t.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",u||"...","/"]})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),t.jsx("input",{value:d,onChange:R=>g(R.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"})]}),I&&t.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:I})]})}),t.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:f?t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:T,disabled:!u||!d||p,className:"machine-btn",style:{background:u&&d?"rgba(34,197,94,0.12)":void 0,borderColor:u&&d?"rgba(34,197,94,0.3)":void 0,color:u&&d?"#86efac":void 0,opacity:!u||!d||p?.4:1},children:p?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Nx({machineId:e,providers:s,sendDaemonCommand:r}){var C;const[n,o]=a.useState([]),[i,c]=a.useState(!1),[l,u]=a.useState(null),[m,d]=a.useState("all"),[g,p]=a.useState(null),[w,I]=a.useState(!1),[b,f]=a.useState(null),[x,y]=a.useState("normal"),[k,T]=a.useState(""),[v,R]=a.useState(!1),j=a.useCallback(async()=>{if(e)try{const A=await r(e,"get_provider_source_config",{}),P=gi(A);P&&(f(P),y(P.sourceMode),T(P.explicitProviderDir||""))}catch{}},[e,r]),S=a.useCallback(async()=>{if(e){c(!0);try{const A=await r(e,"get_provider_settings",{}),P=yx(A);if(P){const B=vx(P,s);B.sort((q,N)=>q.category.localeCompare(N.category)||q.displayName.localeCompare(N.displayName)),o(B)}}catch{}c(!1)}},[e,s,r]);a.useEffect(()=>{n.length===0&&S(),b||j()},[]);const h=async(A,P,B)=>{u(`${A}.${P}`),o(q=>q.map(N=>N.type===A?{...N,values:{...N.values,[P]:B}}:N));try{const q=await r(e,"set_provider_setting",{providerType:A,key:P,value:B});q!=null&&q.success||S()}catch{S()}u(null)},E=async()=>{R(!0);try{const A=await r(e,"set_provider_source_config",{providerSourceMode:x,providerDir:wx(k)}),P=gi(A);P?(f(P),y(P.sourceMode),T(P.explicitProviderDir||"")):await j(),await S()}catch{await j()}R(!1)};return t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-4",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(A=>t.jsx("button",{onClick:()=>d(A),className:`machine-btn text-[10px] px-2 py-0.5 ${m===A?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:A.toUpperCase()},A))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>I(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),t.jsx("button",{onClick:S,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Existing running sessions may need restart."})]}),t.jsx("button",{onClick:j,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),t.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),t.jsxs("select",{value:x,onChange:A=>y(A.target.value),className:"machine-input text-[11px]",children:[t.jsx("option",{value:"normal",children:"normal"}),t.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),t.jsx("input",{type:"text",value:k,onChange:A=>T(A.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void E(),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"})]}),t.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(b==null?void 0:b.userDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(b==null?void 0:b.upstreamDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((C=b==null?void 0:b.providerRoots)==null?void 0:C.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(A=>A.category===m).length>1&&(()=>{const A=n.filter(N=>N.category===m),P=new Map;for(const N of A)for(const L of N.schema){if(L.type!=="boolean")continue;const U=P.get(L.key),$=!!(N.values[L.key]??L.default);U?(U.onCount+=$?1:0,U.total+=1):P.set(L.key,{label:L.label||L.key,onCount:$?1:0,total:1})}const B=[...P.entries()].filter(([,N])=>N.total===A.length);if(B.length===0)return null;const q=async(N,L)=>{for(const U of A)await h(U.type,N,L)};return t.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[t.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",m.toUpperCase()," providers (",A.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:B.map(([N,L])=>{const U=L.onCount===L.total,$=L.onCount===0;return t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:"text-text-secondary font-medium",children:L.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",L.onCount,"/",L.total,")"]}),t.jsx("button",{onClick:()=>void q(N,!0),disabled:U,className:`machine-btn text-[9px] px-1.5 py-px ${U?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void q(N,!1),disabled:$,className:`machine-btn text-[9px] px-1.5 py-px ${$?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},N)})})]})})(),i&&n.length===0?t.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):t.jsx("div",{className:"flex flex-col gap-2",children:n.filter(A=>m==="all"||A.category===m).map(A=>t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[t.jsx("span",{className:"text-lg",children:A.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:A.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:A.category==="acp"?"rgba(139,92,246,0.08)":A.category==="cli"?"rgba(59,130,246,0.08)":A.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:A.category==="acp"?"#a78bfa":A.category==="cli"?"#60a5fa":A.category==="ide"?"#86efac":"var(--status-warning)"},children:A.category}),A.category==="ide"&&t.jsx("button",{onClick:()=>p(s.find(P=>P.type===A.type)||{type:A.type,name:A.displayName,displayName:A.displayName,icon:A.icon,category:A.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"})]}),t.jsx("div",{className:"flex flex-col gap-2",children:A.schema.map(P=>t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[P.label||P.key,l===`${A.type}.${P.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),P.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:P.description})]}),t.jsx("div",{className:"shrink-0",children:P.type==="boolean"?t.jsx("button",{onClick:()=>h(A.type,P.key,!(A.values[P.key]??P.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:A.values[P.key]??P.default?"#8b5cf6":"var(--border-subtle)"},children:t.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:A.values[P.key]??P.default?21:3}})}):P.type==="number"?t.jsx("input",{type:"number",value:Number(A.values[P.key]??P.default??0)||0,min:P.min,max:P.max,onChange:B=>{const q=parseInt(B.target.value)||0;P.min!==void 0&&q<P.min||P.max!==void 0&&q>P.max||h(A.type,P.key,q)},className:"machine-input w-20 text-center text-[11px]"}):P.type==="select"&&P.options?t.jsx("select",{value:String(A.values[P.key]??P.default??""),onChange:B=>h(A.type,P.key,B.target.value),className:"machine-input text-[11px]",children:P.options.map(B=>t.jsx("option",{value:B,children:B},B))}):t.jsx("input",{type:"text",value:String(A.values[P.key]??P.default??""),onBlur:B=>h(A.type,P.key,B.target.value),className:"machine-input w-[120px] text-[11px]"})})]},P.key))})]},A.type))}),g&&t.jsx(kx,{machineId:e,provider:g,sendDaemonCommand:r,onClose:()=>p(null)}),w&&t.jsx(Sx,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>I(!1),onCreated:()=>{I(!1),S()}})]})}const Cx=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Ix({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function Ax(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function Mx(e){return e.trim().toLowerCase()}function kn(e,s){const r=Mx(s);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function uo(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function ur(e,s=220){const r=uo(e);return r?r.length>s?`${r.slice(0,s)}…`:r:""}function Tx(e){const s=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(s))return{kind:s.length>0?"structured":"empty",entries:s.map(r=>{const n=r;return{timestamp:Number(n.ts)||0,level:n.level||"info",message:`[${String(n.category||"daemon")}] ${String(n.message||"")}`.trim()}}),rawText:""};if(typeof s=="string"){const r=s.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function wl(e,s){return e.filter(r=>kn([r.level,r.message],s))}function Lx(e,s){return e.split(`
64
+ `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>kn([r],s))}function jl(e,s){return e.filter(r=>kn([r.level,r.category,r.stage,r.interactionId,uo(r.payload)],s))}function kl(e,s){return e.filter(r=>kn([r.kind,r.topic,r.interactionId,uo(r.payload)],s))}function vi(e){return e==="warn"||e==="error"}function Rx({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){return{all:e.length+s.length+r.length+n.length,info:e.filter(o=>o.level!=="debug").length+r.filter(o=>o.level!=="debug").length+n.length,issues:e.filter(o=>vi(o.level)).length+r.filter(o=>vi(o.level)).length}}function Px({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){const o=[];return e.length>0?o.push(["[daemon logs]",...e.map(i=>`${new Date(i.timestamp).toISOString()} ${i.level.toUpperCase()} ${i.message}`)].join(`
65
+ `)):s.length>0&&o.push(["[daemon logs]",...s].join(`
66
+ `)),r.length>0&&o.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${ur(i.payload,500)}`.trim())].join(`
67
+ `)),n.length>0&&o.push(["[browser events]",...n.map(i=>`${new Date(i.ts).toISOString()} ${i.kind}${i.topic?` topic=${i.topic}`:""} ${ur(i.payload,500)}`.trim())].join(`
68
+ `)),o.join(`
69
+
70
+ `)}function _x({daemonLogs:e,trace:s,webEvents:r,daemonLogKind:n,daemonFetchError:o,traceFetchError:i,searchQuery:c}){const l=wl(e,c),u=jl(s,c),m=kl(r,c),d=l.filter(w=>w.level==="warn"||w.level==="error").map(w=>({source:"daemon",level:w.level,timestamp:w.timestamp,label:"daemon",detail:w.message})),g=u.filter(w=>w.level==="warn"||w.level==="error").map(w=>({source:"trace",level:w.level,timestamp:w.ts,label:`${w.category}.${w.stage}`,detail:ur(w.payload,320)||`${w.category}.${w.stage}`})),p=[...d,...g].sort((w,I)=>I.timestamp-w.timestamp);return{daemonCount:l.length,traceCount:u.length,webCount:m.length,issueCount:p.length,latestIssue:p[0]||null,hasAnyData:n==="text"||l.length>0||u.length>0||m.length>0,hasBlockingError:!!(o||i)}}function wi(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function ji(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 Xn(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 Dx({machineId:e,sendDaemonCommand:s}){var we,Re;const[r,n]=a.useState([]),[o,i]=a.useState("empty"),[c,l]=a.useState(""),[u,m]=a.useState([]),[d,g]=a.useState([]),[p,w]=a.useState(0),[I,b]=a.useState(0),[f,x]=a.useState(null),[y,k]=a.useState(!0),[T,v]=a.useState("info"),[R,j]=a.useState("info"),[S,h]=a.useState("all"),[E,C]=a.useState(""),[A,P]=a.useState(!0),[B,q]=a.useState(!0),[N,L]=a.useState(""),[U,$]=a.useState(""),[K,X]=a.useState(0),[te,le]=a.useState({daemon:!0,trace:!1,web:!1}),he=a.useRef(null),Ce=a.useRef(!1),ke=a.useMemo(()=>Ax(u,S),[u,S]),z=a.useMemo(()=>wl(r,E),[r,E]),xe=a.useMemo(()=>Lx(c,E),[c,E]),D=a.useMemo(()=>jl(ke,E),[ke,E]),W=a.useMemo(()=>kl(d,E),[d,E]),Y=a.useMemo(()=>R==="issues"?z.filter(M=>M.level==="warn"||M.level==="error"):R==="info"?z.filter(M=>M.level!=="debug"):z,[z,R]),ae=a.useMemo(()=>R==="all"?xe:[],[xe,R]),ce=a.useMemo(()=>R==="issues"?D.filter(M=>M.level==="warn"||M.level==="error"):R==="info"?D.filter(M=>M.level!=="debug"):D,[D,R]),Se=a.useMemo(()=>R==="issues"?[]:W,[W,R]),oe=a.useMemo(()=>Rx({daemonLogs:z,daemonRawLines:xe,trace:D,webEvents:W}),[z,xe,D,W]),de=a.useMemo(()=>_x({daemonLogs:r,trace:ke,webEvents:d,daemonLogKind:o,daemonFetchError:N,traceFetchError:U,searchQuery:E}),[N,o,r,ke,E,U,d]),ee=a.useCallback(async()=>{if(!e)return;const[M,me]=await Promise.allSettled([s(e,"get_logs",{count:200,minLevel:T,since:p}),s(e,"get_debug_trace",Ix({count:120,since:I,category:S}))]);if(M.status==="fulfilled"){const ge=M.value,Z=(ge==null?void 0:ge.result)||ge,ye=Tx(Z);if(P(!1),L((ge==null?void 0:ge.success)===!1?String((ge==null?void 0:ge.error)||"Could not load daemon logs"):""),i(ye.kind),l(ye.rawText),ye.entries.length>0){n(We=>(p>0?[...We,...ye.entries]:ye.entries).slice(-300));const Ae=ye.entries.reduce((We,De)=>Math.max(We,Number(De.timestamp||0)),p);Ae>p&&w(Ae)}else ye.kind!=="structured"&&p===0&&n([])}else P(!1),L(M.reason instanceof Error?M.reason.message:"Could not load daemon logs");if(me.status==="fulfilled"){const ge=me.value,Z=(ge==null?void 0:ge.result)||ge;if((ge==null?void 0:ge.success)===!1)$(String((ge==null?void 0:ge.error)||"Could not load daemon trace"));else if(Array.isArray(Z==null?void 0:Z.trace)){$(""),m(Z.trace.slice(-120));const ye=Z.trace.reduce((Ae,We)=>Math.max(Ae,Number(We.ts||0)),I);ye>I&&b(ye)}else $(""),m([]);q(!1)}else q(!1),$(me.reason instanceof Error?me.reason.message:"Could not load daemon trace");g(Ps.list({limit:120})),x(Date.now())},[p,I,T,e,s,S]);a.useEffect(()=>{if(!e||(ee(),!y))return;const M=setInterval(()=>{ee()},3e3);return()=>clearInterval(M)},[y,ee,e,K]),a.useEffect(()=>{if(y&&(Y.length>0||ae.length>0||ce.length>0||Se.length>0)){const M=Ce.current?"smooth":"instant";setTimeout(()=>{var me;(me=he.current)==null||me.scrollIntoView({behavior:M}),Ce.current=!0},50)}},[Y.length,ae.length,ce.length,Se.length,y]),a.useEffect(()=>{m([]),b(0),q(!0)},[S]);const ue=((we=de.latestIssue)==null?void 0:we.level)==="error"?"danger":((Re=de.latestIssue)==null?void 0:Re.level)==="warn"?"warning":"good",se=N||U?"danger":y?"good":"neutral",je=a.useCallback(async()=>{var me;const M=Px({daemonLogs:Y,daemonRawLines:ae,trace:ce,webEvents:Se});if(!M.trim()){dt.showToast("복사할 visible logs가 없습니다.","info");return}try{await((me=navigator.clipboard)==null?void 0:me.writeText(M)),dt.showToast("Visible logs를 클립보드에 복사했습니다.","success")}catch(ge){dt.showToast(ge instanceof Error?ge.message:"Could not copy visible logs","warning")}},[Y,ae,ce,Se]);return t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"Level"}),["debug","info","warn","error"].map(M=>t.jsx("button",{onClick:()=>{v(M),n([]),l(""),i("empty"),w(0),P(!0)},className:`machine-btn text-[10px] px-2 py-0.5 ${T===M?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:M.toUpperCase()},M)),t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider ml-3 mr-1",children:"Trace"}),Cx.map(M=>t.jsx("button",{onClick:()=>h(M.value),className:`machine-btn text-[10px] px-2 py-0.5 ${S===M.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:M.label},M.value))]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${oe.info})`},{id:"issues",label:`Issues (${oe.issues})`},{id:"all",label:`All (${oe.all})`}].map(M=>t.jsx("button",{type:"button",onClick:()=>j(M.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${R===M.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:M.label},M.id))}),t.jsx("input",{value:E,onChange:M=>C(M.target.value),placeholder:"Search visible logs, trace, events…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"}),t.jsx("button",{onClick:()=>{je()},className:"machine-btn",children:"Copy visible"}),t.jsx("button",{onClick:()=>k(M=>!M),className:`machine-btn ${y?"text-green-500 border-green-500/30":""}`,children:y?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>X(M=>M+1),className:"machine-btn",children:"↻ Refresh"}),t.jsx("button",{onClick:()=>{n([]),l(""),i("empty"),m([]),g([]),w(0),b(0),x(null),L(""),$(""),P(!0),q(!0),Ps.clear()},className:"machine-btn",children:"Clear"})]})]}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[t.jsxs("div",{className:`rounded-xl border p-3 ${Xn(de.issueCount>0?"warning":"good")}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Visible signals"}),t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:["daemon ",Y.length+ae.length," · trace ",ce.length," · web ",Se.length]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:E.trim()?`Filtered by “${E.trim()}”`:"Showing the latest buffered entries"})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${Xn(ue)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Attention needed"}),de.latestIssue?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[de.latestIssue.source," · ",de.latestIssue.label]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:de.latestIssue.detail}),t.jsxs("div",{className:"text-[10px] text-text-muted mt-2",children:[de.issueCount," warn/error signal(s) · ",wi(de.latestIssue.timestamp)]})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No recent warn/error signal"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use search or lower the log level if you need more context."})]})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${Xn(se)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Fetch status"}),t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:N||U?"Needs attention":y?"Live polling every 3s":"Paused"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",wi(f)]}),(N||U)&&t.jsxs("div",{className:"text-[11px] text-red-300 mt-2 space-y-1",children:[N&&t.jsxs("div",{children:["Daemon logs: ",N]}),U&&t.jsxs("div",{children:["Daemon trace: ",U]})]})]})]}),t.jsxs("div",{className:"grid gap-3",children:[t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>le(M=>({...M,daemon:!M.daemon})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:o==="text"?`${ae.length} visible raw line(s) from file fallback`:`${Y.length} visible structured line(s)`})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:te.daemon?"Hide":"Show"})]}),te.daemon&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[A&&!de.hasAnyData&&!N&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!A&&N&&o==="empty"&&t.jsx("div",{className:"p-6 text-center text-red-300",children:N}),!A&&o==="empty"&&!N&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),o==="text"&&ae.length===0&&c&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:R==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),o==="structured"&&Y.length===0&&r.length>0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),o==="text"&&ae.map((M,me)=>t.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:M},`raw-${me}`)),o!=="text"&&Y.map((M,me)=>t.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${ji(M.level)}`,children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(M.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:M.level==="error"?"ERR":M.level==="warn"?"WRN":M.level==="debug"?"DBG":"INF"}),t.jsx("span",{className:"break-words",children:M.message})]},`log-${me}`))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>le(M=>({...M,trace:!M.trace})),children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",S==="session_host"?" · session_host only":""]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[ce.length," visible trace event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:te.trace?"Hide":"Show"})]}),te.trace&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[B&&ce.length===0&&!U&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!B&&U&&ce.length===0&&t.jsx("div",{className:"p-6 text-center text-red-300",children:U}),!B&&ce.length===0&&!U&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:E.trim()?"No trace entries match the current search.":S==="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."}),ce.map(M=>t.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${ji(M.level)}`,children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(M.ts).toLocaleTimeString()}),t.jsx("span",{children:M.level.toUpperCase()}),t.jsxs("span",{children:[M.category,".",M.stage]}),M.interactionId&&t.jsxs("span",{children:["ix=",M.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:ur(M.payload,360)||"No payload"})]},M.id))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>le(M=>({...M,web:!M.web})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[Se.length," visible browser event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:te.web?"Hide":"Show"})]}),te.web&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[Se.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:E.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),Se.map(M=>t.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(M.ts).toLocaleTimeString()}),t.jsx("span",{children:M.kind}),M.topic&&t.jsxs("span",{children:["topic=",M.topic]}),M.interactionId&&t.jsxs("span",{children:["ix=",M.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:ur(M.payload,360)||"No payload"})]},M.id))]})]})]}),t.jsx("div",{ref:he})]})}function Ex(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 Sl(e){const s=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return s?s==="auto_resumed"?"restored after restart":s==="resume_failed"?"restore failed":s==="host_restart_interrupted"?"host restart interrupted":s==="orphan_snapshot"?"snapshot recovered":s.replace(/_/g," "):null}function $x(e){var o;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=Sl((i==null?void 0:i.meta)||void 0),u=((o=i==null?void 0:i.meta)==null?void 0:o.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?s.push(i):(c==="stopped"||c==="failed")&&(u||l)?r.push(i):n.push(i)}return{liveRuntimes:s,recoverySnapshots:r,inactiveRecords:n}}function Bx(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Jn(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 Qn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Zn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function ki(e){if(!e)return"unknown";const s=Date.now()-e,r=Math.max(0,Math.round(s/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const o=Math.round(n/60);return o<48?`${o}h ago`:`${Math.round(o/24)}d ago`}function Kx(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Ox(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 Wx(e){var r;const s=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const o=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!o)continue;const i=`${n.providerType}::${n.workspace}::${o}`;s.set(i,(s.get(i)||0)+1)}return Array.from(s.values()).filter(n=>n>1).length}function Hx({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,o]=a.useState(""),[i,c]=a.useState(null),[l,u]=a.useState(!1),m=ep(e,{enabled:!!e,includeSessions:!0,limit:Oo,intervalMs:gm}),d=m.diagnostics,g=m.loading,p=m.applyDiagnostics,w=a.useMemo(()=>Ex({diagnostics:d,loading:g,refreshing:l,error:n}),[d,g,l,n]),I=a.useMemo(()=>new Map(s.map(C=>[C.sessionId||C.id,C])),[s]),b=a.useCallback(async()=>{if(e){u(!0);try{const C=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Oo}),A=Qn(C);if(!(A!=null&&A.success))throw new Error((A==null?void 0:A.error)||"Could not load hosted runtime diagnostics");p(A.diagnostics||A.result||null),o("")}catch(C){const A=C instanceof Error?C.message:"Could not load hosted runtime diagnostics";o(A)}finally{u(!1)}}},[p,e,r]);a.useEffect(()=>{!e||d||g||l||b()},[d,g,e,b,l]);const f=a.useCallback(async(C,A)=>{const P=`${C}:${A.sessionId}`;if(!(C==="session_host_stop_session"&&!window.confirm(`Stop ${A.displayName}?
71
+ This will terminate the hosted runtime.`))){c(P);try{const B=await r(e,C,{sessionId:A.sessionId}),q=Qn(B);if(!(q!=null&&q.success))throw new Error((q==null?void 0:q.error)||"Session host action failed");const N=C==="session_host_resume_session"?"resumed":C==="session_host_restart_session"?"restarted":"stopped";dt.showToast(`Session host ${N}: ${A.displayName}`,"success"),await b()}catch(B){const q=B instanceof Error?B.message:"Session host action failed";dt.showToast(q,"warning"),o(q)}finally{c(B=>B===P?null:B)}}},[e,b,r]),x=a.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
72
+ 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 A=await r(e,"session_host_prune_duplicate_sessions",{}),P=Qn(A);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const B=P.result||{},q=Array.isArray(B.prunedSessionIds)?B.prunedSessionIds.length:0,N=typeof B.duplicateGroupCount=="number"?B.duplicateGroupCount:0;dt.showToast(`Pruned ${q} duplicate runtime(s) across ${N} group(s)`,"success"),await b()}catch(A){const P=A instanceof Error?A.message:"Duplicate prune failed";dt.showToast(P,"warning"),o(P)}finally{c(A=>A==="session_host_prune_duplicate_sessions"?null:A)}}},[e,b,r]),y=a.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((C,A)=>(A.lastActivityAt||0)-(C.lastActivityAt||0)),[d==null?void 0:d.sessions]),k=a.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:$x(y),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,y]),T=k.liveRuntimes,v=k.recoverySnapshots,R=k.inactiveRecords,j=a.useMemo(()=>Wx(T),[T]),S=a.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),h=a.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(C=>C.level==="warn"||C.level==="error")||null,[d==null?void 0:d.recentLogs]),E=(C,A)=>{var X;const P=i===`session_host_resume_session:${C.sessionId}`,B=i===`session_host_restart_session:${C.sessionId}`,q=i===`session_host_stop_session:${C.sessionId}`,N=Sl(C.meta),L=I.get(C.sessionId),U=C.attachedClients.length===1?"1 client":`${C.attachedClients.length} clients`,$=A==="recovery"?"Recover":"Resume",K=Bx(A);return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:C.displayName||(L==null?void 0:L.cliName)||C.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Ox(C.lifecycle)}`,children:C.lifecycle}),N&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:N})]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:"text-text-primary/90",children:C.workspaceLabel||(L==null?void 0:L.runtimeWorkspaceLabel)||C.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:C.runtimeKey}),C.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",C.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((X=C.writeOwner)==null?void 0:X.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Kx(C.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(Ei,{size:11})," ",U]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",ki(C.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",K]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[A==="recovery"&&(C.lifecycle==="interrupted"||C.lifecycle==="failed"||C.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{f("session_host_resume_session",C)},children:P?`${$}ing…`:$}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{f("session_host_restart_session",C)},children:B?"Restarting…":"Restart"}),A==="live"&&(C.lifecycle==="running"||C.lifecycle==="starting"||C.lifecycle==="interrupted")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{f("session_host_stop_session",C)},children:q?"Stopping…":"Stop"})]})]})},C.sessionId)};return t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[t.jsx(ws,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:af()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{x()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${j})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${w.toneClass}`,children:w.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{b()},disabled:g||l,children:[t.jsx(fr,{size:13}),g||l?"Refreshing…":"Refresh"]})]})]}),n&&!d&&t.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(or,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),d&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.runtimeCount})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:v.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.recentRequests.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),t.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:ki(d.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Zn(d.hostStartedAt)})]})]}),h&&t.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[t.jsx(or,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:h.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Zn(h.timestamp),h.sessionId?` · ${h.sessionId}`:""]})]}),t.jsxs("div",{className:"mb-4 space-y-4",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(Ta,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Jn("live")}),T.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:T.map(C=>E(C,"live"))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(ws,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Jn("recovery")}),v.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):t.jsx("div",{className:"space-y-2",children:v.map(C=>E(C,"recovery"))})]}),R.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Jn("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:R.map(C=>E(C,"inactive"))})]})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),S.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:S.map(C=>{var P;const A=y.find(B=>B.sessionId===C.sessionId);return t.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary font-medium",children:(A==null?void 0:A.displayName)||((P=I.get(C.sessionId))==null?void 0:P.cliName)||C.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[C.action,C.lifecycle?` · ${C.lifecycle}`:"",C.detail?` · ${C.detail}`:"",C.error?` · ${C.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${C.success===!1?"text-red-300":"text-text-secondary"}`,children:Zn(C.timestamp)})]},`${C.sessionId}:${C.timestamp}:${C.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Fx({machine:e,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick:o}=r;return t.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:t.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[t.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),t.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),t.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?t.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>t.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{o(null),n({cliType:s.cliType,workspaceId:i.id,argsStr:s.argsStr,model:s.model})},children:[t.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{o(null),n({cliType:s.cliType,useDefaultWorkspace:!0,argsStr:s.argsStr,model:s.model})},children:"Default workspace"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),n({cliType:s.cliType,useHome:!0,argsStr:s.argsStr,model:s.model})},children:"Home directory"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})}function ea({icon:e,children:s}){return t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,t.jsx("span",{children:s})]})}function ta({children:e,className:s=""}){return t.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${s}`,children:e})}function Ux({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:o,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),d=tr(e,"0.8.100");return t.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[l.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ea,{icon:t.jsx(es,{size:13}),children:"Current Chats"}),t.jsx(ta,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(g=>{const p=ma(g);return t.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(g),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:ct(g)}),p>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:pn(p)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ks(g)})]},g.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ea,{icon:t.jsx(Wi,{size:13}),children:"Recent Launches"}),t.jsx(ta,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(g=>{const{metaText:p,updatedLabel:w}=nl(g);return t.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(g),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:g.label}),w&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:w})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:p})]},g.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ea,{icon:t.jsx(or,{size:13}),children:"Daemon Update"}),t.jsx(ta,{className:"border-amber-500/20 bg-amber-500/5",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:d?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:d?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),t.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:o,children:[t.jsx(fr,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function zx(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const Vx={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 Fr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function sa({category:e,machine:s,machineId:r,providers:n,managedEntries:o,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:m}){const d=Os(),{handleLaunchIde:g,handleStopCli:p,handleRestartIde:w,handleStopIde:I,handleDetectIdes:b,launchingIde:f,launchingAgentType:x,addLog:y}=c,[k,T]=a.useState(null),v=a.useCallback(_=>{_&&d(ns(_))},[d]),R=Vx[e],j=e==="ide",S=e==="acp",h=a.useMemo(()=>n.filter(_=>_.category===e&&(e==="ide"||_.installed!==!1)),[e,n]),E=a.useMemo(()=>new Map(h.map(_=>[_.type,_.displayName||_.type])),[h]),[C,A]=a.useState(""),[P,B]=a.useState(""),[q,N]=a.useState([]),[L,U]=a.useState(""),[$,K]=a.useState(""),[X,te]=a.useState([]),[le,he]=a.useState(!1),[Ce,ke]=a.useState(!1),[z,xe]=a.useState(""),[D,W]=a.useState(!1),[Y,ae]=a.useState(()=>yt()),[ce,Se]=a.useState(null),[oe,de]=a.useState(m?"__custom__":u||s.defaultWorkspaceId||""),[ee,ue]=a.useState(m||""),[se,je]=a.useState([]),[we,Re]=a.useState(!1),[M,me]=a.useState(""),[ge,Z]=a.useState([]),[ye,Ae]=a.useState(!1),[We,De]=a.useState(""),Fe=a.useRef(null),[Je,bt]=a.useState(null),rt=a.useRef("__home__"),[ut,ht]=a.useState("__home__"),[kt,ft]=a.useState(!1),nt=a.useRef(0),Me=se.filter(_=>!o.some(G=>G.type===_&&wt(G.status)!=="stopped")),Ye=a.useRef({});a.useEffect(()=>{s.defaultWorkspaceId&&!oe&&de(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),a.useEffect(()=>{if(m){de("__custom__"),ue(m);return}u&&(de(u),ue(""))},[u,m]),a.useEffect(()=>{j||C&&(h.some(_=>_.type===C)||(A(""),K("")))},[h,j,C]);const Ue=(()=>{if(oe==="__custom__")return ee.trim();if(!oe)return"";const _=(s.workspaces||[]).find(G=>G.id===oe);return(_==null?void 0:_.path)||""})(),Ve=a.useCallback(_=>{const G=Ye.current[_];G&&(clearTimeout(G),delete Ye.current[_]),je(ie=>ie.includes(_)?ie.filter(Ee=>Ee!==_):ie)},[]),St=a.useRef(new Set),gt=a.useCallback(async _=>{if(l){Ae(!0),De("");try{const G=await vn(l,r,_);me(G.path),ue(G.path),Z(G.directories)}catch(G){De(G instanceof Error?G.message:"Could not load folder")}finally{Ae(!1)}}},[r,l]),J=a.useCallback(()=>{if(!l)return;de("__custom__"),Re(!0);const _=o.map(ie=>ie.workspace),G=yn(s.platform,gn(ee.trim(),Ue,m,_,s.defaultWorkspacePath,(s.workspaces||[]).map(ie=>ie.path)));gt(G)},[ee,m,gt,s.defaultWorkspacePath,s.platform,s.workspaces,o,Ue,l]),_e=a.useCallback(_=>{const G=String(_.workspace||"").trim();if(!G)return;const ie=(s.workspaces||[]).find(Ee=>Fr(Ee.path)===Fr(G));if(ie){de(ie.id),ue("");return}de("__custom__"),ue(G)},[s.workspaces]),$e=a.useCallback(_=>{const G=String(_.workspace||"").trim();if(!G)return{workspaceId:null,workspacePath:"",useHome:!0};const ie=(s.workspaces||[]).find(Ee=>Fr(Ee.path)===Fr(G));return ie?{workspaceId:ie.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:G,useHome:!1}},[s.workspaces]),tt=a.useCallback(async _=>{if(!l||!_||e!=="cli"){te([]),he(!1),ke(!1),xe("");return}const G=nt.current+1;nt.current=G,he(!0),xe("");try{const ie=await l(r,"list_saved_sessions",{providerType:_,kind:"cli",limit:30});if(nt.current!==G)return;const Ee=(ie==null?void 0:ie.result)??ie;te(Array.isArray(Ee==null?void 0:Ee.sessions)?Ee.sessions:[])}catch(ie){if(nt.current!==G)return;te([]),xe(ie instanceof Error?ie.message:"Could not load saved sessions")}finally{nt.current===G&&(he(!1),ke(!0))}},[e,r,l]),Bt=a.useMemo(()=>{if(e!=="cli"||!C)return null;const _=E.get(C)||C;return{routeId:r,daemonId:r,providerSessionId:$||void 0,transport:"pty",mode:"chat",agentName:_,agentType:C,status:"idle",title:_,messages:[],ideType:C,workspaceName:Ue,displayPrimary:_,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${C}`}},[e,r,E,Ue,$,C]),Ct=a.useCallback(_=>{if(e==="ide"||!_){N([]);return}N(bl(r,_))},[e,r]);a.useEffect(()=>{nt.current+=1,K(""),Ct(C),ke(!1),te([]),xe(""),he(!1)},[e,Ct,tt,C]);const Nt=a.useMemo(()=>X.find(_=>_.providerSessionId===$)||null,[X,$]);a.useEffect(()=>{if(!$)return;const _=X.find(G=>G.providerSessionId===$);_!=null&&_.canResume||K("")},[X,$]);const Kt=a.useCallback((_,G)=>{Fe.current=G,rt.current=_.selectedWorkspaceKey||"__home__",ht(_.selectedWorkspaceKey||"__home__"),bt(_)},[]),It=a.useCallback(()=>{Fe.current&&(ft(!0),Fe.current().finally(()=>{Fe.current=null,ft(!1),bt(null)}))},[]),At=a.useCallback(_=>{if(!_)return;je(ie=>ie.includes(_)?ie:[...ie,_]);const G=Ye.current[_];G&&clearTimeout(G),Ye.current[_]=setTimeout(()=>{je(ie=>ie.includes(_)?ie.filter(Ee=>Ee!==_):ie),delete Ye.current[_]},2e4)},[]);a.useEffect(()=>{for(const G of o)wt(G.status)!=="stopped"&&(se.includes(G.type)&&!St.current.has(G.type)&&(St.current.add(G.type),y("info",`${E.get(G.type)||G.type} launched`,!0)),Ve(G.type));const _=new Set(o.filter(G=>wt(G.status)!=="stopped").map(G=>G.type));St.current.forEach(G=>{!se.includes(G)&&!_.has(G)&&St.current.delete(G)})},[y,Ve,o,se,E]),a.useEffect(()=>()=>{Object.values(Ye.current).forEach(clearTimeout),Ye.current={}},[]);const[O,H]=a.useState({}),[F,V]=a.useState(null);a.useEffect(()=>{if(!j||!r||!l)return;(async()=>{try{const G=await l(r,"get_ide_extensions",{}),ie=(G==null?void 0:G.result)||G;ie!=null&&ie.success&&(ie!=null&&ie.ideExtensions)&&H(ie.ideExtensions)}catch{}})()},[j,r,l]);const re=_=>j?it(_.type):e==="cli"?_.cliName:_.acpName,Ne=j?s.detectedIdes||[]:[],Ie=a.useCallback(async _=>{const G=(_==null?void 0:_.type)||C,ie=(_==null?void 0:_.workspacePath)??Ue;if(j){await g(G,ie?{workspace:ie}:void 0)&&At(G);return}const Ee=await c.runLaunchCliCore({cliType:G,dir:_!=null&&_.workspaceId?void 0:ie||void 0,workspaceId:(_==null?void 0:_.workspaceId)||void 0,useHome:(_==null?void 0:_.useHome)||!(_!=null&&_.workspaceId)&&!ie,argsStr:(_==null?void 0:_.argsStr)??(P||void 0),model:(_==null?void 0:_.model)??(S&&L||void 0),resumeSessionId:(_==null?void 0:_.resumeSessionId)||!S&&e==="cli"&&G===C&&$||void 0});if(Ee.success||Ee.pending){const Te=(_==null?void 0:_.argsStr)??P;!j&&(Te!=null&&Te.trim())&&(gl(r,G,Te),Ct(G)),At(G),Ee.success&&Ee.sessionId&&v(Ee.sessionId)}},[c,g,S,j,P,L,Ct,At,r,v,Ue,$,C]),Le=Mc(j?"ide":S?"acp":"cli",!j&&!S&&!!$),Ke=Tc(j?"ide":S?"acp":"cli",!j&&!S&&!!$),Q=()=>{var Te;const _=j?it(C):E.get(C)||C,G=!j&&!S&&!!$,{options:ie,selectedKey:Ee}=gs({machine:s,currentWorkspaceId:oe&&oe!=="__custom__"?oe:null,currentWorkspacePath:Ue});Kt({title:G?Ga(_):ps("start-fresh",_),description:G?qa():hs("start-fresh"),confirmLabel:Le,busyLabel:Ke,workspaceOptions:ie,selectedWorkspaceKey:Ee,details:[{label:"Mode",value:R.label},{label:"Provider",value:_},...!j&&e==="cli"&&$?[{label:"Resume",value:((Te=X.find(Be=>Be.providerSessionId===$))==null?void 0:Te.title)||$}]:[],...!j&&P.trim()?[{label:"Arguments",value:P.trim()}]:[],...S&&L.trim()?[{label:"Model",value:L.trim()}]:[]]},async()=>{const Be=ie.find(Ge=>Ge.key===rt.current);Be!=null&&Be.workspaceId?(de(Be.workspaceId),ue("")):Be!=null&&Be.workspacePath?(de("__custom__"),ue(Be.workspacePath)):(de(""),ue("")),await Ie({workspaceId:(Be==null?void 0:Be.workspaceId)??null,workspacePath:(Be==null?void 0:Be.workspacePath)??"",useHome:!(Be!=null&&Be.workspaceId)&&!(Be!=null&&Be.workspacePath)})})},ve=_=>{j?I(_):p(_.type,_.workspace,_.id)},Ze=a.useCallback(async(_,G,ie=!1)=>{if(_.mode===G){ie&&_.sessionId&&v(_.sessionId);return}if(!l||!_.sessionId){ie&&_.sessionId&&v(_.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:_.sessionId,cliType:_.type,mode:G}),ie&&v(_.sessionId)}catch(Ee){const Te=ro(Ee);so(Ee)?console.warn(Te?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Ee instanceof Error?Ee.message:String(Ee)):console.error("Failed to switch CLI view mode:",Ee)}},[r,v,l]),ze=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:oe,onChange:_=>{const G=_.target.value;if(de(G),G==="__custom__"&&l){J();return}G!=="__custom__"&&ue("")},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:(s.workspaces||[]).length>0?t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map(_=>t.jsxs("option",{value:_.id,children:[_.id===s.defaultWorkspaceId?"⭐ ":"",xn(_.path,_.label)]},_.id)),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]}):t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]})}),oe==="__custom__"&&(l?t.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:J,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:ee,onChange:_=>ue(_.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),t.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:oe==="__custom__"?Ue?t.jsx("span",{className:"font-mono truncate block",title:Ue,children:Ue}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Ue?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:oe===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:Ue,children:Ue})]}):"No workspace selected. This launches in the home directory."})]});return t.jsxs("div",{children:[t.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${R.accent} relative overflow-hidden`,children:[t.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[t.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",R.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:j?Ne.length>0?Ne.map(_=>{const G=o.find(Ge=>(Ge.type||"").toLowerCase()===(_.type||"").toLowerCase()&&wt(Ge.status)!=="stopped"),ie=_.running||!!G,Ee=!!G&&G.cdpConnected,Te=se.includes(_.type||_.id||""),Be=C===(_.type||"");return t.jsxs("button",{onClick:()=>{if(Ee&&G){const Ge=G.sessionId;Ge?d(ns(Ge),{state:{openRemoteForTabKey:Ge}}):d("/dashboard",{state:{openRemoteForTabKey:G.id}});return}Te||A(Ge=>Ge===(_.type||"")?"":_.type||"")},disabled:!!f||Te,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Ee?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Be?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:f&&f!==_.type?.4:1},children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(_.type)}),ie&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Ee?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.name||it(_.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Ee?"text-green-400":Te?"text-orange-400":Be?"text-accent-primary":"text-text-muted"}`,children:Ee?"Open Session":Te?"Starting...":Be?"Configure":"Select"})]})]},_.type)}):t.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",t.jsxs("button",{onClick:b,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[t.jsx(Ad,{size:14})," Scan System"]})]}):h.length>0?h.map(_=>{const G=C===_.type,ie=se.includes(_.type),Te=!!o.find(Be=>Be.type===_.type&&wt(Be.status)!=="stopped");return t.jsxs("button",{onClick:()=>A(Be=>Be===_.type?"":_.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${G?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:_.icon}),Te&&t.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ie?"text-orange-400":G?"text-accent-primary":"text-text-muted"}`,children:ie?"Starting...":G?"Configure":"Select"})]})]},_.type)}):t.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",t.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),C&&(j?Ne.find(_=>_.type===C):h.find(_=>_.type===C))&&t.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:j?it(C):E.get(C)||C})]}),ze,!j&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!S&&e==="cli"&&t.jsx(vl,{busy:!!x||!!f||se.includes(C),savedSessionsLoading:le,savedSessionsError:z,selectedSession:Nt,onRefresh:()=>void tt(C),onOpenHistory:()=>{C&&(W(!0),yl({hasLoadedInitialResults:Ce,isLoading:le})&&tt(C))},onClearSelection:()=>K("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[S&&t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),t.jsx("input",{type:"text",placeholder:"Leave empty for default",value:L,onChange:_=>U(_.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),t.jsx("input",{type:"text",placeholder:"Optional flags...",value:P,onChange:_=>B(_.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"}),q.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:q.map(_=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>B(_),title:_,children:_},_))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:Q,disabled:!!x||!!f||se.includes(C),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:x===C||f===C?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",o.length+se.filter(_=>!o.some(G=>G.type===_&&wt(G.status)!=="stopped")).length,")"]}),o.length===0&&Me.length===0?t.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",R.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Me.map(_=>t.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i(_)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:j?it(_):E.get(_)||_}),t.jsx("div",{className:"text-[11px] text-text-muted",children:x===_?"Launching process...":"Waiting for process and session to register..."})]})]}),t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${_}`)),o.map(_=>{const G=j?_:null,ie=!j&&!S?_:null,Ee=wt(_.status);return t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center mb-2",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i(_.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[re(_),(G==null?void 0:G.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",G.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:_.workspace||"—"}),(ie==null?void 0:ie.mode)&&t.jsx("span",{className:ie.mode==="chat"?"text-violet-400":"text-text-secondary",children:ie.mode==="chat"?"Chat view":"Terminal view"})]}),ie&&(ie.runtimeKey||ie.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ie.runtimeKey&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),t.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",ie.runtimeKey]}),t.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Te;(Te=navigator.clipboard)==null||Te.writeText(`adhdev attach ${ie.runtimeKey}`),T(ie.runtimeKey||null),window.setTimeout(()=>{T(Be=>Be===ie.runtimeKey?null:Be)},1200)},children:k===ie.runtimeKey?"Copied":"Copy"})]}),ie.runtimeWriteOwner&&t.jsx("span",{style:{color:ie.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ie.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:zx(ie.runtimeWriteOwner)})]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Ee==="stopped"?"bg-red-500/[0.08] text-red-500":Ee==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Ee}),j&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Te=_.sessionId;if(Te){d(ns(Te),{state:{openRemoteForTabKey:Te}});return}d("/dashboard",{state:{openRemoteForTabKey:_.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:t.jsx(Rt,{size:13})}),t.jsx("button",{onClick:()=>{const Te=_.workspace||"",{options:Be,selectedKey:Ge}=gs({machine:s,currentWorkspacePath:Te});Kt({title:ps("restart-ide",it(_.type)),description:hs("restart-ide"),confirmLabel:Bs("restart-ide"),busyLabel:Ks("restart-ide"),workspaceOptions:Be,selectedWorkspaceKey:Ge,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:it(_.type)}]},async()=>{const Pe=Be.find(Ut=>Ut.key===rt.current),Oe=(Pe==null?void 0:Pe.workspacePath)??"";if(Oe&&Oe!==Te){await Ie({type:_.type,workspacePath:Oe});return}await w(_)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:t.jsx(fr,{size:14})})]}),S&&t.jsx("button",{onClick:()=>{const Te=_.sessionId;Te&&v(Te)},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:!_.sessionId,children:t.jsx(es,{size:14})}),ie&&Ee!=="stopped"&&t.jsxs(t.Fragment,{children:[ie.mode&&t.jsx(Ua,{mode:ie.mode,onChange:Te=>void Ze(ie,Te,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Te=_.sessionId;Te&&v(Te)},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:!_.sessionId,children:ie.mode==="chat"?t.jsx(es,{size:14}):t.jsx(Rt,{size:13})})]}),Ee==="stopped"?t.jsx("button",{onClick:()=>{const Te=_.workspace||"",Be=j?it(_.type):re(_),{options:Ge,selectedKey:Pe}=gs({machine:s,currentWorkspacePath:Te});Kt({title:ps("restart-stopped",Be),description:hs("restart-stopped"),confirmLabel:Bs("restart-stopped"),busyLabel:Ks("restart-stopped"),workspaceOptions:Ge,selectedWorkspaceKey:Pe,details:[{label:"Mode",value:R.label},{label:"Provider",value:Be}]},async()=>{const Oe=Ge.find(Ut=>Ut.key===rt.current);await Ie({type:_.type,workspaceId:(Oe==null?void 0:Oe.workspaceId)??null,workspacePath:(Oe==null?void 0:Oe.workspacePath)??"",useHome:!(Oe!=null&&Oe.workspaceId)&&!(Oe!=null&&Oe.workspacePath)})})},disabled:se.includes(_.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:se.includes(_.type)?"⏳":t.jsx(La,{size:14})}):t.jsx("button",{onClick:()=>ve(_),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:t.jsx(Mt,{size:14})})]})]}),G&&G.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:G.aiAgents.map(Te=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Qi(Te.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Te.name," · ",wt(Te.status)]},Te.id))}),G&&(O[G.type]||[]).length>0&&l&&t.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[t.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:(O[G.type]||[]).map(Te=>t.jsxs("button",{disabled:F===`${G.type}.${Te.type}`,onClick:async()=>{const Be=`${G.type}.${Te.type}`;V(Be);try{await l(r,"set_ide_extension",{ideType:G.type,extensionType:Te.type,enabled:!Te.enabled}),H(Ge=>({...Ge,[G.type]:(Ge[G.type]||[]).map(Pe=>Pe.type===Te.type?{...Pe,enabled:!Pe.enabled}:Pe)}))}catch(Ge){console.error("Extension toggle failed:",Ge)}finally{V(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 ${Te.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Te.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Te.name,t.jsx("span",{className:"text-[9px] font-normal",children:Te.enabled?"ON":"OFF"})]},Te.type))})]})]},_.id)})]}),we&&l&&t.jsx(wn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:M,directories:ge,busy:ye,error:We,confirmLabel:"Use this folder",onClose:()=>Re(!1),onNavigate:_=>{gt(_)},onConfirm:_=>{ue(_),de("__custom__"),Re(!1)}}),Je&&t.jsx(co,{title:Je.title,description:Je.description,details:Je.details,workspaceOptions:Je.workspaceOptions,selectedWorkspaceKey:ut,onWorkspaceChange:_=>{rt.current=_,ht(_)},confirmLabel:Je.confirmLabel,busyLabel:Je.busyLabel,busy:kt,onConfirm:It,onCancel:()=>{Fe.current=null,bt(null)}}),D&&Bt&&t.jsx(Ya,{activeConv:Bt,ides:[],isCreatingChat:!1,isRefreshingHistory:le,savedSessions:X,isSavedSessionsLoading:le,isResumingSavedSessionId:ce,savedHistoryFilters:Y,onSavedHistoryFiltersChange:ae,onClose:()=>W(!1),onNewChat:()=>{K(""),W(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{tt(C)},onResumeSavedSession:_=>{if(!_.canResume||ce)return;const G=$e(_);K(_.providerSessionId),_e(_),Se(_.providerSessionId),W(!1),Ie({type:_.providerType,workspaceId:G.workspaceId,workspacePath:G.workspacePath,useHome:G.useHome,resumeSessionId:_.providerSessionId}).finally(()=>{Se(ie=>ie===_.providerSessionId?null:ie)})}})]})}const Si=[{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 Gx({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:o,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:m,initialWorkspacePath:d,sendDaemonCommand:g}){var b;const[p,w]=a.useState(u);a.useEffect(()=>{w(u)},[u]);const I=a.useMemo(()=>({ide:n.length,cli:o.length,acp:i.length}),[n.length,o.length,i.length]);return t.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[t.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),t.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),t.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[t.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:Si.map(f=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${p===f.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>w(f.id),children:[t.jsx("span",{children:f.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${p===f.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:I[f.id]})]},f.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(b=Si.find(f=>f.id===p))==null?void 0:b.helper})]}),p==="ide"&&t.jsx(sa,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:g,initialWorkspaceId:m,initialWorkspacePath:d}),p==="cli"&&t.jsx(sa,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:o,getIcon:l,actions:c,sendDaemonCommand:g,initialWorkspaceId:m,initialWorkspacePath:d}),p==="acp"&&t.jsx(sa,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:g,initialWorkspaceId:m,initialWorkspacePath:d})]})}function qx({onNicknameSynced:e}={}){var Se,oe,de,ee,ue,se,je,we,Re;const{id:s}=id(),r=Os(),n=Ia(),{sendCommand:o}=Tt(),i=br(),c=Uc(),l=wc(),u=l.ides||[],m=l.initialLoaded??!0,d=u.find(M=>M.id===s&&M.type==="adhdev-daemon"),g=u.some(M=>M.type==="adhdev-daemon"),[p,w]=a.useState("workspace"),[I,b]=a.useState("ide"),f=a.useRef(null),[x,y]=a.useState(null),k=a.useRef("__home__"),[T,v]=a.useState("__home__"),[R,j]=a.useState(!1),S=a.useRef(null);a.useEffect(()=>{!s||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,d,s]),a.useEffect(()=>{if(!s||!d||p!=="overview")return;const M=d.machine;(typeof(M==null?void 0:M.cpus)!="number"||typeof(M==null?void 0:M.totalMem)!="number"||typeof(M==null?void 0:M.arch)!="string"||typeof(M==null?void 0:M.release)!="string")&&c(s,{minFreshMs:3e4}).catch(()=>{})},[p,c,d,s]),Zf(s&&p==="overview"?[s]:[],{enabled:p==="overview",intervalMs:pm});const h=()=>{if(g){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},E=bx({machineId:s,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:S});a.useEffect(()=>dt.onToast(me=>{l.setToasts(Z=>{if(Z.some(We=>We.message===me.message&&me.timestamp-We.timestamp<3e3))return Z;const Ae={id:me.id,message:me.message,type:me.type,timestamp:me.timestamp,targetKey:me.targetKey,actions:me.actions};return[...Z.slice(-4),Ae]});const ge=me.duration||5e3;setTimeout(()=>l.setToasts(Z=>Z.filter(ye=>ye.id!==me.id)),ge)}),[l]);const C=(d==null?void 0:d.availableProviders)||[],A={};for(const M of C)A[M.type]=M.icon;const P=M=>A[M]||"",B=d?{id:d.id,hostname:Zi(d,{fallbackId:d.id}),platform:((Se=d.machine)==null?void 0:Se.platform)||"unknown",arch:((oe=d.machine)==null?void 0:oe.arch)||"",cpus:((de=d.machine)==null?void 0:de.cpus)||0,totalMem:((ee=d.machine)==null?void 0:ee.totalMem)||0,freeMem:(ue=d.machine)==null?void 0:ue.freeMem,availableMem:(se=d.machine)==null?void 0:se.availableMem,loadavg:(je=d.machine)==null?void 0:je.loadavg,uptime:(we=d.machine)==null?void 0:we.uptime,release:((Re=d.machine)==null?void 0:Re.release)||"",cdpConnected:!!d.cdpConnected,machineNickname:d.machineNickname||null,p2p:d.p2p?{screenshotActive:!1,...d.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:d.detectedIdes||[],workspaces:d.workspaces||[],defaultWorkspaceId:d.defaultWorkspaceId??d.activeWorkspaceId??null,defaultWorkspacePath:d.defaultWorkspacePath??d.activeWorkspacePath??null}:null,q=u.filter(M=>M.daemonId===s&&M.type!=="adhdev-daemon").filter(M=>!lr(M)&&!Ts(M)).map(M=>({id:M.id,sessionId:M.sessionId,type:M.type,version:M.version||"",instanceId:M.instanceId||"",status:M.status,workspace:M.workspace||null,terminals:M.terminals||0,aiAgents:wu(M.aiAgents||(M.agents||[]).map(me=>({id:me.name,name:me.name,status:me.status,version:me.version}))),activeChat:M.activeChat||null,chats:M.chats||[],childSessions:M.childSessions||[],cdpConnected:M.cdpConnected||!1,daemonId:s})),N=u.filter(M=>M.daemonId===s&&lr(M)).map(M=>({id:M.id,sessionId:M.sessionId,type:M.type,cliName:M.cliName||M.type,status:M.status,workspace:M.workspace||"",activeChat:M.activeChat||null,providerSessionId:M.providerSessionId,mode:M.mode,runtimeKey:M.runtimeKey,runtimeDisplayName:M.runtimeDisplayName,runtimeWorkspaceLabel:M.runtimeWorkspaceLabel,runtimeWriteOwner:M.runtimeWriteOwner||null,runtimeAttachedClients:M.runtimeAttachedClients||[],daemonId:s})),L=u.filter(M=>M.daemonId===s&&Ts(M)).map(M=>({id:M.id,sessionId:M.sessionId,type:M.type,acpName:M.cliName||M.type,status:M.status,workspace:M.workspace||"",activeChat:M.activeChat||null,providerSessionId:M.providerSessionId,daemonId:s})),U=d?$t(d,{fallbackId:s}):"",$="workspace",K=n.state,X=K==null?void 0:K.initialMachineTab,te=K==null?void 0:K.initialWorkspaceCategory,le=K==null?void 0:K.initialWorkspaceId,he=K==null?void 0:K.initialWorkspacePath,Ce=X==="ides"||X==="clis"||X==="acps"?"workspace":X||$,ke=X==="ides"?"ide":X==="clis"?"cli":X==="acps"?"acp":te,z=[...q.map(M=>{var me,ge,Z,ye,Ae;return{id:`ide:${M.type}:${M.workspace||""}`,label:((me=M.activeChat)==null?void 0:me.title)||M.type,kind:"ide",providerType:M.type,subtitle:M.workspace||void 0,workspace:M.workspace||void 0,lastLaunchedAt:((Ae=(ye=(Z=(ge=M.activeChat)==null?void 0:ge.messages)==null?void 0:Z.at)==null?void 0:ye.call(Z,-1))==null?void 0:Ae.timestamp)||0}}),...N.map(M=>{var me,ge,Z,ye,Ae;return{id:`cli:${M.type}:${M.workspace||""}`,label:((me=M.activeChat)==null?void 0:me.title)||M.cliName,kind:"cli",providerType:M.type,providerSessionId:M.providerSessionId,subtitle:M.workspace||void 0,workspace:M.workspace||void 0,lastLaunchedAt:((Ae=(ye=(Z=(ge=M.activeChat)==null?void 0:ge.messages)==null?void 0:Z.at)==null?void 0:ye.call(Z,-1))==null?void 0:Ae.timestamp)||0}}),...L.map(M=>{var me,ge,Z,ye,Ae;return{id:`acp:${M.type}:${M.workspace||""}`,label:((me=M.activeChat)==null?void 0:me.title)||M.acpName,kind:"acp",providerType:M.type,providerSessionId:M.providerSessionId,subtitle:js(M.summaryMetadata)||M.workspace||void 0,workspace:M.workspace||void 0,lastLaunchedAt:((Ae=(ye=(Z=(ge=M.activeChat)==null?void 0:ge.messages)==null?void 0:Z.at)==null?void 0:ye.call(Z,-1))==null?void 0:Ae.timestamp)||0}})].sort((M,me)=>(me.lastLaunchedAt||0)-(M.lastLaunchedAt||0)),xe=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(M=>({id:M.id,label:M.title||M.providerName||M.providerType,kind:M.kind,providerType:M.providerType,providerSessionId:M.providerSessionId,subtitle:js(M.summaryMetadata)||M.workspace||void 0,workspace:M.workspace,summaryMetadata:M.summaryMetadata,lastLaunchedAt:M.lastLaunchedAt})):z,D=a.useMemo(()=>{var me;const M=((me=l.connectionStates)==null?void 0:me[s||""])||void 0;return u.filter(ge=>ge.daemonId===s&&ge.type!=="adhdev-daemon").flatMap(ge=>Xa(ge,{},{connectionStates:s&&M?{[s]:M}:void 0,defaultConnectionState:M})).filter(ge=>!(ge.transport==="pty"&&ge.mode==="terminal")).sort((ge,Z)=>ma(Z)-ma(ge))},[u,l.connectionStates,s]),W=a.useCallback(M=>{const me=Wa(M);me&&r(ns(me))},[r]),Y=a.useCallback(()=>{f.current&&(j(!0),f.current().finally(()=>{f.current=null,j(!1),y(null)}))},[]),ae=a.useCallback(M=>{if(!B)return;const{options:me,selectedKey:ge}=gs({machine:B,currentWorkspacePath:M.workspace}),Z=async()=>{b(M.kind),w("workspace")};f.current=async()=>{const ye=me.find(De=>De.key===k.current),Ae=(ye==null?void 0:ye.workspacePath)??null,We=(ye==null?void 0:ye.workspaceId)??null;if(M.kind==="ide"&&M.providerType){await E.handleLaunchIde(M.providerType,Ae?{workspace:Ae}:void 0);return}if((M.kind==="cli"||M.kind==="acp")&&M.providerType){await E.runLaunchCliCore({cliType:M.providerType,dir:We?void 0:Ae||"",workspaceId:We||void 0,model:M.kind==="acp"&&tc(M.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:M.providerSessionId});return}await Z()},k.current=ge,v(ge),y({title:M.kind==="ide"?ps("restart-ide",M.label):M.providerSessionId?Ga(M.label):ps("start-fresh",M.label),description:M.kind==="ide"?hs("restart-ide"):M.providerSessionId?qa():hs("start-fresh"),confirmLabel:M.kind==="ide"?Bs("restart-ide"):M.providerSessionId?on(!0):Bs("start-fresh"),busyLabel:M.kind==="ide"?Ks("restart-ide"):M.providerSessionId?za(!0):Ks("start-fresh"),workspaceOptions:me,details:[{label:"Mode",value:M.kind.toUpperCase()},...M.providerType?[{label:"Provider",value:M.providerType}]:[]]})},[E,B]);if(a.useEffect(()=>{w(Ce)},[$,Ce,s]),a.useEffect(()=>{ke&&b(ke)},[ke,s]),!B)return m?t.jsxs("div",{className:"p-10 text-center text-text-muted",children:[t.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),t.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),t.jsx("button",{onClick:h,className:"machine-btn-back",children:"← Back"})]}):t.jsx("div",{className:"p-10 text-center text-text-muted",children:t.jsx("p",{children:"⏳ Loading machine..."})});const ce=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Rt,{size:14})," Workspace"]}),count:q.length+N.length+L.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(ws,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(mn,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Md,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Cd,{size:14})," Logs"]})}];return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[t.jsx("div",{className:"flex items-center justify-between w-full",children:t.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[t.jsx("button",{onClick:h,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),t.jsxs("div",{className:"flex flex-col min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[E.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:E.nicknameInput,onChange:M=>E.setNicknameInput(M.target.value),onKeyDown:M=>{M.key==="Enter"&&E.handleSaveNickname(),M.key==="Escape"&&E.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),t.jsx("button",{onClick:E.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),t.jsx("button",{onClick:()=>E.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):t.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{E.setEditingNickname(!0),E.setNicknameInput(B.machineNickname||"")},title:"Click to set nickname",children:U}),t.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),t.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[t.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[B.platform," · ",B.arch]}),t.jsxs("span",{children:[B.cpus," cores"]}),(d==null?void 0:d.version)&&t.jsxs("span",{children:["v",d.version]}),B.p2p.available&&t.jsxs("span",{children:["P2P ",B.p2p.state==="connected"?"connected":B.p2p.state]}),B.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:B.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ce.map(M=>t.jsxs("button",{onClick:()=>w(M.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${p===M.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[M.label,M.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${p===M.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:M.count})]},M.id))})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:t.jsx("div",{className:"max-w-7xl mx-auto h-full",children:t.jsxs("div",{className:"h-full",children:[p==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(Ux,{machineEntry:d,providers:C,recentLaunches:xe,currentConversations:D,onUpgradeDaemon:async()=>{try{await o(s,"daemon_upgrade",{})}catch{}},onOpenRecent:ae,onOpenConversation:W}),t.jsx(Gx,{machine:B,machineId:s,providers:C,ideSessions:q,cliSessions:N,acpSessions:L,actions:E,getIcon:P,initialCategory:I,initialWorkspaceId:le,initialWorkspacePath:he,sendDaemonCommand:o})]}),p==="providers"&&t.jsx(Nx,{machineId:s,providers:C,sendDaemonCommand:o}),p==="overview"&&t.jsx(gx,{machineId:s,machine:B,ideSessions:q,cliSessions:N,acpSessions:L,actions:E,sendDaemonCommand:o}),p==="session-host"&&t.jsx(Hx,{machineId:s,cliSessions:N,sendDaemonCommand:o}),p==="logs"&&t.jsx(Dx,{machineId:s,sendDaemonCommand:o})]})})}),E.launchPick&&B&&t.jsx(Fx,{machine:B,launchPick:E.launchPick,actions:E}),x&&t.jsx(co,{title:x.title,description:x.description,details:x.details,workspaceOptions:x.workspaceOptions,selectedWorkspaceKey:T,onWorkspaceChange:M=>{k.current=M,v(M)},confirmLabel:x.confirmLabel,busyLabel:x.busyLabel,busy:R,onConfirm:Y,onCancel:()=>{f.current=null,y(null)}}),t.jsx(Lc,{toasts:l.toasts||[],onDismiss:M=>l.setToasts(me=>me.filter(ge=>ge.id!==M)),onClickToast:M=>{M.targetKey&&r(ns(M.targetKey))}}),t.jsx("style",{children:`
73
+ @keyframes toast-in {
74
+ from { opacity: 0; transform: translateX(40px); }
75
+ to { opacity: 1; transform: translateX(0); }
76
+ }
77
+ `})]})}function mo(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Yx(e){if(typeof window>"u")return e;const s=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=mo();return r&&!s.searchParams.has("token")&&s.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?s.toString():`${s.pathname}${s.search}${s.hash}`}async function Vt(e,s){return await fetch(Yx(e),{credentials:"same-origin",...s})}function Nl(){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 Xx{constructor(){qe(this,"adapters",new Map);qe(this,"states",new Map);qe(this,"runtimeListeners",new Map);qe(this,"screenshotCallbacks",new Map);qe(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}onScreenshot(s,r){return this.screenshotCallbacks.set(s,r),()=>{this.screenshotCallbacks.delete(s)}}emitScreenshot(s,r){this.screenshotCallbacks.forEach(n=>n(s,r))}onStatus(s){return this.statusCallbacks.add(s),()=>{this.statusCallbacks.delete(s)}}emitStatus(s,r){this.statusCallbacks.forEach(n=>n(s,r))}emitRuntimeSnapshot(s,r,n=0,o=!1,i,c){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:o,cols:i,rows:c})}emitSessionOutput(s,r,n){!s||typeof r!="string"||!r||this.emitRuntimeEvent(s,{type:"session_output",sessionId:s,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(s,r){const n=this.runtimeListeners.get(s)||new Set;return n.add(r),this.runtimeListeners.set(s,n),()=>{const o=this.runtimeListeners.get(s);o&&(o.delete(r),o.size===0&&this.runtimeListeners.delete(s))}}async requestRuntimeSnapshot(s,r){if(!r)return;const n=await Vt(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`);if(!n.ok)return;const o=await n.json();this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof o.seq=="number"?o.seq:0,text:typeof o.text=="string"?o.text:"",truncated:!!o.truncated,cols:typeof o.cols=="number"?o.cols:void 0,rows:typeof o.rows=="number"?o.rows:void 0})}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(o=>o(r))}}const Jt=new Xx;function Jx(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=mo();return r?`${s}?token=${encodeURIComponent(r)}`:s}const Ur=Jx(),Ni=3e3,Qx=3e4;let Gt=null,Zx=0;const un=new Map;let ls=null,rr=null;function Ci(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function Xs(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function eb(e){return e==="connected"?"connected":e}async function Qr(e,s,r){const n=gf(e,r||{}),o=Gt;if(o&&o.readyState===WebSocket.OPEN){const i=`req_${++Zx}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{un.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);un.set(i,{resolve:m=>{clearTimeout(u),c(m)},reject:m=>{clearTimeout(u),l(m)}}),o.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function ka(e,s){const r=Gt;if(!r||r.readyState!==WebSocket.OPEN||!s||s.type!=="subscribe"&&s.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class tb{constructor(s){qe(this,"daemonId");qe(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Gt==null?void 0:Gt.readyState)===WebSocket.OPEN}get connectionState(){return(Gt==null?void 0:Gt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Qr(this.daemonId,s,r)}async sendInput(s,r){return Qr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,ls&&(clearInterval(ls),ls=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Qr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const o=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Jt.emitScreenshot(this.daemonId,o)}}catch{}};r(),ls=setInterval(r,2e3)}stopScreenshots(s){ls&&(clearInterval(ls),ls=null)}}let Et=null;function sb(e){return(!Et||Et.daemonId!==e)&&(Et=new tb(e)),Et}function rb({children:e}){const s=a.useRef(ar()),r=ar();s.current=r;const{setUserName:n}=vs(),o=a.useRef(n);o.current=n;const i=a.useRef(null),c=a.useRef(null),[,l]=a.useState("disconnected"),u=a.useCallback((b,f)=>{l(b),rr==null||rr(b,f)},[]),m=a.useRef(null),d=a.useRef(),g=a.useRef(Ni),p=a.useRef(!0),w=a.useRef(!1),I=a.useRef("initial_connect");return a.useEffect(()=>{p.current=!0,w.current=!1;function b(){var y,k;if(!p.current||((y=m.current)==null?void 0:y.readyState)===WebSocket.OPEN||((k=m.current)==null?void 0:k.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Ur}...`),Xs("connect_attempt",{url:Ur,reason:I.current,delayMs:g.current});let x;try{x=new WebSocket(Ur)}catch(T){console.error("[Standalone WS] Failed to create WebSocket:",T),f();return}m.current=x,x.onopen=()=>{if(!p.current){x.close();return}u("connected"),g.current=Ni,Xs("open",{url:Ur,reason:I.current}),as.resubscribeAll({sendData:ka}),console.log("[Standalone WS] Connected")},Gt=x,x.onmessage=T=>{var v,R;try{const j=JSON.parse(T.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const S=un.get(j.requestId);S&&(un.delete(j.requestId),j.type==="error"?S.reject(new Error(((v=j.data)==null?void 0:v.message)||"Command failed")):S.resolve(j.data));return}if(j.type==="session_output"){const S=j.sessionId||j.cliId||j.cliType;S&&Jt.emitSessionOutput(S,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){Jt.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated,typeof j.cols=="number"?j.cols:void 0,typeof j.rows=="number"?j.rows:void 0);return}if(j.type==="topic_update"){const S=j.update;S&&as.publish(S);return}if(j.type==="status"||j.type==="initial_state"){const S=j.data;if(!S)return;const{injectEntries:h,markLoaded:E,getIdes:C}=s.current,A=S.instanceId||"standalone",P=C().find(N=>N.id===A),B=sb(A);Jt.register(A,B),Jt.setState(A,"connected"),u("connected",A),Jt.emitStatus(A,S);const q=an(S,{daemonId:A,existingDaemon:P,existingEntries:C()});Ci("ws_status",{type:j.type,daemonId:A,sessions:(S.sessions||[]).map(N=>({id:N.id,parentId:N.parentId,providerType:N.providerType,kind:N.kind,transport:N.transport,unread:N.unread,inboxBucket:N.inboxBucket,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,title:N.title})),recentLaunches:(S.recentLaunches||[]).map(N=>({id:N.id,providerType:N.providerType,kind:N.kind,workspace:N.workspace,lastLaunchedAt:N.lastLaunchedAt}))}),Ci("entries",{daemonId:A,entries:q.filter(N=>N.type!=="adhdev-daemon").map(N=>({id:N.id,type:N.type,unread:N.unread,inboxBucket:N.inboxBucket,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,sessionId:N.sessionId}))}),q.length>0&&h(q,{authoritativeDaemonIds:[A]}),E(),c.current!==A&&((R=i.current)==null||R.call(i),c.current=A,i.current=as.subscribe({sendData:ka},A,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${A}`,params:{includeSessions:!0}},N=>{if(N.topic!=="daemon.metadata")return;const L=s.current.getIdes(),U=L.find(K=>K.id===A),$=an(N.status,{daemonId:A,existingDaemon:U,existingEntries:L,timestamp:N.timestamp});$.length>0&&s.current.injectEntries($),N.userName&&o.current&&o.current(N.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},x.onclose=T=>{p.current&&(Et==null||Et.stopScreenshots(),Et&&Jt.setState(Et.daemonId,"disconnected"),u("disconnected"),m.current=null,I.current=`close:${T.code}${T.wasClean?":clean":":unclean"}`,Xs("close",{code:T.code,reason:T.reason||"",wasClean:T.wasClean}),f())},x.onerror=T=>{w.current||!p.current||(I.current="error",Xs("error",{message:T instanceof Event?"event":String(T),readyState:x.readyState}),console.warn("[Standalone WS] Error, will reconnect:",T))}}function f(){if(!p.current)return;clearTimeout(d.current);const x=g.current;console.log(`[Standalone WS] Reconnecting in ${x}ms...`),Xs("schedule_reconnect",{reason:I.current,delayMs:x}),d.current=setTimeout(()=>{g.current=Math.min(g.current*1.5,Qx),b()},x)}return b(),()=>{var x;p.current=!1,w.current=!0,(x=i.current)==null||x.call(i),i.current=null,c.current=null,clearTimeout(d.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,Gt=null),Et&&(Et.stopScreenshots(),Jt.unregister(Et.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function nb({children:e}){const[s,r]=a.useState("disconnected"),[n,o]=a.useState(null);a.useEffect(()=>(rr=(c,l)=>{r(c),l&&o(l)},()=>{rr=null}),[]);const i=a.useMemo(()=>{const c=s==="connected",l=eb(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(xd,{connectionOverrides:i,children:t.jsx(rb,{children:e})})}const Cl="adhdev_standalone_font_preferences",ys={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Sn=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],mr=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],ab=new Set(Sn.map(e=>e.id)),ob=new Set(mr.map(e=>e.id));function Yt(e){const s=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Zr("chat",s.chat),code:Zr("code",s.code),terminal:Zr("terminal",s.terminal)}}function Zr(e,s){const r=ys[e],n=s&&typeof s=="object"&&!Array.isArray(s)?s:{},o=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?ab:ob).has(o)?o==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:o}:r}function en(e,s){var o;const r=Zr(e,s);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?Sn:mr;return((o=n.find(i=>i.id===r.preset))==null?void 0:o.family)||n[0].family}function ib(e){const s=Yt(e),r=en("chat",s.chat),n=en("code",s.code),o=en("terminal",s.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":o,"--chat-tool-font-family":o}}function us(e,s=document.documentElement){const r=Yt(e),n=ib(r);s.setAttribute("data-standalone-fonts","custom");for(const[o,i]of Object.entries(n))s.style.setProperty(o,i);return r}function Sa(e){const s=Yt(e);try{localStorage.setItem(Cl,JSON.stringify(s))}catch{}return s}function cb(){try{const e=localStorage.getItem(Cl);if(e)return Yt(JSON.parse(e))}catch{}return ys}function lb(){return us(cb())}function Js(e,s){var n;const r=e==="chat"?Sn:mr;return((n=r.find(o=>o.id===s))==null?void 0:n.label)||r[0].label}const db=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Di,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(ws,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(mn,{}),label:"Settings"}];function ub({children:e}){const s=Os(),r=Ia(),[n,o]=a.useState(!1),[i,c]=a.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),l=d=>{s(d),o(!1)},u=()=>{c(d=>{const g=!d;try{localStorage.setItem("sidebar-collapsed",g?"1":"0")}catch{}return g})},m=d=>`nav-item${r.pathname.startsWith(d)?" active":""} cursor-pointer ${i?"justify-center py-2.5 px-0":""}`;return t.jsxs("div",{className:`app-layout${n?" mobile-menu-open":""}${i?" sidebar-collapsed":""}`,children:[t.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:()=>o(!0),children:[t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"})]}),n&&t.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:()=>o(!1),onKeyDown:d=>d.key==="Escape"&&o(!1)}),t.jsxs("aside",{className:`sidebar ${n?"sidebar-open":""}`,children:[t.jsxs("div",{className:"sidebar-header",children:[t.jsxs("div",{className:`sidebar-logo ${i?"justify-center gap-0":""}`,children:[t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&t.jsx("span",{children:"ADHDev"})]}),t.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:()=>o(!1),children:t.jsx(Mt,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:db.map(d=>t.jsxs("div",{className:m(d.path),id:`nav-${d.id}`,onClick:()=>l(d.path),title:i?d.label:void 0,children:[t.jsx("span",{className:"nav-icon",children:d.icon}),!i&&d.label]},d.id))}),t.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":""}`,id:"nav-docs",onClick:()=>window.open("https://docs.adhf.dev","_blank"),title:i?"Docs":void 0,children:[t.jsx("span",{className:"nav-icon",children:t.jsx($i,{})}),!i&&t.jsxs(t.Fragment,{children:["Docs",t.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]})]}),t.jsxs("div",{className:`nav-item cursor-pointer${r.pathname==="/about"?" active":""} ${i?"justify-center py-2.5 px-0":""}`,id:"nav-about",onClick:()=>s("/about"),title:i?"About":void 0,children:[t.jsx("span",{className:"nav-icon",children:t.jsx(Bi,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.100"]}),t.jsx(Tf,{collapsed:i}),t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:u,title:i?"Expand sidebar":"Collapse sidebar",children:[t.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&t.jsx("span",{className:"text-xs",children:"Collapse"})]})]})]}),t.jsx("main",{className:"main-content relative",children:t.jsx("div",{className:"main-content-inner",children:e})})]})}const mb=[{icon:t.jsx(ws,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(es,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(Ki,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Rt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(ir,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx($i,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],fb=[{icon:t.jsx(Ld,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Di,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(fn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(Nd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(Ei,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(Id,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],pb=[{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 hb(){return t.jsxs($c,{icon:t.jsx(Bi,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:t.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.8.100"]}),children:[t.jsx(Lt,{children:t.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[t.jsxs("div",{className:"max-w-2xl",children:[t.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),t.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),t.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),t.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),t.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),t.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),t.jsx(Lt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:mb.map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Lt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:t.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:_c.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Ec.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Dc.map(e=>`${e.icon} ${e.name}`)}].map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[t.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),t.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(s=>t.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:s},s))})]},e.label))})}),t.jsx(Lt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:fb.map(e=>t.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Lt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:t.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:t.jsxs("table",{className:"w-full text-[13px]",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"bg-bg-secondary",children:[t.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),t.jsx("tbody",{children:pb.map((e,s)=>t.jsxs("tr",{className:s%2===0?"bg-bg-glass":"bg-transparent",children:[t.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?t.jsx("span",{className:"text-emerald-500",children:"✓"}):t.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:t.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),t.jsx(Bc,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:"Cloud is optional, not required",description:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",action:t.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[t.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),t.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[t.jsx(Wd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function ra(e,s,r){return{...e,[s]:r}}function na({surface:e,title:s,description:r,value:n,options:o,onChange:i}){return t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-text-primary",children:s}),t.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:c=>{const l=c.target.value;i(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:o.map(c=>t.jsx("option",{value:c.id,children:c.label},c.id))}),n.preset==="custom"&&t.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:c=>i({preset:"custom",customFamily:c.target.value})}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:[t.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",t.jsx("span",{className:"font-mono break-all",children:en(e,n)})]})]})]})}function xb({value:e,savedValue:s,saving:r=!1,error:n,notice:o,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:u}){const m=JSON.stringify(e)!==JSON.stringify(s);return t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&t.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),o&&t.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:o}),t.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[t.jsx(na,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Sn,onChange:d=>i(ra(e,"chat",d))}),t.jsx(na,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:mr,onChange:d=>i(ra(e,"code",d))}),t.jsx(na,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:mr,onChange:d=>i(ra(e,"terminal",d))})]}),t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),t.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",Js("chat",e.chat.preset)," · Code: ",Js("code",e.code.preset)," · Terminal: ",Js("terminal",e.terminal.preset)]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Js("chat",ys.chat.preset)," / ",Js("code",ys.code.preset)]})]}),t.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:t.jsxs("div",{className:"chat-container-content",children:[t.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:t.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[t.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[t.jsx("span",{className:"chat-sender",children:"Hermes"}),t.jsx("span",{className:"chat-time",children:"now"})]}),t.jsxs("div",{className:"chat-markdown",children:[t.jsxs("p",{children:["Readable prose, ",t.jsx("strong",{children:"bold text"}),", and ",t.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),t.jsx("pre",{children:t.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),t.jsxs("div",{className:"chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"▸"}),t.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),t.jsxs("div",{className:"chat-msg-terminal",children:[t.jsx("div",{className:"chat-msg-header",children:"Terminal"}),t.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick: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"}),t.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"}),t.jsx("button",{type:"button",onClick:u,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 bb(){const{ides:e}=vs(),s=e.find(D=>D.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Tt(),{userName:o}=vs(),[i,c]=a.useState(o||""),[l,u]=a.useState(null),[m,d]=a.useState(null),[g,p]=a.useState(ys),[w,I]=a.useState(!1),[b,f]=a.useState(""),[x,y]=a.useState(""),[k,T]=a.useState("127.0.0.1"),[v,R]=a.useState(""),[j,S]=a.useState(""),[h,E]=a.useState(""),[C,A]=a.useState(""),[P,B]=a.useState(""),[q,N]=a.useState(!1),L=async()=>{const W=await(await Vt("/auth/session")).json();u(W)},U=async()=>{const W=await(await Vt("/api/v1/standalone/preferences")).json();d(W),T(W.standaloneBindHost);const Y=Yt(W.standaloneFontPreferences);p(Y),us(Y),Sa(Y)};a.useEffect(()=>{o!==void 0&&c(o)},[o]),a.useEffect(()=>{Promise.all([L(),U()]).catch(D=>{A(D instanceof Error?D.message:String(D))})},[]),a.useEffect(()=>{us(g)},[g]);const $=D=>{const W=D.target.value.trim();s!=null&&s.id&&W!==o&&n(s.id,"set_user_name",{userName:W}).catch(console.error)},[K,X]=a.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),te=D=>{X(D);try{localStorage.setItem("adhdev_sound",D?"1":"0")}catch{}},le=async()=>{f(""),y(""),I(!0);try{const D=Yt(g),W=await Vt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:D})}),Y=await W.json();if(!W.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to save standalone font preferences");const ae=Yt(Y.standaloneFontPreferences);d(Y),p(ae),us(ae),Sa(ae),y("Standalone chat fonts saved for this self-hosted dashboard.")}catch(D){f(D instanceof Error?D.message:String(D))}finally{I(!1)}},he=()=>{const D=Yt(m==null?void 0:m.standaloneFontPreferences);f(""),y(""),p(D),us(D)},Ce=()=>{f(""),y(""),p(ys),us(ys)},ke=async()=>{A(""),B(""),N(!0);try{const D=await Vt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:k})}),W=await D.json();if(!D.ok)throw new Error((W==null?void 0:W.error)||"Failed to save standalone network preference");d(W),T(W.standaloneBindHost),B(W.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(D){A(D instanceof Error?D.message:String(D))}finally{N(!1)}},z=async()=>{if(A(""),B(""),j.trim().length<4){A("Password must be at least 4 characters.");return}if(j!==h){A("New password and confirmation do not match.");return}N(!0);try{const D=await Vt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:j})}),W=await D.json();if(!D.ok)throw new Error((W==null?void 0:W.error)||"Failed to save password");u(W),await U(),R(""),S(""),E(""),B(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Nl()}catch(D){A(D instanceof Error?D.message:String(D))}finally{N(!1)}},xe=async()=>{A(""),B(""),N(!0);try{const D=await Vt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),W=await D.json();if(!D.ok)throw new Error((W==null?void 0:W.error)||"Failed to clear password");u(W),await U(),R(""),S(""),E(""),B("Standalone password disabled.")}catch(D){A(D instanceof Error?D.message:String(D))}finally{N(!1)}};return t.jsxs($c,{icon:t.jsx(mn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(Pr,{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)&&t.jsx(Pr,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),t.jsx(Lt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:t.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[t.jsx("span",{className:"text-text-muted",children:"Version"}),t.jsxs("span",{className:"font-mono text-xs",children:["v","0.8.100"]}),t.jsx("span",{className:"text-text-muted",children:"Status"}),t.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),t.jsx("span",{className:"text-text-muted",children:"Current bind"}),t.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Default bind"}),t.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.standaloneBindHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Auth"}),t.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),t.jsx(Lt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:k==="127.0.0.1",onChange:()=>T("127.0.0.1")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),t.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),t.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:k==="0.0.0.0",onChange:()=>T("0.0.0.0")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),t.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:()=>{ke()},disabled:q,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:q?"Saving…":"Save default network mode"}),t.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),t.jsx(Lt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children: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."}),C&&t.jsx(Pr,{variant:"error",children:C}),P&&t.jsx(Pr,{variant:"success",children:P}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:v,onChange:D=>R(D.target.value)}),t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:j,onChange:D=>S(D.target.value)}),t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:h,onChange:D=>E(D.target.value)})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{z()},disabled:q,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:q?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&t.jsx("button",{type:"button",onClick:()=>{xe()},disabled:q,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),t.jsx(Lt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?t.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):t.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(D=>t.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:`w-2 h-2 rounded-full ${D.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:D.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:D.type})]},D.type))})}),t.jsx(Lt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(_f,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Lt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),t.jsx(Bf,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI."}),t.jsx(Vf,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),t.jsx(xb,{value:g,savedValue:Yt(m==null?void 0:m.standaloneFontPreferences),saving:w,error:b,notice:x,onChange:p,onSave:()=>{le()},onResetToSaved:he,onResetToDefaults:Ce})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),t.jsx(Yf,{})]})]})}),t.jsx(Lt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(Lf,{}),t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Od,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:K,onChange:te})]})}),t.jsx(Lt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:t.jsx("div",{className:"flex flex-col gap-3",children:t.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[t.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[t.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[t.jsx(Sd,{size:16,className:"text-text-secondary"})," Display Name"]}),t.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),t.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:i,onChange:D=>c(D.target.value),onBlur:$,onKeyDown:D=>{D.key==="Enter"&&D.currentTarget.blur()}})]})})})]})}Mf();Uf();lb();const gb=Ri({baseUrl:"",getToken:mo});function yb({children:e}){const[s,r]=a.useState(null),[n,o]=a.useState(!0),[i,c]=a.useState(""),[l,u]=a.useState(""),[m,d]=a.useState(!1),g=async()=>{o(!0),u("");try{const I=await(await Vt("/auth/session")).json();r(I)}catch(w){u(w instanceof Error?w.message:String(w))}finally{o(!1)}};a.useEffect(()=>{g()},[]),a.useEffect(()=>{if(!s||s.required&&!s.authenticated)return;let w=!1;return(async()=>{try{const I=await Vt("/api/v1/standalone/preferences");if(!I.ok)return;const b=await I.json();if(w)return;const f=Yt(b.standaloneFontPreferences);us(f),Sa(f)}catch{}})(),()=>{w=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const p=async w=>{w.preventDefault(),d(!0),u("");try{const I=await Vt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),b=await I.json();if(!I.ok)throw new Error((b==null?void 0:b.error)||"Login failed");r(b),c(""),Nl()}catch(I){u(I instanceof Error?I.message:String(I))}finally{d(!1)}};return n?t.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):s?!s.required||s.authenticated?t.jsx(t.Fragment,{children:e}):t.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:t.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),t.jsx("p",{className:"text-sm text-text-muted mt-1",children:s.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),s.hasPasswordAuth?t.jsxs("form",{className:"flex flex-col gap-3",onSubmit:p,children:[t.jsx("input",{type:"password",value:i,onChange:w=>c(w.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),t.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"})]}):t.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),l&&t.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:l})]})}):t.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 Ii(){const{ides:e,initialLoaded:s}=vs();if(!s)return t.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?t.jsx(ia,{to:`/machines/${r.id}`,replace:!0}):t.jsx(ia,{to:"/dashboard",replace:!0})}function vb(){const e=a.useMemo(()=>({sendCommand:Qr,sendData:ka}),[]);return t.jsx(cd,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(yd,{client:gb,children:t.jsx(yb,{children:t.jsx(nb,{children:t.jsx(wd,{value:e,children:t.jsx(ub,{children:t.jsxs(ld,{children:[t.jsx(is,{path:"/dashboard",element:t.jsx(xx,{})}),t.jsx(is,{path:"/machine",element:t.jsx(Ii,{})}),t.jsx(is,{path:"/machines/:id",element:t.jsx(qx,{})}),t.jsx(is,{path:"/machines",element:t.jsx(Ii,{})}),t.jsx(is,{path:"/about",element:t.jsx(hb,{})}),t.jsx(is,{path:"/settings",element:t.jsx(bb,{})}),t.jsx(is,{path:"*",element:t.jsx(ia,{to:"/dashboard",replace:!0})})]})})})})})})})}Fm({connectionManager:Jt});dd(document.getElementById("root")).render(t.jsx(vb,{}));