@adhdev/daemon-standalone 0.9.11 → 0.9.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +81 -44
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/index-CWraVFQO.js +76 -0
- package/public/index.html +1 -1
- package/public/assets/index-BbUILAkr.js +0 -76
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-Bv6gUGuY.js","assets/vendor-BRZ4K-AC.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
var Wl=Object.defineProperty;var Hl=(e,s,r)=>s in e?Wl(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var Ve=(e,s,r)=>Hl(e,typeof s!="symbol"?s+"":s,r);import{r as o,j as t,M as ua,a as ma,b as ui,c as mi,u as Is,R as St,d as zs,t as Fl,e as Ul,D as zl,f as Fn,g as Un,h as fa,i as Vl,k as Gl,B as ql,l as Yl,m as Yt,N as zn,n as Xl}from"./vendor-BRZ4K-AC.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const c of i.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).observe(document,{childList:!0,subtree:!0});function r(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(a){if(a.ep)return;a.ep=!0;const i=r(a);fetch(a.href,i)}})();function Jl(e={}){const s=Math.max(1,Math.floor(e.capacity||200)),r=[];return{record(n){const a={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...n,payload:n.payload?{...n.payload}:{}};return r.push(a),r.length>s&&r.splice(0,r.length-s),a},list(n={}){const a=Math.max(1,Math.floor(n.limit||100));return r.filter(i=>!n.interactionId||i.interactionId===n.interactionId).filter(i=>!n.topic||i.topic===n.topic).filter(i=>!n.kind||i.kind===n.kind).slice(-a).map(i=>({...i,payload:i.payload?{...i.payload}:{}}))},clear(){r.splice(0,r.length)}}}const js=Jl();function ao(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 Ql(e,s){return typeof e=="string"&&e.trim().length>0&&e!==s}function Zl(e,s){return Object.prototype.hasOwnProperty.call(e,s)}function fi(e,s){if(!e)return s??null;if(!s)return e??null;const r=Zl(e,"messages"),n=r?Array.isArray(e.messages)?e.messages:[]:s.messages,a=e.activeModal||(e.status==="waiting_approval"?s.activeModal:null),i={...s,...e,activeModal:a,inputContent:e.inputContent??s.inputContent};return r?{...i,messages:n}:i}function Bs(e,s){const r=Ql(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:fi(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 pi(e,s,r){if(!(s!=null&&s.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(s)?s:e;if(!(e!=null&&e.length))return s;const n=s.map(a=>{const i=e.find(c=>c.id===a.id);return i?Bs(a,i):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(s.map(i=>i.id));for(const i of e)a.has(i.id)||n.push(i)}return n}function oo(e){return!!e&&typeof e=="object"&&"text"in e}function pa(e,s){const r=(s==null?void 0:s.joiner)??" ",n=(s==null?void 0:s.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(i=>typeof i=="string"?i:oo(i)?String(i.text||""):"").join(r):oo(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Vs(e){return pa(e,{normalizeWhitespace:!0})}const hi=o.createContext({ides:[],updateRouteChats:()=>{},initialLoaded:!1,toasts:[],setToasts:()=>{},wsStatus:"connected",isConnected:!0,connectionStates:{},connectionTransports:{},showReconnected:!1,userName:void 0,setUserName:()=>{},isP2PActive:!1,p2pStates:{},userRole:void 0}),xi=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function io(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 bi(e,s,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=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 a&&(n.version=a),i&&(n.serverVersion=i),u&&(n.versionUpdateReason=u),a&&i&&a===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((s.versionMismatch===!0||c&&a&&i&&a!==i)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function ed(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 dn(e){if(!e||typeof e!="object")return"";const s=e,r=ed(Vs(s.content).slice(0,512));return[String(s.id||""),String(s._localId||""),String(s._turnKey||""),String(s.index??""),String(s.role||""),String(s.receivedAt??s.timestamp??""),r].join(":")}function td(e,s){if(!Array.isArray(e))return e;if(s!=null&&s.has(e))return{count:e.length,sharedRef:!0};let r=2166136261;for(const n of e){const a=dn(n);for(let i=0;i<a.length;i+=1)r^=a.charCodeAt(i),r=Math.imul(r,16777619)>>>0}return{count:e.length,hash:r.toString(16).padStart(8,"0"),first:dn(e[0]),last:dn(e[e.length-1])}}function Vn(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function Gn(e,s,r){if(!e||!s||typeof e!="object"||typeof s!="object")return;if(Vn(e)&&Vn(s)){const c=e.messages;Array.isArray(c)&&c===s.messages&&r.add(c)}if(Array.isArray(e)&&Array.isArray(s)){const c=Math.min(e.length,s.length);for(let l=0;l<c;l+=1)Gn(e[l],s[l],r);return}const n=e,a=s,i=new Set([...Object.keys(n),...Object.keys(a)]);for(const c of i)c!=="messages"&&Gn(n[c],a[c],r)}function Ks(e,s){return Array.isArray(e)?e.map(r=>Ks(r,s)):!e||typeof e!="object"?e:Vn(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?td(a,s):Ks(a,s)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,Ks(n,s)]))}function sd(e,s){try{const r=new WeakSet;return Gn(e,s,r),JSON.stringify(Ks(e,r))===JSON.stringify(Ks(s,r))}catch{return!1}}function qn(e,s,r){return sd(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function gi(e){var s;return e.daemonId||((s=e.id)==null?void 0:s.split(":")[0])||e.id}function rd(e,s,r){s[r]!==void 0&&(e[r]=s[r])}function co(e,s,r,n){var l;const a=(l=s.chats)!=null&&l.length?s.chats:e.chats,i=pi(e.childSessions,s.childSessions,{preserveMissing:n}),c=fi(s.activeChat,e.activeChat);return bi(e,s,{...e,...s,chats:a,childSessions:i,activeChat:c,_lastUpdate:r})}function nd(e,s,r){var a,i;const n={};s.status&&s.status!==e.status&&(n.status=s.status),s.cdpConnected!==void 0&&(n.cdpConnected=s.cdpConnected),s.childSessions!==void 0&&(n.childSessions=pi(e.childSessions,s.childSessions,{preserveMissing:r})),(a=s.chats)!=null&&a.length&&!((i=e.chats)!=null&&i.length)&&(n.chats=s.chats);for(const c of["title","workspace","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion"])rd(n,s,c);return s.machineNickname!==void 0&&s.machineNickname!==e.machineNickname&&(n.machineNickname=s.machineNickname),s.versionMismatch===!0&&(n.versionMismatch=!0),n}function ad(e,s,r,n){const a=nd(e,s,n),i=Object.keys(a).length>0?bi(e,s,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return qn(e,i,r)}function od(e){const s=new Set(e.map(a=>a.id)),r=new Set,n=new Set;for(const a of e){const i=gi(a);i&&r.add(i),i&&a.type!=="adhdev-daemon"&&n.add(i)}return{incomingIds:s,incomingDaemonIds:r,daemonIdsWithSessionEntries:n}}function id(e,s,r,n,a,i){return!a.has(s)||!i.has(s)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function cd(e,s,r,n){return!!(r.has(s)&&e.transport&&!n.has(s))}function ld(e,s,r){var f,d;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return e.map(h=>({...h,_lastUpdate:n}));const i=new Map;for(const h of s)i.set(h.id,h);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:u}=od(e);for(const h of e){const m=i.get(h.id);if(!m){i.set(h.id,{...h,_lastUpdate:n});continue}const j=io(h),S=io(m),p=gi(h),x=!a.has(p);if(j>S){const C=co(m,h,n,x);i.set(h.id,qn(m,C,n));continue}if(j<S){i.set(h.id,ad(m,h,n,x));continue}const v=h.timestamp||n,b=m._lastUpdate||m.timestamp||0;if(v>=b){const C=co(m,h,n,x);i.set(h.id,qn(m,C,n));continue}(f=h.chats)!=null&&f.length&&!((d=m.chats)!=null&&d.length)&&i.set(h.id,{...m,chats:h.chats})}for(const[h,m]of i){const j=m.daemonId||h.split(":")[0];if(!l.has(j))continue;if(a.has(j)&&!c.has(h)){i.delete(h);continue}const S=n-(m._lastUpdate||m.timestamp||0);id(m,j,S,c,a,u)&&i.delete(h)}for(const[h,m]of i){const j=m.daemonId||h.split(":")[0];if(cd(m,j,l,u))continue;n-(m._lastUpdate||m.timestamp||0)>3e5&&m.status!=="online"&&i.delete(h)}return Array.from(i.values())}function dd(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 ud({children:e,connectionOverrides:s}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[u,f]=o.useState(void 0),d=o.useRef(r);o.useEffect(()=>{d.current=r},[r]);const h=o.useCallback((v,b)=>{n(C=>{let A=!1;const y=C.map(I=>I.id!==v||I.chats===b?I:(A=!0,{...I,chats:b}));return A?y:C})},[]),m=o.useCallback((v,b)=>{n(C=>{const A=C.length===0?v:ld(v,C,b),y=!dd(C,A);return y&&js.record({kind:"dashboard.entries_applied",payload:{incoming:ao(v),next:ao(A)}}),y?A:C})},[]),j=o.useCallback(()=>i(!0),[]),S=o.useMemo(()=>({injectEntries:m,markLoaded:j,getIdes:()=>d.current}),[m,j]),p=s,x=o.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:a,toasts:c,setToasts:l,wsStatus:(p==null?void 0:p.wsStatus)??"connected",isConnected:(p==null?void 0:p.isConnected)??!0,connectionStates:(p==null?void 0:p.connectionStates)??{},connectionTransports:(p==null?void 0:p.connectionTransports)??{},showReconnected:(p==null?void 0:p.showReconnected)??!1,retryConnection:p==null?void 0:p.retryConnection,retryServerConnection:p==null?void 0:p.retryServerConnection,isP2PActive:(p==null?void 0:p.isP2PActive)??!1,p2pStates:(p==null?void 0:p.p2pStates)??{},userRole:p==null?void 0:p.userRole,userName:u,setUserName:f}),[r,h,a,c,p==null?void 0:p.wsStatus,p==null?void 0:p.isConnected,p==null?void 0:p.connectionStates,p==null?void 0:p.connectionTransports,p==null?void 0:p.showReconnected,p==null?void 0:p.retryConnection,p==null?void 0:p.retryServerConnection,p==null?void 0:p.isP2PActive,p==null?void 0:p.p2pStates,p==null?void 0:p.userRole,u]);return t.jsx(xi.Provider,{value:S,children:t.jsx(hi.Provider,{value:x,children:e})})}function cs(){return o.useContext(hi)}function Gs(){return o.useContext(xi)}function yi(e){const{baseUrl:s,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${s}${l.startsWith("/")?"":"/"}${l}`}function i(l){const u=r==null?void 0:r(),f=a(l),d=l.startsWith("http")?new URL(f):new URL(f,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 f={"Content-Type":"application/json",...u.headers||{}},d=r==null?void 0:r();d&&(f.Authorization=`Bearer ${d}`);const h=a(l),m=new AbortController,j=setTimeout(()=>m.abort(),15e3);try{const S=await fetch(h,{...u,headers:f,signal:m.signal});if(S.status===401)throw n==null||n(),new Error("Unauthorized");if(!S.ok){const p=await S.json().catch(()=>({error:S.statusText}));throw new Error(p.error||`API Error: ${S.status}`)}return S.json()}finally{clearTimeout(j)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,u,f={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:u,payload:f})}),execTerminal:(l,u,f)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:f})}),sendAgentMessage:(l,u,f)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:f})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,u,f)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:u,action:f?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,u,f={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:f})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const md=yi({baseUrl:"http://localhost:3847"}),fd=o.createContext(md);function pd({client:e,children:s}){return t.jsx(fd.Provider,{value:e,children:s})}const hd={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},vi=o.createContext(hd);function xd({value:e,children:s}){return t.jsx(vi.Provider,{value:e,children:s})}function jt(){return o.useContext(vi)}function bd(e){let s=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)s^=n.charCodeAt(a),s=Math.imul(s,16777619)>>>0;s^=255,s=Math.imul(s,16777619)>>>0}return s.toString(16).padStart(8,"0")}function gd(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function wi(e){return e?bd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),gd(e.content)]):""}const De={size:18};function ji({size:e=De.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 ha({size:e=De.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 ls({size:e=De.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 ki({size:e=De.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 yd({size:e=De.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 vd({size:e=De.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 Si({size:e=De.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 wd({size:e=De.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 Yr({size:e=De.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 Ni({size:e=De.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 jd({size:e=De.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 Ft({size:e=De.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 Ct({size:e=De.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 xa({size:e=De.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 kd({size:e=De.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 ks({size:e=De.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 er({size:e=De.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 qs({size:e=De.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 Ys({size:e=De.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 Ci({size:e=De.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 Ii({size:e=De.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 Mi({size:e=De.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 Sd({size:e=De.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 ba({size:e=De.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 Nd({size:e=De.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 ga({size:e=De.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 Ai({size:e=De.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 wt({size:e=De.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 Cd({size:e=De.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 Id({size:e=De.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 Md({size:e=De.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 Ad({size:e=De.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 Xr({size:e=De.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 Td({size:e=De.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 Ld({size:e=De.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 Rd({size:e=De.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 Pd({size:e=De.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 _d({size:e=De.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 Dd({size:e=De.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 Ed({size:e=De.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 $d({size:e=De.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 Bd({size:e=De.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 Kd({size:e=De.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 Od({size:e=De.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 Wd({size:e=De.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),t.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),t.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const un=new Map;function lo(e,s){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(s||""):!0}function Hd(e){if(!Array.isArray(e)||e.length===0)return"0:empty";const s=e[e.length-1];return`${e.length}:${wi(s)}`}function Fd(e,s){return!e&&s}function uo(e,s){const r=Math.max(0,e.scrollHeight-e.clientHeight-s.fromBottom);e.scrollTop=Number.isFinite(r)?r:s.top}function Ti(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Ud(e,s,r){return Number(e.receivedAt||r[Kr(e,s)]||0)||0}function Li(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function zd(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function dr(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 mn(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}):Li(e)?t.jsx(ua,{remarkPlugins:[ma,ui,mi],children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function ur({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 a=mn(r);return a?t.jsx("img",{src:a,alt:dr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=mn(r);return a?t.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=mn(r);return a?t.jsx("video",{controls:!0,src:a,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:dr(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||dr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=dr(r.resource.uri,"resource");if(r.resource.text)return t.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[t.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),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:a},`resource-uri-${n}`)}return null})})}function Kr(e,s){const r=e,n=pa(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 Vd=o.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(ua,{remarkPlugins:[ma],children:s.text}),t.jsx("span",{className:"action-time",children:Ti(s.timestamp)})]})},(e,s)=>e.log===s.log),Gd=o.memo(function({message:s,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var I,k,w;const u=(s.role||"").toLowerCase(),f=u==="user"||u==="human",d=s.kind||(u==="tool"?"tool":"standard"),h=zd(s.content)?s.content:null,m=!!(h!=null&&h.some(g=>g.type!=="text")),j=pa(s.content,{joiner:`
|
|
4
|
-
`});if(d==="thought"){const g=typeof((I=s.meta)==null?void 0:I.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(Md,{size:13}),t.jsx("span",{children:g})]}),t.jsx("div",{className:"chat-msg-body",children:j})]})}if(d==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),m&&h?t.jsx("div",{className:"tool-text w-full",children:t.jsx(ur,{parts:h,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:j})]});if(d==="terminal"){const g=(k=s.meta)!=null&&k.isRunning?"⏳":"✅",E=typeof((w=s.meta)==null?void 0:w.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:g}),t.jsx("span",{children:E})]}),m&&h?t.jsx("div",{className:"chat-msg-body",children:t.jsx(ur,{parts:h,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:j})]})}if(d==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:m&&h?t.jsx(ur,{parts:h,renderAsPreformatted:!1}):j.slice(0,100)});const S=s.meta,x=(typeof(S==null?void 0:S.renderMode)=="string"?S.renderMode.trim():"")==="preformatted",v=j,b=!1,C=v,A=x,y=!A&&Li(C);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${f?"self-end":"self-start"}`,children:(v||m||f)&&t.jsxs("div",{className:`chat-bubble ${f?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${v||m?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:f?a||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:Ti(r)})]}),(v||m)&&t.jsx("div",{className:"chat-markdown",children:m&&h?t.jsx(ur,{parts:h,renderAsPreformatted:A}):A?t.jsx("pre",{className:"chat-preformatted",children:C}):y?t.jsx(ua,{remarkPlugins:[ma,ui,mi],children:C}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:C})}),b]})})},(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=o.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:u={},emptyState:f,onLoadMore:d,isLoadingMore:h,hasMoreHistory:m,hiddenLiveCount:j=0,loadError:S,scrollToBottomRequestNonce:p,isVisible:x=!0},v){const b=o.useRef(null),C=o.useRef(null),A=o.useRef(null),y=o.useRef(0),I=o.useRef(""),k=o.useRef(!1),w=o.useRef(null),g=o.useRef(!1),E=o.useRef(null),T=o.useRef(!1),[M,P]=o.useState(new Set),K=o.useRef(!1),U=o.useRef(!1),L=o.useRef(x),R=()=>{const V=b.current;return V?V.scrollHeight-V.scrollTop-V.clientHeight<200:!0},z=o.useCallback((V="auto")=>{const Q=b.current;Q&&Q.scrollTo({top:Q.scrollHeight,behavior:V})},[]),$=o.useCallback(()=>{var le;const V=b.current,Q=(le=window.getSelection)==null?void 0:le.call(window);if(!V||!Q||Q.rangeCount===0||Q.isCollapsed){T.current=!1;return}const ue=Q.anchorNode,re=Q.focusNode;T.current=!!(ue&&re&&V.contains(ue)&&V.contains(re))},[]),_=Hd(s),Y=o.useCallback(()=>{const V=b.current;!V||!l||un.set(l,{top:V.scrollTop,fromBottom:Math.max(0,V.scrollHeight-V.scrollTop-V.clientHeight),messageFingerprint:_})},[l,_]),J=o.useCallback((V="auto")=>{w.current!=null&&cancelAnimationFrame(w.current),w.current=requestAnimationFrame(()=>{w.current=null,z(V)})},[z]),pe=o.useCallback(()=>{K.current=!1,g.current=!0,U.current=!0,E.current!=null&&window.clearTimeout(E.current),E.current=window.setTimeout(()=>{g.current=!1,E.current=null},180)},[]);o.useEffect(()=>{const V=!k.current,Q=I.current!==l;if(I.current=l,V||Q){if(k.current=!0,K.current=!1,g.current=!0,!T.current){const re=l?un.get(l):null;re&&lo(re,_)?requestAnimationFrame(()=>{const le=b.current;le&&(uo(le,re),U.current=!0)}):J("auto")}y.current=s.length;return}s.length>y.current?!K.current&&!T.current&&J("auto"):R()&&!K.current&&!T.current&&J("auto"),y.current=s.length},[_,l,c,s.length,J]),o.useEffect(()=>{p&&(pe(),T.current||J("auto"))},[pe,J,p]),o.useEffect(()=>{const V=L.current;L.current=x,Fd(V,x)&&(pe(),T.current||J("auto"))},[x,pe,J]),o.useEffect(()=>()=>{Y(),w.current!=null&&cancelAnimationFrame(w.current),E.current!=null&&window.clearTimeout(E.current)},[Y]),o.useEffect(()=>{const V=C.current;if(!V)return;const Q=()=>{E.current!=null&&window.clearTimeout(E.current),E.current=window.setTimeout(()=>{g.current=!1,E.current=null},180)},ue=new ResizeObserver(()=>{g.current&&(T.current||(J("auto"),Q()))});return ue.observe(V),()=>{ue.disconnect(),E.current!=null&&(window.clearTimeout(E.current),E.current=null)}},[J,l]),o.useImperativeHandle(v,()=>({scrollToBottom:(V="smooth")=>{z(V)}}),[z]),o.useEffect(()=>{const V=b.current;if(!V)return;let Q;const ue=()=>{clearTimeout(Q),Q=setTimeout(()=>{K.current=!R(),Y()},50)};return V.addEventListener("scroll",ue,{passive:!0}),()=>{V.removeEventListener("scroll",ue),clearTimeout(Q)}},[Y]),o.useEffect(()=>(document.addEventListener("selectionchange",$),()=>document.removeEventListener("selectionchange",$)),[$]);const ae=o.useRef(0),be=o.useRef(!1);o.useEffect(()=>{const V=b.current;if(!V||!be.current||ae.current===0)return;const Q=V.scrollHeight-ae.current;Q>0&&(V.scrollTop=Q),Y(),ae.current=0,be.current=!1},[s.length,Y]),o.useEffect(()=>{if(U.current||!l)return;const V=un.get(l),Q=b.current;if(!(!V||!Q)){if(!lo(V,_)){z("auto"),U.current=!0;return}uo(Q,V),U.current=!0}},[l,_,s.length,z]);const ye=()=>{const V=b.current;V&&(ae.current=V.scrollHeight),be.current=!0,d==null||d()},ve=o.useMemo(()=>{const V=s.map((le,se)=>({type:"message",data:le,index:se,ts:Ud(le,se,u)}));if(!r||r.length===0)return V;const Q=[...r].sort((le,se)=>le.timestamp-se.timestamp).map((le,se)=>({type:"action",data:le,index:se,ts:le.timestamp})),ue=[];let re=0;for(const le of V){for(;re<Q.length&&le.ts>0&&Q[re].ts<le.ts;)ue.push(Q[re++]);ue.push(le)}for(;re<Q.length;)ue.push(Q[re++]);return ue},[s,r,u]),Ie=j>0||!!m,H=j>0?`↑ Show ${Math.min(j,80)} earlier messages${j>80?` (${j} hidden)`:""}`:S?`↻ ${S}`:"↑ Load older messages";return t.jsx("div",{ref:b,"data-chat-scroll":!0,className:"chat-container",children:t.jsxs("div",{ref:C,className:"chat-container-content",children:[h&&t.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),Ie&&!h&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{onClick:ye,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${S&&j===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:H})}),ve.length===0&&!Ie&&(f||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),ve.map(V=>{if(V.type==="action"){const ne=V.data;return t.jsx(Vd,{log:ne},`action-${V.index}`)}const Q=V.data,ue=V.index,re=Kr(Q,ue),le=Q.receivedAt||u[re],se=`${l}-${re}`,me=M.has(se);return t.jsx(Gd,{message:Q,receivedAt:le,agentName:n,userName:a,isCliMode:i,isTextExpanded:me,onToggleTextExpanded:()=>P(ne=>{const ce=new Set(ne);return me?ce.delete(se):ce.add(se),ce})},`msg-${re}`)}),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:A})]})})}),Yd=o.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&&e.isVisible===s.isVisible),Xd="modulepreload",Jd=function(e){return"/"+e},fo={},Qd=function(s,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=Promise.allSettled(r.map(u=>{if(u=Jd(u),u in fo)return;fo[u]=!0;const f=u.endsWith(".css"),d=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const h=document.createElement("link");if(h.rel=f?"stylesheet":Xd,f||(h.as="script"),h.crossOrigin="",h.href=u,l&&h.setAttribute("nonce",l),document.head.appendChild(h),f)return new Promise((m,j)=>{h.addEventListener("load",m),h.addEventListener("error",()=>j(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 a.then(c=>{for(const l of c||[])l.status==="rejected"&&i(l.reason);return s().catch(i)})};let po=!1;const Ri=o.forwardRef(({onInput:e,onViewportMetrics:s,fontSize:r=13,readOnly:n=!1,sizingMode:a="measured"},i)=>{const c=o.useRef(null),[l,u]=o.useState(null),f=o.useRef([]),d=o.useRef(!1),h=o.useRef(!1),m=o.useRef(!1),j=()=>{const S=c.current;if(S){d.current&&(S.clear(),d.current=!1);for(const p of f.current)S.write(p);f.current=[],h.current&&(S.fit(),h.current=!1),m.current&&(S.bumpResize(),m.current=!1)}};return o.useImperativeHandle(i,()=>({write:S=>{c.current?c.current.write(S):f.current.push(S)},clear:()=>{c.current?c.current.clear():(f.current=[],d.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(f.current=[],d.current=!0)},resize:(S,p)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(S,p)},fit:()=>{c.current?c.current.fit():h.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():m.current=!0}}),[]),o.useEffect(()=>{l&&j()},[l]),o.useEffect(()=>{let S=!1;return Qd(()=>import("./terminal-Bv6gUGuY.js"),__vite__mapDeps([0,1,2])).then(p=>{po||(po=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),S||u(()=>p.GhosttyTerminalView)}).catch(p=>{console.error("[CliTerminal] failed to load terminal renderer",p)}),()=>{S=!0}},[]),l?t.jsx(l,{ref:c,onInput:e,onViewportMetrics:s,fontSize:r,readOnly:n,sizingMode:a,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"}})});Ri.displayName="CliTerminal";function mr({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 ho({value:e,max:s,label:r,color:n="#8b5cf6",detail:a,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)`}})}),a&&t.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function Zd({cursorPos:e,viewportRef:s,imgRef:r}){var b;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(b=s.current)==null?void 0:b.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,u=c/l,f=a.width/a.height;let d,h,m,j;u>f?(d=a.width,h=a.width/u,m=0,j=(a.height-h)/2):(h=a.height,d=a.height*u,m=(a.width-d)/2,j=0);const S=a.left-i.left+m+d*e.nx,p=a.top-i.top+j+h*e.ny,x=Math.max(8,Math.min(i.width-8,S)),v=Math.max(8,Math.min(i.height-8,p));return t.jsxs("div",{style:{position:"absolute",left:x-8,top:v-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 eu({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:u,isConnActive:f,zoom:d,isMobile:h,mobileFillZoom:m,onZoomOut:j,onZoomReset:S,onZoomIn:p,transportType:x,screenshotUsage:v,lastActionStatus:b}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:C=>C.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[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(C=>!C),i(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children: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:C=>C.stopPropagation(),onChange:C=>l(C.target.value),onKeyDown:C=>{u(C)},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(C=>!C),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children: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:f?"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:f?"#22c55e":"#eab308",boxShadow:f?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:f?"#22c55e":"#eab308"},children:f?"Connected":"WS"})]}),d>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),x==="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"}),x==="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"}),v&&v.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:v.budgetExhausted?"#ef4444":"#c4b5fd",background:v.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:v.budgetExhausted?"TURN blocked":`TURN ${v.dailyUsedMinutes}/${v.dailyBudgetMinutes}m`}),b&&t.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:b})]})]}),a&&t.jsxs("div",{onTouchStart:C=>C.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[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<=(h?m:1)+.01?h?"FILL":"FIT":`${Math.round(d*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:C=>{C.stopPropagation(),j()},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:C=>{C.stopPropagation(),S()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:h?"FILL":"FIT"}),t.jsx("button",{onClick:C=>{C.stopPropagation(),p()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function tu({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 su(){if(typeof window>"u")return!1;try{return window.__ADHDEV_DEBUG_RENDERS__===!0||window.localStorage.getItem("adhdev_debug_renders")==="1"}catch{return window.__ADHDEV_DEBUG_RENDERS__===!0}}function xo(e){return e==null||typeof e=="number"||typeof e=="boolean"?e:typeof e=="string"?e.length>64?`${e.slice(0,61)}...`:e:Array.isArray(e)?`Array(${e.length})`:typeof e=="object"?"Object":typeof e}function tr(e,s){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!su())return;n.current+=1;const a=r.current;if(!a){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(s).map(([c,l])=>[c,xo(l)]))}),r.current=s;return}const i=Object.keys({...a,...s}).filter(c=>!Object.is(a[c],s[c]));i.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:i,snapshot:Object.fromEntries(i.map(c=>[c,xo(s[c])]))}),r.current=s})}function ru({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:u,setPanX:f,setPanY:d,setZoom:h,lastWheelTimeRef:m,onAction:j,setLastActionStatus:S,spawnRippleFromNormalized:p,clampPan:x,isMobile:v,mobileFillZoom:b}){const[C,A]=o.useState(null),y=o.useRef(null),I=o.useRef(null),k=o.useRef(null),w=o.useRef(!1),g=o.useRef(null),E=o.useRef(0),T=o.useRef(null),M=o.useRef(1),P=o.useRef({x:0,y:0}),K=o.useRef(!1),U=o.useRef(n),L=o.useRef(j),R=30,z=550,$=18,_=60,Y=400,J=12,pe=()=>{if(y.current)return;const ye={nx:.5,ny:.5};y.current=ye,A(ye)};return o.useEffect(()=>{U.current=n,n==="mouse"&&pe()},[n]),o.useEffect(()=>{L.current=j},[j]),o.useEffect(()=>{const ye=e.current;if(!ye)return;const ve=re=>{if(!r.current)return null;const le=r.current.getBoundingClientRect();return!le.width||!le.height?null:{nx:Math.max(0,Math.min(1,(re.clientX-le.left)/le.width)),ny:Math.max(0,Math.min(1,(re.clientY-le.top)/le.height))}},Ie=(re,le)=>{if(!r.current)return{dnx:0,dny:0};const se=r.current,me=se.getBoundingClientRect(),ne=se.naturalWidth||me.width,ce=se.naturalHeight||me.height,oe=ne/ce,we=me.width/me.height;let he,Se;return oe>we?(he=me.width,Se=me.width/oe):(Se=me.height,he=me.height*oe),{dnx:re/he,dny:le/Se}},H=(re,le,se)=>{if(se<=1.05)return;const me=-(re-.5)*100,ne=-(le-.5)*100,ce=x(me,ne,se);(Math.abs(ce.x-l.current)>.1||Math.abs(ce.y-u.current)>.1)&&(f(ce.x),d(ce.y),l.current=ce.x,u.current=ce.y)},V=re=>{const le=s.current;if(le&&re.target instanceof Node&&le.contains(re.target))re.preventDefault();else return;if(re.touches.length===1){const se=re.touches[0];I.current={x:se.clientX,y:se.clientY,time:Date.now()},k.current={x:se.clientX,y:se.clientY},K.current||(w.current=!1),g.current=setTimeout(()=>{if(!w.current&&!K.current)if(w.current=!0,U.current==="mouse"){const me=y.current||{nx:.5,ny:.5};S("Right Click"),p(me.nx,me.ny,"right"),L.current("input_click",{...me,button:"right"}).catch(()=>{})}else{const me=ve(se);me&&(S("Right Click"),p(me.nx,me.ny,"right"),L.current("input_click",{...me,button:"right"}).catch(()=>{}))}},500);return}if(re.touches.length===2){g.current&&clearTimeout(g.current),w.current=!0,K.current=!0;const se=re.touches[1].clientX-re.touches[0].clientX,me=re.touches[1].clientY-re.touches[0].clientY;T.current=Math.sqrt(se*se+me*me),M.current=c.current,P.current={x:(re.touches[0].clientX+re.touches[1].clientX)/2,y:(re.touches[0].clientY+re.touches[1].clientY)/2}}},Q=re=>{const le=s.current;if(le&&re.target instanceof Node&&le.contains(re.target)&&re.preventDefault(),re.touches.length===1&&k.current){const se=re.touches[0],me=se.clientX-k.current.x,ne=se.clientY-k.current.y;if(!w.current&&I.current){const ce=se.clientX-I.current.x,oe=se.clientY-I.current.y;Math.sqrt(ce*ce+oe*oe)>8&&(w.current=!0,g.current&&clearTimeout(g.current))}if(w.current)if(U.current==="mouse"){const ce=Ie(me,ne),oe=y.current||{nx:.5,ny:.5},we=Math.max(0,Math.min(1,oe.nx+ce.dnx)),he=Math.max(0,Math.min(1,oe.ny+ce.dny));y.current={nx:we,ny:he},A({nx:we,ny:he}),S(`Cursor: ${Math.round(we*100)}%, ${Math.round(he*100)}%`),H(we,he,c.current);const Se=Date.now();Se-m.current>=30&&(m.current=Se,L.current("input_mouseMoved",{nx:we,ny:he}).catch(()=>{}))}else if(c.current>1){const ce=s.current;if(ce){const oe=ce.clientWidth,we=ce.clientHeight,he=l.current+me/oe*100,Se=u.current+ne/we*100,N=x(he,Se,c.current);f(N.x),d(N.y),l.current=N.x,u.current=N.y}}else{const ce=ve(se);if(ce){const oe=Date.now();oe-m.current>=40&&(m.current=oe,S("Scroll"),L.current("input_wheel",{nx:ce.nx,ny:ce.ny,deltaX:Math.round(-me*2.5),deltaY:Math.round(-ne*2.5)}).catch(()=>{}))}}k.current={x:se.clientX,y:se.clientY};return}if(re.touches.length===2&&T.current!==null){const se=re.touches[1].clientX-re.touches[0].clientX,me=re.touches[1].clientY-re.touches[0].clientY,ce=Math.sqrt(se*se+me*me)/T.current,oe=(re.touches[0].clientX+re.touches[1].clientX)/2,we=(re.touches[0].clientY+re.touches[1].clientY)/2,he=oe-P.current.x,Se=we-P.current.y,N=Math.abs(ce-1)>.03;if(U.current==="mouse"){if(N){const O=Math.max(i,Math.min(5,M.current*ce));h(O),c.current=O}else if(Math.abs(he)>2||Math.abs(Se)>2){const O=y.current||{nx:.5,ny:.5},G=Date.now();G-m.current>=30&&(m.current=G,S("Scroll"),L.current("input_wheel",{nx:O.nx,ny:O.ny,deltaX:Math.round(-he*3),deltaY:Math.round(-Se*3)}).catch(()=>{}))}}else{const O=Math.max(i,Math.min(5,M.current*ce));h(O),c.current=O;const G=s.current;if(G&&O>1){const Z=G.clientWidth,fe=G.clientHeight,ge=l.current+he/Z*100,Pe=u.current+Se/fe*100,Ee=x(ge,Pe,O);f(Ee.x),d(Ee.y),l.current=Ee.x,u.current=Ee.y}}P.current={x:oe,y:we}}},ue=re=>{var le;if(g.current&&clearTimeout(g.current),T.current=null,re.touches.length===1&&K.current){const se=re.touches[0];I.current={x:se.clientX,y:se.clientY,time:Date.now()},k.current={x:se.clientX,y:se.clientY},w.current=!0;return}if(re.touches.length===0){if(K.current){K.current=!1,w.current=!1;return}if(re.changedTouches.length===1){const se=re.changedTouches[0],me=Date.now(),ne=me-(((le=I.current)==null?void 0:le.time)||0),ce=I.current?se.clientX-I.current.x:0,oe=I.current?se.clientY-I.current.y:0,we=Math.sqrt(ce*ce+oe*oe);if(U.current==="mouse"){if(ne<R||ne>z||we>$){w.current=!1;return}const he=y.current||ve(se);he&&(S(`Click: ${Math.round(he.nx*100)}%, ${Math.round(he.ny*100)}%`),p(he.nx,he.ny,"left"),L.current("input_click",{...he}).catch(()=>{}))}else{if(w.current){w.current=!1;return}if(ne<_||ne>Y||we>J){w.current=!1;return}const he=ve(se);if(!he)return;me-E.current<300?(S("Double tap"),p(he.nx,he.ny,"double"),L.current("input_click",{...he,clickCount:2}).catch(()=>{}),E.current=0):(S(`Tap: ${Math.round(he.nx*100)}%, ${Math.round(he.ny*100)}%`),p(he.nx,he.ny,"left"),L.current("input_click",{...he}).catch(()=>{}),E.current=me)}}w.current=!1}};return ye.addEventListener("touchstart",V,{passive:!1}),ye.addEventListener("touchmove",Q,{passive:!1}),ye.addEventListener("touchend",ue,{passive:!1}),()=>{ye.removeEventListener("touchstart",V),ye.removeEventListener("touchmove",Q),ye.removeEventListener("touchend",ue),g.current&&clearTimeout(g.current)}},[e,s,r,i,c,l,u,f,d,h,m,S,p,x]),{cursorPos:C,cursorPosRef:y,handleToggleInputMode:()=>{a(ye=>{const ve=ye==="touch"?"mouse":"touch";return ve==="mouse"&&pe(),ve})},handleZoomReset:()=>{const ye=v?b:1;h(ye),c.current=ye,f(0),d(0),l.current=0,u.current=0}}}function Pi({onAction:e,addLog:s,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),u=o.useRef(null),[f,d]=o.useState(null),[h,m]=o.useState(""),[,j]=o.useState(!1),[S,p]=o.useState([]),x=o.useRef(0),[v,b]=o.useState(!1),[C,A]=o.useState(!1),y=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[I,k]=o.useState(y?"mouse":"touch"),[w,g]=o.useState(1),E=o.useRef(!1),[T,M]=o.useState(1),[P,K]=o.useState(0),[U,L]=o.useState(0);tr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:I,zoom:T,panX:P,panY:U,isMenuOpen:v,isImeOpen:C});const R=o.useRef(0),z=o.useRef(T),$=o.useRef(P),_=o.useRef(U);o.useEffect(()=>{z.current=T},[T]),o.useEffect(()=>{$.current=P},[P]),o.useEffect(()=>{_.current=U},[U]),o.useEffect(()=>{var ne;(ne=c.current)==null||ne.focus()},[]);const Y=r==="connected",J=n,pe=Y?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ae=Y?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!y||E.current||!J)return;const ne=u.current,ce=l.current;if(!ne||!ce)return;const oe=()=>{const we=ce.clientWidth,he=ce.clientHeight,Se=ne.naturalWidth,N=ne.naturalHeight;if(!Se||!N||!we||!he)return;const O=Math.min(we/Se,he/N),Z=Math.max(we/Se,he/N)/O;Z>1.01&&(g(Z),M(Z),z.current=Z),E.current=!0};ne.complete&&ne.naturalWidth?oe():ne.addEventListener("load",oe,{once:!0})},[J,y]);const be=.5;o.useEffect(()=>{T<=be&&(K(0),L(0))},[T,be]);const ye=(ne,ce,oe)=>{if(oe<=be)return{x:0,y:0};const we=(oe-1)/(2*oe)*100,he=(oe-1)/(2*oe)*100;return{x:Math.max(-we,Math.min(we,ne)),y:Math.max(-he,Math.min(he,ce))}},ve=(ne,ce)=>{if(!u.current)return null;const oe=u.current.getBoundingClientRect();return!oe.width||!oe.height?null:{nx:Math.max(0,Math.min(1,(ne-oe.left)/oe.width)),ny:Math.max(0,Math.min(1,(ce-oe.top)/oe.height))}},Ie=(ne,ce,oe)=>{const we=l.current;if(!we)return;const he=we.getBoundingClientRect(),Se=++x.current;p(N=>[...N,{id:Se,x:ne-he.left,y:ce-he.top,type:oe}]),setTimeout(()=>p(N=>N.filter(O=>O.id!==Se)),600)},H=(ne,ce,oe)=>{const we=u.current,he=l.current;if(!we||!he)return;const Se=we.getBoundingClientRect(),N=he.getBoundingClientRect(),O=we.naturalWidth||Se.width,G=we.naturalHeight||Se.height,Z=O/G,fe=Se.width/Se.height;let ge,Pe,Ee,We;Z>fe?(ge=Se.width,Pe=Se.width/Z,Ee=0,We=(Se.height-Pe)/2):(Pe=Se.height,ge=Se.height*Z,Ee=(Se.width-ge)/2,We=0);const ze=Se.left-N.left+Ee+ge*ne,Qe=Se.top-N.top+We+Pe*ce,Ze=++x.current;p(it=>[...it,{id:Ze,x:ze,y:Qe,type:oe}]),setTimeout(()=>p(it=>it.filter(yt=>yt.id!==Ze)),600)},V=async ne=>{var oe;const ce=ve(ne.clientX,ne.clientY);if(ce){d(`Click: ${Math.round(ce.nx*100)}%, ${Math.round(ce.ny*100)}%`),Ie(ne.clientX,ne.clientY,"left"),(oe=c.current)==null||oe.focus();try{const we=await e("input_click",{nx:ce.nx,ny:ce.ny});we!=null&&we.success||s(`❌ Click failed: ${we==null?void 0:we.error}`)}catch(we){s(`❌ Click error: ${we.message||we}`)}}},Q=async(ne,ce,oe,we=0)=>{try{await e("input_key",{type:oe?"char":"keyDown",key:ne,code:ce,text:oe?ne:void 0,unmodifiedText:oe?ne:void 0,modifiers:we})}catch(he){s(`❌ Key error: ${he.message||he}`)}},ue=async ne=>{if(ne.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ne.key)&&ne.preventDefault();let oe=0;ne.altKey&&(oe|=1),ne.ctrlKey&&(oe|=2),ne.metaKey&&(oe|=4),ne.shiftKey&&(oe|=8),d(`Key: ${ne.key}`),await Q(ne.key,ne.code,ne.key.length===1,oe)},re=async ne=>{if(ne.key==="Enter"){if(ne.nativeEvent.isComposing)return;if(h){const ce=h;m(""),d(`IME Sent: ${ce}`);try{const oe=await e("input_type",{text:ce});oe!=null&&oe.success||s(`❌ IME error: ${oe==null?void 0:oe.error}`)}catch(oe){s(`❌ IME error: ${oe.message}`)}}else d("Key: Enter"),await Q("Enter","Enter",!1)}};o.useEffect(()=>{const ne=c.current;if(!ne)return;const ce=oe=>{var we;if((we=u.current)!=null&&we.contains(oe.target)){oe.preventDefault();const he=Date.now();if(he-R.current<40)return;R.current=he;const Se=ve(oe.clientX,oe.clientY);if(!Se)return;d(`Scroll: ${Math.round(oe.deltaY)}`),e("input_wheel",{nx:Se.nx,ny:Se.ny,deltaX:Math.round(oe.deltaX),deltaY:Math.round(oe.deltaY)}).catch(()=>{})}};return ne.addEventListener("wheel",ce,{passive:!1}),()=>ne.removeEventListener("wheel",ce)},[e]);const{cursorPos:le,handleToggleInputMode:se,handleZoomReset:me}=ru({containerRef:c,viewportRef:l,imgRef:u,inputMode:I,setInputMode:k,minZoom:be,zoomRef:z,panXRef:$,panYRef:_,setPanX:K,setPanY:L,setZoom:M,lastWheelTimeRef:R,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:H,clampPan:ye,isMobile:y,mobileFillZoom:w});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ue,onContextMenu:ne=>ne.preventDefault(),onFocus:()=>j(!0),onBlur:()=>j(!1),tabIndex:0,children:[t.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[J?t.jsx("img",{ref:u,src:J,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${T}) translate(${P}%, ${U}%)`,transformOrigin:"center center",cursor:I==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:V,onContextMenu:ne=>ne.preventDefault(),onDragStart:ne=>ne.preventDefault()}):t.jsx(tu,{waitingLabel:pe,waitingHint:ae,transportType:i}),I==="mouse"&&J&&t.jsx(Zd,{cursorPos:le,viewportRef:l,imgRef:u}),S.map(ne=>{const oe={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ne.type];return t.jsxs("div",{style:{position:"absolute",left:ne.x,top:ne.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${oe}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),t.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${oe}, 0.9)`,boxShadow:`0 0 12px rgba(${oe}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ne.id)})]}),t.jsx(eu,{inputMode:I,onToggleInputMode:se,isImeOpen:C,setIsImeOpen:A,isMenuOpen:v,setIsMenuOpen:b,imeText:h,setImeText:m,handleImeSubmit:re,isConnActive:Y,zoom:T,isMobile:y,mobileFillZoom:w,onZoomOut:()=>M(ne=>Math.max(.5,ne-.25)),onZoomReset:me,onZoomIn:()=>M(ne=>Math.min(5,ne+.25)),transportType:i,screenshotUsage:a,lastActionStatus:f}),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 Jr(e,s={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=s,i=Date.now()-e,c=Math.floor(i/1e3);if(c<a)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const u=Math.floor(l/60);if(u<24)return`${u}h${r}`;const f=Math.floor(u/24);return f<7?`${f}d${r}`:new Date(e).toLocaleDateString()}const _i=e=>Jr(e);function nu(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 Ms(e){const s=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",a=e.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:a}}function au(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...nu(a)})};for(const n of e)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const a of n.childSessions||[])r(a.id,a)}return s}function Or(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 Qr(e,s,r){const n=Or(e,s),a=Ms(e),i=a.isReconnecting,c=a.isConnecting,l=a.isGenerating,u=a.isWaiting,f=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||u,d=n.inboxBucket==="working"||l,m=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:m,requiresAction:f,isWorking:d,isReconnecting:i,isConnecting:c,isGenerating:l,isWaiting:u,inboxBucket:f?"needs_attention":d?"working":m?"task_complete":"idle"}}function ou(e,s,r){return Qr(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Di({activeConv:e,onModalButton:s}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Ms(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(qs,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,u)=>{const f=c(l).toLowerCase(),d=/^(run|approve|accept|yes|allow|always)/.test(f),h=/^(reject|deny|delete|remove|abort)/.test(f),m=r===l,j=r!==null;return t.jsx("button",{onClick:()=>i(l),disabled:j,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${d?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${j&&!m?"opacity-40":"opacity-100"} ${j?"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)"}:h?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:m?"⏳ ...":c(l)},u)})})]})]})}const ya="adhdev_controls_bar_visible",Yn="adhdev:controlsbarvisibilitychange";function fn(e){if(!e)return!1;try{return e.getItem(ya)==="1"}catch{return!1}}function bo(e,s){if(s)try{s.setItem(ya,e?"1":"0")}catch{}}function go(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Yn,{detail:{visible:e}}))}function Ei(){const[e,s]=o.useState(()=>typeof window>"u"?!1:fn(window.localStorage));o.useEffect(()=>{const a=c=>{const l=c.detail;if(typeof(l==null?void 0:l.visible)=="boolean"){s(l.visible);return}s(fn(window.localStorage))},i=c=>{c.key===ya&&s(fn(window.localStorage))};return window.addEventListener(Yn,a),window.addEventListener("storage",i),()=>{window.removeEventListener(Yn,a),window.removeEventListener("storage",i)}},[]);const r=o.useCallback(a=>{s(a),typeof window<"u"&&bo(a,window.localStorage),go(a)},[]),n=o.useCallback(()=>{s(a=>{const i=!a;return typeof window<"u"&&bo(i,window.localStorage),go(i),i})},[]);return{isVisible:e,setVisibility:r,toggleVisibility:n}}var iu=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function cu(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function bt(e,s){if(cu(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":iu.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 $i(e){return bt(e)==="generating"}function tt(e){return e?e.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" "):"IDE"}function lu(e){if(e<60)return`${Math.round(e)}s`;const s=Math.floor(e/60);if(s<60)return`${s}m`;const r=Math.floor(s/60),n=s%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const a=Math.floor(r/24),i=r%24;return`${a}d ${i}h`}function pn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Zr(e,s){const r=typeof s=="string"?s.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const a=n.replace(/[\\/]+$/,""),i=a.split(/[\\/]/).filter(Boolean);return i[i.length-1]||a}function du(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 uu(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function mu(e){return du(e.trim().replace(/\.local$/i,""))}function fu(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function Bi(e,s={}){var a,i;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(i=e.system)==null?void 0:i.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!uu(c));if(r&&r!=="Unknown")return mu(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function Tt(e,s={}){return fu(e)||Bi(e,s)}function Ki(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 Oi(e,s,r={}){const n=String(s).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(i=>String((i==null?void 0:i.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function ds(e,s){return Ki(e).join(" · ")}function Xs(e){return e.transport==="pty"}function gs(e){return e.transport==="acp"}function pu(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:tt(e)}function yo(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=tt(r||"").trim().toLowerCase();return n===a||n===i||n===c}function hu(e){return bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function xu(e){if(!Array.isArray(e)||e.length<=1)return e;const s=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),i=s.get(a),c=bt(n.status);if(!i){s.set(a,{...n,status:c});continue}const l=r.indexOf(i.status||"idle"),u=r.indexOf(c||"idle");u>=0&&(l<0||u<l)&&s.set(a,{...n,status:c})}return Array.from(s.values())}function bu(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 gu(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&&bu(s.receivedAt)||0}function yu(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Xn(e){return Math.max(yu(e),gu(e.activeChat))}function vu(e,s,r,n,a,i){const c=s-e;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:a.localeCompare(i)}function va(e,s){return vu(Xn(e),Xn(s),Tt(e,{fallbackId:e.id}),Tt(s,{fallbackId:s.id}),e.id,s.id)}const Wi="adhdev_notification_prefs",vo={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function wu(){try{const e=localStorage.getItem(Wi);if(e){const s=JSON.parse(e);return{...vo,...s}}}catch{}return{...vo}}function ju(e){try{localStorage.setItem(Wi,JSON.stringify(e))}catch{}}let Wt=wu(),Ar=[];function ku(){Ar.forEach(e=>e())}function Su(e){Wt={...Wt,...e},ju(Wt),ku()}function Nu(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Ar.push(r),()=>{Ar=Ar.filter(n=>n!==r)}},[]);const s=o.useCallback(r=>{Su(r)},[]);return[{...Wt},s]}function Os(e){if(!Wt.globalEnabled)return!1;switch(e){case"disconnect":return Wt.disconnectAlert;case"completion":return Wt.completionAlert;case"approval":return Wt.approvalAlert;case"browser":return Wt.browserNotifications;default:return!0}}const Cu={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Hi(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Fi(){return"Notification"in window&&Notification.permission==="granted"}let Xt=null;async function Iu(){if(Xt!==null)return Xt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Xt=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Xt=!!await e.pushManager.getSubscription(),Xt):(Xt=!1,!1)}catch{return Xt=!1,!1}}function Jn(e,s,r){if(Fi())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 Mu(e,s={}){const r={...Cu,...s},n=o.useRef(new Map),a=o.useRef(0),i=o.useRef(null);o.useEffect(()=>{Iu().then(l=>{i.current=l})},[]);const c=o.useCallback((l,u,f)=>{const d=Date.now();d-a.current<r.throttleMs||(a.current=d,Jn(l,u,f))},[r.throttleMs]);o.useEffect(()=>{var l;if(!(!r.enabled||!Fi())&&Os("browser")&&i.current!==!0){if(document.hasFocus()){for(const u of e)n.current.set(u.id,bt(u.status,{activeModal:u.activeModal}));return}for(const u of e){const f=n.current.get(u.id),d=bt(u.status,{activeModal:u.activeModal}),h=u.name||u.id;if(r.onApproval&&Os("approval")&&d==="waiting_approval"&&f!=="waiting_approval"){const m=((l=u.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${h} — Approval needed`,m.slice(0,120),`approval-${u.id}`)}r.onComplete&&Os("completion")&&$i(f)&&d==="idle"&&c(`✅ ${h} — Task complete`,"Agent has finished generating",`complete-${u.id}`),r.onError&&d==="error"&&f!=="error"&&c(`⚠️ ${h} — 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 Au=/^(run|approve|accept|yes|allow|always)/,Tu=/^(run|approve|accept|yes|allow|always|proceed|save)/,Lu=/^(reject|deny|delete|remove|abort|cancel|no)/;function wa(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Ru(e){const s=wa(e).toLowerCase();return Au.test(s)?"primary":Lu.test(s)?"danger":"default"}function Pu(e){return Tu.test(wa(e).toLowerCase())?"approve":"reject"}function _u(e){return e.map((s,r)=>({label:wa(s),variant:Ru(s),action:Pu(s),button:s,buttonIndex:r}))}function Du(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Eu(e,s,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,s,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,s,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class $u{constructor(){Ve(this,"dedupMap",new Map);Ve(this,"DEDUP_WINDOW_MS",5e3);Ve(this,"DEDUP_MAX_SIZE",50);Ve(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ve(this,"toastCallbacks",[]);Ve(this,"resolveActionFn",null);Ve(this,"viewRequestRespondFn",null);Ve(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==s)}}setResolveAction(s){this.resolveActionFn=s}setIdes(s){this.ides=s}setViewRequestRespond(s){this.viewRequestRespondFn=s}emitToast(s){for(const r of this.toastCallbacks)r(s)}showToast(s,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:s,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(s){const r=Date.now(),n=this.dedupMap.get(s)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(s,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,i]of this.dedupMap)r-i>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(s){if(s.daemonId){const a=this.ides.find(i=>i.id===s.daemonId&&i.type==="adhdev-daemon");if(a)return a}const r=s.targetSessionId&&this.findOwningSession(s.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const i=this.ides.find(c=>c.id===a&&c.type==="adhdev-daemon");if(i)return i}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(s){for(const r of this.ides)if(r.id===s||r.sessionId===s||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===s))return r;return null}resolveActionRouteTarget(s){if(s.targetSessionId){const r=this.findOwningSession(s.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return s.daemonId||null}resolveConversationKey(s){return s.targetSessionId?s.targetSessionId:s.daemonId?s.daemonId:null}handleRawEvent(s,r){var S;const n=this.resolveConversationKey(s),a=Number.isFinite(s.timestamp)?Number(s.timestamp):Date.now(),i=n||s.daemonId||"",c=s.requestId||s.targetName||s.requesterName||s.modalMessage||String(a),l=`${i}:${s.event}:${c}`;if(this.isDuplicate(l))return;const u=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,f=(u==null?void 0:u.type)||"";let d=tt(f);const h=this.resolveOwningDaemon(s);if(h){const p=Tt(h,{fallbackId:h.id});p&&(d=!f||f==="adhdev-daemon"?p:`${p}/${d}`)}let m="",j="info";if(s.event==="agent:generating_completed"){const p=s.duration?` (${s.duration}s)`:"";m=`✅ ${d} agent task completed${p}`,j="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(m=`⚡ ${d} approval needed`,j="warning",(S=s.modalButtons)!=null&&S.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(s);if(!p)return;const x=this.resolveActionFn,v=_u(s.modalButtons).map(A=>({label:A.label,variant:A.variant,onClick:()=>{x(p,"resolve_action",{action:A.action,button:A.button,buttonIndex:A.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),b=Du(d,s.modalMessage,m),C=Date.now();this.emitToast({id:C,message:b,type:j,timestamp:C,targetKey:n||p,actions:v,duration:15e3}),m=""}}else if(s.event==="monitor:long_generating"){const p=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";m=`⚠️ ${d} agent is taking a long time${p}`,j="warning",Os("browser")&&!document.hasFocus()&&Jn(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const p=s.requesterName||"A team member",x=s.requestId,v=s.orgId;if(m=`👁️ ${p} wants to view your session`,j="warning",x&&v&&this.viewRequestRespondFn){const b=Date.now(),C=Eu(v,x,this.viewRequestRespondFn,(A,y)=>console.error(`[EventManager] ${A} view request failed:`,y));this.emitToast({id:b,message:m,type:j,timestamp:b,actions:C,duration:3e4}),m=""}Os("browser")&&!document.hasFocus()&&Jn("👁️ View Request",`${p} wants to view your session`,`view-request-${x}`)}else s.event==="team:view_request_approved"?(m="✅ View request approved",j="success"):s.event==="team:view_request_rejected"&&(m=`❌ ${s.targetName||"Team member"} declined your view request`,j="warning");if(m){const p=Date.now();this.emitToast({id:p,message:m,type:j,timestamp:p,targetKey:n||s.daemonId,duration:5e3})}}}const lt=new $u,wo=new Map;function Wr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ys(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function en(e){return Wr(e)?Wr(e.result)?e.result:e:null}function Bu(e){const s=en(e);return!s||!Wr(s.controlResult)||!Array.isArray(s.controlResult.options)?null:s.controlResult}function fr(e){const s=en(e);return!s||!Wr(s.controlResult)||typeof s.controlResult.ok!="boolean"?null:s.controlResult}function Ls(e){const s=en(e);if(!(!s||typeof s.error!="string"||!s.error.trim()))return s.error}function pr(e){const s=en(e);return!!s&&s.success===!1}function Ku(e){var s,r;for(const n of e||[]){if(n.type==="toast"&&((s=n.toast)!=null&&s.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";lt.showToast(n.toast.message,a);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const a=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";lt.showToast(n.notification.body,a)}}}function Ou(e,s){return e&&ys(e.currentValue)?e.currentValue:s}function Wu(e,s){return ys(s)?ys(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Hu(e,s){var i,c;if((s.now??Date.now())<s.localOverrideUntil){const l=s.localValues[e];if(ys(l))return l}const n=(i=s.controlValues)==null?void 0:i[e];if(ys(n))return n;const a=(c=s.defaultValues)==null?void 0:c[e];return ys(a)?a:void 0}function Tr(e,s){return e.options||s[e.id]||[]}const Fu={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 Uu(e,s,r){var n;return((n=Fu[s])==null?void 0:n.has(r.id))===!0}function ja(e,s){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Uu(s.hostIdeType,s.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function hn(e,s){return{value:s}}function zu(e,s,r){var a;return r?((a=Tr(e,s).find(i=>i.value===r))==null?void 0:a.label)||r:""}const Vu={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Gu({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=jt(),u=`${e}:${s||n}`,f=Vu[n]||"#94a3b8",[d,h]=o.useState({}),m=o.useRef({}),j=o.useRef(c);m.current=d,j.current=c;const S=o.useRef(0),p={};for(const R of i||[])R.defaultValue!==void 0&&(p[R.id]=R.defaultValue);const x={...p,...c||{},...Date.now()<S.current?d:{}};o.useEffect(()=>{c&&Date.now()>S.current&&h({})},[c]);const[v,b]=o.useState(wo.get(u)||{}),[C,A]=o.useState(null),[y,I]=o.useState(null),k=o.useCallback(async(R,z={})=>{const $={...z,...s&&{targetSessionId:s}};return await l(e,R,$)},[e,s,l]),w=o.useCallback(async(R,z={})=>{const $=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await k("invoke_provider_script",{...$,scriptName:R,...z})},[k,n,r,s]),g=o.useCallback((R,z,$)=>{const _=Ou($,z);h(Y=>({...Y,[R.id]:_})),Ku($==null?void 0:$.effects)},[]),E=o.useCallback((R,z)=>{h($=>{const _={...$};return z===void 0?delete _[R.id]:_[R.id]=z,_}),S.current=0},[]);if(!i||i.length===0)return null;const T=ja(i,{hostIdeType:r,providerType:n});if(T.length===0)return null;const M=async R=>{if(C===R.id){A(null);return}if(Tr(R,v).length>0){A(R.id);return}if(R.dynamic&&R.listScript){I(R.id);try{const $=await w(R.listScript,{}),_=Bu($);if(!_){const pe=Ls($);pe&<.showToast(pe,"warning");return}const Y=_.options;b(pe=>{const ae={...pe,[R.id]:Y};return wo.set(u,ae),ae});const J=Hu(R.id,{localOverrideUntil:S.current,localValues:m.current,controlValues:j.current,defaultValues:p});if(Wu(J,_.currentValue)){const pe=_.currentValue;h(ae=>({...ae,[R.id]:pe}))}A(R.id)}catch($){const _=$ instanceof Error?$.message:`Could not load ${R.label}`;lt.showToast(_,"warning")}finally{I(null)}}},P=async(R,z)=>{A(null);const $=(c==null?void 0:c[R.id])??p[R.id];h(_=>({..._,[R.id]:z})),S.current=Date.now()+5e3;try{if(!R.setScript)return;const _=await w(R.setScript,hn(R,z)),Y=fr(_);if(Y&&!Y.ok||pr(_))throw new Error((Y==null?void 0:Y.error)||Ls(_)||`Could not update ${R.label}`);g(R,z,Y)}catch(_){E(R,$);const Y=_ instanceof Error?_.message:`Could not update ${R.label}`;lt.showToast(Y,"warning")}},K=async R=>{const z=Tr(R,v).map(ae=>ae.value);if(z.length===0)return;const $=String(x[R.id]||""),Y=(z.indexOf($)+1)%z.length,J=z[Y];if(typeof J!="string")return;const pe=(c==null?void 0:c[R.id])??p[R.id];h(ae=>({...ae,[R.id]:J})),S.current=Date.now()+5e3;try{if(!R.setScript)return;const ae=await w(R.setScript,hn(R,J)),be=fr(ae);if(be&&!be.ok||pr(ae))throw new Error((be==null?void 0:be.error)||Ls(ae)||`Could not update ${R.label}`);g(R,J,be)}catch(ae){E(R,pe);const be=ae instanceof Error?ae.message:`Could not update ${R.label}`;lt.showToast(be,"warning")}},U=async R=>{const $=!x[R.id],_=(c==null?void 0:c[R.id])??p[R.id];h(Y=>({...Y,[R.id]:$})),S.current=Date.now()+5e3;try{if(!R.setScript)return;const Y=await w(R.setScript,hn(R,$)),J=fr(Y);if(J&&!J.ok||pr(Y))throw new Error((J==null?void 0:J.error)||Ls(Y)||`Could not update ${R.label}`);g(R,$,J)}catch(Y){E(R,_);const J=Y instanceof Error?Y.message:`Could not update ${R.label}`;lt.showToast(J,"warning")}},L=async R=>{if(!R.invokeScript)return;if(R.confirmMessage){const $=[R.confirmTitle,R.confirmMessage,R.confirmLabel].filter(Y=>typeof Y=="string"&&Y.trim().length>0);if(!window.confirm($.join(`
|
|
28
|
-
|
|
29
|
-
`)))return}const z=(c==null?void 0:c[R.id])??p[R.id];try{const $=await w(R.invokeScript),_=fr($);if(_&&!_.ok||pr($))throw new Error((_==null?void 0:_.error)||Ls($)||`Could not run ${R.label}`);_&&g(R,z??!0,_)}catch($){E(R,z);const _=$ instanceof Error?$.message:`Could not run ${R.label}`;lt.showToast(_,"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:`${f}33`,background:`${f}12`,color:f},children:a}),T.map(R=>{const z=String(x[R.id]||""),$=zu(R,v,z),_=C===R.id,Y=y===R.id,J=Tr(R,v),pe="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(R.type){case"select":return t.jsxs("div",{className:"relative max-w-full",children:[t.jsxs("button",{type:"button",className:`${pe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:_?`${f}55`:"var(--border-default)",background:_?`${f}10`:"var(--surface-tertiary)",color:z?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void M(R),title:R.label,children:[R.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:Y?"Loading…":$||R.label}),t.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),_&&J.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>A(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:R.label}),J.map(ae=>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:ae.value===z?`${f}14`:"transparent",color:ae.value===z?"var(--text-primary)":"var(--text-secondary)",borderLeft:ae.value===z?`2px solid ${f}`:"2px solid transparent"},title:ae.description||ae.label,onMouseEnter:be=>{be.currentTarget.style.background=`${f}10`},onMouseLeave:be=>{be.currentTarget.style.background=ae.value===z?`${f}14`:"transparent"},onClick:()=>void P(R,ae.value),children:[t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ae.label}),ae.value===z&&t.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:f},children:"✓"})]},ae.value))]})]})]},R.id);case"cycle":return t.jsxs("button",{type:"button",className:`${pe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:z?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void K(R),title:`Click to cycle: ${J.map(ae=>ae.label).join(" → ")}`,children:[R.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:$||R.label}),t.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},R.id);case"toggle":return t.jsxs("button",{type:"button",className:`${pe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:z?`${f}44`:"var(--border-default)",background:z?`${f}14`:"var(--surface-tertiary)",color:z?f:"var(--text-muted)"},onClick:()=>void U(R),"aria-pressed":!!z,children:[R.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),R.label]},R.id);case"action":return t.jsxs("button",{type:"button",className:`${pe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void L(R),children:[R.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:R.resultDisplay==="inline"&&z?`${R.label}: ${z}`:R.label})]},R.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:z?"var(--text-primary)":"var(--text-muted)"},children:[R.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:z?`${R.label}: ${z}`:R.label})]},R.id);default:return null}})]})})}function qu({isActive:e=!0,isCliTerminal:s=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:f}=Ei(),d=ja(l,{hostIdeType:a,providerType:i});return!e||s||d.length===0||!f?null:t.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:t.jsx(Gu,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:d,controlValues:u})})}function Yu({hasDraft:e,isBusy:s=!1}){return!e||s}const Ui=o.memo(function({contextKey:s,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:u=!1,animateVisibility:f=!0}){const d=o.useRef(null),[h,m]=o.useState(""),{isVisible:j,toggleVisibility:S}=Ei();o.useEffect(()=>{m("")},[s]),o.useEffect(()=>{var x;l&&((x=d.current)==null||x.focus({preventScroll:!0}))},[s,l]);const p=async()=>{const x=h.trim();if(!x||a)return;await c(x)!==!1&&m("")};return t.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",f?"transition-all duration-200 ease-out":""].filter(Boolean).join(" "),style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[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:S,"aria-label":j?"Hide controls":"Show controls","aria-pressed":j,title:j?"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:d,type:"text",placeholder:i||`Send message to ${r}...`,value:h,onChange:x=>m(x.target.value),onPaste:x=>{const v=x.clipboardData.getData("text");v&&m(b=>b+v),x.preventDefault()},onKeyDown:x=>{if(x.key==="Enter"){if(x.nativeEvent.isComposing){x.preventDefault();return}x.preventDefault(),p()}},onBlur:x=>{if(window.innerWidth<768){const v=x.relatedTarget;if((v==null?void 0:v.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:()=>{p()},disabled:Yu({hasDraft:!!h.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${h.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:h.trim()&&!a?{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:h.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})]})}),Je=e=>e.transport==="pty",As=(e,s)=>Je(e)?e.mode||"terminal":"chat",zi=(e,s)=>Je(e)&&As(e)==="terminal",Ge=e=>e.transport==="acp";function zt(e){return e.streamSource!=="agent-stream"}function qt(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function Vi(e){return e.machineName||""}function sr(e){return qt(e)}function _t(e){return e.agentType||""}function Hr(e){return e.hostIdeType||""}function ka(e){return e.displayPrimary||e.agentName||"Agent"}function Gi(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Xu(e){return e.lastMessagePreview||e.displaySecondary||""}function qi(e){return[e.displaySecondary,Vi(e)].filter(Boolean)}function Ss(e){return e.agentName||tt(_t(e))}function Ju(e){var s,r;if(!zt(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return tt(Hr(e)||_t(e))}function Yi(e){return zt(e)?e.sessionId:e.nativeSessionId}function jo(e){return zt(e)?"native":e.tabKey}function Qu(e){return e.sessionId}function Zu(e,s){if(s)return zt(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function em(e,s){const r=_t(e),n=zt(e),a=Je(e)||Ge(e),i=n?a?Ss(e)||(s==null?void 0:s.cliName)||tt(Hr(e)||r):s!=null&&s.type?tt(s.type):tt(Hr(e)||r):Ss(e);return{isNativeConversation:n,isCli:Je(e),isAcp:Ge(e),isCliTerminal:zi(e),providerType:r,displayLabel:i,targetEntry:Zu(e,s)}}function gt(e){return(typeof e=="string"?e.trim():"")||void 0}function Ht(e,s){const r=gt(s);return r?`${e}:${r}`:void 0}function Ut(e,s,r){const n=Ht(s,r),a=gt(r);n&&e.push(n),a&&e.push(a)}function bs(e){const s=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),s.push(n));return s}function Xi(e){return gt(e.providerSessionId)||gt(e.sessionId)||gt(e.tabKey)||gt(e.routeId)}function Sa(e){return bs([gt(e.providerSessionId),gt(e.sessionId)])}function vs(e){const s=[];return Ut(s,"provider",e.providerSessionId),Ut(s,"session",e.sessionId),Ut(s,"tab",e.tabKey),Ut(s,"route",e.routeId),bs(s)}function tm(e){const s=[];return gt(e.providerSessionId)?(Ut(s,"provider",e.providerSessionId),bs(s)):gt(e.sessionId)?(Ut(s,"session",e.sessionId),bs(s)):gt(e.tabKey)?(Ut(s,"tab",e.tabKey),bs(s)):gt(e.routeId)?(Ut(s,"route",e.routeId),bs(s)):[]}function Na(e){return Ht("provider",e.providerSessionId)||Ht("session",e.sessionId)||Ht("tab",e.tabKey)||Ht("route",e.routeId)||"unknown:"}function rr(e){return Sa(e)[0]}function sm(e){const s=gt(e.providerSessionId),r=gt(e.sessionId),n=gt(e.tabKey),a=gt(e.routeId),i=[Ht("provider",s),Ht("session",r),Ht("tab",n),Ht("route",a)].filter(u=>typeof u=="string"),c=vs({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),l=Na({providerSessionId:s,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:s,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:Xi({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),historySessionId:rr({providerSessionId:s,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function Qn(e,s){const r=sm(e);return tm(s).some(n=>r.lookupKeys.includes(n))}function ko(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 es(e){const s=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],r=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,n=ko(s==null?void 0:s.receivedAt)||ko(s==null?void 0:s.timestamp)||0;return Math.max(r,n)}function Zn(e,s=0){return es(e)||e.lastUpdated||s||0}function Ji(e){return es(e)||e.lastUpdated||0}function Qi(e,s,r=Ji){const n=r(s)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(s.machineName||"");if(a!==0)return a;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 ea(e){var r;const s=bt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function rm(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!ea(e)&&!e.title.trim()}function nm(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(ea(r))-Number(ea(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:Qi(s,r)})[0]||null}function Dt(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,a=r.filter(c=>c.streamSource==="agent-stream"),i=nm(a);return n?i&&rm(n)?i:n:i||r[0]||null}function Vt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ca(e){return rr(e)||e.tabKey||e.routeId||null}function Zi(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 a=Dt(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?Ca(a):null}function ec({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Is(),c=qt(e),l=Vi(e),u=e.transport==="cdp-page"||e.transport==="cdp-webview",f=e.streamSource==="agent-stream"&&!!e.agentName,d=!f&&(e.transport==="pty"||e.transport==="acp"),h=Ss(e),m=Ju(e),j=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),S=o.useCallback(()=>{if(r){r();return}const p=Ca(e);p&&i(Vt(p))},[e,i,r]);return t.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[u&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:m,children:[t.jsx(Ct,{size:12}),t.jsx("span",{children:m})]}):t.jsxs("span",{className:"conversation-meta-chip",title:m,children:[t.jsx(Ct,{size:12}),t.jsx("span",{children:m})]})),f&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[t.jsx(Ys,{size:12}),t.jsx("span",{children:h})]}),d&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[t.jsx(Ys,{size:12}),t.jsx("span",{children:h})]}),l&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:j,title:l,children:[t.jsx(ls,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(ls,{size:12}),t.jsx("span",{children:l})]}))]})}function xn(e,s){return`${e}:${s}`}function am(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function hr(e,s){am()&&console.debug(`[subscription-manager] ${e}`,s)}class om{constructor(){Ve(this,"active",new Map)}subscribe(s,r,n,a){var f;const i=xn(n.topic,n.key),c=this.active.get(i);let l=!0;if(c)c.handlers.add(a),c.lastUpdate&&a(c.lastUpdate);else{const d={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,d),hr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((f=s.sendData)==null?void 0:f.call(s,r,n))??!1}const u=()=>{var m;const d=this.active.get(i);if(!d||(d.handlers.delete(a),d.handlers.size>0))return;this.active.delete(i);const h={type:"unsubscribe",topic:n.topic,key:n.key};hr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(m=s.sendData)==null||m.call(s,r,h)};return u.initialSendAccepted=l,u}publish(s){const r=xn(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,js.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.publish",topic:s.topic,payload:{key:s.key}}),n.handlers.forEach(a=>{a(s),js.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.handler_invoked",topic:s.topic,payload:{key:s.key}})}))}updateParams(s,r,n){const a=xn(s,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(s){var r;hr("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=s.sendData)==null||r.call(s,n.daemonId,n.request)}resubscribeForDaemon(s,r){var a;const n=Array.from(this.active.values()).filter(i=>i.daemonId===s);hr("resubscribe_daemon",{daemonId:s,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(a=r.sendData)==null||a.call(r,i.daemonId,i.request)}}const Gt=new om;function im(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 cm(e){const s=[],r=new Map;for(const n of e)if(n.parentId){const a=r.get(n.parentId)||[];a.push(n),r.set(n.parentId,a)}else s.push(n);return{topLevel:s,childrenByParent:r}}function Fr(e,s){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=s,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:f,childrenByParent:d}=cm(u),h=im(i,n),m=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,j=f.filter(x=>x.kind==="workspace"&&x.transport==="cdp-page"),S=f.filter(x=>x.kind==="agent"&&x.transport==="pty"),p=f.filter(x=>x.kind==="agent"&&x.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...m&&{machine:m,platform:m.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:j.some(x=>!!x.cdpConnected)});for(const x of j){const v=h.get(x.id),b=Bs(x,v),C=(d.get(x.id)||[]).map(A=>Bs(A,h.get(A.id)));r.push({id:`${n}:ide:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,status:b.cdpConnected?"online":"detected",daemonId:n,instanceId:x.id,workspace:b.workspace,terminals:0,childSessions:C,agents:C.map(A=>({id:A.id,name:A.providerName||A.providerType,type:A.providerType,status:A.status})),activeChat:b.activeChat,chats:[],cdpConnected:b.cdpConnected,...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l})}for(const x of S){const v=h.get(x.id),b=Bs(x,v);r.push({id:`${n}:cli:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:x.id,cliName:b.providerName||b.providerType,mode:b.mode||(v==null?void 0:v.mode)||"terminal",workspace:b.workspace||"",activeChat:b.activeChat,...b.resume!==void 0&&{resume:b.resume},...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l,_isCli:!0})}for(const x of p){const v=h.get(x.id),b=Bs(x,v);r.push({id:`${n}:acp:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:x.id,cliName:b.providerName||b.providerType,mode:"chat",workspace:b.workspace||"",activeChat:b.activeChat,...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const lm=15e3,dm=15e3,um=6e4,mm=1200,So=12,fm=8e3,pm=4e3,bn=new Map,gn=new Map,xr=new Set,Ws=new Map;function hm(e){if(!e||typeof e!="object")return null;const s=e,r=s.status;if(r&&typeof r=="object")return r;const n=s.result;if(n&&typeof n=="object"&&"status"in n){const a=n.status;if(a&&typeof a=="object")return a}return s}function No(e,s){const r=Ws.get(e);!r||r.size===0||(Ws.delete(e),r.forEach(n=>n(s)))}function xm(e,s){return new Promise(r=>{const n=Ws.get(e)||new Set;Ws.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&Ws.delete(e),r(c)},i=setTimeout(()=>a(!1),s);n.add(a)})}function nr(){const{sendCommand:e,sendData:s}=jt(),{injectEntries:r,getIdes:n}=Gs();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??um,l=gn.get(a)||0;if(!(i!=null&&i.force)&&xr.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=bn.get(a);if(u)return u;const f=(async()=>{if(s&&!xr.has(a)){const p=Gt.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},x=>{const v=n(),b=v.find(A=>A.id===a),C=Fr(x.status,{daemonId:a,existingDaemon:b,existingEntries:v,timestamp:x.timestamp});C.length>0&&r(C),gn.set(a,Date.now()),No(a,!0)});if(p.initialSendAccepted?xr.add(a):xr.delete(a),!(i!=null&&i.force)&&p.initialSendAccepted&&await xm(a,mm))return}const d=await e(a,"get_status_metadata"),h=hm(d);if(!h)return;const m=n(),j=m.find(p=>p.id===a),S=Fr(h,{daemonId:a,existingDaemon:j,existingEntries:m,timestamp:h.timestamp||Date.now()});S.length>0&&r(S,{authoritativeDaemonIds:[a]}),gn.set(a,Date.now()),No(a,!0)})().finally(()=>{bn.delete(a)});return bn.set(a,f),f},[n,r,e,s])}function bm(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function ws(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:Je(e)||Ge(e)?{agentType:_t(e)}:e.streamSource==="agent-stream"?{agentType:_t(e)}:s}function Js(e){return e?sr(e):""}function Rs(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Ia(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function gm(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 ym=60,vm=1e3;function tc(e={}){return e.isCliLike?vm:ym}function wm(e={}){return tc(e)}const ar=60,jm=1e3,Ma=12e4,km=new Set(["generating","waiting_approval","starting","streaming","working"]),Co=new Map;function sc(e,s){return`${e}::${s}`}function ta(e=ar){return{liveMessages:[],cursor:rc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function sa(e){return wi(e)}function rc(e,s=ar){return{knownMessageCount:e.length,lastMessageSignature:sa(e[e.length-1]),tailLimit:s}}function br(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 Sm(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 Nm{constructor(s){Ve(this,"manager");Ve(this,"sendData");Ve(this,"daemonId");Ve(this,"sessionId");Ve(this,"historySessionId");Ve(this,"subscriptionKey");Ve(this,"snapshot");Ve(this,"transportSubscription",null);Ve(this,"listeners",new Set);Ve(this,"retainCount",0);Ve(this,"loadHistoryPromise",null);Ve(this,"pendingDisconnectTimer",null);Ve(this,"pendingSubscribeRetryTimer",null);this.manager=s.manager||Gt,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.snapshot=ta(Math.max(0,s.tailLimit??ar))}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,a=rc(n,this.snapshot.cursor.tailLimit);br(this.snapshot.liveMessages)===br(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a},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(),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},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()},jm))}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=typeof s.lastMessageSignature=="string"?s.lastMessageSignature:"",n=sa(this.snapshot.liveMessages[this.snapshot.liveMessages.length-1]);if(s.syncMode!=="full"&&r&&n===r){const u={knownMessageCount:Math.max(this.snapshot.cursor.knownMessageCount,Number(s.totalMessages||0)),lastMessageSignature:r,tailLimit:this.snapshot.cursor.tailLimit};this.snapshot.cursor.knownMessageCount===u.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===u.lastMessageSignature||(this.snapshot={...this.snapshot,cursor:u},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:u.knownMessageCount,lastMessageSignature:u.lastMessageSignature}));return}const a=Sm(this.snapshot.liveMessages,s),i={knownMessageCount:a.length,lastMessageSignature:typeof s.lastMessageSignature=="string"?s.lastMessageSignature:sa(a[a.length-1]),tailLimit:this.snapshot.cursor.tailLimit};br(this.snapshot.liveMessages)===br(a)&&this.snapshot.cursor.knownMessageCount===i.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===i.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:a,cursor:i},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:i.knownMessageCount,lastMessageSignature:i.lastMessageSignature}),this.emit())}}function nc(e){const s=sc(e.daemonId,e.sessionId),r=Co.get(s);if(r)return r.updateOptions(e),r;const n=new Nm(e);return Co.set(s,n),n}function Cm(e,s){return{...e,loadHistoryPage:s}}function Im(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function Mm(e,s={}){const r=String(e.status||"").trim().toLowerCase();if(km.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=s.now??Date.now(),a=Math.max(0,Number(s.recentActivityMs??Ma)),i=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return i>0?n-i<=a:Array.isArray(e.messages)&&e.messages.length>0}function Am(e=Ma){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Tm(e,s={}){const r=new Set,n=[];for(const a of e){if(!Mm(a,s))continue;const i=sr(a),c=a.sessionId||"";if(!i||!c)continue;const l=sc(i,c);if(r.has(l))continue;r.add(l);const u=rr(a);n.push({daemonId:i,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(Im),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Lm(e,s){const{sendData:r,sendCommand:n}=jt(),a=(s==null?void 0:s.enabled)!==!1,i=sr(e),c=e.sessionId||"",l=rr(e)||c,u=`daemon:${i}:session:${c}`,f=Math.max(0,(s==null?void 0:s.tailLimit)??ar),d=o.useMemo(()=>!a||!i||!c?null:nc({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:f}),[i,a,l,r,c,u,f]),[h,m]=o.useState(()=>(d==null?void 0:d.getSnapshot())||ta(f));o.useEffect(()=>{if(!d){m(ta(f));return}d.retain(),m(d.getSnapshot());const S=d.subscribe(p=>{m(p)});return()=>{S(),d.release()}},[d,f]),o.useEffect(()=>{d&&(d.hydrateLiveMessages(e.messages),m(d.getSnapshot()))},[e.messages,d]);const j=o.useCallback(async()=>{!d||!i||!c||await d.loadHistoryPage(async()=>{const S=e.agentType,p=await n(i,"chat_history",{agentType:S,offset:d.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),x=p&&typeof p=="object"&&"result"in p?p.result||{}:p||{};return{messages:Array.isArray(x.messages)?x.messages:[],hasMore:x.hasMore===!0}})},[e.agentType,d,i,l,n,c]);return o.useMemo(()=>Cm(h,j),[j,h])}function Rm(e,s){const{sendData:r}=jt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,(s==null?void 0:s.tailLimit)??ar),i=Math.max(0,Number((s==null?void 0:s.recentActivityMs)??Ma)),c=Am(i),[l,u]=o.useState(0);o.useEffect(()=>{if(!n||e.length===0)return;const d=setInterval(()=>{u(h=>h+1)},c);return()=>{clearInterval(d)}},[e.length,n,c]);const f=o.useMemo(()=>Tm(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||f.descriptors.length===0)return;const d=f.descriptors.map(h=>nc({...h,sendData:r,tailLimit:a}));return d.forEach(h=>h.retain()),()=>{d.forEach(h=>h.release())}},[f.signature,n,r,a])}function Pm(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function _m(e){return Pm(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Dm=60;function ra({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:f=!1,scrollToBottomRequestNonce:d,isInputActive:h=!0,isVisible:m=!0}){var ye,ve,Ie,H,V;const j=o.useRef(new Map),S=nr();tr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const p=St.useMemo(()=>Ms(e),[e.status,e.connectionState]),x=o.useMemo(()=>em(e,s),[e,s]),v=o.useMemo(()=>{var Q;return ja((Q=x.targetEntry)==null?void 0:Q.providerControls,{hostIdeType:e.hostIdeType,providerType:x.providerType})},[e.hostIdeType,x.providerType,(ye=x.targetEntry)==null?void 0:ye.providerControls]),b=tc({isCliLike:x.isCli||x.isAcp}),C=wm({isCliLike:x.isCli||x.isAcp}),A=Lm(e,{enabled:m&&!!e.sessionId,tailLimit:C}),[y,I]=o.useState(b),k=e.tabKey,w=A.historyMessages,g=A.hasMoreHistory,E=A.historyError,T=A.liveMessages.length>0?A.liveMessages:e.messages;o.useEffect(()=>{I(b)},[b,k]);const M=Math.max(0,T.length-y),P=ka(e),K=sr(e),U=_m(e),L=Ia(e),R=a||L,z=!!L,[$,_]=o.useState(!1);o.useEffect(()=>{const Q=x.targetEntry;K&&(!Q||Q.providerControls===void 0||Q.controlValues===void 0)&&S(K,{minFreshMs:3e4}).catch(()=>{})},[K,x.isAcp,(ve=x.targetEntry)==null?void 0:ve.providerControls,(Ie=x.targetEntry)==null?void 0:Ie.controlValues,S]);const Y=o.useCallback(async()=>{if(!$){if(T.length>y){I(Q=>Math.min(T.length,Q+Dm));return}_(!0);try{await A.loadHistoryPage()}finally{_(!1)}}},[A,$,T.length,y]),{allMessages:J,receivedAtMap:pe}=o.useMemo(()=>{const Q=M>0?T.slice(-y):T,ue=w.length===0?Q:[...w,...Q],re={};return ue.forEach((le,se)=>{const me=`${e.tabKey}:${Kr(le,se)}`;let ne=bm(le)||j.current.get(me)||0;ne||(ne=Date.now(),j.current.set(me,ne)),re[Kr(le,se)]=ne}),{allMessages:ue,receivedAtMap:re}},[e.tabKey,M,w,T,y]),ae=o.useMemo(()=>l.filter(Q=>Q.routeId===e.tabKey).sort((Q,ue)=>Q.timestamp-ue.timestamp),[l,e.tabKey]),be=o.useMemo(()=>{if(T.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((p.isGenerating||e.status==="streaming")&&_(!1),e.status==="not_monitored"&&U)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(Ys,{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(ks,{size:14})," Open ",P," 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"&&U)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(Ci,{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(ks,{size:14})," Open ",P," 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"&&!$)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,U,i,c,$,T.length,P,p.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[f&&t.jsx(ec,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(Yd,{messages:J,actionLogs:ae,agentName:Ss(e)||P||"Agent",userName:u,isCliMode:x.isCli||x.isAcp,isWorking:p.isGenerating,contextKey:e.tabKey,receivedAtMap:pe,onLoadMore:Y,isLoadingMore:$,hasMoreHistory:g,hiddenLiveCount:M,loadError:E??void 0,emptyState:be,scrollToBottomRequestNonce:d,isVisible:m}),t.jsx(qu,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:x.providerType,displayLabel:x.displayLabel,controls:(H=x.targetEntry)==null?void 0:H.providerControls,controlValues:(V=x.targetEntry)==null?void 0:V.controlValues,isActive:h,isCliTerminal:x.isCliTerminal}),!x.isCliTerminal&&t.jsx(Ui,{contextKey:e.tabKey,panelLabel:P,isSending:n,isBusy:z,statusMessage:R,onSend:r,isActive:h,showControlsToggle:v.length>0})]})}let ac=cs;function oc(){return ac()}class Em{constructor(){Ve(this,"listeners",new Map)}send(s){}isConnected(){return!1}on(s,r){return this.listeners.has(s)||this.listeners.set(s,new Set),this.listeners.get(s).add(r),()=>{var n;(n=this.listeners.get(s))==null||n.delete(r)}}emit(s,...r){var n;(n=this.listeners.get(s))==null||n.forEach(a=>a(...r))}}let ic=new Em;class $m{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({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let ot=new $m;function Bm(e){e.dashboardWS&&(ic=e.dashboardWS),e.connectionManager&&(ot=e.connectionManager),e.useDaemonsHook&&(ac=e.useDaemonsHook)}const Km=.5,Om=1.25;function Io(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 Wm(e){return[...e].reverse().find(s=>!(s!=null&&s._localId))||e[e.length-1]}function Hm(e){return Io(e==null?void 0:e.receivedAt)||Io(e==null?void 0:e.timestamp)||0}function rt(e){return ka(e)}function us(e){return qi(e).join(" · ")}function cc(e){const s=Wm(e.messages),r=Vs(s==null?void 0:s.content),n=Hm(s),a=Vs(e.lastMessagePreview),i=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0;return a&&(!r||i>0&&i>=n)?a:r||a||(e.title?e.title:us(e)||"No messages yet")}function lc(e,s){const{isReconnecting:r,isConnecting:n}=Ms(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function Fm(e,s){const r=["Chat",...qi(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function ts(e){return lc(e)||us(e)}function Um(e){return`${rt(e)} · ${cc(e)}`}function zm(e){const s=Hr(e),r=s?tt(s):Ss(e);return`${rt(e)} — ${r||"Agent"}`}function Vm(e){return Ss(e)||"CLI"}function dc(e){return Gi(e)}function uc(e){return e?`Remote · ${rt(e)||e.workspaceName||"Session"}`:"Remote"}function Gm({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var N;cs();const{sendPtyInput:u}=jt(),[f,d]=o.useState(!1),[h,m]=o.useState("Runtime terminal unavailable"),[j,S]=o.useState(1),[p,x]=o.useState({width:0,height:0}),[v,b]=o.useState({width:0,height:0}),C=o.useRef(null),A=o.useRef(null),y=o.useRef(!1),I=o.useRef(!1),k=o.useRef(0),w=o.useRef(!1),g=o.useRef(""),E=o.useRef(null),T=o.useRef(!1),M=o.useRef(null),P=32*1024,K=()=>{var O,G,Z,fe;return((G=(O=C.current)==null?void 0:O.ownerDocument)==null?void 0:G.defaultView)||((fe=(Z=A.current)==null?void 0:Z.ownerDocument)==null?void 0:fe.defaultView)||window},U=O=>{const G=K();return{ownerWindow:G,frameId:G.requestAnimationFrame(O)}},L=()=>{const O=M.current;if(O){try{O.ownerWindow.cancelAnimationFrame(O.frameId)}catch{}M.current=null}},R=()=>{c&&M.current===null&&(M.current=U(()=>{oe()}))},z=e.tabKey,$=e.sessionId||"",_=e.daemonId||((N=e.routeId)==null?void 0:N.split(":")[0])||e.routeId||"",Y=Ia(e),J=f?i||Y:h,pe=Km,ae=Om,be=.05,ye=Number.isFinite(j)&&j>0?j:1,ve=Number((13*j).toFixed(2)),Ie=()=>{const O=v.width>0?Math.max(p.width,Math.round(v.width)):p.width,G=v.height>0?Math.max(p.height,Math.round(v.height)):p.height;if(!Number.isFinite(p.width)||p.width<=0||!Number.isFinite(p.height)||p.height<=0||!Number.isFinite(O)||O<=0||!Number.isFinite(G)||G<=0)return 1;const Z=O/ye,fe=G/ye;if(!Number.isFinite(Z)||Z<=0||!Number.isFinite(fe)||fe<=0)return 1;const ge=p.width/Z,Pe=p.height/fe;return Number(Math.min(ae,Math.max(pe,Math.min(ge,Pe))).toFixed(2))},H=Ie(),V=y.current&&j>H,Q=v.width>p.width+1||v.height>p.height+1,ue=v.width>0?Math.max(p.width,Math.round(v.width)):p.width,re=v.height>0?Math.max(p.height,Math.round(v.height)):p.height,le=v.width>0?Math.round(v.width):ue,se=v.height>0?Math.round(v.height):re,me=()=>{U(()=>{const O=A.current;O&&(O.scrollLeft=0,O.scrollTop=O.scrollHeight-O.clientHeight)})},ne=()=>{var O,G;k.current=0,w.current=!1,g.current="",E.current=null,T.current=!1,y.current||(I.current=!1,S(1)),M.current!==null&&L(),d(!1),m("Runtime terminal unavailable"),(G=(O=r.current)==null?void 0:O.reset)==null||G.call(O)},ce=()=>{var O,G;k.current=0,w.current=!1,g.current="",E.current=null,T.current=!1,M.current!==null&&L(),d(!0),m(""),(G=(O=r.current)==null?void 0:O.reset)==null||G.call(O)},oe=()=>{var Z;if(M.current=null,!c)return;const O=g.current;if(!O)return;const G=O.slice(0,P);g.current=O.slice(G.length),(Z=r.current)==null||Z.write(G),g.current.length>0&&R()},we=O=>{O&&(g.current+=O,R())},he=(O,G=0,Z,fe)=>{var ge,Pe,Ee,We;G>0&&k.current>=G||G===0&&w.current||(k.current=G,d(!0),m(""),typeof Z=="number"&&typeof fe=="number"&&Z>0&&fe>0&&((Pe=(ge=r.current)==null?void 0:ge.resize)==null||Pe.call(ge,Z,fe)),g.current="",(We=(Ee=r.current)==null?void 0:Ee.reset)==null||We.call(Ee),O&&we(O))};o.useEffect(()=>{ne()},[$]),o.useEffect(()=>{var G;if(!$)return;const O=((G=ot.onRuntimeEvent)==null?void 0:G.call(ot,$,Z=>{if(!(!Z||Z.sessionId!==$)){if(Z.type==="runtime_snapshot"){if(!c){E.current={text:Z.text||"",seq:Z.seq||0,cols:Z.cols,rows:Z.rows};return}he(Z.text||"",Z.seq||0,Z.cols,Z.rows);return}if(Z.type==="session_output"){w.current=!0,typeof Z.seq=="number"&&(k.current=Math.max(k.current,Z.seq)),f||d(!0),f||m(""),typeof Z.data=="string"&&we(Z.data);return}if(Z.type==="session_cleared"){if(!c){T.current=!0,g.current="",E.current=null;return}ce()}}}))||(()=>{});return()=>{O()}},[_,$,r,c,f]);const Se=async()=>{var O;if(!(!_||!$)){m("Loading runtime terminal...");try{const G=await((O=ot.requestRuntimeSnapshot)==null?void 0:O.call(ot,_,$));G&&G.success===!1&&(d(!1),m(`Runtime terminal unavailable: ${G.error}`))}catch(G){d(!1),m(`Runtime terminal unavailable: ${(G==null?void 0:G.message)||String(G)}`)}}};return o.useEffect(()=>{var G,Z;if(!$)return;_&&((G=ot.getState)==null?void 0:G.call(ot,_))==="connected"&&Se();const O=(Z=ot.onStateChange)==null?void 0:Z.call(ot,(fe,ge)=>{fe!==_||ge!=="connected"||Se()});return()=>{O==null||O()}},[_,$,r]),o.useEffect(()=>{s&&ne()},[s,z,r]),o.useEffect(()=>{var fe,ge;const O=C.current,G=(ge=(fe=O==null?void 0:O.ownerDocument)==null?void 0:fe.defaultView)==null?void 0:ge.ResizeObserver;if(!O||!G)return;const Z=new G(Pe=>{const Ee=Pe[0];if(!Ee)return;const{width:We,height:ze}=Ee.contentRect;x(Qe=>{const Ze=Math.round(We),it=Math.round(ze);return Qe.width===Ze&&Qe.height===it?Qe:{width:Ze,height:it}})});return Z.observe(O),()=>Z.disconnect()},[]),o.useEffect(()=>{if(y.current)return;const O=Ie();!Number.isFinite(O)||O<=0||S(G=>I.current?O<G-be?O:G:(I.current=!0,O))},[v.height,v.width,p.height,p.width]),o.useEffect(()=>{!Q&&!V||me()},[Q,V,re,ue]),o.useEffect(()=>{var G;if(!c)return;T.current&&(T.current=!1,ce());const O=E.current;O&&(E.current=null,he(O.text,O.seq,O.cols,O.rows)),_&&$&&((G=ot.getState)==null?void 0:G.call(ot,_))==="connected"&&Se(),g.current&&M.current===null&&R(),U(()=>{var Z;(Z=r.current)==null||Z.bumpResize()})},[_,c,$]),o.useEffect(()=>()=>{M.current!==null&&L()},[]),o.useEffect(()=>{const O=fe=>{var Pe;const ge=fe.detail;ge!=null&&ge.sessionId&&ge.sessionId!==$||f&&((Pe=r.current)==null||Pe.bumpResize())},G=K(),Z=G===window?[window]:[window,G];for(const fe of Z)fe.addEventListener("adhdev:fit-cli-terminal",O);return()=>{for(const fe of Z)fe.removeEventListener("adhdev:fit-cli-terminal",O)}},[f,$,r]),t.jsxs(t.Fragment,{children:[t.jsxs("div",{ref:C,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:()=>{y.current=!0,S(O=>{const G=Math.max(H,Number((O-.1).toFixed(2)));return G>H&&me(),G})},title:"Shrink terminal viewport",children:"-"}),t.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{y.current=!0,S(O=>{const G=Math.min(ae,Number((O+.1).toFixed(2)));return G>H&&me(),G})},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{ref:A,className:Q?"w-full h-full overflow-x-auto overflow-y-hidden rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",style:{display:"flex",justifyContent:"flex-start",alignItems:"flex-end"},children:t.jsx("div",{style:{width:le>0?`${le}px`:ue>0?`${ue}px`:"100%",height:se>0?`${se}px`:re>0?`${re}px`:"100%",minWidth:le>0?`${le}px`:"100%",minHeight:se>0?`${se}px`:"100%",position:"relative"},children:t.jsx("div",{style:{width:"100%",height:"100%",position:"absolute",left:0,bottom:0},children:t.jsx(Ri,{ref:r,readOnly:!f||!c,sizingMode:"measured",fontSize:ve,onViewportMetrics:b,onInput:O=>{!f||(u==null||u(_,$,O))}})})})}),!f&&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:h})]}),t.jsx(Ui,{contextKey:e.tabKey,panelLabel:rt(e),isSending:a,isBusy:!f||!!Y,statusMessage:J,onSend:async O=>!f||Y?!1:n(O),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}function qm({wsStatus:e,showReconnected:s,loginUrl:r,onReconnect:n}){const a=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)"},f="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",d={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return t.jsxs(t.Fragment,{children:[a&&t.jsx("div",{className:f,style:d,children:t.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-4 py-3 text-[13px] font-semibold flex items-center gap-2.5 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:c[i],border:l[i],color:u[i]},children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),t.jsxs("span",{className:"min-w-0 text-center",children:[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-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:n,disabled:e==="offline",children:"Reconnect now"})]})}),s&&e==="connected"&&t.jsx("div",{className:f,style:d,children:t.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function Ym({terminalBackend:e,isStandalone:s=!1,machineLabel:r,machineKey:n}){const a=o.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,c]=o.useState(!1);if(o.useEffect(()=>{if(!a){c(!1);return}try{c(localStorage.getItem(a)==="1")}catch{c(!1)}},[a]),!s||!e||e.backend!=="xterm"||i)return null;const l=(r==null?void 0:r.trim())||"This machine",u=()=>{if(a)try{localStorage.setItem(a,"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 Aa({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(ba,{size:n}):t.jsx(Ft,{size:n})})}const Bt="New session",mc="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 Xm({wsStatus:e,isConnected:s,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),i=a.filter(l=>l==="connected").length,c=a.filter(l=>l==="connecting"||l==="new"||l==="checking").length;return r>0&&c>0&&i===0?{tone:"limited",title:"Connected to dashboard",subtitle:"Connecting to machine..."}:s?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function Mo({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Ao({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=Jr(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(),a()},children:"Mark unread"}),t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),i()},children:"Delete"})]})]})}function Jm({activeConv:e,wsStatus:s,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:u,onHideConversation:f,hiddenConversations:d=[],onShowConversation:h,onShowAllHidden:m,onResetPanelsToMain:j,inboxOpen:S,onInboxOpenChange:p,hiddenOpen:x,onHiddenOpenChange:v,onOpenNewSession:b,actionShortcuts:C,notifications:A,notificationUnreadCount:y,onOpenNotification:I,onMarkNotificationRead:k,onMarkNotificationUnread:w,onDeleteNotification:g}){const{ides:E,p2pStates:T={}}=cs(),M=!!e&&Je(e)&&!Ge(e),P=!!e&&Ge(e),K=l||(e?zi(e)?"terminal":"chat":null),[U,L]=o.useState(!1),R=o.useRef(null),z=o.useRef(null),$=E.filter(H=>H.type==="adhdev-daemon"),_=Xm({wsStatus:s,isConnected:r,daemonCount:$.length,p2pStates:T}),Y=_.subtitle,J=_.tone==="connected"?"#22c55e":_.tone==="limited"?"#eab308":"#ef4444",pe=_.tone==="connected"?"0 0 4px #22c55e80":_.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",ae=o.useMemo(()=>A.filter(H=>!H.readAt),[A]),be=o.useMemo(()=>A.filter(H=>!!H.readAt),[A]),ye=o.useMemo(()=>ae.slice(0,9),[ae]),ve=y;o.useEffect(()=>{if(!S)return;const H=V=>{var Q;(Q=R.current)!=null&&Q.contains(V.target)||p(!1)};return document.addEventListener("mousedown",H),()=>document.removeEventListener("mousedown",H)},[S,p]),o.useEffect(()=>{if(!x)return;const H=V=>{var Q;(Q=z.current)!=null&&Q.contains(V.target)||v(!1)};return document.addEventListener("mousedown",H),()=>document.removeEventListener("mousedown",H)},[x,v]),o.useEffect(()=>{if(!x&&!S)return;const H=V=>{if(!V.altKey)return;const Q=V.code.match(/^Digit([1-9])$/);if(!Q)return;const ue=Number(Q[1])-1,re=x?d[ue]:void 0,le=S?ye[ue]:void 0;if(!(!re&&!le)){if(V.preventDefault(),V.stopPropagation(),re){h==null||h(re),v(!1);return}le&&(I(le),p(!1))}};return window.addEventListener("keydown",H,!0),()=>window.removeEventListener("keydown",H,!0)},[d,x,S,ye,v,p,I,h]);const Ie=H=>{if(!H)return;const V=n.find(Q=>Q.tabKey===H);V&&(f==null||f(V))};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(Ft,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?rt(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:J,boxShadow:pe}})})]}),t.jsxs("div",{className:"header-subtitle flex items-center",children:[t.jsx("span",{title:_.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:J,boxShadow:pe}}),Y&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",Y]}),b&&t.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:Bt,"aria-label":Bt,children:t.jsx(Ai,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(M||P||!Ge(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:us(e)||rt(e),children:rt(e)}),(M||P)&&c&&t.jsxs(t.Fragment,{children:[M&&u&&K&&t.jsx(Aa,{mode:K,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(wt,{size:14})})]}),!Ge(e)&&t.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(xa,{size:14})}),!M&&!Ge(e)&&t.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(Ct,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:R,children:[t.jsxs("div",{className:`dashboard-header-hidden${U?" is-drop-target":""}`,ref:z,onDragEnter:H=>{H.dataTransfer.types.includes("text/tab-key")&&(H.preventDefault(),L(!0))},onDragOver:H=>{H.dataTransfer.types.includes("text/tab-key")&&(H.preventDefault(),H.dataTransfer.dropEffect="move",L(!0))},onDragLeave:H=>{H.currentTarget.contains(H.relatedTarget)||L(!1)},onDrop:H=>{const V=H.dataTransfer.getData("text/tab-key");H.preventDefault(),L(!1),Ie(V)},children:[t.jsxs("button",{type:"button",onClick:()=>v(!x),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${C!=null&&C.toggleHiddenTabs?` (${C.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(Ii,{size:16}),d.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:d.length})]}),x&&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(Mo,{value:C==null?void 0:C.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[j&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:j,children:"Reset panels"}),d.length>0&&m&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{m(),v(!1)},children:"Restore all"})]})]}),e&&f&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>f(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(Mo,{value:C==null?void 0:C.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:rt(e)})]}),d.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(H=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(H),v(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:rt(H)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(H)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(H)+1]}):null,us(H)]})]},H.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>p(!S),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(Xr,{size:16}),ve>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:ve})]}),S&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[ae.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),ae.map(H=>t.jsx(Ao,{notification:H,shortcutIndex:ye.indexOf(H)>=0?ye.indexOf(H)+1:void 0,onOpen:()=>I(H),onMarkRead:()=>k(H.id),onMarkUnread:()=>w(H.id),onDelete:()=>g(H.id)},H.id))]}),be.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),be.map(H=>t.jsx(Ao,{notification:H,onOpen:()=>I(H),onMarkRead:()=>k(H.id),onMarkUnread:()=>w(H.id),onDelete:()=>g(H.id)},H.id))]}),A.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function pt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Qm(e,s){return String(e||"")!==String(s||"")}function Zm(e,s={}){const r=String(s.textQuery||"").trim().toLowerCase(),n=String(s.workspaceQuery||"").trim().toLowerCase(),a=String(s.modelQuery||"").trim().toLowerCase(),i=!!s.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(u=>String(u||"").toLowerCase()).join(`
|
|
30
|
-
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!Ki(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
|
|
31
|
-
`).includes(a)))}function ef(e,s="recent"){const r=e.slice();return r.sort((n,a)=>{if(s==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(s==="messages"){const i=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(i!==0)return i}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function fc(e,s={}){return ef(Zm(e,s),s.sortMode||"recent")}function Ur(e){return e?"Resume saved history":"Start fresh"}function Ta(e){return e?"Resuming saved history…":"Starting fresh…"}function tf(){return"Start fresh"}function pc(e,s=!1){return e==="cli"?Ur(s):e==="ide"?"Start IDE":"Start ACP session"}function hc(e,s=!1){return e==="cli"?Ta(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function sf(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function rf(){return"Open saved history"}function nf(){return"Saved History"}function La(){return"Use saved history when you want continuity in the same provider conversation."}function af(){return"No saved history found yet."}function of(){return"Refresh saved history"}function cf(){return"Refreshing saved history…"}function ss(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function rs(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 Ns(e){return e==="start-fresh"?"Start fresh":"Restart"}function Cs(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Ra(e){return`Resume saved history with ${e}?`}function Pa(){return"Review or change the target workspace before resuming saved history."}function lf(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 _a({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:f,onNewChat:d,onSwitchSession:h,onRefreshHistory:m,onResumeSavedSession:j}){var w;const S=s.find(g=>g.id===e.routeId),p=(S==null?void 0:S.chats)||[],x=(w=S==null?void 0:S.activeChat)==null?void 0:w.id,v=Je(e)&&!Ge(e),[b,C]=o.useState(()=>pt()),A=l||b,y=g=>{if(u){u(g);return}C(g)},I=o.useMemo(()=>fc(a,{textQuery:A.textQuery,workspaceQuery:A.workspaceQuery,modelQuery:A.modelQuery,resumableOnly:A.resumableOnly,sortMode:A.sortMode}),[A.modelQuery,A.resumableOnly,A.sortMode,A.textQuery,A.workspaceQuery,a]),k=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:f,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:v?nf():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:zm(e)}),v&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:La()})]}),t.jsx("button",{onClick:f,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(wt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!v&&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"}),v?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:A.textQuery,onChange:g=>y({...A,textQuery:g.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:A.workspaceQuery,onChange:g=>y({...A,workspaceQuery:g.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:A.modelQuery,onChange:g=>y({...A,modelQuery:g.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:A.sortMode,onChange:g=>y({...A,sortMode:g.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:A.resumableOnly,onChange:g=>y({...A,resumableOnly:g.target.checked})}),"Resume-ready only"]})]}),I.map(g=>{const E=e.providerSessionId===g.providerSessionId,T=E||!g.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{T||!j||j(g)},disabled:T,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"} ${T?"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:g.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:g.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:lf(g.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:g.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:[g.workspace||"Workspace unknown",ds(g.summaryMetadata)?` · ${ds(g.summaryMetadata)}`:"",g.messageCount>0?` · ${g.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:E?"ACTIVE":g.canResume?c===g.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},g.id)})]}):p.map(g=>t.jsxs("div",{onClick:()=>{h(e.routeId,g.id),f()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${x===g.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 ${x===g.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:g.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:[g.id.substring(0,12),"..."]}),x===g.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},g.id)),(v&&!i&&I.length===0||!v&&p.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(Ad,{size:32})}),t.jsx("div",{className:"text-[13px]",children:v?a.length>0?"No saved history matches these filters.":af():"No recent chat sessions found."})]}),v&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:cf()})})]}),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:m,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(er,{size:13})," ",v?of():"Refresh History"]})})})]})]});return typeof document>"u"?k:zs.createPortal(k,document.body)}const To={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 xc({toasts:e,onDismiss:s,onClickToast:r}){return t.jsx("div",{className:"fixed right-4 z-[9999] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const a=To[n.type]||To.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, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),t.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),s(n.id)},"aria-label":"Dismiss",children:t.jsx(wt,{size:14})}),t.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[t.jsx("div",{className:"flex items-center gap-2 pr-8",children:t.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),t.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&t.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((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 df=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function uf(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function mf(e){return e.sessionId||e.instanceId||e.agentType}function yn(e,s){return e||s}function bc(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=Tt(r,{fallbackId:r.id}));return s}function gc(e,s={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=s.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:s.connectionStates?s.connectionStates[r]||s.defaultConnectionState||"new":s.defaultConnectionState}}function Da(e,s={}){return ff(e,gc(e,s))}function ff(e,s={}){var d,h,m,j,S,p;const r=[],n=s.machineName,a=s.connectionState,i=uf(e),c=pu(e.type,{agentName:e.cliName}),l=Je(e)||Ge(e)?c:tt(e.type),u=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var v,b;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||tt(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((v=x.activeChat)==null?void 0:v.messages)||[],activeModal:((b=x.activeChat)==null?void 0:b.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,surfaceHidden:x.surfaceHidden}}):[],f=df(e);if(f){const x=e.sessionId||e.instanceId,v=c,b=(d=e.activeChat)==null?void 0:d.activeModal,C=b&&Array.isArray(b.buttons)&&b.buttons.length>0,A=bt((h=e.activeChat)==null?void 0:h.status,{activeModal:(m=e.activeChat)==null?void 0:m.activeModal})||bt((S=(j=e.agents)==null?void 0:j[0])==null?void 0:S.status)||"idle",y=e.activeChat||{title:"",messages:[]};let I=y.title&&String(y.title).trim()?String(y.title).trim():"";const k=(p=e.activeChat)==null?void 0:p.id,w=e.chats;if(k&&Array.isArray(w)&&w.length>0){const M=w.find(P=>P.id===k||P.id&&String(P.id)===String(k));M!=null&&M.title&&String(M.title).trim()&&(I=String(M.title).trim())}const g=(Je(e)||Ge(e),e.type),E=(Je(e)||Ge(e))&&yo(I,v,g)?"":I,T=y.messages||[];r.push({routeId:e.id,sessionId:x,providerSessionId:e.providerSessionId,nativeSessionId:x,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:Je(e)?e.mode||"terminal":"chat",agentName:v,agentType:g,status:A,title:E,messages:T,resume:e.resume,hostIdeType:!Je(e)&&!Ge(e)?e.type:void 0,workspaceName:i,displayPrimary:E||i||(Je(e)?e.mode==="chat"?v:"Terminal":v),displaySecondary:l,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:C?b.buttons:void 0,modalMessage:C?b.message:void 0,streamSource:"native",tabKey:yn(x,e.id),machineName:n,connectionState:a})}if(f&&(Je(e)||Ge(e)))return r;for(const x of u){const v=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,b=hu(x),C=mf(x),A=`${e.id}:${C}`,y=x.title&&String(x.title).trim()||"",I=yo(y,x.agentName,x.agentType)?"":y,k=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||k.length>0||v||I||!["idle","panel_hidden","disconnected","not_monitored"].includes(b))&&r.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:b,title:I,messages:k,hostIdeType:e.type,workspaceName:i,displayPrimary:I||i||x.agentName||l,displaySecondary:`${l} · ${x.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,lastUpdated:x.lastUpdated||e.lastUpdated,modalButtons:v?x.activeModal.buttons:void 0,modalMessage:v?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:yn(x.sessionId||x.instanceId,A),machineName:n,connectionState:a})}return r.length===0&&r.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:i,displayPrimary:i||l,displaySecondary:l,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:yn(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function pf(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 yc(e,s){const r=pf(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const vc=[{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:"🏄"}],wc=[{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:"🧩"}],jc=[{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:"🟠"}],hf=vc,xf=wc,bf=jc;function ms(...e){return Fl(Ul(e))}function gf({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:ms("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})]}),a&&t.jsx("div",{className:"flex gap-2",children:a})]})}function kc({icon:e,title:s,subtitle:r,badge:n,actions:a,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsx(gf,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:ms("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const na="adhdev:themechange";function yf(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function hs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function xs(e){return e==="system"?yf():e}function Sc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Lr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(na,{detail:{preference:e,theme:s}}))}function vf(){const e=hs(),s=xs(e);Sc(s),Lr(e,s)}function Ea(){const[e,s]=o.useState(hs),[r,n]=o.useState(()=>xs(hs()));o.useEffect(()=>{Sc(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const f=u.matches?"light":"dark";n(f),Lr("system",f)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const f=u.detail||{},d=f.preference,h=f.theme;s(d==="dark"||d==="light"||d==="system"?d:hs()),n(h==="dark"||h==="light"?h:xs(hs()))},l=u=>{if(u.key!=="theme")return;const f=hs(),d=xs(f);s(f),n(d)};return window.addEventListener(na,c),window.addEventListener("storage",l),()=>{window.removeEventListener(na,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=xs(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}Lr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=xs(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Lr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const Lo={dark:"Dark",light:"Light",system:"System"};function wf({collapsed:e}){const{preference:s,cycleTheme:r}=Ea(),n=s==="dark"?t.jsx(Ld,{size:16}):s==="light"?t.jsx(Td,{size:16}):t.jsx(Rd,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Lo[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:Lo[s]})]})}function vn(e,s){return e?typeof e=="function"?e(s):e:null}function jf({children:e,brand:s,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:i,footerActions:c,preMainContent:l,collapsedStorageKey:u="sidebar-collapsed"}){const[f,d]=o.useState(!1),[h,m]=o.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),j=()=>d(!0),S=()=>d(!1),p=()=>{m(C=>{const A=!C;try{localStorage.setItem(u,A?"1":"0")}catch{}return A})},x=o.useMemo(()=>({collapsed:h,mobileMenuOpen:f,openMobileMenu:j,closeMobileMenu:S,toggleCollapsed:p}),[h,f]),v=C=>`nav-item${C.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${C.className?` ${C.className}`:""}`,b=C=>t.jsxs("div",{className:v(C),id:`nav-${C.id}`,onClick:()=>{C.onSelect(),S()},title:h?C.title??(typeof C.label=="string"?C.label:void 0):C.title,children:[t.jsx("span",{className:"nav-icon",children:C.icon}),!h&&C.label]},C.id);return t.jsxs("div",{className:`app-layout${f?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[t.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:j,children:[t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"})]}),f&&t.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:S,onKeyDown:C=>C.key==="Escape"&&S()}),t.jsxs("aside",{className:`sidebar ${f?"sidebar-open":""}`,children:[t.jsxs("div",{className:"sidebar-header",children:[t.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:vn(s,x)}),t.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:S,children:t.jsx(wt,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:r.map(b)}),n.map(C=>t.jsxs("div",{className:C.className??"border-t border-border-subtle pt-2 mt-2",children:[!h&&C.title?t.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:C.title}):null,C.items.map(b)]},C.key)),t.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(b),vn(i,x),t.jsx(wf,{collapsed:h}),vn(c,x)]})]}),t.jsx("main",{className:"main-content relative",children:t.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function Nt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:ms("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&t.jsxs("div",{className:"mb-4",children:[e&&t.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[s&&t.jsx("span",{className:"mr-1.5",children:s}),e]}),r&&t.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function Nc({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:ms("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[t.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),t.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:s}),t.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const 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 gr({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:ms("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:ms("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:ms("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Cf[e])}),n]})}function Qt({label:e,description:s,checked:r,disabled:n,onChange:a,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:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[t.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),t.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function Mf({onPrefChange:e}){const[s,r]=Nu(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Xr,{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(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ct,{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:()=>{Hi().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&t.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&t.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),s.globalEnabled&&s.browserNotifications&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Pd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:c=>i("completionAlert",c)}),t.jsx(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(_d,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:c=>i("approvalAlert",c)}),t.jsx(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ys,{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 zr(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Af(e,s){const r=zr(e),n=zr(s);if(!r||!n)return e.localeCompare(s);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function Cc(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function Hs(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Af(r,s)>=0)return!1;const n=zr(r),a=zr(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Tf(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function wn(e,s){return e instanceof Error?e.message:s}function Lf({ides:e,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?t.jsx(Nc,{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(Pf,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Ro({title:e,message:s,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:i}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return zs.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:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function Rf(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...hf,...xf,...bf].find(a=>a.id===s||s.includes(a.id)||a.id.includes(s));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function Pf({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var K,U;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[f,d]=o.useState(null),[h,m]=o.useState("idle"),[j,S]=o.useState(""),p=e.version||null,x=((K=e.machine)==null?void 0:K.platform)||((U=e.system)==null?void 0:U.platform)||"",v=Tt(e,{fallbackId:e.id}),b=x==="win32"?"🪟":x==="darwin"?"🍎":"🐧",C=s.filter(L=>L.daemonId===e.id&&L.transport==="cdp-page"),A=s.filter(L=>L.daemonId===e.id&&L.transport==="pty"),y=s.filter(L=>L.daemonId===e.id&&L.transport==="acp"),I=e.p2p,k=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const L=Tf(await r(e.id,"daemon_upgrade",{}));L.alreadyLatest?(c("done"),u(`Already on v${L.version||"latest"}.`)):L.upgraded||L.success?(c("done"),u(`Upgrade to v${L.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(L.error||"Upgrade failed"))}catch(L){c("error"),u(wn(L,"Connection lost during upgrade"))}}},w=async()=>{if(d(null),!!n){m("loading");try{await n(e.id),m("done"),S("Machine disconnected.")}catch(L){m("error"),S(wn(L,"Failed to disconnect"))}}},g=async()=>{if(d(null),!!a){m("loading");try{await a(e.id),m("done"),S("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(L){m("error"),S(wn(L,"Failed to revoke token"))}}},E="0.9.11",T=Cc(e,E),M=Hs(e,E),P=C.length+A.length+y.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:b}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:v}),t.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[t.jsxs("span",{children:[e.id.substring(0,12),"…"]}),p&&t.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${T?"":"bg-bg-secondary"}`,style:T?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!T&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&T&&t.jsx("button",{onClick:k,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":`${M?"↑ Update now":`↑ Update${` to v${E}`}`}`}),n&&t.jsx("button",{onClick:()=>d("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&t.jsx("button",{onClick:()=>d("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(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:[I&&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 ${I.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${I.state==="connecting"||I.state==="new"?"animate-pulse":""}`,style:I.state==="connecting"||I.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",I.state==="connected"?"connected":I.state==="connecting"||I.state==="new"?"connecting...":I.state||"off"]}),I.peers!==void 0&&I.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",I.peers," peer",I.peers!==1?"s":"",")"]})]}),I&&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:[C.map(L=>{const R=Rf(L.type),z=L.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:R.icon}),t.jsx("span",{children:R.name}),z!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${z?"bg-green-400":"animate-pulse"}`,style:z?void 0:{background:"var(--status-warning)"},title:z?"CDP connected":"CDP connecting..."})]},L.id)}),A.map(L=>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:L.cliName||"CLI"})]},L.id)),y.map(L=>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:L.cliName||"ACP"})]},L.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||j)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||h==="error"?"text-red-400":i==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:j||l})]}),f==="disconnect"&&t.jsx(Ro,{title:"🔌 Disconnect Machine",message:`Disconnect "${v}" from ADHDev?
|
|
32
|
-
|
|
33
|
-
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
34
|
-
|
|
35
|
-
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:w,onCancel:()=>d(null)}),f==="revoke"&&t.jsx(Ro,{title:"⚠️ Remove Machine",message:`Remove "${v}" from your dashboard?
|
|
36
|
-
|
|
37
|
-
This will:
|
|
38
|
-
• Immediately disconnect the machine
|
|
39
|
-
• Delete the machine registration
|
|
40
|
-
• Require restarting ADHDev on that machine
|
|
41
|
-
|
|
42
|
-
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:g,onCancel:()=>d(null)})]})}const _f=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Df(){const{preference:e,setPreference:s}=Ea();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 Ef(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 $f(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function jn(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function Po(e){const{r:s,g:r,b:n}=$f(e);return .2126*jn(s)+.7152*jn(r)+.0722*jn(n)}function _o(e,s){const r=Po(e),n=Po(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function Ic(e){const s=Ef(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return _o(s,r)>=_o(s,n)?r:n}const aa={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},oa={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},Bf=[{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"}}}],Mc="adhdev-chat-theme",Ac="adhdev-chat-theme-custom";function Rr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Mc)||"ember"}catch{return"ember"}}function Pt(e){try{const s=localStorage.getItem(Ac);if(s){const r=JSON.parse(s);return{...e==="dark"?aa:oa,...r[e]}}}catch{}return e==="dark"?aa:oa}function yr(e,s){try{localStorage.setItem(Ac,JSON.stringify({dark:e,light:s}))}catch{}}function Mt(e,s){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${s})`}function Vr(e,s){const r=Math.min(255,parseInt(e.slice(1,3),16)+s),n=Math.min(255,parseInt(e.slice(3,5),16)+s),a=Math.min(255,parseInt(e.slice(5,7),16)+s);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const Kf={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Fs(e,s){var a;const r=(a=Kf[e])==null?void 0:a[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",Vr(r,24)),n.style.setProperty("--accent-on-primary",Ic(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Vr(r,18)})`),n.style.setProperty("--border-accent",Mt(r,.35)),n.style.setProperty("--nav-active-bg",Mt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Mt(r,.06)}`)}function ns(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Mt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Mt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Mt(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",Mt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Mt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",Vr(e.accentColor,30)),s.style.setProperty("--accent-on-primary",Ic(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Vr(e.accentColor,40)})`),s.style.setProperty("--border-accent",Mt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Mt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Mt(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 ${Mt(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 $a(){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 Of(e){try{localStorage.setItem(Mc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=as()?"dark":"light";ns(Pt(s))}else $a(),Fs(e,as()?"dark":"light")}function Wf(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Rr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=as()?"dark":"light";ns(Pt(s))}else $a(),Fs(e,as()?"dark":"light")}function as(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function xt({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 Ps({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 Hf({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>Pt(r));o.useEffect(()=>{a(Pt(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const f={...u,[c]:l},h=Pt(r==="dark"?"light":"dark");return r==="dark"?yr(f,h):yr(h,f),ns(f),s(f),f})},[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(Ps,{title:"App Background",children:[t.jsx(xt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(xt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(xt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs(Ps,{title:"App Text",children:[t.jsx(xt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(xt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(xt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs(Ps,{title:"Borders & Accent",children:[t.jsx(xt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(xt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(xt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs(Ps,{title:"Chat Bubbles",children:[t.jsx(xt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(xt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(xt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(xt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs(Ps,{title:"Chat Layout",children:[t.jsx(xt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(xt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(xt,{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?aa:oa,u=Pt(e?"light":"dark");e?yr(c,u):yr(u,c),a(c),ns(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 Ff(){const[e,s]=o.useState(Rr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Pt("dark"));o.useEffect(()=>{n(as());const u=new MutationObserver(()=>{const h=as();n(h);const m=Rr();m==="custom"?ns(Pt(h?"dark":"light")):Fs(m,h?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const h=as();n(h);const m=Rr();m==="custom"?ns(Pt(h?"dark":"light")):Fs(m,h?"dark":"light")};return f.addEventListener("change",d),()=>{u.disconnect(),f.removeEventListener("change",d)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ns(Pt(r?"dark":"light")):($a(),Fs(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Pt(r?"dark":"light"))},[r]);const c=u=>{s(u),Of(u)},l=[...Bf,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return t.jsxs("div",{children:[t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(u=>{const f=e===u.id,d=r?u.preview.dark:u.preview.light,h=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return t.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:f?"var(--bg-glass-hover)":"var(--bg-glass)",border:f?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:f?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:h},children:"Fix the bug please"}),t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[f&&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(Hf,{dark:r,onColorsChange:u=>i(u)})]})}const Ba="adhdev_mobileDashboardMode_v1",ia="adhdev:mobile-dashboard-mode-change";function Ka(){try{return localStorage.getItem(Ba)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Uf(e){if(typeof window>"u")return()=>{};const s=a=>{e(a??Ka())},r=a=>{const i=a.detail;s(i)},n=a=>{a.key&&a.key!==Ba||s()};return window.addEventListener(ia,r),window.addEventListener("storage",n),()=>{window.removeEventListener(ia,r),window.removeEventListener("storage",n)}}function zf(e){try{localStorage.setItem(Ba,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ia,{detail:e}))}function Vf(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(Ka()==="chat")},[]),t.jsx(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ft,{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),zf(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const kn=new Map,Do=new Map;function Gf(e){if(!e||typeof e!="object")return null;const s=e,r=s.result&&typeof s.result=="object"?s.result:s,n=r.machine;return!n||typeof n!="object"?null:{machine:n,timestamp:typeof r.timestamp=="number"?r.timestamp:void 0}}function qf(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 Tc(){const{sendCommand:e}=jt(),{injectEntries:s,getIdes:r}=Gs();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??dm,c=Do.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=kn.get(n);if(l)return l;const u=(async()=>{const f=await e(n,"get_machine_runtime_stats"),d=Gf(f);if(!d)return;const h=r().find(j=>j.id===n),m=qf(h,n,d.machine,d.timestamp||Date.now());s([m]),Do.set(n,Date.now())})().finally(()=>{kn.delete(n)});return kn.set(n,u),u},[r,s,e])}function Yf(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 Xf(e,s){const{sendData:r}=jt(),{injectEntries:n,getIdes:a}=Gs(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(u=>Gt.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:s==null?void 0:s.intervalMs}},d=>{const h=a().find(j=>j.id===u),m=Yf(h,u,d);n([m])}));return()=>{l.forEach(u=>u())}},[i,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}function Jf(e,s){const{sendData:r}=jt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const u=Gt.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}:{}}},f=>{l&&(clearTimeout(l),l=null),a(f.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},pm):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:a}}function Qf(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Lc(e){const{sendData:s}=jt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=Qf(e);if(!a||!e.sessionId||!s){n({});return}const i=Gt.subscribe({sendData:s},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),js.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 Rc="adhdev_hiddenTabs";function Zf(){try{const e=localStorage.getItem(Rc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function fs(e){try{localStorage.setItem(Rc,JSON.stringify([...e]))}catch{}}function Sn(e){return Na(e)}function Oa(e,s){return vs(s).some(r=>e.has(r))}function ep(){const[e,s]=o.useState(Zf),r=o.useCallback(f=>{const d=Sn(f);s(h=>{const m=new Set(h);return m.has(d)?m.delete(d):m.add(d),fs(m),m})},[]),n=o.useCallback(f=>{const d=Sn(f);s(h=>{if(h.has(d))return h;const m=new Set(h);return m.add(d),fs(m),m})},[]),a=o.useCallback(f=>{const d=Sn(f);s(h=>{if(!h.has(d))return h;const m=new Set(h);return m.delete(d),fs(m),m})},[]),i=o.useCallback(()=>{s(f=>{if(f.size===0)return f;const d=new Set;return fs(d),d})},[]),c=o.useCallback((f,d)=>{s(h=>{const m=new Set(h);for(const j of d)m.add(j);return fs(m),m})},[]),l=o.useCallback((f,d)=>{s(h=>{const m=new Set(h);for(const j of d)m.delete(j);return fs(m),m})},[]),u=o.useCallback(f=>Oa(e,f),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function Pc(e){return e instanceof Error?e.message:String(e||"")}function Wa(e){const s=Pc(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 Ha(e){const s=Pc(e);return s.includes("P2P command timeout")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function Eo(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 tp(e,s){if(!Array.isArray(e)||e.length===0||!s||Object.keys(s).length===0)return e;let r=!1;const n=e.map(a=>{const i=Eo(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>Eo(u,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function _c(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 sp(e,s){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,i]of Object.entries(e))_c(s,a)===i&&(delete n[a],r=!0);return r?n:e}function rp({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Hi()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:dc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Mu(a),o.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),f={};for(const[d,h]of Object.entries(l))u-h<5e3&&(f[d]=h);return Object.keys(f).length===Object.keys(l).length?l:f})},5500);return()=>clearTimeout(c)},[s,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const u=l.filter(f=>f.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(i)},[n]),null}function np(e){const s=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of s){const a=r.get(n.id);if(!a){r.set(n.id,n);continue}const i=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function Nn(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 ap(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 $o(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?ap(Vs(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 op(e){const s=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),$o(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastMessageAt||""),r.lastMessagePreview||"",r.lastMessageRole||"",String(r.lastUpdated||""),$o(r.activeChat)].join(":"))].join("|")}function ip(e,s){const r=Date.now();return e.map(n=>{const a=s[n.tabKey];return a&&r-a<5e3?{...n,messages:[],title:""}:n})}function cp(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const i of vs({routeId:n.routeId}))r.set(i,a);for(const i of vs({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of vs({tabKey:n.tabKey}))r.set(i,n)}return r}function lp(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function dp(e){const s=lp(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=Vs(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function up({ides:e,connectionStates:s,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>np(e),[e]),i=o.useMemo(()=>bc(e),[e]),c=o.useRef([]),l=o.useRef([]),u=o.useRef([]),f=o.useRef(new Map),d=o.useRef(new Map),h=o.useMemo(()=>{const A=new Map,y=[];for(const g of a){const{connectionState:E="new",machineName:T}=gc(g,{machineNames:i,connectionStates:s,defaultConnectionState:"new"}),M=op(g),P=f.current.get(g.id);if(P&&P.ide===g&&P.sourceSignature===M&&P.connectionState===E&&P.machineName===T){A.set(g.id,P),y.push(...P.conversations);continue}const K=Da(g,{machineNames:i,connectionStates:s,defaultConnectionState:"new"}),U={ide:g,sourceSignature:M,connectionState:E,machineName:T,conversations:K};A.set(g.id,U),y.push(...K)}f.current=A;const I=new Map,k=g=>{const E=dp(g),T=d.current.get(g.tabKey);if(T&&T.signature===E)return I.set(g.tabKey,T),T.timestamp;const M={signature:E,timestamp:Ji(g)||(T==null?void 0:T.timestamp)||0};return I.set(g.tabKey,M),M.timestamp},w=[...y].sort((g,E)=>Qi(g,E,k));return d.current=I,w},[a,s,i]),m=o.useMemo(()=>{const A=ip(h,r);return Nn(c.current,A)?c.current:(c.current=A,A)},[h,r]),j=o.useMemo(()=>{const A=new Map,y=Array.from(new Set(m.map(I=>I.routeId)));for(const I of y){const k=Dt(m,I);k&&A.set(I,k)}return A},[m]),S=o.useMemo(()=>{const A=new Map;for(const y of m){const I=j.get(y.routeId),k=y.streamSource==="native"&&I?I:y;for(const w of vs({providerSessionId:y.providerSessionId,sessionId:y.sessionId}))A.set(w,k)}return A},[m,j]),p=o.useMemo(()=>cp(m,j),[m,j]),x=o.useCallback(A=>{if(A)return S.get(A)},[S]),v=o.useCallback(A=>{if(A)return p.get(A)},[p]),b=o.useMemo(()=>{const A=m.filter(y=>!Oa(n,y));return Nn(l.current,A)?l.current:(l.current=A,A)},[m,n]),C=o.useMemo(()=>{const A=b.map(y=>y.tabKey);return Nn(u.current,A)?u.current:(u.current=A,A)},[b]);return{chatIdes:a,conversations:m,visibleConversations:b,visibleTabKeys:C,resolveConversationBySessionId:x,resolveConversationByTarget:v}}function mp({isMobile:e,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),i=o.useMemo(()=>{var l;return!e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),c=o.useCallback(()=>{s&&n(l=>{const u=new URLSearchParams(l);return u.delete("activeTab"),u},{replace:!0})},[n,s]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function fp({ides:e,sendDaemonCommand:s,setToasts:r,resolveConversationByTarget:n}){o.useEffect(()=>{lt.setIdes(e)},[e]),o.useEffect(()=>{lt.setResolveAction((a,i,c)=>{s(a,i,c).catch(()=>{})})},[s]),o.useEffect(()=>{const a=lt.onToast(i=>{r(l=>l.some(f=>f.message===i.message&&i.timestamp-f.timestamp<3e3)?l:[...l.slice(-4),{id:i.id,message:i.message,type:i.type,timestamp:i.timestamp,targetKey:i.targetKey,actions:i.actions}]);const c=i.duration||5e3;setTimeout(()=>r(l=>l.filter(u=>u.id!==i.id)),c)});return()=>{a()}},[r]),o.useEffect(()=>{const a=ic.on("status_event",i=>{lt.handleRawEvent(i,"ws")});return()=>{a()}},[]),o.useEffect(()=>{var i;const a=c=>{var p;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const u=l.targetSessionId||l.targetKey||l.daemonId,f=n(u),d=(f==null?void 0:f.routeId)||l.daemonId;if(!d)return;const h=Number(l.buttonIndex),m=l.button||((p=f==null?void 0:f.modalButtons)==null?void 0:p[h])||"Approve",j=String(m).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(j);s(d,"resolve_action",{action:S?"approve":"reject",button:m,...Number.isFinite(h)&&{buttonIndex:h},...(f==null?void 0:f.sessionId)&&{targetSessionId:f.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};return(i=navigator.serviceWorker)==null||i.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,s])}const pp="adhdev_dashboardLayout_v1",hp="adhdev_dashboardDockview_v1",xp="adhdev_dashboardDockviewHiddenRestore_v1",_s={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Fa(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function bp(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Dc(e){return`${pp}:${e}`}function gp(e){const s=Dc(e);return Fa(s,null)}function yp(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=Dc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function Ec(e){return`${hp}:${e}`}function vp(e){const s=Ec(e);return Fa(s,null)}function wp(e,s){try{const r=Ec(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function $c(e){return`${xp}:${e}`}function jp(e){const s=$c(e);return Fa(s,{})}function kp(e,s){try{const r=$c(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Sp(){return{groupAssignments:[..._s.groupAssignments],focusedGroup:_s.focusedGroup,groupActiveTabIds:{..._s.groupActiveTabIds},groupTabOrders:{..._s.groupTabOrders},groupSizes:[..._s.groupSizes]}}function Np(e,s){return e?e.length===s.length&&e.every((r,n)=>r===s[n]):s.length===0}function Cp(){const[e]=o.useState(()=>bp(typeof window<"u"?window.innerWidth:1280)),[s,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,u]=o.useState({}),[f,d]=o.useState([]),[h,m]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[j,S]=o.useState(!1),p=o.useCallback(()=>{if(j)return;const g=gp(e)??Sp();r(new Map(g.groupAssignments)),a(g.focusedGroup),c(g.groupActiveTabIds),u(g.groupTabOrders),d(g.groupSizes),S(!0)},[j,e]);o.useEffect(()=>{j&&yp(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:f})},[j,e,s,n,i,l,f]),o.useEffect(()=>{const g=window.matchMedia("(max-width: 767px)"),E=T=>m(T.matches);return g.addEventListener("change",E),()=>g.removeEventListener("change",E)},[]);const x=o.useCallback(g=>{r(g)},[]),v=o.useCallback(g=>{a(g)},[]),b=o.useCallback(g=>{c(g)},[]),C=o.useCallback(g=>{u(g)},[]),A=o.useCallback(g=>{d(g)},[]),y=o.useCallback(g=>{v(g)},[v]),I=o.useCallback((g,E)=>{c(T=>(T[g]??null)===(E??null)?T:{...T,[g]:E})},[]),k=o.useCallback((g,E)=>{u(T=>{const M=T[g];return Np(M,E)?T:{...T,[g]:E}})},[]),w=o.useCallback((g,E)=>{const T=E.get(g)??0;return I(T,g),y(T),T},[y,I]);return{layoutProfile:e,groupAssignments:s,updateGroupAssignments:x,focusedGroup:n,updateFocusedGroup:v,focusGroup:y,groupActiveTabIds:i,updateGroupActiveTabIds:b,setGroupActiveTab:I,groupTabOrders:l,updateGroupTabOrders:C,setGroupTabOrder:k,groupSizes:f,updateGroupSizes:A,isMobile:h,hasHydratedStoredLayout:j,hydrateStoredLayout:p,focusConversationTab:w}}function Ip(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=Sa(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Mp({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,focusConversationTab:c,setSearchParams:l,historyModalOpen:u,activeConv:f,isRefreshingHistory:d,ides:h,handleRefreshHistory:m}){const j=o.useRef(!1),S=o.useRef(!1),p=o.useRef(null),x=o.useRef(!1);o.useEffect(()=>{if(!e||j.current||s.length===0)return;if(!a){i();return}const v=r(e);v&&(c(v.tabKey,n),j.current=!0,S.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(b=>{const C=new URLSearchParams(b);return C.delete("activeTab"),C},{replace:!0}))},[e,s,r,n,a,i,c,l]),o.useEffect(()=>{if(!(S.current||a)&&s.length!==0){if(!e){i(),S.current=!0;return}if(j.current){S.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(S.current||a)&&(i(),S.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,s.length,a,i]),o.useEffect(()=>{if(!u){x.current=!1;return}if(!f||x.current||d)return;const v=h.find(b=>b.id===f.routeId);v&&(!v.chats||v.chats.length===0||Ip(v.chats,f))&&(x.current=!0,m())},[u,f,d,h,m]),o.useEffect(()=>{if(!f)return;let v=null,b=0,C=-1,A=0;const y=()=>{v=null;const I=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(w=>w.offsetParent!==null);if(I.length===0){b<18&&(b+=1,v=requestAnimationFrame(y));return}let k=0;for(const w of I)w.scrollTop=w.scrollHeight,k+=w.scrollHeight;k===C?A+=1:(A=0,C=k),b+=1,!(A>=2||b>=18)&&(v=requestAnimationFrame(y))};return v=requestAnimationFrame(y),()=>{v!=null&&cancelAnimationFrame(v)}},[f==null?void 0:f.tabKey])}function Cn(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=Sa(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Bc({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:i}){const[c,l]=o.useState(!1),[u,f]=o.useState(!1),d=o.useCallback(async S=>{try{await e("standalone","launch_ide",{ideType:S,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),h=o.useCallback(async(S,p)=>{try{const x=S||(s==null?void 0:s.daemonId)||"",v=await e(x,"switch_chat",{id:p,sessionId:p,...ws(s)}),b=v==null?void 0:v.result;if((v==null?void 0:v.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Rs(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Rs(a,`⚠️ Switch error: ${b}`):Rs(a,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),Rs(a,`❌ Switch failed: ${x.message||"connection error"}`)}},[s,e,a]),m=o.useCallback(async()=>{if(!(!s||c)){l(!0);try{const S=Js(s);await e(S,"new_chat",{...ws(s)}),i(p=>({...p,[s.tabKey]:Date.now()}))}catch(S){console.error("New chat failed",S)}finally{l(!1)}}},[s,c,e,i]),j=o.useCallback(async()=>{var S,p;if(!(!s||u)){f(!0);try{const x=Js(s),v=async()=>e(x,"list_chats",{forceExpand:!0,...ws(s)});let b=await v(),C=(b==null?void 0:b.chats)||((S=b==null?void 0:b.result)==null?void 0:S.chats);Cn(C,s)&&(await new Promise(A=>setTimeout(A,450)),b=await v(),C=(b==null?void 0:b.chats)||((p=b==null?void 0:b.result)==null?void 0:p.chats)),b!=null&&b.success&&Array.isArray(C)&&(n(s.routeId,C),Cn(C,s)&&!Cn(r,s)&&Rs(a,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{f(!1)}}},[s,r,u,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:h,handleNewChat:m,handleRefreshHistory:j}}function Ap(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 Tp(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function Bo(e,s){const r=Object.keys(e),n=Object.keys(s);return r.length!==n.length?!1:r.every(a=>s[Number(a)]===e[Number(a)])}function vr(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 a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const u=a[l];typeof u=="number"&&u>0&&i.set(c,u)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function Ko(e,s){const r={};for(const[n,a]of Object.entries(e)){const i=s[Number(n)];typeof i=="number"&&(r[i]=a)}return r}function Lp(e,s,r){if(s.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...s].reverse().find(a=>a<e)??s[0];return r[n]??0}function Rp(e,s,r){if(s.length<=1)return[];const n=s.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===s.length?n:Array(r).fill(100/r),i=a.reduce((c,l)=>c+l,0);return i>0?a.map(c=>c/i*100):Array(r).fill(100/r)}function Oo(e,s){const r={};for(const[n,a]of Object.entries(e)){const i=Number(n);r[i>=s?i+1:i]=a}return r}function Wo(e){return Array(e).fill(100/e)}function Pp({groupAssignments:e,updateGroupAssignments:s,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:i,updateGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:f}){const d=o.useRef(null),h=o.useMemo(()=>vr(e,f),[e,f]),m=h.assignments,j=o.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),S=j>1,p=o.useCallback((y,I)=>{s(k=>{const w=new Map(vr(k,f).assignments);return I===0?w.delete(y):w.set(y,I),w}),n(k=>({...k,[I]:y})),r(I)},[s,f,n,r]),x=o.useCallback(y=>{s(I=>{const k=vr(I,f).assignments,w=new Map;for(const[g,E]of k)E!==y&&(E>y?w.set(g,E-1):w.set(g,E));return w}),c(I=>{if(I.length<=1)return[];const k=[...I];k.splice(y,1);const w=k.reduce((g,E)=>g+E,0);return w>0?k.map(g=>g/w*100):[]}),r(0)},[s,f,c,r]),v=o.useCallback((y,I)=>{I.preventDefault();const k=d.current;if(!k)return;const w=I.clientX,g=k.offsetWidth,E=i.length===j?[...i]:Wo(j),T=P=>{const U=(P.clientX-w)/g*100,L=[...E];L[y]=Math.max(15,E[y]+U),L[y+1]=Math.max(15,E[y+1]-U),c(L)},M=()=>{document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",M),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",T),document.addEventListener("mouseup",M)},[i,j,c]),b=o.useCallback((y,I,k)=>{if(j>=4)return;const w=k==="left"?I:I+1;s(g=>{const E=vr(g,f).assignments,T=new Map;for(const M of u){const P=E.get(M.tabKey)??0,K=P>=w?P+1:P;K>0&&T.set(M.tabKey,K)}return w>0&&T.set(y,w),T}),c(g=>{const E=g.length===j?[...g]:Wo(j),T=E[I]??100/j,M=Math.max(15,T/2),P=Math.max(15,T/2),K=[...E];K[I]=M,K.splice(w,0,P);const U=K.reduce((L,R)=>L+R,0);return K.map(L=>L/U*100)}),n(g=>{const E=Oo(g,w);return E[w]=y,E}),a(g=>{const E=Oo(g,w);return E[w]=[y],E}),r(w)},[j,s,f,u,c,n,a,r]);o.useEffect(()=>{Ap(e,m)||s(m)},[e,m,s]),o.useEffect(()=>{const{mapping:y,usedGroups:I}=h;n(k=>{const w=Ko(k,y);return Bo(k,w)?k:w}),a(k=>{const w=Ko(k,y);return Bo(k,w)?k:w}),r(k=>{const w=l?0:Lp(k,I,y);return k===w?k:w}),c(k=>{const w=l?[]:Rp(k,I,h.groupCount);return Tp(k,w)?k:w})},[h,l,n,a,r,c]);const C=o.useMemo(()=>{const y=Array.from({length:j},()=>[]);for(const I of u){const k=m.get(I.tabKey)??0,w=Math.min(k,j-1);y[w].push(I)}return y},[u,m,j]),A=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:d,normalizedGroupAssignments:m,numGroups:j,isSplitMode:S,groupedConvs:C,moveTabToGroup:p,closeGroup:x,handleResizeStart:v,splitTabRelative:b,clearAllSplits:A}}function _p({ides:e,sendDaemonCommand:s}){const r="0.9.11",n=o.useMemo(()=>e.filter(d=>d.type!=="adhdev-daemon"?!1:Cc(d,r)).sort((d,h)=>Number(Hs(h,r))-Number(Hs(d,r))),[r,e]),a=o.useMemo(()=>n.some(d=>Hs(d,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),f=o.useCallback(async d=>{var h,m;u(j=>({...j,[d]:"upgrading"}));try{const j=await s(d,"daemon_upgrade",{});(h=j==null?void 0:j.result)!=null&&h.upgraded||(m=j==null?void 0:j.result)!=null&&m.success?u(S=>({...S,[d]:"done"})):u(S=>({...S,[d]:"error"}))}catch{u(j=>({...j,[d]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:f}}const Kc=80;function Pr(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function Dp(e){return{...e,createdAt:Pr(e.createdAt),updatedAt:Pr(e.updatedAt,e.createdAt),lastEventAt:Pr(e.lastEventAt,e.updatedAt||e.createdAt)}}function Ep(e){const s=Na(e);return s==="unknown:"?e.id:s}function $p(e){return[e.type,Xi(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Bp(e,s=Kc){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Ep(n),i=r.get(a);if(!i){r.set(a,n);continue}(n.updatedAt>i.updatedAt||n.updatedAt===i.updatedAt&&n.createdAt>i.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const i=a.updatedAt-n.updatedAt;return i!==0?i:a.createdAt-n.createdAt}).slice(0,Math.max(0,s))}function Kp(e,s){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?s.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=Qr(a,s),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const u=Pr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),f=$p({type:l,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(i==null?void 0:i.lastUpdated)||a.lastUpdated});n.push(Dp({id:f,dedupKey:f,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Gi(a),preview:Xu(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return Bp(n)}function Op(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function Wp(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=Kc}=e,a=o.useMemo(()=>Kp(s,r).slice(0,Math.max(0,n)),[s,r,n]),i=o.useMemo(()=>Op(a),[a]);return{notifications:a,unreadCount:i}}function Hp({notifications:e,sendDaemonCommand:s}){const r=o.useCallback(i=>{const c=e.find(u=>u.id===i),l=Math.max(Date.now(),(c==null?void 0:c.updatedAt)||0);c!=null&&c.sessionId&&s(c.machineId||c.routeId,"mark_session_seen",{sessionId:c.sessionId,seenAt:l}).catch(()=>{})},[e,s]),n=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&s(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,s]),a=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&s(c.machineId||c.routeId,"delete_notification",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,s]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}function tn(...e){const s=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();s.has(c)||(s.add(c),r.push(i))};for(const a of e){if(Array.isArray(a)){for(const i of a)n(i);continue}n(a)}return r}function Fp(e){const s=e.trim();if(!s)return null;if(s.startsWith("~"))return s;if(/^[A-Za-z]:$/.test(s))return`${s[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(s))return`${s[0].toUpperCase()}:${s.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(s))return`${s[0].toUpperCase()}:\\${s.slice(2).replace(/[\\/]+/g,"\\")}`;const r=s.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function sn(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=Fp(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 Up(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 zp(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function rn(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=zp(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const i=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=i.includes("\\")?"\\":"/",l=(f,d)=>/^[A-Za-z]:\\?$/.test(f)?`${f.replace(/\\?$/,"\\")}${d}`:f==="/"||f==="\\"?`${c}${d}`:`${f.replace(/[\\/]+$/,"")}${c}${d}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(f=>(f==null?void 0:f.type)==="directory"&&typeof(f==null?void 0:f.name)=="string").map(f=>({name:f.name,path:typeof(f==null?void 0:f.path)=="string"&&f.path.trim()?f.path:l(i,f.name)})).sort((f,d)=>f.name.localeCompare(d.name)):[];return{path:i,directories:u}}function Vp(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Ho(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Gp(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function qp({ides:e,conversations:s,onOpenSession:r}){const[n,a]=o.useState(null),i=o.useCallback(c=>{a(c)},[]);return o.useEffect(()=>{if(!n)return;const c=Ho(n.workspacePath),l=e.find(f=>{var S,p,x,v;if(!f||f.type==="adhdev-daemon"||Vp(f.daemonId||f.id)!==n.machineId||(Xs(f)?"cli":gs(f)?"acp":"ide")!==n.kind||String(f.agentType||f.type||"")!==n.providerType)return!1;if(n.resumeSessionId)return String(f.providerSessionId||"")===n.resumeSessionId;if(c){const b=Ho(f.workspace||f.runtimeWorkspaceLabel);return b?b===c:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((v=(x=(p=(S=f.activeChat)==null?void 0:S.messages)==null?void 0:p.at)==null?void 0:x.call(p,-1))==null?void 0:v.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const u=Zi({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:s});u&&(a(null),r(u))},[s,e,r,n]),o.useEffect(()=>{if(!n)return;const c=window.setTimeout(()=>{a(l=>!l||l.startedAt!==n.startedAt?l:null)},45e3);return()=>window.clearTimeout(c)},[n]),{trackPendingLaunch:i}}function Yp({sendDaemonCommand:e,trackPendingLaunch:s,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=o.useCallback(async(m,j)=>rn(e,m,j),[e]),l=o.useCallback(async(m,j)=>{if(!j.trim())return{ok:!1,error:"Choose a workspace path first."};try{const S=await e(m,"workspace_add",{path:j.trim()});return S!=null&&S.success?{ok:!0}:{ok:!1,error:(S==null?void 0:S.error)||"Could not save workspace"}}catch(S){return{ok:!1,error:S instanceof Error?S.message:"Could not save workspace"}}},[e]),u=o.useCallback(async(m,j,S)=>{var p;try{const x={ideType:j,enableCdp:!0};(p=S==null?void 0:S.workspacePath)!=null&&p.trim()&&(x.workspace=S.workspacePath.trim());const v=await e(m,"launch_ide",x);return!(v!=null&&v.success)&&(v==null?void 0:v.success)!==void 0?{ok:!1,error:(v==null?void 0:v.error)||"Could not launch IDE"}:(s({machineId:m,kind:"ide",providerType:j,workspacePath:(S==null?void 0:S.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Could not launch IDE"}}},[e,s]),f=o.useCallback(async(m,j,S,p)=>{var v,b,C;const x=Date.now();try{const A={cliType:S};(v=p==null?void 0:p.workspacePath)!=null&&v.trim()?A.dir=p.workspacePath.trim():p!=null&&p.workspaceId&&(A.workspaceId=p.workspaceId),(b=p==null?void 0:p.resumeSessionId)!=null&&b.trim()&&(A.resumeSessionId=p.resumeSessionId.trim()),Array.isArray(p==null?void 0:p.cliArgs)&&p.cliArgs.length>0&&(A.cliArgs=p.cliArgs),(C=p==null?void 0:p.initialModel)!=null&&C.trim()&&(A.initialModel=p.initialModel.trim());const y=await e(m,"launch_cli",A),I=(y==null?void 0:y.result)||y,k=(I==null?void 0:I.sessionId)||(I==null?void 0:I.id);return y!=null&&y.success&&k?(r(k),{ok:!0}):y!=null&&y.success?(s({machineId:m,kind:j,providerType:S,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:x}),{ok:!0}):{ok:!1,error:(y==null?void 0:y.error)||(I==null?void 0:I.error)||`Could not launch ${j.toUpperCase()} session`}}catch(A){return Gp(A)?(s({machineId:m,kind:j,providerType:S,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:x}),{ok:!0}):{ok:!1,error:A instanceof Error?A.message:`Could not launch ${j.toUpperCase()} session`}}},[r,e,s]),d=o.useCallback(async(m,j)=>{if(!m||!j)return[];try{const S=await e(m,"list_saved_sessions",{providerType:j,kind:"cli",limit:30}),p=(S==null?void 0:S.result)??S;return Array.isArray(p==null?void 0:p.sessions)?p.sessions:[]}catch(S){return console.error("List saved sessions failed",S),[]}},[e]),h=o.useCallback(async m=>{if(!n||!Je(n)||Ge(n))return;const j=As(n);if(j===m)return;const S=n.sessionId;S&&i(p=>({...p,[S]:m}));try{await e(qt(n)||n.routeId,"set_cli_view_mode",{targetSessionId:n.sessionId,cliType:_t(n),mode:m})}catch(p){const x=Ha(p);S&&!x&&i(v=>{const b={...v};return j===_c(a,S)?delete b[S]:b[S]=j,b}),Wa(p)?console.warn(x?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",p instanceof Error?p.message:String(p)):console.error("Failed to switch CLI view mode:",p)}},[n,a,e,i]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:l,handleLaunchMachineIde:u,handleLaunchMachineProvider:f,handleListMachineSavedSessions:d,setActiveCliViewMode:h}}function Xp(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 Jp(e,s,r=Date.now()){return!e||!Xp(s)?null:{tabKey:e,nonce:r}}function Qp({isMobile:e,conversations:s,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:i,setSearchParams:c}){const[l,u]=o.useState(null),[f,d]=o.useState(null),h=o.useMemo(()=>{var x,v;if(!e){if(l){const b=s.find(C=>C.tabKey===l);if(b)return b}return r[0]}const p=n[a];if(p){const b=s.find(C=>C.tabKey===p);if(b)return b}return((x=i[a])==null?void 0:x[0])||((v=i[0])==null?void 0:v[0])},[s,l,a,n,i,e,r]),m=o.useCallback(p=>{u(p)},[]),j=o.useCallback(p=>{u(p.tabKey),c(x=>{const v=new URLSearchParams(x),b=Qu(p);return b?v.set("activeTab",b):v.delete("activeTab"),v},{replace:!0})},[c]),S=o.useCallback((p,x)=>{const v=Jp(p,x);v&&d(v)},[]);return{activeConv:h,openDesktopConversation:j,requestScrollToBottom:S,scrollToBottomRequest:f,setDesktopActiveTab:m}}function Zp({activeConv:e,remoteDialogConv:s,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:u}){var L;const[f,d]=o.useState(!1),[h,m]=o.useState([]),[j,S]=o.useState(()=>pt()),[p,x]=o.useState(!1),[v,b]=o.useState(null),C=o.useRef(null),A=o.useMemo(()=>r||s||e,[e,r,s]),y=!!A&&Je(A)&&!Ge(A),I=o.useMemo(()=>{if(!A||!y)return null;const R=A.daemonId||A.routeId||"",z=_t(A);return`${R}:${z}`},[A,y]),{isCreatingChat:k,isRefreshingHistory:w,handleSwitchSession:g,handleNewChat:E,handleRefreshHistory:T}=Bc({sendDaemonCommand:a,activeConv:A,chats:(L=n.find(R=>R.id===(A==null?void 0:A.routeId)))==null?void 0:L.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),M=o.useCallback(()=>{d(!0)},[]),P=o.useCallback(()=>{d(!1)},[]),K=o.useCallback(async()=>{if(!(!A||!y||p)){x(!0);try{const R=A.daemonId||A.routeId,z=_t(A),$=await a(R,"list_saved_sessions",{agentType:z,providerType:z,kind:"cli",limit:50}),_=($==null?void 0:$.result)??$;m(Array.isArray(_==null?void 0:_.sessions)?_.sessions:[])}catch(R){console.error("Refresh saved sessions failed",R),m([])}finally{x(!1)}}},[A,p,y,a]);o.useEffect(()=>{if(!f){C.current=null;return}if(!y){C.current=null,m([]),x(!1);return}!I||p||C.current!==I&&(C.current=I,K())},[K,f,p,y,I]);const U=o.useCallback(async R=>{if(!A||!y||!R.providerSessionId||!R.workspace)return;const z=A.daemonId||A.routeId,$=_t(A);try{b(R.providerSessionId);const _=await a(z,"launch_cli",{cliType:$,dir:R.workspace,resumeSessionId:R.providerSessionId,initialModel:Oi(R.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Y=(_==null?void 0:_.result)??_,J=typeof(Y==null?void 0:Y.sessionId)=="string"?Y.sessionId:typeof(Y==null?void 0:Y.id)=="string"?Y.id:"";J&&u(pe=>{const ae=new URLSearchParams(pe);return ae.set("activeTab",J),ae},{replace:!0}),P()}catch(_){console.error("Resume saved session failed",_)}finally{b(null)}},[P,A,y,a,u]);return{historyModalOpen:f,openHistoryModal:M,closeHistoryModal:P,historyTargetConv:A,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:k,isHistoryRefreshingHistory:w,handleHistorySwitchSession:g,handleHistoryNewChat:E,handleHistoryRefresh:T,savedHistorySessions:h,savedHistoryFilters:j,setSavedHistoryFilters:S,isSavedHistoryLoading:p,resumingSavedHistorySessionId:v,handleRefreshSavedHistory:K,handleResumeSavedHistorySession:U}}function eh({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,f]=o.useState(null),[d,h]=o.useState(null),m=o.useMemo(()=>{if(e||!n)return null;const v=l(n);return v&&!Je(v)&&!Ge(v)?v:null},[e,n,l]),j=o.useMemo(()=>{const v=u==null?void 0:u.routeId;if(!v)return null;const b=u!=null&&u.tabKey?i.find(C=>C.tabKey===u.tabKey):a?i.find(C=>C.tabKey===a):null;return(b==null?void 0:b.routeId)===v?b:Dt(i,v)},[i,u,a]),S=o.useMemo(()=>{if(j)return c.find(v=>v.id===j.routeId)},[c,j]);o.useEffect(()=>{m&&(f({routeId:m.routeId,tabKey:jo(m)}),h(m),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,m]);const p=o.useCallback(v=>{v&&(f({routeId:v.routeId,tabKey:jo(v)}),h(v))},[]),x=o.useCallback(()=>{f(null),h(null)},[]);return{remoteDialogConv:j,remoteDialogIdeEntry:S,remoteDialogActiveConv:d,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:x}}function th({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l,activeConv:u,sendDaemonCommand:f}){const{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:m,setRemoteDialogActiveConv:j,openRemoteDialog:S,closeRemoteDialog:p}=eh({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[x,v]=o.useState(!1),[b,C]=o.useState(null),A=o.useCallback(async k=>{const w=k||u;!w||!Je(w)&&!Ge(w)||(C(w),v(!0))},[u]),y=o.useCallback(()=>{v(!1),C(null)},[]),I=o.useCallback(async k=>{const w=b||u;if(!w||!Je(w)&&!Ge(w)){y();return}v(!1);try{const g=_t(w),E=w.routeId||w.daemonId||"";await f(E,"stop_cli",{cliType:g,targetSessionId:w.sessionId,mode:k})}catch(g){console.error("Stop CLI failed:",g)}finally{C(null)}},[u,y,b,f]);return{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:m,setRemoteDialogActiveConv:j,openRemoteDialog:S,closeRemoteDialog:p,cliStopDialogOpen:x,cliStopTargetConv:b,requestCliStop:A,cancelCliStop:y,confirmCliStop:I}}function Oc(){return"select_session"}function sh(){return"open_panel"}function rh({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function nh(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function Fo(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function Uo(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Ua(e){return e instanceof Error?e.message:String(e||"")}function zo(e){const s=Ua(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Vo(e,s){const r=Ua(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function nn({sendDaemonCommand:e,activeConv:s,setActionLogs:r,isStandalone:n}){const[a,i]=o.useState(!1),[c,l]=o.useState(!1),[u,f]=o.useState(null),d=o.useRef(!1),h=o.useRef(null);o.useEffect(()=>{f(null)},[s==null?void 0:s.tabKey]);const m=o.useCallback(async x=>{if(!s)return!1;const v=x.trim(),b=Ia(s);if(rh({hasMessage:!!v,blockedMessage:b,sendInFlight:d.current}))return b&&f(b),!1;const C=Date.now(),A={tabKey:s.tabKey,message:v,timestamp:C};if(nh(h.current,A))return f(null),!0;d.current=!0,l(!0),f(null),h.current=A;try{const y=Js(s);if(!y)return h.current=Fo(h.current,A),f("Unable to send message right now."),!1;const I=await e(y,"send_chat",{message:v,...ws(s)}),k=Uo(I);if(k!=null&&k.deduplicated)return f(null),!0;if((k==null?void 0:k.sent)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");if((k==null?void 0:k.success)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");return f(null),!0}catch(y){const I=Ua(y);return I.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",I):console.warn("Send blocked/failed",y),h.current=Fo(h.current,A),f(gm(y)),!1}finally{d.current=!1,l(!1)}},[s,e]),j=o.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]),S=o.useCallback(async x=>{if(s)try{const b=(s.modalButtons||[]).indexOf(x),C=x.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),A=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(C),y=Js(s);if(!y)return;const I=await e(y,"resolve_action",{button:x,action:A?"approve":"reject",...b>=0&&{buttonIndex:b},...ws(s)}),k=Uo(I);k.success||r(w=>[...w,{routeId:s.tabKey,text:Vo(x,k==null?void 0:k.error),timestamp:Date.now()}])}catch(v){zo(v)||console.error("[ModalButton] Error:",v),r(b=>[...b,{routeId:s.tabKey,text:zo(v)?Vo(x,v):`❌ **${x}** error`,timestamp:Date.now()}])}},[s,e,r]),p=o.useCallback(async()=>{if(!(!s||a)){i(!0);try{await e(s.routeId,sh(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(x){console.error("Focus agent failed",x)}finally{i(!1)}}},[s,a,e]);return{isSendingChat:c,sendFeedbackMessage:u,isFocusingAgent:a,handleSendChat:m,handleRelaunch:j,handleModalButton:S,handleFocusAgent:p}}const za=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d=null,handleFocusAgent:h,isFocusingAgent:m,actionLogs:j,userName:S,scrollToBottomRequestNonce:p,isInputActive:x=!0}){const[v,b]=o.useState(n),C=o.useRef(n);o.useEffect(()=>{const w=C.current;if(C.current=n,!n){b(!1);return}if(w){b(!0);return}b(!1);let g=0,E=0;return g=window.requestAnimationFrame(()=>{E=window.requestAnimationFrame(()=>{b(!0)})}),()=>{window.cancelAnimationFrame(g),window.cancelAnimationFrame(E)}},[n]);const A=n&&v,y=!n||!v,I=Lc(s),k=I.status||I.modalMessage||I.modalButtons?{...s,...I.status?{status:I.status}:{},...I.modalMessage!==void 0?{modalMessage:I.modalMessage}:{},...I.modalButtons!==void 0?{modalButtons:I.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(Di,{activeConv:k,onModalButton:c}),k.transport!=="pty"&&k.transport!=="acp"&&k.cdpConnected===!1?t.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:t.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[t.jsx("span",{className:"text-sm",children:t.jsx(qs,{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,k.transport==="pty"?t.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[t.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:A?"visible":"hidden",pointerEvents:A?"auto":"none"},children:t.jsx(Gm,{activeConv:k,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,isVisible:n,isInputActive:x&&n})}),t.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:y?"visible":"hidden",pointerEvents:y?"auto":"none"},children:t.jsx(ra,{activeConv:k,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:m,actionLogs:j,userName:S,scrollToBottomRequestNonce:p,isInputActive:x&&y,isVisible:y})})]}):t.jsx(ra,{activeConv:k,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:m,actionLogs:j,userName:S,scrollToBottomRequestNonce:p,isInputActive:x})]})},(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 ah({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:f,onOpenNativeConversation:d,onOpenMachine:h,onOpenHistory:m,onOpenRemote:j,onHideConversation:S,onStopCli:p,cliViewMode:x,onSetCliViewMode:v,handleSendChat:b,handleFocusAgent:C,handleModalButton:A,handleRelaunch:y}){const I=o.useRef(null),k=Je(e)&&!s,w=k&&x==="terminal",g=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 ${g} 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:f,type:"button","aria-label":"Back",children:t.jsx(ha,{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:rt(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(ec,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>h(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[k&&x&&t.jsx(Aa,{mode:x,onChange:v,compact:!0}),k&&p&&t.jsx("button",{onClick:()=>{p(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(wt,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(e),type:"button",children:t.jsx(xa,{size:14})}),!s&&!k&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>j(e),type:"button",children:t.jsx(Ct,{size:14})}),S&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",title:"Close chat",children:t.jsx(wt,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(za,{activeConv:e,clearToken:0,isCliTerminal:w,ideEntry:n,terminalRef:I,handleModalButton:A,handleRelaunch:y,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:C,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const In={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 oh(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Wc(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(oh())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(In[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:In[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:In[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:a?"✓":"📋"})]}),t.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",t.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function Hc({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Ct},{key:"chats",label:"Chats",icon:Ft}];return t.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:t.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:a,icon: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:a})]},n)})})})}function wr({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 ps({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 Ds({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 jr({item:e,type:s,getAvatarText:r,onOpenConversation:n}){const a=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",l=s==="task_complete",{isReconnecting:u,isConnecting:f}=Ms(e.conversation),d=rt(e.conversation),h=us(e.conversation),m=lc(e.conversation,{requiresAction:s==="needs_attention"}),j=a?"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",S=a?"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",p=c?"text-text-secondary":"text-text-primary",x=c?"text-text-muted":"text-text-secondary",v=c?"text-text-secondary opacity-80":"text-text-muted",b=c?"text-text-muted opacity-80":"text-text-muted",C="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] ${j}`,onClick:()=>n(e.conversation),type:"button",children:[a||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 ${S}`,style:a?{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 ${p}`,children:d}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${b}`,children:_i(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${x}`,children:[h,u?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${C} animate-pulse`,children:"Reconnecting…"})]}):f?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):m==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:C,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${v}`,children:e.preview})]}),a&&!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 Go({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 ih({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:f,onShowAllHidden:d,onOpenNewSession:h,onOpenMachine:m,onOpenSettings:j,onSectionChange:S,wsStatus:p="connected",isStandalone:x=!1}){const v=p==="disconnected"||p==="reconnecting"||p==="offline"||p==="auth_failed",b=c.length>0,C=s.length>0||r.length>0||n.length>0||a.length>0,A=e==="machines"?"Machines":"Chats",y=x?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",I=x?"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 ${y}`,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:A}),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(Xr,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:j,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(Yr,{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] ${I}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:v?t.jsx(Ds,{icon:t.jsx(Go,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:p==="offline"?"Your device appears to be offline. Waiting for network…":p==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?t.jsx(Ds,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:x?"Waiting for your daemon":"Connect your machines",subtitle:x?"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:!x&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(Wc,{})})}):t.jsx(ps,{children:c.map((k,w)=>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] ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>m(k.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(k.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:k.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:k.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[k.unread," new"]}):k.total>0?`${k.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:k.subtitle}),k.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[k.total," chat",k.total!==1?"s":"",k.unread>0?` · ${k.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},k.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(wr,{title:"Needs attention",className:"mb-0"}),t.jsx(ps,{children:s.map((k,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(jr,{item:k,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},k.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(wr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(ps,{children:r.map((k,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(jr,{item:k,type:"task_complete",getAvatarText:l,onOpenConversation:u})},k.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(wr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(ps,{children:n.map((k,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(jr,{item:k,type:"working",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&t.jsx(wr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(ps,{children:a.map((k,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(jr,{item:k,type:"earlier",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))}):C?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):v?t.jsx(Ds,{icon:t.jsx(Go,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):b?t.jsx(Ds,{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(Ft,{size:20})}),title:"No conversations yet",subtitle:mc,children:h&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":Bt,title:Bt,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:Bt})]})}):t.jsx(Ds,{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(ps,{className:"bg-bg-secondary/25",children:i.map((k,w)=>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 ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(k),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(rt(k))}),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:rt(k)}),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:us(k)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},k.tabKey))})]})]}),e==="chats"&&h&&C&&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:h,"aria-label":Bt,title:Bt,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(Hc,{section:e,onSectionChange:S})]})}function ch(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 Fc(e){const s=[e.workspace||"Workspace unknown"],r=ds(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=ch(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function an({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:f}){const[d,h]=o.useState(r);o.useEffect(()=>{h(r)},[r]);const m=Up(r),j=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(wt,{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:()=>{!m||a||u(m)},disabled:!m||a,children:[t.jsx(ha,{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:S=>h(S.target.value),onKeyDown:S=>{S.key!=="Enter"||!j||a||(S.preventDefault(),u(j))},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:()=>{!j||a||u(j)},disabled:!j||a,children:"Go"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):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(S=>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(S.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(ks,{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:S.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:S.path})]})]},S.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:()=>f(j||r),disabled:!j&&!r||a,children:c})]})]})})}function Va({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:f,argsValue:d,onArgsChange:h,showModelInput:m,modelValue:j,onModelChange:S,historyProviderNode:p,onConfirm:x,onCancel:v}){const b=n==null?void 0:n.find(C=>C.key===a);return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:t.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:v,"aria-label":"Close launch confirmation",children:t.jsx(wt,{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:a||"",onChange:C=>i(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:n.map(C=>t.jsx("option",{value:C.key,children:C.label},C.key))}),(b==null?void 0:b.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:b.description})]}),p,r.map(C=>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:C.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:C.value})]},`${C.label}:${C.value}`)),m&&S&&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:j||"",onChange:C=>S(C.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),f&&h&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),t.jsx("input",{type:"text",value:d||"",onChange:C=>h(C.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled: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:v,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:x,disabled:u,children:[t.jsx(ga,{size:14}),u?l:c]})]})]})})}function qo(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function os(e){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of s.workspaces||[])i.push({key:`saved:${u.id}`,label:`${u.id===s.defaultWorkspaceId?"⭐ ":""}${qo(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:qo(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(f=>f.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 lh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function dh(e){return[lh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function uh(e){return e.lastLaunchedAt?Jr(e.lastLaunchedAt):""}function Uc(e){return{metaText:dh(e),updatedLabel:uh(e)}}function Mn(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function mh({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var yt,ut,Ye,nt;const c=nr(),[l,u]=o.useState(!1),f=(((yt=e.detectedIdes)==null?void 0:yt.length)||0)>0,d=o.useMemo(()=>(e.workspaces||[]).map(je=>({id:je.id,path:je.path,label:je.label})),[e]),h=e.defaultWorkspaceId||null,[m,j]=o.useState(h||((ut=d[0])==null?void 0:ut.id)||""),[S,p]=o.useState(""),[x,v]=o.useState(""),[b,C]=o.useState([]),[A,y]=o.useState(!1),[I,k]=o.useState(""),[w,g]=o.useState(!1),[E,T]=o.useState(Mn(f,s.length,r.length)),M=o.useRef(null),[P,K]=o.useState(null),U=o.useRef("__home__"),[L,R]=o.useState("__home__"),[z,$]=o.useState(""),[_,Y]=o.useState(""),[J,pe]=o.useState(""),[ae,be]=o.useState([]),[ye,ve]=o.useState(()=>pt().textQuery),[Ie,H]=o.useState(()=>pt().workspaceQuery),[V,Q]=o.useState(()=>pt().modelQuery),[ue,re]=o.useState(()=>pt().resumableOnly),[le,se]=o.useState(()=>pt().sortMode),[me,ne]=o.useState(!1),[ce,oe]=o.useState(!1),we=o.useRef(null),he=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const Se=m==="__custom__"?S.trim():((Ye=d.find(je=>je.id===m))==null?void 0:Ye.path)||"",N=m==="__custom__"&&!!Se&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),O=m!=="__custom__"&&((nt=d.find(je=>je.id===m))==null?void 0:nt.path)||"",G=o.useMemo(()=>(e.recentLaunches||[]).map(je=>je.workspace),[e]),Z=o.useCallback(async je=>{y(!0),k("");try{const $e=await a(je);v($e.path),p($e.path),C($e.directories)}catch($e){k($e instanceof Error?$e.message:"Could not load folder")}finally{y(!1)}},[a]),fe=o.useCallback(()=>{var $e;j("__custom__"),g(!0);const je=sn(e.platform,tn(S.trim(),O,G,e.defaultWorkspacePath,($e=d.find(Ke=>Ke.id===h))==null?void 0:$e.path,d.map(Ke=>Ke.path)));Z(je)},[S,h,Z,G,O,e.platform,d]),ge=o.useCallback(je=>{if(je!=null&&je.workspaceId){j(je.workspaceId),p("");return}if(je!=null&&je.workspacePath){j("__custom__"),p(je.workspacePath);return}j(""),p("")},[]),Pe=o.useCallback(je=>{if(j(je),je==="__custom__"){fe();return}p("")},[fe]),Ee=o.useCallback(je=>{j("__custom__"),p(je)},[]),We=o.useCallback((je,$e)=>{M.current=$e,U.current=je.selectedWorkspaceKey||"__home__",R(je.selectedWorkspaceKey||"__home__"),$(je.initialArgs||""),Y(je.initialModel||""),pe(""),be([]);const Ke=je.providerType?`${e.id}:${je.providerType}`:null;if(Qm(he.current,Ke)){const st=pt();ve(st.textQuery),H(st.workspaceQuery),Q(st.modelQuery),re(st.resumableOnly),se(st.sortMode)}he.current=Ke,K(je),je.providerType&&i&&(ne(!0),i(je.providerType).then(st=>be(st||[])).catch(st=>console.warn("Failed to load saved sessions",st)).finally(()=>ne(!1)))},[i,e.id]),ze=o.useMemo(()=>fc(ae,{textQuery:ye,workspaceQuery:Ie,modelQuery:V,resumableOnly:ue,sortMode:le}),[V,ue,ae,le,ye,Ie]);o.useEffect(()=>{J&&(ze.some(je=>je.providerSessionId===J)||pe(""))},[ze,J]);const Qe=o.useCallback(()=>{M.current&&(oe(!0),M.current().finally(()=>{M.current=null,oe(!1),K(null)}))},[]),Ze=o.useCallback(()=>{M.current=null,K(null)},[]),it=o.useCallback(je=>{U.current=je,R(je)},[]);return o.useEffect(()=>{var je;we.current!==e.id&&(we.current=e.id,j(h||((je=d[0])==null?void 0:je.id)||"__custom__"),p(""),v(""),C([]),k(""),g(!1),ve(pt().textQuery),H(pt().workspaceQuery),Q(pt().modelQuery),re(pt().resumableOnly),se(pt().sortMode),he.current=null,T(Mn(f,s.length,r.length)))},[r.length,s.length,h,f,e.id,d]),o.useEffect(()=>{var je;m!=="__custom__"&&(m&&d.some($e=>$e.id===m)||j(h||((je=d[0])==null?void 0:je.id)||"__custom__"))},[h,m,d]),o.useEffect(()=>{E==="ide"&&f||E==="cli"&&s.length>0||E==="acp"&&r.length>0||T(Mn(f,s.length,r.length))},[E,r.length,s.length,f]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:f,workspaceRows:d,defaultWorkspaceId:h,workspaceChoice:m,customWorkspacePath:S,browseCurrentPath:x,browseDirectories:b,browseBusy:A,browseError:I,browseDialogOpen:w,activeLauncherKind:E,launchConfirm:P,launchConfirmWorkspaceKeyRef:U,launchConfirmWorkspaceKey:L,launchConfirmArgs:z,launchConfirmModel:_,launchConfirmResumeId:J,launchConfirmSavedSessions:ae,launchConfirmTextFilter:ye,launchConfirmWorkspaceFilter:Ie,launchConfirmModelFilter:V,launchConfirmResumableOnly:ue,launchConfirmSortMode:le,filteredLaunchConfirmSavedSessions:ze,launchConfirmSessionsLoading:me,launchConfirmBusy:ce,resolvedWorkspacePath:Se,canCreateMissingWorkspace:N,openBrowseDialog:fe,loadBrowsePath:Z,handleWorkspaceChoiceChange:Pe,chooseCustomWorkspacePath:Ee,setCustomWorkspacePath:p,setBrowseDialogOpen:g,setActiveLauncherKind:T,openLaunchConfirm:We,handleConfirmLaunch:Qe,closeLaunchConfirm:Ze,setWorkspaceSelectionFromOption:ge,setLaunchConfirmWorkspaceKeyAndSync:it,setLaunchConfirmArgs:$,setLaunchConfirmModel:Y,setLaunchConfirmResumeId:pe,setLaunchConfirmTextFilter:ve,setLaunchConfirmWorkspaceFilter:H,setLaunchConfirmModelFilter:Q,setLaunchConfirmResumableOnly:re,setLaunchConfirmSortMode:se}}function fh({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:f,showBottomNav:d,onBack:h,onSectionChange:m,onOpenConversation:j,onOpenRecent:S,onOpenMachineDetails:p,onMachineUpgrade:x,onLaunchDetectedIde:v,onAddWorkspace:b,onBrowseDirectory:C,onLaunchWorkspaceProvider:A,onListSavedSessions:y}){const I=L=>L==="ide"?"IDE":L==="cli"?"CLI":"ACP",k=r.slice(0,4),w=s.slice(0,3),g=mh({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:C,onListSavedSessions:y}),E=o.useMemo(()=>k.map(L=>{const{metaText:R,updatedLabel:z}=Uc(L);return{key:`recent-launch:${L.id}`,primary:L.label,secondary:R,updatedLabel:z,onClick:()=>{const{options:$,selectedKey:_}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspacePath:L.workspace});g.openLaunchConfirm({title:L.kind==="ide"?ss("restart-ide",L.label):L.providerSessionId?Ra(L.label):ss("start-fresh",L.label),description:L.kind==="ide"?rs("restart-ide"):L.providerSessionId?Pa():rs("start-fresh"),confirmLabel:L.kind==="ide"?Ns("restart-ide"):L.providerSessionId?Ur(!0):Ns("start-fresh"),busyLabel:L.kind==="ide"?Cs("restart-ide"):L.providerSessionId?Ta(!0):Cs("start-fresh"),workspaceOptions:$,selectedWorkspaceKey:_,details:[{label:"Mode",value:I(L.kind)},...L.providerType?[{label:"Provider",value:L.providerType}]:[]]},async()=>{const Y=$.find(J=>J.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(Y),await S({...L,workspace:(Y==null?void 0:Y.workspacePath)??null})})}}}),[g,S,k]),T=o.useMemo(()=>w.map(L=>({key:`recent-chat:${L.conversation.tabKey}`,primary:rt(L.conversation),secondary:Fm(L.conversation,{timestampLabel:L.timestamp?_i(L.timestamp):null}),unread:L.unread,onClick:()=>j(L.conversation)})),[j,w]),M=g.showAllRecent?E:E.slice(0,4),P=E.length>0,K=T.length>0,U=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 ${U} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":"Back",children:t.jsx(ha,{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:Tt(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:[K&&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:T.map(L=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${L.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:L.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:L.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.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:M.map(L=>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:L.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:L.primary}),L.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:L.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.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:()=>g.setShowAllRecent(L=>!L),children:g.showAllRecent?"Show fewer":`Show ${E.length-4} more`})})]}),(g.hasIdeOptions||n.length>0||a.length>0)&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:t.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),t.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),t.jsx("select",{value:g.workspaceChoice,onChange:L=>g.handleWorkspaceChoiceChange(L.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:g.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[g.workspaceRows.map(L=>t.jsxs("option",{value:L.id,children:[L.id===g.defaultWorkspaceId?"⭐ ":"",Zr(L.path,L.label)||L.path]},L.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),g.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(ks,{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:g.resolvedWorkspacePath||g.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:g.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:()=>{g.resolvedWorkspacePath&&b(g.resolvedWorkspacePath)},disabled:!g.resolvedWorkspacePath||g.browseBusy,children:"Save as workspace"})]})]}),g.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[g.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${g.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:()=>g.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${g.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:()=>g.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${g.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:()=>g.setActiveLauncherKind("acp"),children:"ACP"})]}),g.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:g.activeLauncherKind==="ide"?"Choose an IDE":g.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:g.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(L=>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:R,selectedKey:z}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.openLaunchConfirm({title:`Launch ${L.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:R,selectedWorkspaceKey:z,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:L.name}]},async()=>{const $=R.find(_=>_.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption($),v(L.type,{workspacePath:($==null?void 0:$.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:L.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},L.type)):(g.activeLauncherKind==="cli"?n:a).map(L=>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 R=g.activeLauncherKind==="cli"?"cli":"acp",{options:z,selectedKey:$}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.openLaunchConfirm({title:`Launch ${L.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${R.toUpperCase()}`,workspaceOptions:z,selectedWorkspaceKey:$,details:[{label:"Mode",value:R.toUpperCase()},{label:"Provider",value:L.displayName}],showArgsInput:!0,showModelInput:R==="acp",initialArgs:"",initialModel:"",providerType:L.type},async()=>{const _=z.find(Y=>Y.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(_),A(R,L.type,{workspaceId:(_==null?void 0:_.workspaceId)??null,workspacePath:(_==null?void 0:_.workspacePath)??null,args:g.launchConfirmArgs,model:g.launchConfirmModel,resumeSessionId:g.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[L.icon?`${L.icon} `:"",L.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},L.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,g.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:()=>b(g.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:x,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:p,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),g.browseDialogOpen&&t.jsx(an,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:g.browseCurrentPath,directories:g.browseDirectories,busy:g.browseBusy,error:g.browseError,confirmLabel:"Use this folder",onClose:()=>g.setBrowseDialogOpen(!1),onNavigate:L=>{g.loadBrowsePath(L)},onConfirm:L=>{g.chooseCustomWorkspacePath(L),g.setBrowseDialogOpen(!1)}}),g.launchConfirm&&t.jsx(Va,{title:g.launchConfirm.title,description:g.launchConfirm.description,details:g.launchConfirm.details,workspaceOptions:g.launchConfirm.workspaceOptions,selectedWorkspaceKey:g.launchConfirmWorkspaceKey,onWorkspaceChange:g.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:g.launchConfirm.providerType?Ur(!!g.launchConfirmResumeId):g.launchConfirm.confirmLabel,busyLabel:g.launchConfirm.providerType?void 0:g.launchConfirm.busyLabel,busy:g.launchConfirmBusy,showArgsInput:g.launchConfirm.showArgsInput,argsValue:g.launchConfirmArgs,onArgsChange:g.setLaunchConfirmArgs,showModelInput:g.launchConfirm.showModelInput,modelValue:g.launchConfirmModel,onModelChange:g.setLaunchConfirmModel,historyProviderNode:g.launchConfirm.providerType&&(g.launchConfirmSessionsLoading||g.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"}),g.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:La()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:g.launchConfirmTextFilter,onChange:L=>g.setLaunchConfirmTextFilter(L.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:g.launchConfirmWorkspaceFilter,onChange:L=>g.setLaunchConfirmWorkspaceFilter(L.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:g.launchConfirmModelFilter,onChange:L=>g.setLaunchConfirmModelFilter(L.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),t.jsxs("select",{value:g.launchConfirmSortMode,onChange:L=>g.setLaunchConfirmSortMode(L.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:g.launchConfirmBusy||g.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:g.launchConfirmResumableOnly,onChange:L=>g.setLaunchConfirmResumableOnly(L.target.checked),disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:g.launchConfirmResumeId,onChange:L=>g.setLaunchConfirmResumeId(L.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:tf()}),g.filteredLaunchConfirmSavedSessions.map(L=>t.jsxs("option",{value:L.providerSessionId,disabled:!L.canResume,children:[L.title||L.providerSessionId," ",L.canResume?"":"(workspace missing)"]},L.providerSessionId))]}),!g.launchConfirmSessionsLoading&&g.launchConfirmSavedSessions.length>0&&g.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),g.launchConfirmResumeId&&(()=>{const L=g.filteredLaunchConfirmSavedSessions.find(z=>z.providerSessionId===g.launchConfirmResumeId);if(!L)return null;const R=Fc(L);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:R.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:R.providerSessionId}),t.jsx("div",{className:"mt-1",children:R.metaLine}),R.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:R.updatedLabel}),R.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:R.preview})]})})()]}),onConfirm:g.handleConfirmLaunch,onCancel:g.closeLaunchConfirm}),d&&t.jsx(Hc,{section:f,onSectionChange:m})]})}function ph(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 hh(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:ds(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,f,d;const a=Xs(n)?"cli":gs(n)?"acp":"ide",i=ds(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(Xs(n)?n.cliName||n.type:gs(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:gs(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((d=(f=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:f.call(u,-1))==null?void 0:d.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function xh(e,s){const r=new Map;for(const n of s){const a=qt(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((h,m)=>m.timestamp-h.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=Xn(n),u=a.filter(h=>h.unread||h.requiresAction).length,f=ph(n),d=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:Tt(n,{fallbackId:n.id}),subtitle:d.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?Um(c):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,a)=>{const i=n.latestTimestamp||n.fallbackActivityAt||0,c=a.latestTimestamp||a.fallbackActivityAt||0;return c!==i?c-i:n.label.localeCompare(a.label)})}function 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 bh({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:j,setSelectedTabKey:S,setScreen:p,setSelectedMachineId:x,setSection:v,setMachineBackTarget:b,resetMachineAction:C}){const A=o.useRef(null),y=o.useCallback(I=>{if(!(I!=null&&I.sessionId))return;const k=Or(I,c),w=Math.max(Date.now(),es(I),k.lastUpdated||0);kr("mark_read:start",{tabKey:I.tabKey,sessionId:I.sessionId,displayPrimary:rt(I),inboxBucket:k.inboxBucket,unread:k.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,activityAt:es(I),readAt:w}),l(qt(I)||I.routeId,"mark_session_seen",{sessionId:I.sessionId,seenAt:w}).then(g=>{kr("mark_read:result",{tabKey:I.tabKey,sessionId:I.sessionId,result:g})}).catch(g=>{kr("mark_read:error",{tabKey:I.tabKey,sessionId:I.sessionId,error:g instanceof Error?g.message:String(g)})})},[c,l]);return o.useEffect(()=>{var k;if(!n){p("inbox"),S(((k=e[0])==null?void 0:k.tabKey)||null),A.current=null;return}if(i!=="chat"){A.current=null;return}const I=`${n.tabKey}:${n.sessionId||""}`;A.current!==I&&(A.current=I,y(n))},[e,y,i,n,p,S]),o.useEffect(()=>{if(!u)return;const I=e.find(k=>k.tabKey===u);I&&(S(I.tabKey),p("chat"),f==null||f())},[e,f,u,p,S]),o.useEffect(()=>{if(!d)return;const I=s.find(k=>k.id===d);I&&(x(I.id),C(),v("machines"),b("inbox"),p("machine"),h==null||h())},[s,h,d,C,b,p,v,x]),o.useEffect(()=>{m&&(v(m),p("inbox"),j==null||j())},[j,m,p,v]),o.useEffect(()=>{const I=r.filter(k=>k.inboxBucket==="task_complete"||k.unread);I.length!==0&&kr("inbox_state",{screen:i,selectedTabKey:a,items:I.map(k=>{const w=Or(k.conversation,c);return{liveState:w,tabKey:k.conversation.tabKey,sessionId:k.conversation.sessionId,displayPrimary:rt(k.conversation),serverBucket:w.inboxBucket,computedBucket:k.inboxBucket,serverUnread:w.unread,computedUnread:k.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:es(k.conversation)}})})},[r,c,i,a]),{markConversationRead:y}}function gh(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Yo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function yh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function vh({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,f]=o.useState(null),d=o.useCallback(()=>{i("idle"),l(""),f(null)},[]),h=o.useCallback(async(b,C,A)=>{var y;try{i("loading"),l(`Launching ${C}…`);const I={ideType:C,enableCdp:!0};(y=A==null?void 0:A.workspacePath)!=null&&y.trim()&&(I.workspace=A.workspacePath.trim()),await e(b,"launch_ide",I),i("done"),l(`${C} launch requested`)}catch(I){i("error"),l(I instanceof Error?I.message:"Launch IDE failed"),console.error("Launch IDE failed",I)}},[e]),m=o.useCallback(async(b,C,A)=>{if(C.trim())try{i("loading"),l(A!=null&&A.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(b,"workspace_add",{path:C.trim(),createIfMissing:(A==null?void 0:A.createIfMissing)===!0});if(y!=null&&y.success){i("done"),l(A!=null&&A.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((y==null?void 0:y.error)||"Could not save workspace")}catch(y){i("error"),l(y instanceof Error?y.message:"Could not save workspace")}},[e]),j=o.useCallback(async b=>{var C,A,y,I,k,w;try{i("loading"),l("Starting daemon upgrade…");const g=await e(b,"daemon_upgrade",{});if((C=g==null?void 0:g.result)!=null&&C.alreadyLatest){i("done"),l(`Already on v${((A=g==null?void 0:g.result)==null?void 0:A.version)||"latest"}.`);return}if((y=g==null?void 0:g.result)!=null&&y.upgraded||(I=g==null?void 0:g.result)!=null&&I.success){i("done"),l(`Upgrade to v${((k=g==null?void 0:g.result)==null?void 0:k.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((w=g==null?void 0:g.result)==null?void 0:w.error)||"Upgrade failed")}catch(g){i("error"),l(g instanceof Error?g.message:"Upgrade failed")}},[e]),S=o.useCallback(async(b,C,A,y)=>{var w,g,E;const I=Date.now(),k={machineId:b,kind:C,providerType:A,workspaceId:(y==null?void 0:y.workspaceId)||null,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:I};try{i("loading"),l(`Launching ${A}…`),f(k);const T={cliType:A};(w=y==null?void 0:y.workspacePath)!=null&&w.trim()?T.dir=y.workspacePath.trim():y!=null&&y.workspaceId&&(T.workspaceId=y.workspaceId),y!=null&&y.resumeSessionId&&(T.resumeSessionId=y.resumeSessionId),(g=y==null?void 0:y.args)!=null&&g.trim()&&(T.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(E=y==null?void 0:y.model)!=null&&E.trim()&&(T.initialModel=y.model.trim());const M=await e(b,"launch_cli",T),P=(M==null?void 0:M.result)||M,K=(P==null?void 0:P.sessionId)||(P==null?void 0:P.id);if(M!=null&&M.success&&K){f(null),i("done"),l(`${A} launched`),s(Vt(K));return}if(M!=null&&M.success){i("loading"),l(`${A} launch requested — waiting for session…`);return}f(null),i("error"),l((M==null?void 0:M.error)||(P==null?void 0:P.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(T){if(yh(T)){i("loading"),l(`${A} launch requested — waiting for session…`);return}f(null),i("error"),l(T instanceof Error?T.message:`Could not launch ${C.toUpperCase()} workspace`)}},[s,e]),p=o.useCallback(async(b,C)=>{try{const A=await e(b,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),y=(A==null?void 0:A.result)??A;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(A){return console.error("Failed to list saved sessions on mobile:",A),[]}},[e]),x=o.useCallback(async(b,C)=>rn(e,b,C),[e]);o.useEffect(()=>{if(!u)return;const b=Yo(u.workspacePath),C=r.find(y=>{var T,M,P,K;if(!y||y.type==="adhdev-daemon"||gh(y.daemonId||y.id)!==u.machineId||(y.transport==="acp"?"acp":y.transport==="pty"?"cli":null)!==u.kind||String(y.agentType||y.type||"")!==u.providerType)return!1;const g=String(y.providerSessionId||"");if(u.resumeSessionId&&g)return g===u.resumeSessionId;if(b){const U=Yo(y.workspace||y.runtimeWorkspaceLabel);return U?U===b:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((K=(P=(M=(T=y.activeChat)==null?void 0:T.messages)==null?void 0:M.at)==null?void 0:P.call(M,-1))==null?void 0:K.timestamp)||0)>=u.startedAt-5e3});if(!C)return;const A=Zi({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:n});A&&(f(null),i("done"),l(`${u.providerType} launched`),s(Vt(A)))},[n,r,s,u]),o.useEffect(()=>{if(!u)return;const b=window.setTimeout(()=>{f(C=>!C||C.startedAt!==u.startedAt?C:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(b)},[u]);const v=o.useCallback(async(b,C)=>{if(C.kind==="ide"&&C.providerType){await h(b,C.providerType,{workspacePath:C.workspace||null});return}(C.kind==="cli"||C.kind==="acp")&&C.providerType&&await S(b,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[h,S]);return{machineAction:{state:a,message:c},resetMachineAction:d,handleLaunchDetectedIde:h,handleAddWorkspace:m,handleMachineUpgrade:j,handleLaunchWorkspaceProvider:S,handleListSavedSessions:p,handleBrowseDirectory:x,handleOpenRecent:v}}function wh({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:f}){const d=o.useCallback(v=>{i(v.tabKey),c("chat"),n(v)},[n,c,i]),h=o.useCallback(v=>{const b=e.find(C=>C.routeId===v.routeId&&C.streamSource==="native");b&&(i(b.tabKey),c("chat"),n(b))},[e,n,c,i]),m=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),j=o.useCallback((v,b="inbox")=>{l(v),a(),u("machines"),f(b),c("machine")},[a,f,c,u,l]),S=o.useCallback(v=>{const b=qt(v);b&&j(b,"chat")},[j]),p=o.useCallback(()=>{a(),c(r)},[r,a,c]),x=o.useCallback(v=>{u(v),c("inbox")},[c,u]);return{openConversation:d,openNativeConversation:h,backFromConversation:m,openMachine:j,openConversationMachine:S,backFromMachine:p,changeMachineSection:x}}function jh(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Sr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function kh({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:j,onOpenHistory:S,onOpenRemote:p,onStopCli:x,wsStatus:v,isConnected:b,onShowHiddenConversation:C,onShowAllHiddenConversations:A,onHideConversation:y,onOpenNewSession:I,liveSessionInboxState:k}){const[w,g]=o.useState(()=>{var N;return((N=e[0])==null?void 0:N.tabKey)||null}),[E,T]=o.useState(()=>e[0]?"chat":"inbox"),[M,P]=o.useState("chats"),[K,U]=o.useState(null),[L,R]=o.useState("inbox"),z=Is(),$="0.9.11",_=o.useMemo(()=>e.find(N=>N.tabKey===w)||e[0]||null,[e,w]),Y=o.useMemo(()=>_?r.find(N=>N.id===_.routeId):void 0,[r,_]),J=o.useMemo(()=>!_||Ge(_)||!Je(_)?null:As(_),[_]),pe=o.useMemo(()=>r.filter(N=>N.type==="adhdev-daemon").sort(va),[r]),ae=o.useMemo(()=>pe.find(N=>N.id===K)||null,[pe,K]),be=nn({sendDaemonCommand:a,activeConv:_||void 0,setActionLogs:i,isStandalone:c}),ye=vh({sendDaemonCommand:a,navigate:z,ides:r,conversations:e}),ve=o.useMemo(()=>e.map(N=>{const O=E==="chat"&&(_==null?void 0:_.tabKey)===N.tabKey,G=Qr(N,k,{hideOpenTaskCompleteUnread:!0,isOpenConversation:O}),Z=es(N),fe=cc(N);return{conversation:N,timestamp:Z,preview:fe,unread:G.unread,requiresAction:G.requiresAction,isWorking:G.isWorking,inboxBucket:G.inboxBucket}}),[e,k,E,_]),{markConversationRead:Ie}=bh({conversations:e,machineEntries:pe,items:ve,selectedConversation:_,selectedTabKey:w,screen:E,liveSessionInboxState:k,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:j,setSelectedTabKey:g,setScreen:T,setSelectedMachineId:U,setSection:P,setMachineBackTarget:R,resetMachineAction:ye.resetMachineAction}),H=wh({conversations:e,selectedConversation:_,machineBackTarget:L,markConversationRead:Ie,resetMachineAction:ye.resetMachineAction,setSelectedTabKey:g,setScreen:T,setSelectedMachineId:U,setSection:P,setMachineBackTarget:R}),V=o.useMemo(()=>Sr(ve.filter(N=>N.requiresAction)),[ve]),Q=o.useMemo(()=>Sr(ve.filter(N=>N.unread&&!N.requiresAction)),[ve]),ue=o.useMemo(()=>Sr(ve.filter(N=>!N.unread&&!N.requiresAction&&N.isWorking)),[ve]),re=o.useMemo(()=>Sr(ve.filter(N=>!N.unread&&!N.requiresAction&&!N.isWorking)),[ve]),le=o.useMemo(()=>ae?ve.filter(N=>qt(N.conversation)===ae.id):[],[ve,ae]),se=o.useMemo(()=>hh(ae,r),[r,ae]),me=(ae==null?void 0:ae.version)||null,ne=!!ae&&!!me&&!0&&me!==$,ce=o.useMemo(()=>(ae==null?void 0:ae.availableProviders)||[],[ae]),oe=o.useMemo(()=>ce.filter(N=>N.category==="cli"&&N.installed!==!1).map(N=>({type:N.type,displayName:N.displayName||N.type,icon:N.icon})),[ce]),we=o.useMemo(()=>ce.filter(N=>N.category==="acp"&&N.installed!==!1).map(N=>({type:N.type,displayName:N.displayName||N.type,icon:N.icon})),[ce]),he=o.useMemo(()=>xh(pe,ve),[ve,pe]),Se=o.useCallback(async N=>{ae&&await ye.handleOpenRecent(ae.id,N)},[ye,ae]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:E==="chat"&&_?t.jsx(ah,{selectedConversation:_,isAcp:Ge(_),isStandalone:c,selectedIdeEntry:Y,actionLogs:n,userName:l,isSendingChat:be.isSendingChat,sendFeedbackMessage:be.sendFeedbackMessage,isFocusingAgent:be.isFocusingAgent,handleModalButton:be.handleModalButton,handleRelaunch:be.handleRelaunch,onBack:H.backFromConversation,onOpenNativeConversation:H.openNativeConversation,onOpenMachine:H.openConversationMachine,onHideConversation:y,onOpenHistory:S,onOpenRemote:p,onStopCli:x,cliViewMode:J,onSetCliViewMode:async N=>{if(_&&J!==N)try{await a(qt(_)||_.routeId,"set_cli_view_mode",{targetSessionId:_.sessionId,cliType:_t(_),mode:N})}catch(O){const G=Ha(O);Wa(O)?console.warn(G?"CLI view mode result was lost after send; keeping optimistic mobile mode override:":"Skipped CLI view mode switch:",O instanceof Error?O.message:String(O)):console.error("Failed to switch CLI view mode:",O)}},handleSendChat:be.handleSendChat,handleFocusAgent:be.handleFocusAgent}):E==="machine"&&ae?t.jsx(fh,{selectedMachineEntry:ae,selectedMachineConversations:le,selectedMachineRecentLaunches:se,cliProviders:oe,acpProviders:we,selectedMachineNeedsUpgrade:ne,appVersion:$,machineAction:ye.machineAction,isStandalone:c,section:M,showBottomNav:L==="inbox",onBack:H.backFromMachine,onSectionChange:H.changeMachineSection,onOpenConversation:H.openConversation,onOpenRecent:Se,onOpenMachineDetails:()=>z(`/machines/${ae.id}`),onMachineUpgrade:()=>ye.handleMachineUpgrade(ae.id),onLaunchDetectedIde:(N,O)=>ye.handleLaunchDetectedIde(ae.id,N,O),onAddWorkspace:(N,O)=>ye.handleAddWorkspace(ae.id,N,O),onBrowseDirectory:N=>ye.handleBrowseDirectory(ae.id,N),onLaunchWorkspaceProvider:(N,O,G)=>ye.handleLaunchWorkspaceProvider(ae.id,N,O,G),onListSavedSessions:N=>ye.handleListSavedSessions(ae.id,N)}):t.jsx(ih,{section:M,attentionItems:V,unreadItems:Q,workingItems:ue,completedItems:re,hiddenConversations:s,machineCards:he,getAvatarText:jh,onOpenConversation:H.openConversation,onShowConversation:C,onShowAllHidden:A,onOpenNewSession:I,onOpenMachine:H.openMachine,onOpenSettings:()=>z("/settings"),onSectionChange:P,wsStatus:v,isConnected:b,isStandalone:c})})}function An(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function Sh({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[f,d]=o.useState(null),h=o.useCallback(()=>{c.current=0,u(!1),d(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const m=o.useCallback(x=>{x.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),j=o.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!An(s,r)){d("merge");return}const v=x.currentTarget.getBoundingClientRect(),b=x.clientX-v.left,C=v.width/3;b<C?d("split-left"):b>C*2?d("split-right"):d("merge")},[s,r]),S=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),d(null))},[]),p=o.useCallback(x=>{c.current=0,u(!1);const v=x.dataTransfer.getData("text/tab-key"),b=v?e.some(A=>A.tabKey===v):!1,C=f;if(d(null),i(),!!v){if(x.preventDefault(),C==="split-left"&&An(s,r)){r==null||r(v,"split-left");return}if(C==="split-right"&&An(s,r)){r==null||r(v,"split-right");return}if(b){a(v);return}n==null||n(v)}},[e,f,s,r,n,a,i]);return{dragOver:l,dropAction:f,resetDragState:h,handleDragEnter:m,handleDragOver:j,handleDragLeave:S,handleDrop:p}}function Nh(e,s){const r=new Set(s.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),a=s.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...a]}function Ch({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(s??null),[l,u]=o.useState(r??[]),[f,d]=o.useState(null),h=o.useRef(null),m=o.useRef(null),j=o.useRef(n),S=o.useRef(a);o.useEffect(()=>{j.current=n},[n]),o.useEffect(()=>{S.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{u(k=>{const w=Nh(k,e);return w.length===k.length&&w.every((g,E)=>g===k[E])?k:w})},[e]);const p=o.useMemo(()=>{const k=f??l;if(k.length===0)return e;const w=new Map(k.map((g,E)=>[g,E]));return[...e].sort((g,E)=>{const T=w.get(g.tabKey)??999,M=w.get(E.tabKey)??999;return T-M})},[e,f,l]);o.useEffect(()=>{var w,g;if(p.length===0){i!==null&&(c(null),(w=j.current)==null||w.call(j,null));return}if(i&&p.some(E=>E.tabKey===i))return;const k=p[0].tabKey;k!==i&&(c(k),(g=j.current)==null||g.call(j,k))},[p,i]);const x=o.useMemo(()=>p.find(k=>k.tabKey===i),[p,i]),v=o.useCallback(k=>{var w;c(k),(w=j.current)==null||w.call(j,k)},[]),b=o.useCallback((k,w,g)=>{u(E=>{var K;const T=E.filter(U=>U!==k),M=T.indexOf(w);if(M<0)return E;const P=g==="left"?M:M+1;return T.splice(P,0,k),(K=S.current)==null||K.call(S,T),T}),d(null)},[]),C=o.useCallback((k,w,g)=>{const T=(l.length>0?l:e.map(K=>K.tabKey)).filter(K=>K!==k),M=T.indexOf(w);if(M<0)return;const P=g==="left"?M:M+1;T.splice(P,0,k),h.current=T,d(T)},[l,e]),A=o.useCallback(()=>{var w;const k=h.current;k&&(u(k),(w=S.current)==null||w.call(S,k))},[]),y=o.useCallback(()=>{h.current=null,d(null)},[]),I=o.useCallback(k=>{u(w=>{var E;const g=w.filter(T=>T!==k);return g.push(k),(E=S.current)==null||E.call(S,g),g})},[]);return{activeTabId:i,activeConv:x,sortedConversations:p,previewOrderRef:h,draggingTabRef:m,selectTab:v,handleTabReorder:b,updatePreviewOrder:C,commitPreviewOrder:A,clearPreviewOrder:y,moveTabToEnd:I,setDraggingTabKey:k=>{m.current=k}}}function Ih({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 Ga({conversationsCount:e,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:i}){if(a)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",f=n?mc: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:f}),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:Bt,"aria-label":Bt,children:[t.jsx(Ai,{size:14}),t.jsx("span",{children:Bt})]})}),c&&t.jsx(Wc,{}),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 zc="adhdev-tab-shortcuts";function Vc(){try{return JSON.parse(localStorage.getItem(zc)||"{}")}catch{return{}}}function Gc({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>Vc()),[l,u]=o.useState(null),f=o.useCallback(h=>{const m=[];return h.metaKey&&m.push(a?"⌘":"Meta"),h.ctrlKey&&m.push("Ctrl"),h.altKey&&m.push(a?"⌥":"Alt"),h.shiftKey&&m.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(m.push(h.key.length===1?h.key.toUpperCase():h.key),m.join("+"))},[a]),d=o.useCallback(h=>{c(h);try{localStorage.setItem(zc,JSON.stringify(h))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const h=m=>{if(m.preventDefault(),m.stopPropagation(),m.key==="Escape"){u(null);return}const j=f(m);if(!j)return;const S={...i};for(const[p,x]of Object.entries(S))x===j&&delete S[p];S[l]=j,d(S),u(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,i,d,f]),o.useEffect(()=>{if(!e)return;const h=m=>{if(!(!m.ctrlKey&&!m.metaKey&&!m.altKey)){for(const[j,S]of Object.entries(i))if(s.includes(j)&&f(m)===S){m.preventDefault(),r(),n(j);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,i,s,r,n,f]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:d}}const Mh=o.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:f,onConversationActivated:d,onPreviewReorder:h,onReorderTab:m,onCommitPreviewOrder:j,onClearPreviewOrder:S,onDragStateReset:p,onDragTabKeyChange:x,onReceiveTab:v,onOpenContextMenu:b,longPressTimer:C,isGroupActive:A}){const y=Ms(s),I=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",k=y.isReconnecting,w=o.useCallback(R=>{l.current=s.tabKey,x(s.tabKey),R.dataTransfer.setData("text/tab-key",s.tabKey),R.dataTransfer.effectAllowed="move"},[s.tabKey,l,x]),g=o.useCallback(()=>{l.current=null,x(null),j(),S(),p()},[l,x,j,S,p]),E=o.useCallback(R=>{const z=l.current;if(!(!z||z===s.tabKey)&&R.dataTransfer.types.includes("text/tab-key")){R.preventDefault(),R.stopPropagation();const $=R.currentTarget.getBoundingClientRect(),_=R.clientX<$.left+$.width/2?"left":"right";h(z,s.tabKey,_)}},[s.tabKey,l,h]),T=o.useCallback(R=>{R.preventDefault(),R.stopPropagation();const z=R.dataTransfer.getData("text/tab-key");if(z&&z!==s.tabKey){const $=R.currentTarget.getBoundingClientRect(),_=R.clientX<$.left+$.width/2?"left":"right";c.includes(z)?m(z,s.tabKey,_):v&&v(z)}S()},[s.tabKey,c,m,v,S]),M=o.useCallback(R=>{R.stopPropagation(),u(),f(s.tabKey),d(s)},[s,d,u,f]),P=o.useCallback(R=>{R.preventDefault(),b(R.clientX,R.clientY,s.tabKey)},[s.tabKey,b]),K=o.useCallback(R=>{const z=R.touches[0];C.current=setTimeout(()=>{b(z.clientX,z.clientY,s.tabKey)},600)},[s.tabKey,C,b]),U=o.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),L=["adhdev-dockview-tab",I,r&&"is-active",A&&"is-group-active",k&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:L,draggable:!0,onDragStart:w,onDragEnd:g,onDragOver:E,onDrop:T,onClick:M,onContextMenu:P,onTouchStart:K,onTouchEnd:U,onTouchMove:U,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status",children:y.isGenerating?t.jsx("div",{className:"tab-spinner"}):y.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):k?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.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:rt(s),children:rt(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:k?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(s)}):y.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ts(s),t.jsx("span",{className:"connecting-dots"})]}):ts(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 Ah({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:f,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:m,onDragTabKeyChange:j,onReceiveTab:S,onHideTab:p,isGroupActive:x,allowTabShortcuts:v=!0}){const[b,C]=o.useState(null),A=o.useRef(null),y=o.useRef(null),I=o.useMemo(()=>e.map(P=>P.tabKey),[e]);tr("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:k,tabShortcuts:w,shortcutListening:g,setShortcutListening:E,saveShortcuts:T}=Gc({enabled:v,sortedTabKeys:e.map(P=>P.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!b)return;const P=K=>{const U=document.querySelector("[data-pane-context-menu]");U&&U.contains(K.target)||C(null)};return window.addEventListener("mousedown",P,!0),()=>window.removeEventListener("mousedown",P,!0)},[b]),o.useEffect(()=>{const P=y.current;if(!P)return;const K=U=>{Math.abs(U.deltaY)<=Math.abs(U.deltaX)||(U.preventDefault(),P.scrollLeft+=U.deltaY)};return P.addEventListener("wheel",K,{passive:!1}),()=>P.removeEventListener("wheel",K)},[]);const M=o.useCallback((P,K,U)=>{C({x:P,y:K,tabKey:U})},[]);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:y,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(Mh,{conv:P,isActive:s===P.tabKey,isDraggedTab:a.current===P.tabKey,isTaskCompleteUnread:n.has(P.tabKey),shortcut:v?w[P.tabKey]:void 0,conversationKeys:I,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:f,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:m,onDragTabKeyChange:j,onReceiveTab:S,onOpenContextMenu:M,longPressTimer:A,isGroupActive:x},P.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),b&&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:b.x,top:b.y},children:[v&&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(b.tabKey),C(null)},children:["⌨ ",w[b.tabKey]?`Change shortcut (${w[b.tabKey]})`:"Set shortcut"]}),w[b.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={...w};delete P[b.tabKey],T(P),C(null)},children:"✕ Remove shortcut"})]}),p&&t.jsxs(t.Fragment,{children:[v&&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:()=>{p(b.tabKey),C(null)},children:"🚫 Hide from Dashboard"})]})]}),v&&g&&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. ",k?"⌘+1":"Ctrl+1",", ",k?"⌥+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 Th({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,userName:u,groupIndex:f,onFocus:d,isSplitMode:h,numGroups:m,onMoveTab:j,onReceiveTab:S,style:p,onActiveTabChange:x,initialActiveTabId:v,initialTabOrder:b,onTabOrderChange:C,onHideTab:A,isFocused:y,allowTabShortcuts:I=!0,onOpenNewSession:k,liveSessionInboxState:w}){const{sendCommand:g}=jt(),E=o.useRef(null),{activeTabId:T,activeConv:M,sortedConversations:P,draggingTabRef:K,selectTab:U,handleTabReorder:L,updatePreviewOrder:R,commitPreviewOrder:z,clearPreviewOrder:$,moveTabToEnd:_,setDraggingTabKey:Y}=Ch({conversations:e,initialActiveTabId:v,initialTabOrder:b,onActiveTabChange:x,onTabOrderChange:C}),J=nn({sendDaemonCommand:a,activeConv:M,setActionLogs:i,isStandalone:c}),{dragOver:pe,dropAction:ae,resetDragState:be,handleDragEnter:ye,handleDragOver:ve,handleDragLeave:Ie,handleDrop:H}=Sh({conversations:e,numGroups:m,onMoveTab:j,onReceiveTab:S,onOwnTabDrop:_,onClearPreviewOrder:$}),V=M&&!Ge(M)&&As(M)==="terminal",Q=o.useMemo(()=>M?s.find(se=>se.id===M.routeId):void 0,[s,M]),ue=o.useMemo(()=>M?n.filter(se=>se.routeId===M.tabKey):[],[n,M]),re=o.useMemo(()=>new Set(P.filter(se=>ou(se,w,{isOpenConversation:se.tabKey===T})).map(se=>se.tabKey)),[T,w,P]);tr("PaneGroup",{groupIndex:f,conversationCount:e.length,activeTabId:T,dragOver:pe});const le=o.useCallback(se=>{se.streamSource==="agent-stream"&&se.agentType&&g(se.routeId,Oc(),{agentType:se.agentType,...se.sessionId&&{targetSessionId:se.sessionId}}).catch(()=>{})},[g]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:d,style:{...p,outline:pe?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(Ah,{conversations:P,activeTabId:T,groupIndex:f,numGroups:m,unreadTabKeys:re,draggingTabRef:K,onFocus:d,onSelectTab:U,onConversationActivated:le,onPreviewReorder:R,onReorderTab:L,onCommitPreviewOrder:z,onClearPreviewOrder:$,onDragStateReset:be,onDragTabKeyChange:Y,onMoveTab:j,onReceiveTab:S,onHideTab:A,isGroupActive:y??!1,allowTabShortcuts:I}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ye,onDragOver:ve,onDragLeave:Ie,onDrop:H,children:[pe&&t.jsx(Ih,{dropAction:ae,canSplit:!!(m<4&&j)}),M?t.jsx(za,{activeConv:M,clearToken:r[M.tabKey]||0,isCliTerminal:!!V,ideEntry:Q,terminalRef:E,handleModalButton:J.handleModalButton,handleRelaunch:J.handleRelaunch,handleSendChat:J.handleSendChat,isSendingChat:J.isSendingChat,sendFeedbackMessage:J.sendFeedbackMessage,handleFocusAgent:J.handleFocusAgent,isFocusingAgent:J.isFocusingAgent,actionLogs:ue,userName:u,isInputActive:!h||!!y}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(Ga,{conversationsCount:e.length,isSplitMode:h,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:k})})]})]})}function Lh({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:f,isStandalone:d,hasRegisteredMachines:h,userName:m,focusedGroup:j,focusGroup:S,moveTabToGroup:p,splitTabRelative:x,closeGroup:v,handleResizeStart:b,groupActiveTabIds:C,setGroupActiveTab:A,groupTabOrders:y,setGroupTabOrder:I,toggleHiddenTab:k,onOpenNewSession:w,allowTabShortcuts:g=!0,liveSessionInboxState:E}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map((T,M)=>{const P=s&&n.length===r?`${n[M]}%`:void 0;return t.jsxs(St.Fragment,{children:[s&&M>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:K=>b(M-1,K),onDoubleClick:()=>v(M),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(Th,{style:s?{flexBasis:P??`${100/r}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:T,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:f,isStandalone:d,hasRegisteredMachines:h,userName:m,groupIndex:M,isFocused:s&&j===M,onFocus:()=>S(M),isSplitMode:s,numGroups:r,onMoveTab:(K,U)=>{U==="left"&&M>0?p(K,M-1):U==="right"&&M<r-1?p(K,M+1):U==="split-left"&&r<4?x(K,M,"left"):U==="split-right"&&r<4&&x(K,M,"right")},onReceiveTab:K=>p(K,M),onActiveTabChange:K=>A(M,K),initialActiveTabId:C[M],initialTabOrder:y[M],onTabOrderChange:K=>I(M,K),onHideTab:k,onOpenNewSession:w,allowTabShortcuts:g,liveSessionInboxState:E})]},M)})})}function qc({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?ot.onScreenshot("ide-page",(d,h)=>{if(d!==e)return;const m=new FileReader;m.onload=()=>i(m.result),m.readAsDataURL(h)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var d;return e?((d=ot.onStatus)==null?void 0:d.call(ot,(h,m)=>{h===e&&m!=null&&m.screenshotUsage&&l(m.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const f=e?ot.get(e):null;if(!(!f||r!=="connected"))return n!=="chat"&&s?f.startScreenshots(s):f.stopScreenshots(s),()=>{f.stopScreenshots(s)}},[n,r,s,e]);const u=o.useCallback(async(f,d)=>{const h=e?ot.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(f,d,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const Yc="adhdev-dashboard-action-shortcuts",Rh=1200,Ph={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function _h(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function et(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 Xc(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:et("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:et("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:et("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:et("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:et("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:et("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:et("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:et("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:et("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:et("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:et("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:et("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:et("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:et("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:et("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:et("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:et("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:et("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:et("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:et("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:et("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:et("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:et("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:et("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:et("toggleCliView",e)}]}function ca(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Gr(e){const s=Object.fromEntries(Xc(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Yc)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(Ph))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function Jc(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Dh({enabled:e=!0,onTrigger:s}){const r=_h(),[n,a]=o.useState(()=>Gr(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),f=o.useRef({parts:[],timer:null}),d=o.useCallback(p=>{const x=[];return p.metaKey&&x.push(r?"⌘":"Meta"),p.ctrlKey&&x.push("Ctrl"),p.altKey&&x.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&x.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(x.push(Jc(p.key)),x.join("+"))},[r]),h=o.useCallback(p=>{a(p);try{localStorage.setItem(Yc,JSON.stringify(p))}catch{}},[]);o.useEffect(()=>{const p=Gr(r),x=Object.entries(n),v=Object.entries(p);x.length===v.length&&x.every(([b,C])=>p[b]===C)||h(p)},[n,r,h]);const m=o.useCallback(()=>{typeof window<"u"&&f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current={parts:[],timer:null}},[]),j=o.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},Rh))},[]);o.useEffect(()=>{if(!i)return;const p=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){c(null),u([]);return}const v=d(x);if(!v)return;const C=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(v);if(l.length===0&&C){u([v]);return}const y=[...l,v].slice(0,2).join(" "),I={...n};for(const[k,w]of Object.entries(I))w===y&&delete I[k];I[i]=y,h(I),c(null),u([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,d,h,i,l]),o.useEffect(()=>{if(!e||i)return;const p=x=>{if(x.defaultPrevented)return;const v=d(x);if(!v)return;const b=x.metaKey||x.ctrlKey||x.altKey;if(ca(x.target)&&!b)return;const C=f.current.parts,A=b?[v]:[...C.slice(-1),v].slice(-2),y=A.join(" "),I=A[A.length-1],k=Object.entries(n).filter(([,M])=>!!M),w=k.find(([,M])=>M===y);if(w){x.preventDefault(),m(),s(w[0]);return}if(k.some(([,M])=>M.startsWith(`${y} `))){x.preventDefault(),f.current.parts=A,j();return}const E=k.find(([,M])=>M===I);if(E){x.preventDefault(),m(),s(E[0]);return}if(k.some(([,M])=>M.startsWith(`${I} `))){x.preventDefault(),f.current.parts=[I],j();return}m()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,j,e,d,s,m,i]),o.useEffect(()=>()=>m(),[m]);const S=o.useMemo(()=>Xc(r),[r]);return{isMac:r,actionDefinitions:S,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:h}}function Eh({isTabInPopout:e,isTabFloating:s,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(s&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):s?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:r?`Change shortcut (${r})`:"Set shortcut",shortcut:n.setActiveTabShortcut}),r&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:n.hideCurrentTab,tone:"muted"}),a}function Qc(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function Xo({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!Qc(n):!0}function $h({previousVisibleConversationCount:e,visibleConversationCount:s,ides:r}){return s>0||e<=0?!1:Qc(r)}const Zc=o.createContext(null);function on(){const e=o.useContext(Zc);if(!e)throw new Error("DashboardDockviewContext missing");return e}function _r(e){return rt(e)||e.tabKey}function Bh(e){return`remote:${e}`}function Lt(e){return e.startsWith("remote:")}function Jo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Tn(e){var r,n,a,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=(a=e==null?void 0:e.documentElement)==null?void 0:a.focus)==null||i.call(a),(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 Nr(e,s){e.classList.remove(Fn.className,Un.className),e.classList.add(s==="light"?Fn.className:Un.className)}function Qo(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 Kh(e){const[,s]=o.useState(0);o.useEffect(()=>{const r=()=>s(a=>a+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const a of n)a.dispose()}},[e.api,e.containerApi])}function Oh(e,s,r){var c;const n=[s];let a;for(const l of n){let u;for(const f of l){const d=e.addPanel({id:f.tabKey,component:"conversation",title:_r(f),params:{kind:"conversation",tabKey:f.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=d.id)}a=u??a}return r??((c=s[0])==null?void 0:c.tabKey)??null}function Zo(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Lt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of s){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==_r(n)&&a.api.setTitle(_r(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:_r(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 ei(e,s,r){var u,f;const n=r?Bh(r):null;for(const d of[...e.panels])Lt(d.id)&&(!n||d.id!==n)&&e.removePanel(d);if(!r||!n)return;const a=Dt(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=uc(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((f=e.panels.find(d=>!Lt(d.id)))==null?void 0:f.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function Wh({params:e,api:s}){var h;const r=on(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=nn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const m=[s.onDidActiveChange(j=>i(j.isActive)),s.onDidActiveGroupChange(j=>{if(!s.isActive&&!j.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const j of m)j.dispose()}},[s]);const u=o.useMemo(()=>c?r.ides.find(m=>m.id===c.routeId):void 0,[r.ides,c]),f=o.useMemo(()=>c?r.actionLogs.filter(m=>m.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(Ga,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const d=!Ge(c)&&As(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(za,{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:f,userName:r.userName,scrollToBottomRequestNonce:((h=r.scrollToBottomRequest)==null?void 0:h.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a})})}function Hh({params:e}){var u;const s=on(),r=o.useMemo(()=>Dt([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>s.ides.find(f=>f.id===e.routeId),[s.ides,e.routeId]),a=(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}=qc({doId:a,targetSessionId:r?Yi(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(Pi,{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 Fh(){const e=on();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(Ga,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Uh(e){var j,S;Kh(e);const s=on(),r=o.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=Dt([...s.conversationsByTabKey.values()],e.params.routeId),x=((j=e.api.group.activePanel)==null?void 0:j.id)===e.api.id,v=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${x?" is-active":""}${v?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:p!=null&&p.machineName?t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Live remote view"}),t.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),t.jsx("span",{className:"adhdev-dockview-tab-machine",children:p.machineName})]}):t.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(e.params.tabKey);if(!n)return t.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:t.jsx("div",{className:"adhdev-dockview-tab-copy",children:t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,i=e.api.isGroupActive,c=Qr(n,s.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,u=c.isConnecting,f=c.isGenerating,d=c.isWaiting,h=c.unread,m=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:rt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var x;p.preventDefault(),r(p),s.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((x=p.target)==null?void 0:x.ownerDocument)??document})},children:[h&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?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:rt(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ts(n)}):t.jsx("span",{children:ts(n)})})]}),m&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:m,children:m})]})}function zh({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:u,userName:f,toggleHiddenTab:d,actionShortcuts:h,registerActionHandlers:m,onActiveTabChange:j,onOpenNewSession:S,onRequestScrollToBottom:p,requestedActiveTabKey:x,requestedRemoteIdeId:v,onRequestedActiveTabConsumed:b,scrollToBottomRequest:C,liveSessionInboxState:A,layoutProfile:y}){var vt,He,It;const{theme:I}=Ea(),{sendCommand:k}=jt(),w=o.useRef(null),g=o.useRef(null),E=o.useRef(!1),T=o.useRef(!1),M=o.useRef(!1),P=o.useRef(null),K=o.useRef([]),[U,L]=o.useState(null),[R,z]=o.useState(!1),[$,_]=o.useState(!1),[Y,J]=o.useState(0),pe=o.useRef(null),ae=o.useRef(typeof window>"u"?{}:jp(y)),be=o.useMemo(()=>new Map(e.map(B=>[B.tabKey,B])),[e]),ye=o.useMemo(()=>{const B=w.current;return B?B.groups.some(W=>{try{const F=W.model.location.type;return F!=="floating"&&F!=="popout"?!1:W.panels.some(q=>be.has(q.id))}catch{return!1}}):!1},[be,Y,e]),ve=o.useCallback(()=>{var B;(B=w.current)==null||B.focus()},[]),Ie=o.useCallback((B,W)=>{p==null||p(B,W)},[p]),H=o.useCallback(B=>{const W=document,F=B.document;for(const X of W.querySelectorAll('link[rel="stylesheet"]')){const xe=F.createElement("link");xe.rel="stylesheet",xe.href=X.href,X.crossOrigin&&(xe.crossOrigin=X.crossOrigin),F.head.appendChild(xe)}for(const X of W.querySelectorAll("style")){const xe=F.createElement("style");xe.textContent=X.textContent,F.head.appendChild(xe)}const q=[];for(const X of W.styleSheets)try{for(const xe of X.cssRules)xe instanceof CSSStyleRule&&(xe.selectorText===":root"||xe.selectorText==="html")&&q.push(xe.cssText)}catch{}if(q.length>0){const X=F.createElement("style");X.textContent=q.join(`
|
|
43
|
-
`),F.head.appendChild(X)}const ie=W.documentElement.getAttribute("data-theme");ie&&F.documentElement.setAttribute("data-theme",ie),F.documentElement.style.colorScheme=ie==="light"?"light":"dark",F.body.className=W.body.className;const ke=W.documentElement.getAttribute("style");ke&&F.documentElement.setAttribute("style",ke);const Ce=F.getElementById("dv-popout-window");Ce instanceof HTMLElement&&(Ce.classList.add("adhdev-dockview"),Nr(Ce,I))},[I]),V=o.useCallback(()=>{var W;const B=w.current;if(B)for(const F of B.groups)try{const q=(W=F.element)==null?void 0:W.ownerDocument;if(!q||q===document)continue;const ie=q.getElementById("dv-popout-window");ie instanceof HTMLElement&&(ie.classList.add("adhdev-dockview"),Nr(ie,I));const ke=document.documentElement.getAttribute("data-theme");ke&&q.documentElement.setAttribute("data-theme",ke),q.documentElement.style.colorScheme=ke==="light"?"light":"dark",q.body.className=document.body.className;const Ce=document.documentElement.getAttribute("style");Ce?q.documentElement.setAttribute("style",Ce):q.documentElement.removeAttribute("style")}catch{}},[I]),Q=o.useCallback(()=>{var W;const B=w.current;if(B)for(const F of B.groups)try{const q=(W=F.element)==null?void 0:W.ownerDocument;if(!q||q===document)continue;const ie=q.getElementById("dv-popout-window");if(!(ie instanceof HTMLElement))continue;ie.classList.add("adhdev-dockview"),Nr(ie,I),ie.classList.toggle("is-showing-dockview-overlay",$),ie.classList.toggle("is-dragging-dockview",R)}catch{}},[R,$,I]),ue=o.useCallback(B=>{const W=w.current;if(!W)return;const F=W.getPanel(B);F&&W.addPopoutGroup(F,{popoutUrl:"/popout.html",onDidOpen:({window:q})=>{H(q),he();const ie=be.get(B);q.document.title=ie?`${rt(ie)} — ADHDev`:"ADHDev — Popout"}})},[be,H]),re=o.useCallback(B=>{const W=w.current,F=W==null?void 0:W.getPanel(B);if(!W||!F)return;const q=W.groups.filter(ie=>{var ke;try{return((ke=ie.element)==null?void 0:ke.ownerDocument)===document}catch{return!0}});q.length>0?F.api.moveTo({group:q[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),le=o.useCallback(B=>{var q;const W=w.current;if(!W)return!1;const F=W.getPanel(B);if(!F)return!1;try{return((q=F.group.element)==null?void 0:q.ownerDocument)!==document}catch{return!1}},[]),se=o.useCallback(B=>{le(B)&&re(B),d(B)},[le,re,d]),me=o.useCallback(B=>{const W=w.current,F=W==null?void 0:W.getPanel(B);!W||!F||W.addFloatingGroup(F,{width:600,height:500})},[]),ne=o.useCallback(B=>{var F;const W=(F=w.current)==null?void 0:F.getPanel(B);if(!W)return!1;try{return W.group.model.location.type==="floating"}catch{return!1}},[]),ce=o.useCallback(()=>{var W,F;const B=(F=(W=w.current)==null?void 0:W.activePanel)==null?void 0:F.id;return!B||Lt(B)?null:be.has(B)?B:null},[be]),oe=o.useCallback(B=>{const W=w.current,F=W==null?void 0:W.getPanel(B);if(!W||!F)return;const q=W.groups.filter(ie=>{try{return ie.model.location.type==="grid"}catch{return!0}});q.length>0?F.api.moveTo({group:q[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),we=o.useCallback(()=>{var ke;const B=w.current;if(!B)return;const F=B.groups.filter(Ce=>{var X;try{return((X=Ce.element)==null?void 0:X.ownerDocument)===document&&Ce.model.location.type==="grid"}catch{return!1}})[0]||null,q=[...B.panels];for(const Ce of q){const X=(ke=Ce.group.element)==null?void 0:ke.ownerDocument,xe=Ce.group.model.location.type;X===document&&xe==="grid"||(F&&F.id!==Ce.group.id?Ce.api.moveTo({group:F,position:"center"}):Ce.api.moveTo({position:"center"}))}const ie=B.activePanel;ie&&(ie.group.model.openPanel(ie),ie.api.setActive()),Tn(document)},[]),he=o.useCallback(()=>{var W,F;const B=w.current;if(B)for(const q of B.groups){const ie=(W=q.element)==null?void 0:W.ownerDocument;if(!ie||ie===document)continue;const ke=ie.getElementById("dv-popout-window");if(!(ke instanceof HTMLElement))continue;let Ce=null,X=ie.title||"ADHDev",xe="Popout workspace";const Be=q.activePanel;if(Be)if(Ce=Be.id,Lt(Be.id)){const _e=((F=Be.params)==null?void 0:F.routeId)||Be.id.slice(7),D=Dt([...be.values()],_e);X=uc(D),xe=D!=null&&D.machineName?`Remote view · ${D.machineName}`:"Remote view"}else{const _e=be.get(Be.id);X=_e?rt(_e):Be.title||Be.id,xe=_e?ts(_e):"Dockview panel"}ie.title=`${X} — ADHDev`;const Oe=Array.from(ie.querySelectorAll("#adhdev-popout-header"));for(const _e of Oe)_e.remove();const Xe=ie.createElement("div");Xe.id="adhdev-popout-header",ie.body.appendChild(Xe),Xe.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(";")),Xe.innerHTML=`
|
|
44
|
-
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
45
|
-
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
46
|
-
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Jo(X)}</div>
|
|
47
|
-
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Jo(xe)}</div>
|
|
48
|
-
</div>
|
|
49
|
-
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
50
|
-
<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>
|
|
51
|
-
<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>
|
|
52
|
-
</div>
|
|
53
|
-
`,ke.style.top="52px",ke.style.height="calc(100% - 52px)";const qe=Xe.querySelector("[data-adhdev-popout-focus]");qe&&(qe.onclick=()=>{window.focus()});const Ue=Xe.querySelector("[data-adhdev-popout-dock]");Ue&&(Ue.disabled=!Ce,Ue.style.opacity=Ce?"1":"0.5",Ue.style.cursor=Ce?"pointer":"default",Ue.onclick=()=>{var _e;Ce&&re(Ce),(_e=ie.defaultView)==null||_e.focus()})}},[be,re]),Se=o.useCallback(B=>{var q;const W=w.current,F=W==null?void 0:W.getPanel(B);if(!(!W||!F)){F.group.model.openPanel(F),F.api.setActive(),Ie(B,"dockview-shortcut");try{const ie=F.group.model.location;ie.type==="popout"?ie.getWindow().focus():Tn((q=F.group.element)==null?void 0:q.ownerDocument)}catch{}}},[Ie]),N=o.useCallback(B=>{const W=w.current,F=W==null?void 0:W.activePanel,q=(W==null?void 0:W.activeGroup)||(F==null?void 0:F.group);if(!W||!F||!q)return;const ie=q.panels||[];if(ie.length<=1)return;const ke=ie.findIndex(xe=>xe.id===F.id);if(ke<0)return;const Ce=(ke+B+ie.length)%ie.length,X=ie[Ce];X&&(X.group.model.openPanel(X),X.api.setActive(),Lt(X.id)||Ie(X.id,"dockview-shortcut"))},[Ie]),O=o.useCallback(B=>{var qe;const W=w.current,F=(W==null?void 0:W.activeGroup)||((qe=W==null?void 0:W.activePanel)==null?void 0:qe.group);if(!W||!F)return;const q=W.groups||[],ie=q.find(Ue=>Ue.id===F.id);if(!ie)return;const ke=ie.element.getBoundingClientRect(),Ce=ke.left+ke.width/2,X=ke.top+ke.height/2,xe=(Ue,_e,D,te)=>Math.max(0,Math.min(_e,te)-Math.max(Ue,D)),Be=Ue=>{const _e=Ue.element.getBoundingClientRect(),D=_e.left+_e.width/2,te=_e.top+_e.height/2;let de=0,Le=0,Ne=0,Me=!1;if(B==="left"?(Me=D<Ce,de=Math.max(0,ke.left-_e.right),Le=Math.abs(te-X),Ne=xe(ke.top,ke.bottom,_e.top,_e.bottom)):B==="right"?(Me=D>Ce,de=Math.max(0,_e.left-ke.right),Le=Math.abs(te-X),Ne=xe(ke.top,ke.bottom,_e.top,_e.bottom)):B==="above"?(Me=te<X,de=Math.max(0,ke.top-_e.bottom),Le=Math.abs(D-Ce),Ne=xe(ke.left,ke.right,_e.left,_e.right)):(Me=te>X,de=Math.max(0,_e.top-ke.bottom),Le=Math.abs(D-Ce),Ne=xe(ke.left,ke.right,_e.left,_e.right)),!Me)return Number.POSITIVE_INFINITY;const Ae=Ne>0?0:120;return de*3+Le+Ae};let Oe=null,Xe=Number.POSITIVE_INFINITY;for(const Ue of q){if(Ue.id===ie.id)continue;const _e=Be(Ue);Number.isFinite(_e)&&(_e>=Xe||(Xe=_e,Oe=Ue))}return Oe||void 0},[]),G=o.useCallback(B=>{var q;const W=O(B);if(!W)return;const F=W.activePanel||W.panels[0];F&&(W.model.openPanel(F),F.api.setActive(),Lt(F.id)||Ie(F.id,"dockview-focus"),Tn((q=W.element)==null?void 0:q.ownerDocument))},[O,Ie]),Z=o.useCallback((B,W)=>{const F=w.current,q=F==null?void 0:F.activePanel,ie=(F==null?void 0:F.activeGroup)||(q==null?void 0:q.group);if(!F||!q||!ie)return;let ke=O(B);!ke&&(W!=null&&W.createGroupIfMissing)&&(ke=F.addGroup({referenceGroup:ie,direction:B})),ke&&(q.api.moveTo({group:ke,position:"center"}),q.group.model.openPanel(q),q.api.setActive(),Lt(q.id)||Ie(q.id,W!=null&&W.createGroupIfMissing?"dockview-split":"dockview-move"))},[O,Ie]),{isMac:fe,tabShortcuts:ge,shortcutListening:Pe,setShortcutListening:Ee,saveShortcuts:We}=Gc({sortedTabKeys:e.map(B=>B.tabKey),onFocus:ve,onSelectTab:Se}),ze=o.useCallback(()=>{var F;const B=w.current;if(!B)return;const W=B.activePanel;if(W){if(Lt(W.id)){const q=((F=W.params)==null?void 0:F.routeId)||W.id.slice(7),ie=Dt(e,q);ie!=null&&ie.tabKey&&Ee(ie.tabKey);return}be.has(W.id)&&Ee(W.id)}},[be,Se,Ee,e]),Qe=o.useCallback(B=>{const W=[];return B.metaKey&&W.push(fe?"⌘":"Meta"),B.ctrlKey&&W.push("Ctrl"),B.altKey&&W.push(fe?"⌥":"Alt"),B.shiftKey&&B.key.length!==1&&W.push(fe?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(B.key)?null:(W.push(Jc(B.key)),W.join("+"))},[fe]),Ze=o.useCallback(B=>{var W,F;switch(B){case"splitActiveTabRight":Z("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Z("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const q=ce();q&&me(q);return}case"popoutActiveTab":{const q=ce();q&&ue(q);return}case"dockActiveTab":{const q=ce();if(!q)return;le(q)?re(q):ne(q)&&oe(q);return}case"focusLeftPane":G("left");return;case"focusRightPane":G("right");return;case"focusUpPane":G("above");return;case"focusDownPane":G("below");return;case"moveActiveTabToLeftPane":Z("left");return;case"moveActiveTabToRightPane":Z("right");return;case"moveActiveTabToUpPane":Z("above");return;case"moveActiveTabToDownPane":Z("below");return;case"selectPreviousGroupTab":N(-1);return;case"selectNextGroupTab":N(1);return;case"setActiveTabShortcut":ze();return;case"hideCurrentTab":{const q=(F=(W=w.current)==null?void 0:W.activePanel)==null?void 0:F.id;q&&!Lt(q)&&se(q);return}default:return}},[N,oe,G,me,ce,se,ne,le,re,Z,ue,ze]);o.useEffect(()=>{if(!U)return;const B=U.sourceDocument,W=B.defaultView??window,F=q=>{const ie=B.querySelector("[data-dockview-tab-context-menu]");ie&&ie.contains(q.target)||L(null)};return W.addEventListener("mousedown",F,!0),W!==window&&window.addEventListener("mousedown",()=>L(null),!0),()=>{W.removeEventListener("mousedown",F,!0),W!==window&&window.removeEventListener("mousedown",()=>L(null),!0)}},[U]);const it=o.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:be,hasDetachedConversationPanels:ye,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:S,liveSessionInboxState:A,sendDaemonCommand:a,setActionLogs:i,toggleHiddenTab:se,userName:f,scrollToBottomRequest:C,tabShortcuts:ge,openTabContextMenu:({x:B,y:W,tabKey:F,sourceDocument:q})=>L({x:B,y:W,tabKey:F,sourceDocument:q??document}),popoutTab:ue,moveTabBackToMain:re,isTabInPopout:le,floatTab:me,isTabFloating:ne}),[n,s,be,ye,r,c,l,S,A,a,i,se,f,C,ge,ue,re,le,me,ne]),yt=U?Eh({isTabInPopout:le(U.tabKey),isTabFloating:ne(U.tabKey),tabShortcut:ge[U.tabKey],actionShortcuts:h}):[],ut=o.useCallback(B=>{var q;const W=w.current;if((((q=W==null?void 0:W.activePanel)==null?void 0:q.id)??null)===B.id){B.group.model.openPanel(B);return}B.group.model.openPanel(B),B.api.setActive()},[]),Ye=o.useCallback((B,W="requested-tab")=>{if(!B)return!1;const F=w.current;if(!F)return!1;const q=F.getPanel(B);return q?(ut(q),Ie(B,W),b==null||b(),!0):!1},[ut,b,Ie]),nt=o.useCallback(()=>{if(M.current)return!1;const B=Ye(P.current,"stored-layout-restore");return B&&(M.current=!0),B},[Ye]),je=o.useCallback(()=>{var W;const B=w.current;B&&wp(y,{activeTabId:((W=B.activePanel)==null?void 0:W.id)??null,layout:B.toJSON()})},[y]),$e=o.useCallback(()=>{kp(y,ae.current)},[y]),Ke=o.useCallback(B=>{var q,ie,ke,Ce;const W=w.current;if(!W)return{kind:"grid"};const F=W.toJSON();for(const X of F.floatingGroups||[])if((ie=(q=X.data)==null?void 0:q.views)!=null&&ie.includes(B)&&X.position)return{kind:"floating",position:X.position};for(const X of F.popoutGroups||[])if((Ce=(ke=X.data)==null?void 0:ke.views)!=null&&Ce.includes(B))return{kind:"popout",position:X.position,popoutUrl:X.url};return{kind:"grid"}},[]),st=o.useCallback(B=>{const W=w.current;if(!W)return;const F=W.getPanel(B),q=ae.current[B];if(!F||!q||q.kind==="grid")return;if(F.group.model.location.type===q.kind){delete ae.current[B],$e();return}if(q.kind==="floating"){W.addFloatingGroup(F,{x:q.position.left??24,y:q.position.top??24,width:q.position.width,height:q.position.height}),delete ae.current[B],$e();return}delete ae.current[B],$e()},[$e]);o.useEffect(()=>(m==null||m({setShortcutForActiveTab:ze,restoreHiddenTabToSavedLocation:st,activateConversationTab:Se,resetAllPanelsToMain:we,activatePreviousTabInGroup:()=>N(-1),activateNextTabInGroup:()=>N(1),floatActiveTab:()=>{const B=ce();B&&me(B)},popoutActiveTab:()=>{const B=ce();B&&ue(B)},dockActiveTab:()=>{const B=ce();B&&(le(B)?re(B):ne(B)&&oe(B))},splitActiveTabRight:()=>Z("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Z("below",{createGroupIfMissing:!0}),focusLeftPane:()=>G("left"),focusRightPane:()=>G("right"),focusUpPane:()=>G("above"),focusDownPane:()=>G("below"),moveActiveTabToLeftPane:()=>Z("left"),moveActiveTabToRightPane:()=>Z("right"),moveActiveTabToUpPane:()=>Z("above"),moveActiveTabToDownPane:()=>Z("below")}),()=>m==null?void 0:m(null)),[N,oe,me,G,ce,ne,le,Z,re,ue,m,we,st,Se,ze]);const dt=o.useCallback(()=>{const B=g.current;if(!B)return;const W=B.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const F of W)F.setAttribute("data-adhdev-force-hidden","true")},[]),mt=o.useCallback(()=>{const B=g.current;if(!B)return;const W=B.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const F of W)F.removeAttribute("data-adhdev-force-hidden")},[]),ee=o.useCallback(()=>{const B=g.current;if(!B)return;const W=B.querySelectorAll(".dv-drop-target-container");for(const ie of W)ie.remove();const F=B.querySelectorAll(".dv-drop-target-dropzone");for(const ie of F)ie.remove();const q=B.querySelectorAll(".dv-drop-target");for(const ie of q)ie.classList.remove("dv-drop-target")},[]),Te=o.useCallback(()=>{z(!1),_(!1),mt(),dt(),ee(),!(typeof window>"u")&&(pe.current!=null&&window.clearTimeout(pe.current),window.requestAnimationFrame(()=>{dt(),ee()}),pe.current=window.setTimeout(()=>{dt(),ee(),pe.current=null},80))},[mt,dt,ee]),Re=o.useCallback(B=>{var F;w.current=B.api;const W=vp(y);if(P.current=(W==null?void 0:W.activeTabId)??null,W!=null&&W.layout&&B.api.fromJSON(W.layout,{reuseExistingPanels:!1}),T.current=Xo({hasStoredLayout:!!(W!=null&&W.layout),initialDataLoaded:u,visibleConversationCount:e.length,ides:r}),T.current||(Zo(B.api,e),ei(B.api,e,v)),B.api.totalPanels===0&&e.length>0){const q=Oh(B.api,e,x);if(q){const ie=B.api.getPanel(q);ie&&ut(ie)}}else!T.current&&!Ye(x)&&nt();E.current=!0,B.api.onDidActivePanelChange(q=>{var ke;if(P.current=(q==null?void 0:q.id)??null,M.current=!0,he(),q&&Lt(q.id)){const Ce=((ke=q.params)==null?void 0:ke.routeId)||q.id.slice(7),X=Dt(e,Ce);j((X==null?void 0:X.tabKey)??null),je();return}if(j((q==null?void 0:q.id)??null),je(),!q)return;const ie=be.get(q.id);(ie==null?void 0:ie.streamSource)==="agent-stream"&&ie.agentType&&k(ie.routeId,Oc(),{agentType:ie.agentType,...ie.sessionId&&{targetSessionId:ie.sessionId}}).catch(()=>{})}),B.api.onDidLayoutChange(()=>{je(),he(),J(q=>q+1)}),B.api.onWillDragPanel(()=>{z(!0),_(!1),dt()}),B.api.onWillDragGroup(()=>{z(!0),_(!1),dt()}),B.api.onWillShowOverlay(()=>{mt(),_(!0)}),B.api.onDidMovePanel(Te),B.api.onDidDrop(Te),B.api.onDidAddGroup(q=>{requestAnimationFrame(()=>{var ie,ke;try{const Ce=(ie=q.element)==null?void 0:ie.ownerDocument;if(!Ce||Ce===document)return;(ke=Ce.getElementById("dv-popout-window"))==null||ke.classList.add("adhdev-dockview");const X=document.documentElement.getAttribute("data-theme");X&&Ce.documentElement.setAttribute("data-theme",X),Ce.body.className=document.body.className;const xe=document.documentElement.getAttribute("style");xe&&Ce.documentElement.setAttribute("style",xe)}catch{}he(),J(Ce=>Ce+1)})}),j(((F=B.api.activePanel)==null?void 0:F.id)??null)},[ut,Ye,Te,mt,be,r,u,y,dt,j,je,x,v,k,he,e]);o.useLayoutEffect(()=>{const B=w.current;if(!B||!E.current||T.current&&Xo({hasStoredLayout:!0,initialDataLoaded:u,visibleConversationCount:e.length,ides:r}))return;T.current&&(T.current=!1);const W=K.current,F=new Set(W),q=e.map(Oe=>Oe.tabKey),ie=new Set(q),ke=$h({previousVisibleConversationCount:W.length,visibleConversationCount:e.length,ides:r});let Ce=!1;for(const Oe of W)ie.has(Oe)||ke||(ae.current[Oe]=Ke(Oe),Ce=!0);Ce&&$e(),ke||(Zo(B,e),ei(B,e,v));const X=q.filter(Oe=>!F.has(Oe));let xe=!1;for(const Oe of X){const Xe=B.getPanel(Oe),qe=ae.current[Oe];if(!Xe||!qe||qe.kind==="grid")continue;if(Xe.group.model.location.type===qe.kind){delete ae.current[Oe],xe=!0;continue}if(qe.kind==="floating"){B.addFloatingGroup(Xe,{x:qe.position.left??24,y:qe.position.top??24,width:qe.position.width,height:qe.position.height}),delete ae.current[Oe],xe=!0;continue}}if(xe&&$e(),K.current=q,x&&Ye(x))return;!B.activePanel&&B.panels[0]&&ut(B.panels[0]),!!(B.activePanel&&B.getPanel(B.activePanel.id))||nt()},[ut,Ye,nt,r,u,$e,Ke,x,v,e]),o.useEffect(()=>{E.current&&Ye(x)},[Ye,x]),o.useEffect(()=>{if(!R||typeof window>"u")return;const B=()=>Te();return window.addEventListener("pointerup",B),window.addEventListener("mouseup",B),window.addEventListener("dragend",B),()=>{window.removeEventListener("pointerup",B),window.removeEventListener("mouseup",B),window.removeEventListener("dragend",B)}},[Te,R]),o.useEffect(()=>()=>{typeof window>"u"||pe.current!=null&&window.clearTimeout(pe.current)},[]),o.useEffect(()=>{const B=F=>{const q=F.target;if(!q)return;const ie=q.querySelector("[data-tab-key]")||q.closest("[data-tab-key]");if(ie){const ke=ie.getAttribute("data-tab-key");if(ke&&F.dataTransfer){const Ce=q.closest(".dv-tab")||ie.closest(".dv-tab")||ie;F.dataTransfer.effectAllowed="move",F.dataTransfer.setData("text/tab-key",ke),Ce instanceof HTMLElement&&F.dataTransfer.setDragImage(Ce,Math.max(12,Math.round(Ce.clientWidth/2)),Math.max(10,Math.round(Ce.clientHeight/2)))}}};window.addEventListener("dragstart",B);const W=Qo(w.current);for(const F of W)F.addEventListener("dragstart",B);return()=>{window.removeEventListener("dragstart",B);for(const F of W)F.removeEventListener("dragstart",B)}},[Y]),o.useEffect(()=>{var W;const B=(W=g.current)==null?void 0:W.querySelector(".adhdev-dockview");B instanceof HTMLElement&&Nr(B,I),V(),he(),Q()},[he,Q,V,I]),o.useEffect(()=>{he(),Q()},[he,Q]),o.useEffect(()=>{const B=W=>{if(W.defaultPrevented||Pe)return;const F=Qe(W);if(!F)return;const q=W.metaKey||W.ctrlKey||W.altKey;ca(W.target)&&!q||Gr(fe).setActiveTabShortcut!==F||(W.preventDefault(),W.stopPropagation(),ze())};return window.addEventListener("keydown",B,!0),()=>window.removeEventListener("keydown",B,!0)},[Qe,fe,Pe,ze]),o.useEffect(()=>{const B=g.current;if(!B)return;const W=F=>{var X,xe;if(!F.isTrusted)return;const q=(xe=(X=F.target)==null?void 0:X.closest)==null?void 0:xe.call(X,".dv-scrollable");if(!q)return;F.preventDefault(),F.stopPropagation();const ie=Math.abs(F.deltaX),ke=Math.abs(F.deltaY),Ce=ie>ke?F.deltaX:F.deltaY;q.dispatchEvent(new WheelEvent("wheel",{deltaY:Ce,deltaMode:F.deltaMode,bubbles:!1,cancelable:!0}))};return B.addEventListener("wheel",W,{passive:!1,capture:!0}),()=>B.removeEventListener("wheel",W,{capture:!0})},[]),o.useEffect(()=>{const B=Qo(w.current);if(B.length===0)return;const W=B.map(F=>{let q=[],ie=null;const ke=()=>{ie!=null&&F.clearTimeout(ie),ie=null,q=[]},Ce=()=>{ie!=null&&F.clearTimeout(ie),ie=F.setTimeout(()=>{ie=null,q=[]},1200)},X=Be=>{if(!Be.ctrlKey&&!Be.metaKey&&!Be.altKey)return;const Oe=Qe(Be);if(!Oe)return;const Xe=Vc();for(const[qe,Ue]of Object.entries(Xe))if(e.some(_e=>_e.tabKey===qe)&&Ue===Oe){Be.preventDefault(),Se(qe);return}},xe=Be=>{if(Be.defaultPrevented||Pe)return;const Oe=Qe(Be);if(!Oe)return;const Xe=Be.metaKey||Be.ctrlKey||Be.altKey;if(ca(Be.target)&&!Xe)return;const qe=Gr(fe),Ue=Object.entries(qe).filter(([Ae,ft])=>!!ft&&(Ae==="splitActiveTabRight"||Ae==="splitActiveTabDown"||Ae==="floatActiveTab"||Ae==="popoutActiveTab"||Ae==="dockActiveTab"||Ae==="focusLeftPane"||Ae==="focusRightPane"||Ae==="focusUpPane"||Ae==="focusDownPane"||Ae==="moveActiveTabToLeftPane"||Ae==="moveActiveTabToRightPane"||Ae==="moveActiveTabToUpPane"||Ae==="moveActiveTabToDownPane"||Ae==="selectPreviousGroupTab"||Ae==="selectNextGroupTab"||Ae==="setActiveTabShortcut"||Ae==="hideCurrentTab")),_e=Xe?[Oe]:[...q.slice(-1),Oe].slice(-2),D=_e.join(" "),te=_e[_e.length-1],de=Ue.find(([,Ae])=>Ae===D);if(de){Be.preventDefault(),ke(),Ze(de[0]);return}if(Ue.some(([,Ae])=>Ae.startsWith(`${D} `))){Be.preventDefault(),q=_e,Ce();return}const Ne=Ue.find(([,Ae])=>Ae===te);if(Ne){Be.preventDefault(),ke(),Ze(Ne[0]);return}if(Ue.some(([,Ae])=>Ae.startsWith(`${te} `))){Be.preventDefault(),q=[te],Ce();return}ke()};return F.addEventListener("keydown",X),F.addEventListener("keydown",xe),()=>{ke(),F.removeEventListener("keydown",X),F.removeEventListener("keydown",xe)}});return()=>{for(const F of W)F()}},[Qe,fe,Y,Se,Pe,Ze,e]);const at=I==="light"?Fn:Un,ht=((It=(He=(vt=w.current)==null?void 0:vt.activePanel)==null?void 0:He.group.element)==null?void 0:It.ownerDocument)??document;return t.jsxs(Zc.Provider,{value:it,children:[t.jsx("div",{ref:g,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(zl,{className:`h-full min-h-0 min-w-0 adhdev-dockview${R?" is-dragging-dockview":""}${$?" is-showing-dockview-overlay":""}`,components:{conversation:Wh,remote:Hh},defaultTabComponent:Uh,watermarkComponent:Fh,onReady:Re,singleTabMode:"default",tabAnimation:"smooth",theme:at,popoutUrl:"/popout.html"})}),U&&zs.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:U.x,top:U.y},children:yt.map(B=>{if(B.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},B.id);let W=t.jsx(Kd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{};switch(B.id){case"dockInWindow":case"dockBackToGrid":W=t.jsx(Wd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{oe(U.tabKey),L(null)};break;case"moveBackToMain":W=t.jsx(Bd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{re(U.tabKey),L(null)};break;case"floatAsPanel":W=t.jsx(Od,{size:13,className:"shrink-0 opacity-70"}),F=()=>{me(U.tabKey),L(null)};break;case"openInNewWindow":W=t.jsx($d,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ue(U.tabKey),L(null)};break;case"setShortcut":F=q=>{q.stopPropagation(),Ee(U.tabKey),L(null)};break;case"removeShortcut":W=t.jsx(wt,{size:13,className:"shrink-0 opacity-70"}),F=()=>{const q={...ge};delete q[U.tabKey],We(q),L(null)};break;case"hideTab":W=t.jsx(Ii,{size:13,className:"shrink-0 opacity-70"}),F=()=>{se(U.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 ${B.tone==="muted"?"text-text-muted":""}`,onClick:F,children:[W,t.jsx("span",{className:"flex-1 min-w-0",children:B.label}),B.shortcut?t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:B.shortcut}):null]},B.id)})}),U.sourceDocument.body),Pe&&zs.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:()=>Ee(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:B=>B.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. ",fe?"⌘+1":"Ctrl+1",", ",fe?"⌥+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"})]})}),ht.body)]})}const el="adhdev-recent-launch-args-v1",Vh=8;function Gh(e){return String(e||"").trim().replace(/\s+/g," ")}function tl(e,s){return`${e.trim()}::${s.trim()}`}function sl(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(el)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function qh(e){if(!(typeof window>"u"))try{window.localStorage.setItem(el,JSON.stringify(e))}catch{}}function rl(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=sl().byKey[tl(r,n)])==null?void 0:i.items)||[]}function nl(e,s,r){var d;const n=String(e||"").trim(),a=String(s||"").trim(),i=Gh(r);if(!n||!a||!i)return;const c=sl(),l=tl(n,a),u=((d=c.byKey[l])==null?void 0:d.items)||[],f=[i,...u.filter(h=>h!==i)].slice(0,Vh);c.byKey[l]={items:f},qh(c)}function al(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Dr({title:e,description:s,action:r,children:n,className:a="",contentClassName:i=""}){return t.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),s&&t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:s})]}),r?t.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?t.jsx("div",{className:s||r?`mt-3 ${i}`.trim():i,children:n}):null]})}function ol({busy:e,savedSessionsLoading:s,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?Fc(n):null;return t.jsxs(Dr,{title:"Saved history",description:La(),action:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||s,onClick:a,children:s?"Loading…":"Refresh"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:i,children:rf()})]}),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 Ln(e){var n;if(!e)return null;const s=e.availableProviders||[];return s.some(a=>a.category==="cli"&&a.installed!==!1)?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":s.some(a=>a.category==="acp"&&a.installed!==!1)?"acp":null}function Cr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Yh({machines:e,ides:s,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:i,onLaunchProvider:c,onListSavedSessions:l}){var dt,mt;const u=nr(),f=o.useMemo(()=>[...e].sort(va),[e]),[d,h]=o.useState(((dt=f[0])==null?void 0:dt.id)||""),m=o.useMemo(()=>f.find(ee=>ee.id===d)||f[0],[d,f]),j=o.useMemo(()=>((m==null?void 0:m.workspaces)||[]).map(ee=>({id:ee.id,path:ee.path,label:ee.label})),[m]),S=(m==null?void 0:m.defaultWorkspaceId)||null,[p,x]=o.useState(""),[v,b]=o.useState(""),[C,A]=o.useState(Ln(f[0])),[y,I]=o.useState(""),[k,w]=o.useState(""),[g,E]=o.useState([]),[T,M]=o.useState(""),[P,K]=o.useState([]),[U,L]=o.useState(!1),[R,z]=o.useState(!1),[$,_]=o.useState(""),[Y,J]=o.useState(!1),[pe,ae]=o.useState(()=>pt()),[be,ye]=o.useState(null),[ve,Ie]=o.useState(!1),[H,V]=o.useState(""),[Q,ue]=o.useState(!1),[re,le]=o.useState(""),[se,me]=o.useState([]),[ne,ce]=o.useState(!1),[oe,we]=o.useState(""),[he,Se]=o.useState(!1),N=o.useRef(null),O=o.useRef(0);o.useEffect(()=>{var ee;!d&&((ee=f[0])!=null&&ee.id)&&h(f[0].id)},[d,f]),o.useEffect(()=>{!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||u(m.id,{minFreshMs:3e4}).catch(()=>{})},[u,m]);const G=o.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(ee=>ee.category==="cli"&&ee.installed!==!1),[m]),Z=o.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(ee=>ee.category==="acp"&&ee.installed!==!1),[m]),fe=o.useMemo(()=>((m==null?void 0:m.detectedIdes)||[]).map(ee=>({id:ee.type,label:ee.name||ee.type,meta:ee.running?"Detected locally":"Available to open"})),[m]),ge=o.useMemo(()=>C==="cli"?G.map(ee=>({id:ee.type,label:ee.displayName||ee.type,meta:"CLI provider"})):C==="acp"?Z.map(ee=>({id:ee.type,label:ee.displayName||ee.type,meta:"ACP provider"})):fe,[Z,C,G,fe]);o.useEffect(()=>{var Te;if(!m)return;if(N.current!==m.id){N.current=m.id,x(S||((Te=j[0])==null?void 0:Te.id)||"__home__"),b(""),A(Ln(m)),I(""),w(""),M(""),K([]),z(!1),_(""),ae(pt()),V("");return}x(Re=>{var at;return Re==="__custom__"||Re==="__home__"||j.some(ht=>ht.id===Re)?Re:S||((at=j[0])==null?void 0:at.id)||"__home__"}),A(Re=>Re==="ide"&&fe.length>0||Re==="cli"&&G.length>0||Re==="acp"&&Z.length>0?Re:Ln(m))},[Z.length,G.length,S,fe.length,m,j]),o.useEffect(()=>{var ee;C&&(ge.some(Te=>Te.id===y)||I(((ee=ge[0])==null?void 0:ee.id)||""))},[C,ge,y]);const Pe=o.useCallback(async(ee,Te)=>{const Re=O.current+1;return O.current=Re,L(!0),_(""),l(ee,Te).then(at=>{O.current===Re&&K(at)}).catch(at=>{O.current===Re&&(K([]),_(at instanceof Error?at.message:"Could not load saved sessions"))}).finally(()=>{O.current===Re&&(L(!1),z(!0))})},[l]),Ee=o.useCallback((ee,Te)=>{E(rl(ee,Te))},[]);o.useEffect(()=>{O.current+=1,M(""),ae(pt()),!m||!y||C==="ide"?E([]):Ee(m.id,y),z(!1),K([]),_(""),L(!1)},[C,Ee,Pe,m,y]),o.useEffect(()=>{if(!T)return;const ee=P.find(Te=>Te.providerSessionId===T);ee!=null&&ee.canResume||M("")},[P,T]);const We=p==="__custom__"?v.trim():p==="__home__"?"":((mt=j.find(ee=>ee.id===p))==null?void 0:mt.path)||"",ze=o.useMemo(()=>m?s.filter(ee=>ee.id!==m.id&&ee.daemonId===m.id).map(ee=>ee.workspace):[],[s,m]),Qe=o.useMemo(()=>((m==null?void 0:m.recentLaunches)||[]).map(ee=>ee.workspace),[m]),Ze=o.useCallback(ee=>{const Te=String(ee.workspace||"").trim();if(!Te)return;const Re=j.find(at=>Cr(at.path)===Cr(Te));if(Re){x(Re.id),b("");return}x("__custom__"),b(Te)},[j]),it=o.useCallback(ee=>{const Te=String(ee.workspace||"").trim();if(!Te)return{workspaceId:null,workspacePath:null};const Re=j.find(at=>Cr(at.path)===Cr(Te));return Re?{workspaceId:Re.id,workspacePath:null}:{workspaceId:null,workspacePath:Te}},[j]),yt=o.useMemo(()=>P.find(ee=>ee.providerSessionId===T)||null,[P,T]),ut=o.useMemo(()=>{var Te;if(C!=="cli"||!m||!y)return null;const ee=((Te=G.find(Re=>Re.type===y))==null?void 0:Te.displayName)||y;return{routeId:m.id,daemonId:m.id,providerSessionId:T||void 0,transport:"pty",mode:"chat",agentName:ee,agentType:y,status:"idle",title:ee,messages:[],ideType:y,workspaceName:We,displayPrimary:ee,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${m.id}:${y}`,machineName:Tt(m,{fallbackId:m.id})}},[C,G,We,m,T,y]),Ye=o.useCallback(()=>{var Te;if(!m)return;x("__custom__"),ue(!0),we("");const ee=sn(m.platform,tn(v.trim(),We,ze,Qe,m.defaultWorkspacePath,(Te=j.find(Re=>Re.id===S))==null?void 0:Te.path,j.map(Re=>Re.path)));ce(!0),n(m.id,ee).then(Re=>{le(Re.path),b(Re.path),me(Re.directories)}).catch(Re=>{we(Re instanceof Error?Re.message:"Could not load folder")}).finally(()=>ce(!1))},[v,S,Qe,ze,n,We,m,j]),nt=o.useCallback(ee=>{m&&(ce(!0),we(""),n(m.id,ee).then(Te=>{le(Te.path),b(Te.path),me(Te.directories)}).catch(Te=>{we(Te instanceof Error?Te.message:"Could not load folder")}).finally(()=>ce(!1)))},[n,m]),je=o.useCallback(async()=>{if(!m||!We)return;Se(!0),V("");const ee=await a(m.id,We);if(Se(!1),!ee.ok){V(ee.error||"Could not save workspace");return}V("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,We,m]),$e=o.useCallback(async()=>{if(!m||!C||!y)return;Ie(!0),V("");const ee=k.trim()?k.trim().split(/\s+/).filter(Boolean):[],Te=C==="ide"?await i(m.id,y,{workspacePath:We||null}):await c(m.id,C,y,{workspaceId:p!=="__home__"&&p!=="__custom__"?p:null,workspacePath:p==="__custom__"&&We||null,resumeSessionId:C==="cli"&&T?T:null,cliArgs:ee});if(Ie(!1),!Te.ok){V(Te.error||"Could not start session");return}C!=="ide"&&k.trim()&&(nl(m.id,y,k),Ee(m.id,y)),r()},[C,k,Ee,r,i,c,We,m,T,y,p]),Ke=C?pc(C,C==="cli"&&!!T):"Start",st=C?hc(C,C==="cli"&&!!T):"Starting…";return m?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(wt,{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(Dr,{title:"Machine",children:t.jsx("select",{value:m.id,onChange:ee=>h(ee.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:ve,children:f.map(ee=>t.jsx("option",{value:ee.id,children:Tt(ee,{fallbackId:ee.id})},ee.id))})}),t.jsxs(Dr,{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:Ye,disabled:ve,children:"Browse…"}),children:[t.jsxs("select",{value:p,onChange:ee=>{const Te=ee.target.value;x(Te),Te==="__custom__"?Ye():V("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:ve,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),j.map(ee=>t.jsxs("option",{value:ee.id,children:[ee.id===S?"⭐ ":"",Zr(ee.path,ee.label)||ee.path]},ee.id)),t.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:p==="__home__"?"Launch without a workspace.":We||"Select a workspace folder."}),p==="__custom__"&&We&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ye,disabled:ve,children:[t.jsx(ks,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:je,disabled:ve||he,children:he?"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:G.length>0},{id:"ide",label:"IDE",enabled:fe.length>0},{id:"acp",label:"ACP",enabled:Z.length>0}].map(ee=>t.jsx("button",{type:"button",className:`btn btn-sm ${C===ee.id?"btn-primary":"btn-secondary"}`,onClick:()=>A(ee.id),disabled:!ee.enabled||ve,children:ee.label},ee.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:C==="ide"?"Choose IDE":C==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[ge.map(ee=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${y===ee.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>I(ee.id),disabled:ve,children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:ee.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ee.meta})]},ee.id)),ge.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."})]})]}),C!=="ide"&&t.jsxs(Dr,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:k,onChange:ee=>w(ee.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:ve}),g.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:g.map(ee=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>w(ee),disabled:ve,title:ee,children:ee},ee))})]}),C==="cli"&&t.jsx(ol,{busy:ve,savedSessionsLoading:U,savedSessionsError:$,selectedSession:yt,onRefresh:()=>{!m||!y||Pe(m.id,y)},onOpenHistory:()=>{!m||!y||(J(!0),al({hasLoadedInitialResults:R,isLoading:U})&&Pe(m.id,y))},onClearSelection:()=>M("")}),H&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${H.includes("saved")||H.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:H})]}),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:ve,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:$e,disabled:ve||!C||!y||p==="__custom__"&&!We,children:[t.jsx(ga,{size:14}),ve?st:Ke]})]})]})}),Q&&t.jsx(an,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:re,directories:se,busy:ne,error:oe,onClose:()=>ue(!1),onNavigate:nt,onConfirm:ee=>{b(ee),le(ee),x("__custom__"),ue(!1)}}),Y&&ut&&t.jsx(_a,{activeConv:ut,ides:[],isCreatingChat:!1,isRefreshingHistory:U,savedSessions:P,isSavedSessionsLoading:U,isResumingSavedSessionId:be,savedHistoryFilters:pe,onSavedHistoryFiltersChange:ae,onClose:()=>J(!1),onNewChat:()=>{M(""),J(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!m||!y||Pe(m.id,y)},onResumeSavedSession:ee=>{if(!m||!y||be||!ee.canResume)return;const Te=it(ee);M(ee.providerSessionId),Ze(ee),ye(ee.providerSessionId),J(!1),Ie(!0),V(""),c(m.id,"cli",y,{workspaceId:Te.workspaceId,workspacePath:Te.workspacePath,resumeSessionId:ee.providerSessionId}).then(Re=>{if(!Re.ok){V(Re.error||"Could not resume session");return}r()}).finally(()=>{Ie(!1),ye(Re=>Re===ee.providerSessionId?null:Re)})}})]}):null}function Xh({isMobile:e,showMobileChatMode:s,visibleConversationCount:r}){const[n,a]=o.useState(!1),[i,c]=o.useState(!1),[l,u]=o.useState(!1),[f,d]=o.useState(!1),[h,m]=o.useState(!1),[j,S]=o.useState("quickstart"),[p,x]=o.useState("workspace"),v=o.useMemo(()=>!s&&!e,[s,e]),b=o.useCallback(w=>{a(w),w&&c(!1)},[]),C=o.useCallback(w=>{c(w),w&&a(!1)},[]),A=o.useCallback(()=>{S(r===0?"quickstart":"shortcuts"),x("workspace"),u(!0),a(!1),c(!1)},[r]),y=o.useCallback(()=>{u(!1)},[]),I=o.useCallback(()=>{d(!0)},[]),k=o.useCallback(()=>{d(!1)},[]);return o.useEffect(()=>{if(!v){m(!1);return}m(!0);const w=window.setTimeout(()=>{m(!1)},1e4);return()=>window.clearTimeout(w)},[v]),{inboxOpen:n,hiddenOpen:i,shortcutHelpOpen:l,newSessionOpen:f,guideNudgeVisible:h,guideTab:j,shortcutSection:p,isDesktopDashboard:v,setGuideTab:S,setShortcutSection:x,handleInboxOpenChange:b,handleHiddenOpenChange:C,handleOpenShortcutHelp:A,closeShortcutHelp:y,openNewSession:I,closeNewSession:k}}function Jh(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 Qh(e){return e instanceof Error?e.message:String(e||"")}function Zh(e){const s=Qh(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function ex({showMobileChatMode:e,isMobile:s,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetActiveCliViewMode:f,mobileChatConversations:d,hiddenConversations:h,ides:m,actionLogs:j,sendDaemonCommand:S,setActionLogs:p,isStandalone:x,initialDataLoaded:v,userName:b,requestedMobileTabKey:C,onRequestedMobileTabConsumed:A,requestedMachineId:y,onRequestedMachineConsumed:I,requestedMobileSection:k,onRequestedMobileSectionConsumed:w,containerRef:g,isSplitMode:E,numGroups:T,groupSizes:M,groupedConvs:P,clearedTabs:K,focusedGroup:U,focusGroup:L,moveTabToGroup:R,splitTabRelative:z,closeGroup:$,handleResizeStart:_,groupActiveTabIds:Y,setGroupActiveTab:J,groupTabOrders:pe,setGroupTabOrder:ae,toggleHiddenTab:be,visibleConversations:ye,requestedDesktopTabKey:ve,onRequestedDesktopTabConsumed:Ie,onDesktopActiveTabChange:H,onRequestScrollToBottom:V,onHideConversation:Q,onShowHiddenConversation:ue,onShowAllHiddenConversations:re,scrollToBottomRequest:le,machineEntries:se,layoutProfile:me,onBrowseMachineDirectory:ne,onSaveMachineWorkspace:ce,onLaunchMachineIde:oe,onLaunchMachineProvider:we,onListMachineSavedSessions:he,notifications:Se,notificationUnreadCount:N,liveSessionInboxState:O,onMarkNotificationRead:G,onMarkNotificationUnread:Z,onDeleteNotification:fe}){const ge=St.useRef(null),{inboxOpen:Pe,hiddenOpen:Ee,shortcutHelpOpen:We,newSessionOpen:ze,guideNudgeVisible:Qe,guideTab:Ze,shortcutSection:it,isDesktopDashboard:yt,setGuideTab:ut,setShortcutSection:Ye,handleInboxOpenChange:nt,handleHiddenOpenChange:je,handleOpenShortcutHelp:$e,closeShortcutHelp:Ke,openNewSession:st,closeNewSession:dt}=Xh({isMobile:s,showMobileChatMode:e,visibleConversationCount:ye.length}),mt=St.useCallback(X=>{var xe;zs.flushSync(()=>{ue(X)}),(xe=ge.current)==null||xe.restoreHiddenTabToSavedLocation(X.tabKey)},[ue]),ee=St.useCallback(X=>{var Be;const xe=d.find(Oe=>Qn(Oe,X))||h.find(Oe=>Qn(Oe,X));xe&&(h.some(Oe=>Oe.tabKey===xe.tabKey)&&mt(xe),H(xe.tabKey),(Be=ge.current)==null||Be.activateConversationTab(xe.tabKey),V(xe.tabKey,"notification-open")),G(X.id),nt(!1)},[mt,h,d,H,G,V]),Te=St.useCallback(()=>{var xe;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((xe=ge.current)==null||xe.resetAllPanelsToMain(),je(!1))},[je]),Re=St.useCallback(async X=>{var qe;if(!r)return;const xe=(qe=r.modalButtons)==null?void 0:qe[X];if(!xe)return;const Be=Js(r);if(!Be)return;const Oe=xe.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Xe=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Oe);try{await S(Be,"resolve_action",{button:xe,action:Xe?"approve":"reject",buttonIndex:X,...ws(r)})}catch(Ue){Zh(Ue)||console.error("[Shortcut approval] Failed:",Ue)}},[r,S]),{isMac:at,actionDefinitions:ht,actionShortcuts:vt,shortcutListening:He,shortcutListeningDraft:It,setShortcutListening:B,setShortcutListeningDraft:W,saveShortcuts:F}=Dh({enabled:yt&&!We,onTrigger:X=>{var xe,Be,Oe,Xe,qe,Ue,_e,D,te,de,Le,Ne,Me,Ae,ft,ct;if(X==="openShortcutHelp"){$e();return}if(X==="hideCurrentTab"){r&&Q(r);return}if(X==="toggleHiddenTabs"){je(!Ee);return}if(X==="openHistoryForActiveTab"){r&&!Ge(r)&&i(r);return}if(X==="openRemoteForActiveTab"){r&&!Je(r)&&!Ge(r)&&c(r);return}if(X==="splitActiveTabRight"){(xe=ge.current)==null||xe.splitActiveTabRight();return}if(X==="splitActiveTabDown"){(Be=ge.current)==null||Be.splitActiveTabDown();return}if(X==="floatActiveTab"){(Oe=ge.current)==null||Oe.floatActiveTab();return}if(X==="popoutActiveTab"){(Xe=ge.current)==null||Xe.popoutActiveTab();return}if(X==="dockActiveTab"){(qe=ge.current)==null||qe.dockActiveTab();return}if(X==="focusLeftPane"){(Ue=ge.current)==null||Ue.focusLeftPane();return}if(X==="focusRightPane"){(_e=ge.current)==null||_e.focusRightPane();return}if(X==="focusUpPane"){(D=ge.current)==null||D.focusUpPane();return}if(X==="focusDownPane"){(te=ge.current)==null||te.focusDownPane();return}if(X==="moveActiveTabToLeftPane"){(de=ge.current)==null||de.moveActiveTabToLeftPane();return}if(X==="moveActiveTabToRightPane"){(Le=ge.current)==null||Le.moveActiveTabToRightPane();return}if(X==="moveActiveTabToUpPane"){(Ne=ge.current)==null||Ne.moveActiveTabToUpPane();return}if(X==="moveActiveTabToDownPane"){(Me=ge.current)==null||Me.moveActiveTabToDownPane();return}if(X==="triggerPrimaryApprovalAction"){Re(0);return}if(X==="triggerSecondaryApprovalAction"){Re(1);return}if(X==="triggerTertiaryApprovalAction"){Re(2);return}if(X==="setActiveTabShortcut"){(Ae=ge.current)==null||Ae.setShortcutForActiveTab();return}if(X==="selectPreviousGroupTab"){(ft=ge.current)==null||ft.activatePreviousTabInGroup();return}if(X==="selectNextGroupTab"){(ct=ge.current)==null||ct.activateNextTabInGroup();return}!r||!Je(r)||Ge(r)||X==="toggleCliView"&&f(u==="chat"?"terminal":"chat")}}),q=St.useCallback(()=>{Ke(),B(null),W([])},[Ke,B,W]),ie=St.useMemo(()=>it==="all"?ht:ht.filter(X=>Jh(X)===it),[ht,it]),ke=St.useCallback(()=>{const X=Object.fromEntries(ht.map(xe=>[xe.id,""]));F(X)},[ht,F]),Ce=St.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const X=Object.fromEntries(ht.map(xe=>[xe.id,xe.defaultShortcut]));F(X)},[ht,F]);return St.useEffect(()=>{const X=xe=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?xe.metaKey&&xe.key.toLowerCase()==="w":xe.ctrlKey&&xe.key.toLowerCase()==="w")&&(xe.preventDefault(),r&&Q&&Q(r))};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[r,Q]),St.useEffect(()=>{if(!We||He)return;const X=xe=>{xe.key==="Escape"&&(xe.preventDefault(),q())};return window.addEventListener("keydown",X,!0),()=>window.removeEventListener("keydown",X,!0)},[q,We,He]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(Jm,{activeConv:r,wsStatus:n,isConnected:a,conversations:ye,hiddenConversations:h,onOpenHistory:i,onHideConversation:Q,onShowConversation:mt,onShowAllHidden:re,onResetPanelsToMain:Te,notifications:Se,notificationUnreadCount:N,onOpenNotification:ee,onMarkNotificationRead:G,onMarkNotificationUnread:Z,onDeleteNotification:fe,inboxOpen:Pe,onInboxOpenChange:nt,hiddenOpen:Ee,onHiddenOpenChange:je,onOpenNewSession:s?void 0:st,actionShortcuts:vt,onOpenRemote:()=>{!r||Je(r)||Ge(r)||c(r)},onStopCli:l,activeCliViewMode:u,onSetCliViewMode:f}),e?t.jsx(kh,{conversations:d,hiddenConversations:h,ides:m,actionLogs:j,sendDaemonCommand:S,setActionLogs:p,isStandalone:x,userName:b,requestedActiveTabKey:C,onRequestedActiveTabConsumed:A,requestedMachineId:y,onRequestedMachineConsumed:I,requestedMobileSection:k,onRequestedMobileSectionConsumed:w,onOpenHistory:i,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowHiddenConversation:mt,onShowAllHiddenConversations:re,onOpenNewSession:st,liveSessionInboxState:O}):s?t.jsx(Lh,{containerRef:g,isSplitMode:E,numGroups:T,groupSizes:M,groupedConvs:P,clearedTabs:K,ides:m,actionLogs:j,sendDaemonCommand:S,setActionLogs:p,isStandalone:x,hasRegisteredMachines:se.length>0,userName:b,focusedGroup:U,focusGroup:L,moveTabToGroup:R,splitTabRelative:z,closeGroup:$,handleResizeStart:_,groupActiveTabIds:Y,setGroupActiveTab:J,groupTabOrders:pe,setGroupTabOrder:ae,toggleHiddenTab:be,onOpenNewSession:st,allowTabShortcuts:!1,liveSessionInboxState:O}):t.jsx(zh,{visibleConversations:ye,clearedTabs:K,ides:m,actionLogs:j,sendDaemonCommand:S,setActionLogs:p,isStandalone:x,hasRegisteredMachines:se.length>0,initialDataLoaded:v,userName:b,toggleHiddenTab:be,actionShortcuts:vt,registerActionHandlers:X=>{ge.current=X},onActiveTabChange:H,requestedActiveTabKey:ve,onRequestedActiveTabConsumed:Ie,onRequestScrollToBottom:V,scrollToBottomRequest:le,onOpenNewSession:st,liveSessionInboxState:O,layoutProfile:me}),ze&&t.jsx(Yh,{machines:se,ides:m,onClose:dt,onBrowseDirectory:ne,onSaveWorkspace:ce,onLaunchIde:oe,onLaunchProvider:we,onListSavedSessions:he}),We&&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:q,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:X=>X.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:q,"aria-label":"Close dashboard guide",children:t.jsx(wt,{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(X=>t.jsx("button",{type:"button",className:`btn btn-sm ${Ze===X.id?"btn-primary":"btn-secondary"}`,onClick:()=>ut(X.id),children:X.label},X.id))}),Ze==="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 ",at?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Ze==="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."]})]})]})]}),Ze==="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(X=>t.jsx("button",{type:"button",className:`btn btn-sm ${it===X.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ye(X.id),children:X.label},X.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ke,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:Ce,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:ie.map(X=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${He===X.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:X.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:X.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:X.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:He===X.id?It.length>0?`${It.join(" ")} ...`:"Listening...":vt[X.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{B(X.id),W([])},children:He===X.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const xe={...vt};xe[X.id]="",F(xe)},children:"Disable"})]})]})},X.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",at?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&t.jsxs("button",{type:"button",onClick:$e,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 ${Qe?"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:"?"}),Qe&&t.jsx("span",{children:"Guide"})]})]})}const Rn=[{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 tx({onClose:e}){const[s,r]=o.useState(0),n=Rn[s],a=s===Rn.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(wt,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Rn.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]}),a&&t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),t.jsx("div",{className:"flex justify-end items-center mt-6",children:t.jsx("button",{onClick:()=>a?e():r(i=>i+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),t.jsx("style",{children:`
|
|
54
|
-
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
55
|
-
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
56
|
-
`})]})}function sx({hasExtensions:e,ideName:s,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?t.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[t.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${r==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a("native"),children:s}),n.map(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:()=>a(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 rx({ideData:e,allIdes:s,connectionStates:r,ideName:n,preferredTabKey:a}){const[i,c]=o.useState(()=>a||"native"),l=o.useMemo(()=>bc(s),[s]),u=o.useMemo(()=>e?Da(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),f=o.useMemo(()=>u.find(p=>p.streamSource==="native"),[u]),d=o.useMemo(()=>u.filter(p=>p.streamSource==="agent-stream"),[u]),h=o.useMemo(()=>e?Dt(u,e.id):null,[u,e]);o.useEffect(()=>{a&&c(a)},[a]),o.useEffect(()=>{if(a||!h)return;const p=h.streamSource==="native"?"native":h.tabKey;!p||i===p||i==="native"&&c(p)},[i,h,a]),o.useEffect(()=>{var p;i!=="native"&&(d.some(x=>x.tabKey===i)||c(((p=d[0])==null?void 0:p.tabKey)||"native"))},[i,d]),o.useEffect(()=>{i==="native"&&(f||d[0]&&c(d[0].tabKey))},[i,f,d]);const m=o.useMemo(()=>i==="native"&&f?f:d.find(p=>p.tabKey===i)||h||f||d[0],[i,f,h,d]),j=o.useMemo(()=>d.map(p=>({tabKey:p.tabKey,title:dc(p)||n,status:p.status})),[d,n]),S=o.useCallback(p=>{if(p)return u.find(x=>Qn(x,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[u]);return{activeChatTab:i,setActiveChatTab:c,activeConv:m,conversations:u,extensionTabs:j,hasExtensions:j.length>0,resolveConversationByTarget:S}}function nx({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:i,setActionLogs:c,isStandalone:l,userName:u,onOpenHistory:f,onConversationChange:d,onClose:h}){const[m,j]=o.useState("split"),[S,p]=o.useState(()=>zt(e)?"native":e.tabKey),x=o.useRef(null),v=o.useMemo(()=>s||r.find(R=>R.id===e.routeId),[e.routeId,s,r]),b=o.useMemo(()=>tt((v==null?void 0:v.type)||""),[v==null?void 0:v.type]),{conversations:C,extensionTabs:A,hasExtensions:y}=rx({ideData:v,allIdes:r,connectionStates:n,ideName:b||"IDE",preferredTabKey:zt(e)?void 0:e.tabKey}),I=o.useMemo(()=>v?Dt(C,v.id):null,[v,C]);o.useEffect(()=>{const R=x.current,z={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(x.current=z,!(R&&R.routeId===z.routeId&&R.tabKey===z.tabKey&&R.streamSource===z.streamSource)){if(zt(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(S==="native"){if(C.some(R=>R.streamSource==="native"))return;(I==null?void 0:I.streamSource)==="agent-stream"&&p(I.tabKey);return}if(!C.some(R=>R.tabKey===S)){if((I==null?void 0:I.streamSource)==="agent-stream"){p(I.tabKey);return}p("native")}},[C,S,I]);const k=o.useMemo(()=>S==="native"?C.find(R=>R.streamSource==="native")||e:C.find(R=>R.tabKey===S)||e,[e,C,S]),w=Lc(k),g=o.useMemo(()=>w.status||w.modalMessage||w.modalButtons?{...k,...w.status?{status:w.status}:{},...w.modalMessage!==void 0?{modalMessage:w.modalMessage}:{},...w.modalButtons!==void 0?{modalButtons:w.modalButtons}:{}}:k,[k,w]),E=sr(g),T=nn({sendDaemonCommand:i,activeConv:g,setActionLogs:c,isStandalone:l}),{connScreenshot:M,screenshotUsage:P,handleRemoteAction:K}=qc({doId:E,targetSessionId:Yi(g),connState:g.connectionState||"new",viewMode:m}),U=o.useMemo(()=>a.filter(R=>R.routeId===g.tabKey),[a,g.tabKey]);o.useEffect(()=>{d==null||d(g)},[g,d]),o.useEffect(()=>{const R=z=>{z.key==="Escape"&&h()};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[h]);const L=o.useCallback(R=>{R.stopPropagation()},[]);return t.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:h,children:t.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:L,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(Ct,{size:16})}),t.jsx("span",{className:"truncate",children:ka(k)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,children:"Close"})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[t.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(R=>{const z=m===R;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${z?"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:()=>j(R),title:R==="split"?"Split view":"Remote only",children:R==="split"?t.jsx(Nd,{size:15}):t.jsx(Ct,{size:15})},R)})}),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:()=>f(k),title:"Chat History",children:[t.jsx(xa,{size:14,className:"md:mr-1.5"}),t.jsx("span",{className:"hidden md:inline",children:"History"})]}),t.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:h,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${m==="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:[m!=="remote"&&t.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${m==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[t.jsx(sx,{hasExtensions:y,ideName:b||"IDE",activeChatTab:S,extensionTabs:A,onSelectTab:p}),t.jsx(Di,{activeConv:g,onModalButton:T.handleModalButton}),t.jsx(ra,{activeConv:g,ideEntry:v,showMetaChips:!1,handleSendChat:T.handleSendChat,isSendingChat:T.isSendingChat,sendFeedbackMessage:T.sendFeedbackMessage,handleFocusAgent:T.handleFocusAgent,isFocusingAgent:T.isFocusingAgent,actionLogs:U,userName:u})]}),t.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${m==="split"?"order-1 md:order-2":""}`,children:t.jsx(Pi,{addLog:()=>{},connState:g.connectionState||"new",connScreenshot:M,screenshotUsage:P,transportType:g.transport,onAction:K})})]})]})})}function ax({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=Vm(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:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),t.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:"Force Stop"}),t.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function ox({historyModal:e,remoteDialog:s,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:i}){var c;return t.jsxs(t.Fragment,{children:[t.jsx(qm,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&t.jsx(_a,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),s.conversation&&t.jsx(nx,{activeConv:s.conversation,ideEntry:s.ideEntry,ides:s.ides,connectionStates:s.connectionStates,actionLogs:s.actionLogs,sendDaemonCommand:s.sendDaemonCommand,setActionLogs:s.setActionLogs,isStandalone:s.isStandalone,userName:s.userName,onOpenHistory:s.onOpenHistory,onConversationChange:s.onConversationChange,onClose:s.onClose}),r.open&&r.targetConv&&(Je(r.targetConv)||Ge(r.targetConv))&&t.jsx(ax,{activeConv:r.targetConv,canSaveAndStop:Je(r.targetConv)&&!Ge(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),t.jsx(xc,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),i.open&&t.jsx(tx,{onClose:i.onClose})]})}function ix({daemons:e,targetVersion:s,required:r=!1,upgradingDaemons:n,onUpgrade:a,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(er,{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=Tt(c,{fallbackId:c.id}),u=n[c.id],f=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",f]}),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:()=>a(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:()=>a(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(wt,{size:16})})]})}function cx(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function lx(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 dx(e){const s=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,i=[e.tabKey,e.historySessionId||"",s,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&s&&s!==r),autoReadKey:i,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function ux(e){const s=e.machine;return typeof(s==null?void 0:s.cpus)!="number"||typeof(s==null?void 0:s.totalMem)!="number"||typeof(s==null?void 0:s.arch)!="string"||typeof(s==null?void 0:s.release)!="string"}function mx(e){return{metadataDaemonIds:e.map(s=>s.id),runtimeDaemonIds:e.filter(s=>ux(s)).map(s=>s.id)}}function fx(){var Za,eo,to,so;const{sendCommand:e}=jt(),s=nr(),r=Tc(),n=fa(),a=Is(),[i,c]=Vl(),l=i.get("activeTab"),u=((Za=n.state)==null?void 0:Za.openRemoteForTabKey)||null,f=((eo=n.state)==null?void 0:eo.openMachineId)||null,d=((to=n.state)==null?void 0:to.mobileSection)||null,h=oc(),m=h.ides||[],j=h.initialLoaded??!0,{updateRouteChats:S,setToasts:p}=h,[x,v]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),b=h.toasts||[],C=h.wsStatus||"connected",A=h.isConnected??!0,y=h.connectionStates||{},I=h.showReconnected||!1,{layoutProfile:k,groupAssignments:w,updateGroupAssignments:g,focusedGroup:E,updateFocusedGroup:T,focusGroup:M,groupActiveTabIds:P,updateGroupActiveTabIds:K,setGroupActiveTab:U,groupTabOrders:L,updateGroupTabOrders:R,setGroupTabOrder:z,groupSizes:$,updateGroupSizes:_,isMobile:Y,hasHydratedStoredLayout:J,hydrateStoredLayout:pe,focusConversationTab:ae}=Cp(),[be,ye]=o.useState(()=>Ka());o.useEffect(()=>Uf(ye),[]);const ve=o.useMemo(()=>cx({isMobile:Y,mobileViewMode:be}),[Y,be]),[Ie,H]=o.useState([]),[V,Q]=o.useState({}),[ue,re]=o.useState({});tr("Dashboard",{ideCount:m.length,toastCount:b.length,focusedGroup:E,groupCount:Object.keys(w).length,actionLogCount:Ie.length});const le=o.useMemo(()=>m.filter(Fe=>Fe.type==="adhdev-daemon").sort(va),[m]),se=le[0],me=!!se;o.useEffect(()=>{const{metadataDaemonIds:Fe,runtimeDaemonIds:kt}=mx(le);for(const Et of Fe)s(Et,{minFreshMs:3e4}).catch(()=>{});for(const Et of kt)r(Et,{minFreshMs:3e4}).catch(()=>{})},[s,r,le]);const ne=(se==null?void 0:se.terminalBackend)||null,ce=se?Tt(se,{fallbackId:se.id}):null,oe=(se==null?void 0:se.id)||null,we=o.useMemo(()=>tp(m,V),[m,V]),{hiddenTabs:he,hideTarget:Se,toggleTarget:N,showTarget:O,showAllTabs:G}=ep(),{conversations:Z,visibleConversations:fe,visibleTabKeys:ge,resolveConversationBySessionId:Pe,resolveConversationByTarget:Ee}=up({ides:we,connectionStates:y,clearedTabs:ue,hiddenTabs:he}),We=o.useMemo(()=>new Map(Z.map(Fe=>[Fe.tabKey,Fe])),[Z]);Rm(fe,ve),o.useEffect(()=>{Object.keys(V).length!==0&&Q(Fe=>sp(Fe,m))},[m,V]);const ze=o.useMemo(()=>au(m),[m]),{notifications:Qe,unreadCount:Ze}=Wp({conversations:Z,liveSessionInboxState:ze}),{handleMarkDashboardNotificationRead:it,handleMarkDashboardNotificationUnread:yt,handleDeleteDashboardNotification:ut}=Hp({notifications:Qe,sendDaemonCommand:e}),Ye=o.useRef(null),nt=o.useRef(null),je=o.useRef(null),$e=o.useRef(null),Ke=o.useRef(null),{containerRef:st,normalizedGroupAssignments:dt,numGroups:mt,isSplitMode:ee,groupedConvs:Te,moveTabToGroup:Re,closeGroup:at,handleResizeStart:ht,splitTabRelative:vt}=Pp({groupAssignments:w,updateGroupAssignments:g,updateFocusedGroup:T,updateGroupActiveTabIds:K,updateGroupTabOrders:R,groupSizes:$,updateGroupSizes:_,isMobile:Y,visibleConversations:fe,visibleTabKeys:ge}),{activeConv:He,openDesktopConversation:It,requestScrollToBottom:B,scrollToBottomRequest:W,setDesktopActiveTab:F}=Qp({isMobile:Y,conversations:Z,visibleConversations:fe,groupActiveTabIds:P,focusedGroup:E,groupedConvs:Te,setSearchParams:c});o.useEffect(()=>{const Fe=()=>{je.current&&(clearTimeout(je.current),je.current=null),$e.current&&(clearTimeout($e.current),$e.current=null),Ke.current&&(document.removeEventListener("visibilitychange",Ke.current),Ke.current=null),nt.current=null};if(Y){Fe(),Ye.current=null;return}if(!(He!=null&&He.sessionId)){Fe(),Ye.current=null;return}const kt=Or(He,ze),Et=dx({tabKey:He.tabKey,historySessionId:rr(He)||"",lastMessageHash:He.lastMessageHash||"",lastMessageAt:Number(He.lastMessageAt||0),timestamp:es(He),liveState:kt}),ir=Et.autoReadKey,cr=lx({autoReadKey:ir,shouldMarkSeen:Et.shouldMarkSeen,completedKey:Ye.current,pendingKey:nt.current});if(!Et.shouldMarkSeen){cr.shouldCancelPending&&Fe(),Ye.current=ir;return}if(!cr.shouldSchedule)return;cr.shouldCancelPending&&Fe();const ro=()=>{if(document.visibilityState!=="visible"||Ye.current===ir)return;Ye.current=ir,nt.current=null,je.current=null,$e.current=null,Ke.current&&(document.removeEventListener("visibilitychange",Ke.current),Ke.current=null);const lr=Et.readAt;e(He.daemonId||He.routeId,"mark_session_seen",{sessionId:He.sessionId,seenAt:lr}).catch(()=>{})};if(nt.current=cr.nextPendingKey,document.visibilityState==="visible"){je.current=setTimeout(ro,1500);const lr=()=>{document.visibilityState!=="visible"&&je.current&&(clearTimeout(je.current),je.current=null)};Ke.current=lr,document.addEventListener("visibilitychange",lr);return}const no=()=>{document.visibilityState==="visible"&&($e.current&&clearTimeout($e.current),$e.current=setTimeout(ro,800),Ke.current&&(document.removeEventListener("visibilitychange",Ke.current),Ke.current=null))};Ke.current=no,document.addEventListener("visibilitychange",no)},[He,Y,ze,e]),o.useEffect(()=>()=>{je.current&&clearTimeout(je.current),$e.current&&clearTimeout($e.current),Ke.current&&document.removeEventListener("visibilitychange",Ke.current)},[]);const{requestedDesktopTabKey:q,requestedMobileTabKey:ie,consumeRequestedActiveTab:ke}=mp({isMobile:Y,urlActiveTab:l,resolveConversationBySessionId:Pe,setSearchParams:c}),{remoteDialogConv:Ce,remoteDialogIdeEntry:X,remoteDialogActiveConv:xe,setRemoteDialogActiveConv:Be,openRemoteDialog:Oe,closeRemoteDialog:Xe,cliStopDialogOpen:qe,cliStopTargetConv:Ue,requestCliStop:_e,cancelCliStop:D,confirmCliStop:te}=th({isMobile:Y,location:n,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:q,conversations:Z,ides:m,resolveConversationByTarget:Ee,activeConv:He,sendDaemonCommand:e}),{historyModalOpen:de,openHistoryModal:Le,closeHistoryModal:Ne,historyTargetConv:Me,isSavedSessionHistoryTarget:Ae,isHistoryCreatingChat:ft,isHistoryRefreshingHistory:ct,handleHistorySwitchSession:Ts,handleHistoryNewChat:fl,handleHistoryRefresh:pl,savedHistorySessions:hl,savedHistoryFilters:xl,setSavedHistoryFilters:bl,isSavedHistoryLoading:gl,resumingSavedHistorySessionId:yl,handleRefreshSavedHistory:vl,handleResumeSavedHistorySession:wl}=Zp({activeConv:He,remoteDialogConv:Ce,remoteDialogActiveConv:xe,ides:m,sendDaemonCommand:e,updateRouteChats:S,setToasts:p,setClearedTabs:re,setSearchParams:c}),jl=o.useMemo(()=>fe,[fe]),or=Y&&be==="chat",kl=o.useMemo(()=>Z.filter(Fe=>Oa(he,Fe)),[Z,he]),Xa=o.useCallback(Fe=>{const kt=new URLSearchParams(i);kt.set("activeTab",Fe),c(kt,{replace:!0})},[i,c]),{trackPendingLaunch:Sl}=qp({ides:m,conversations:Z,onOpenSession:Xa}),{handleBrowseMachineDirectory:Nl,handleSaveMachineWorkspace:Cl,handleLaunchMachineIde:Il,handleLaunchMachineProvider:Ml,handleListMachineSavedSessions:Al,setActiveCliViewMode:Tl}=Yp({sendDaemonCommand:e,trackPendingLaunch:Sl,onOpenSession:Xa,activeConv:He,ides:m,setCliViewModeOverrides:Q});rp({visibleConversations:fe,clearedTabs:ue,setClearedTabs:re,setActionLogs:H}),fp({ides:m,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Ee});const{isRefreshingHistory:Ll,handleRefreshHistory:Rl}=Bc({sendDaemonCommand:e,activeConv:He,chats:(so=m.find(Fe=>Fe.id===(He==null?void 0:He.routeId)))==null?void 0:so.chats,updateRouteChats:S,setToasts:p,setClearedTabs:re});Mp({urlActiveTab:Y&&!or?l:null,conversations:Z,resolveConversationBySessionId:Pe,normalizedGroupAssignments:dt,hasHydratedStoredLayout:Y&&!or?J:!0,hydrateStoredLayout:Y&&!or?pe:()=>{},focusConversationTab:ae,setSearchParams:c,historyModalOpen:de,activeConv:He,isRefreshingHistory:Ll,ides:m,handleRefreshHistory:Rl});const Pl=o.useMemo(()=>!He||!Je(He)||Ge(He)?null:As(He),[He]),{versionMismatchDaemons:_l,hasRequiredVersionDaemons:Ja,appVersion:Dl,versionBannerDismissed:El,setVersionBannerDismissed:$l,upgradingDaemons:Bl,handleBannerUpgrade:Kl}=_p({ides:m,sendDaemonCommand:e}),Qa=o.useCallback(Fe=>{O(Fe),It(Fe)},[It,O]),Ol=o.useCallback(Fe=>{Se(Fe)},[Se]);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(Ym,{terminalBackend:ne,isStandalone:me,machineLabel:ce,machineKey:oe}),(!El||Ja)&&t.jsx(ix,{daemons:_l,targetVersion:Dl,required:Ja,upgradingDaemons:Bl,onUpgrade:Kl,onDismiss:()=>$l(!0)}),t.jsx(ex,{showMobileChatMode:or,isMobile:Y,activeConv:He,wsStatus:C,isConnected:A,onOpenHistory:Fe=>{Fe&&Be(Fe),Le()},onOpenRemote:Oe,onStopCli:_e,activeCliViewMode:Pl,onSetActiveCliViewMode:Tl,mobileChatConversations:jl,ides:m,actionLogs:Ie,sendDaemonCommand:e,setActionLogs:H,isStandalone:me,initialDataLoaded:j,userName:h.userName,requestedMobileTabKey:ie,onRequestedMobileTabConsumed:ke,requestedMachineId:f,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:d,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:st,isSplitMode:ee,numGroups:mt,groupSizes:$,groupedConvs:Te,clearedTabs:ue,focusedGroup:E,focusGroup:M,moveTabToGroup:Re,splitTabRelative:vt,closeGroup:at,handleResizeStart:ht,groupActiveTabIds:P,setGroupActiveTab:U,groupTabOrders:L,setGroupTabOrder:z,toggleHiddenTab:Fe=>N(We.get(Fe)||{tabKey:Fe}),visibleConversations:fe,hiddenConversations:kl,requestedDesktopTabKey:q,onRequestedDesktopTabConsumed:ke,onDesktopActiveTabChange:F,onRequestScrollToBottom:B,onHideConversation:Ol,onShowHiddenConversation:Qa,onShowAllHiddenConversations:G,scrollToBottomRequest:W,machineEntries:le,layoutProfile:k,onBrowseMachineDirectory:Nl,onSaveMachineWorkspace:Cl,onLaunchMachineIde:Il,onLaunchMachineProvider:Ml,onListMachineSavedSessions:Al,notifications:Qe,notificationUnreadCount:Ze,liveSessionInboxState:ze,onMarkNotificationRead:it,onMarkNotificationUnread:yt,onDeleteNotification:ut}),t.jsx("style",{children:`
|
|
57
|
-
body { overflow: hidden; overscroll-behavior: none; }
|
|
58
|
-
`}),t.jsx(ox,{historyModal:{open:de,targetConv:Me,ides:m,isCreatingChat:ft,isRefreshingHistory:Ae?!1:ct,savedSessions:hl,savedHistoryFilters:xl,onSavedHistoryFiltersChange:bl,isSavedSessionsLoading:gl,isResumingSavedSessionId:yl,onClose:Ne,onNewChat:fl,onSwitchSession:Ts,onRefreshHistory:Ae?vl:pl,onResumeSavedSession:wl},remoteDialog:{conversation:Ce,ideEntry:X,ides:m,connectionStates:y,actionLogs:Ie,sendDaemonCommand:e,setActionLogs:H,isStandalone:me,userName:h.userName,onOpenHistory:Fe=>{Fe&&Be(Fe),Le()},onConversationChange:Be,onClose:Xe},cliStopDialog:{open:qe,targetConv:Ue,onCancel:D,onStopNow:async()=>{await te("hard")},onSaveAndStop:async()=>{await te("save")}},connectionBanner:{wsStatus:C,showReconnected:I,onReconnect:h.retryServerConnection},toastOverlay:{toasts:b,onDismiss:Fe=>p(kt=>kt.filter(Et=>Et.id!==Fe)),onClick:Fe=>{if(Fe.targetKey){const kt=Ee(Fe.targetKey);kt&&(ae(kt.tabKey,dt),Qa(kt),B(kt.tabKey,"toast-open"))}}},onboarding:{open:x,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}v(!1)}}})]})}function px({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,u]=o.useState(null),[f,d]=o.useState(null),[h,m]=o.useState(!1),[j,S]=o.useState(null),[p,x]=o.useState(!1),[v,b]=o.useState(""),C=o.useRef(null),A=o.useCallback($=>{C.current=$},[]),y=o.useCallback(($,_,Y=!1)=>{c(J=>[...J.slice(-100),{timestamp:Date.now(),level:$,message:_}]),setTimeout(()=>{var J;return(J=a.current)==null?void 0:J.scrollIntoView({behavior:"smooth"})},100),Y&<.showToast(_,$==="error"||$==="warn"?"warning":"success")},[a]),I=o.useCallback($=>{const _=$ instanceof Error?$.message:String($||"");return _.includes("P2P command timeout")||_.includes("P2P not connected")||_.includes("P2P not available")},[]),k=o.useCallback(async($,_)=>{var Y;if(!e||l)return!1;u($),y("info",`Launching ${tt($)}${_!=null&&_.workspace?` in ${_.workspace}`:""}...`);try{const J={ideType:$,enableCdp:!0};(Y=_==null?void 0:_.workspace)!=null&&Y.trim()?J.workspace=_.workspace.trim():_!=null&&_.useDefaultWorkspace&&(J.useDefaultWorkspace=!0);const pe=await r(e,"launch_ide",J);return y(pe!=null&&pe.success?"info":"error",pe!=null&&pe.success?`${tt($)} launched`:`Failed: ${pe==null?void 0:pe.error}`,!0),!!(pe!=null&&pe.success)}catch(J){return y("error",`Launch error: ${J.message}`,!0),!1}finally{u(null)}},[e,l,y,r]),w=o.useCallback(async $=>{if(!e)return{success:!1};const{cliType:_,dir:Y,workspaceId:J,useDefaultWorkspace:pe,useHome:ae,argsStr:be,model:ye,resumeSessionId:ve}=$;if(!_)return y("warn","Select a CLI or ACP provider first",!0),{success:!1};const Ie=be?be.split(/\s+/).filter(Boolean):void 0,H=(Y==null?void 0:Y.trim())||(J?"(saved id)":pe?"(default workspace)":ae?"(home)":"");y("info",`Launching ${_}${H?` in ${H}`:""}${ye?` (model: ${ye})`:""}...`),d(_);try{const V={cliType:_,cliArgs:Ie,initialModel:ye||void 0};Y!=null&&Y.trim()?V.dir=Y.trim():J?V.workspaceId=J:pe?V.useDefaultWorkspace=!0:ae&&(V.useHome=!0),ve&&(V.resumeSessionId=ve);const Q=await r(e,"launch_cli",V),ue=(Q==null?void 0:Q.result)||Q;return Q!=null&&Q.success?(y("info",`${_} launched`,!0),(ue==null?void 0:ue.launchSource)==="home"?y("info","📂 Running in home directory (explicit choice)"):(ue==null?void 0:ue.launchSource)==="defaultWorkspace"&&y("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ue==null?void 0:ue.sessionId}):(y("error",`Failed: ${(Q==null?void 0:Q.error)||(ue==null?void 0:ue.error)}`,!0),(Q==null?void 0:Q.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&S({cliType:_,argsStr:be,model:ye}),{success:!1,sessionId:ue==null?void 0:ue.sessionId})}catch(V){return I(V)?(y("warn",`${_} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(y("error",`Launch error: ${V.message}`,!0),{success:!1})}finally{d(null)}},[e,y,I,r]),g=o.useCallback(async($,_,Y,J)=>e?$?_.trim()?w({cliType:$,dir:_,argsStr:Y,model:J}):(S({cliType:$,argsStr:Y,model:J}),{success:!1}):(y("warn","Select a provider",!0),{success:!1}):{success:!1},[e,y,w]),E=o.useCallback(async($,_,Y)=>{if(e&&window.confirm(`Stop ${$}?
|
|
59
|
-
This will terminate the process.`))try{const J=await r(e,"stop_cli",{cliType:$,dir:_,targetSessionId:Y});J!=null&&J.success?y("info",`${$} stopped`,!0):y("error",`Stop failed: ${(J==null?void 0:J.error)||"Unknown error"}`,!0)}catch(J){y("error",`Stop failed: ${J.message}`,!0)}},[e,y,r]),T=o.useCallback(async $=>{try{await r($.daemonId,"restart_ide",{ideType:$.type}),y("info",`${tt($.type)} restart initiated`,!0)}catch(_){y("error",`Restart failed: ${_.message}`,!0)}},[y,r]),M=o.useCallback(async $=>{if(window.confirm(`Stop ${tt($.type)}?
|
|
60
|
-
This will disconnect CDP and optionally kill the process.`))try{const _=await r($.daemonId,"stop_ide",{ideType:$.type,killProcess:!0});_!=null&&_.success?y("info",`${tt($.type)} stopped`,!0):y("error",`Stop failed: ${(_==null?void 0:_.error)||"Unknown error"}`,!0)}catch(_){y("error",`Stop failed: ${_.message}`,!0)}},[y,r]),P=o.useCallback(async()=>{if(e)try{const $=await r(e,"detect_ides",{});y("info",`Found ${(($==null?void 0:$.result)||[]).length} IDE(s)`,!0)}catch($){y("error",`Detection failed: ${$.message}`,!0)}},[e,y,r]),K=o.useCallback(async $=>{if(!e||!$.trim())return!1;m(!0);try{const _=await r(e,"workspace_add",{path:$.trim()});return _!=null&&_.success?(y("info",`Workspace added: ${$.trim()}`),!0):(y("error",(_==null?void 0:_.error)||"workspace_add failed"),!1)}catch(_){return y("error",_.message),!1}finally{m(!1)}},[e,y,r]),U=o.useCallback(async $=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){m(!0);try{const _=await r(e,"workspace_remove",{id:$});_!=null&&_.success?y("info","Workspace removed",!0):y("error",(_==null?void 0:_.error)||"workspace_remove failed",!0)}catch(_){y("error",_.message,!0)}finally{m(!1)}}},[e,y,r]),L=o.useCallback(async $=>{var _;if(e){m(!0);try{const Y=await r(e,"workspace_set_default",$===null?{clear:!0}:{id:$});if(Y!=null&&Y.success){y("info",$?"Default workspace updated":"Default workspace cleared",!0);const J=typeof Y.defaultWorkspacePath=="string"?Y.defaultWorkspacePath:"";J&&((_=C.current)==null||_.call(C,J))}else y("error",(Y==null?void 0:Y.error)||"workspace_set_default failed",!0)}catch(Y){y("error",Y.message,!0)}finally{m(!1)}}},[e,y,r]),R=o.useCallback(async $=>{var Y;if(!e||!$.trim())return;const _=$.trim();m(!0);try{const J=await r(e,"workspace_set_default",{path:_});J!=null&&J.success?(y("info","Default workspace set from history"),(Y=C.current)==null||Y.call(C,_)):y("error",(J==null?void 0:J.error)||"Could not set default (path missing on disk?)")}catch(J){y("error",J.message)}finally{m(!1)}},[e,y,r]),z=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:v}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:v})}catch($){y("warn",`Live nickname updated, but account sync failed: ${$.message}`)}y("info",`Nickname set to "${v||"(cleared)"}"`),x(!1)}catch($){y("error",`Failed: ${$.message}`)}},[e,v,s,y,n,r]);return{logs:i,launchingIde:l,launchingAgentType:f,workspaceBusy:h,launchPick:j,setLaunchPick:S,editingNickname:p,setEditingNickname:x,nicknameInput:v,setNicknameInput:b,addLog:y,handleLaunchIde:k,runLaunchCliCore:w,handleLaunchCli:g,handleStopCli:E,handleRestartIde:T,handleStopIde:M,handleDetectIdes:P,handleWorkspaceAdd:K,handleWorkspaceRemove:U,handleWorkspaceSetDefault:L,handleWorkspaceResumePath:R,handleSaveNickname:z,setOnDefaultWorkspaceChanged:A}}function hx({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var T;const{workspaceBusy:l,handleWorkspaceAdd:u,handleWorkspaceRemove:f,handleWorkspaceSetDefault:d}=i,[h,m]=o.useState(!1),[j,S]=o.useState(""),[p,x]=o.useState([]),[v,b]=o.useState(!1),[C,A]=o.useState(""),y=o.useCallback(async M=>{b(!0),A("");try{const P=await rn(c,e,M);S(P.path),x(P.directories)}catch(P){A(P instanceof Error?P.message:"Could not load folder")}finally{b(!1)}},[e,c]),I=o.useCallback(()=>{m(!0);const M=[...r.map(K=>K.workspace),...n.map(K=>K.workspace),...a.map(K=>K.workspace)],P=sn(s.platform,tn(M,s.defaultWorkspacePath,(s.workspaces||[]).map(K=>K.path)));y(P)},[a,n,r,y,s.defaultWorkspacePath,s.platform,s.workspaces]),k=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,w=s.availableMem??s.freeMem??s.totalMem,g=k&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-w)/s.totalMem*100))):0,E=((T=s.loadavg)==null?void 0:T[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(mr,{icon:t.jsx(Mi,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?lu(s.uptime):"Waiting…"}),t.jsx(mr,{icon:t.jsx(Ct,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(mr,{icon:t.jsx(ba,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(mr,{icon:t.jsx(Id,{size:16}),label:"ACPs",value:`${a.length}`})]}),t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),t.jsxs("div",{className:"flex gap-6",children:[t.jsx(ho,{value:k?Math.min(Math.round(E/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:k?`${E.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(ho,{value:g,max:100,label:"Memory",color:"#3b82f6",detail:k?`${pn(s.totalMem-w)} / ${pn(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${pn(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(ks,{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:M=>void d(M.target.value===""?null:M.target.value),children:[t.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(M=>t.jsx("option",{value:M.id,children:M.label||M.path},M.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:I,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(M=>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:[M.id===s.defaultWorkspaceId&&t.jsx("span",{className:"text-[10px]",children:"⭐"}),t.jsx("span",{className:"font-medium text-text-primary truncate",children:Zr(M.path,M.label)})]}),t.jsx("div",{className:"font-mono truncate text-[10px]",title:M.path,children:M.path})]}),t.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void f(M.id),children:"Remove"})]},M.id))})]}),h&&t.jsx(an,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:j,directories:p,busy:v,error:C,confirmLabel:"Add workspace",onClose:()=>m(!1),onNavigate:M=>{y(M)},onConfirm:M=>{(async()=>{if(!M)return;await u(M)&&m(!1)})()}})]})}function xx(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 bx(e,s,r){const n=[];for(const[a,i]of Object.entries(e.settings)){const c=i;if(c.length===0)continue;const l=s.find(u=>u.type===a);n.push({type:a,displayName:(l==null?void 0:l.displayName)||a,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:c,values:e.values[a]||{}})}return n}function Pn(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 ti(e){if(!e||typeof e!="object")return null;if(Pn(e))return e;const s=e,r=s.result;return Pn(r)?r:Pn(s.sourceConfig)?s.sourceConfig:null}function gx(e){const s=e.trim();return s||null}const si=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],yx=[{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 vx({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[u,f]=o.useState([]),[d,h]=o.useState(""),[m,j]=o.useState([]),[S,p]=o.useState(""),x=o.useRef(null),v=o.useRef(null),b=w=>{f(g=>g.includes(w)?g.filter(E=>E!==w):[...g,w])},C=()=>f([...si]),A=()=>f([]);o.useEffect(()=>{var w;(w=x.current)==null||w.scrollIntoView({behavior:"smooth"})},[m]),o.useEffect(()=>()=>{v.current&&clearInterval(v.current)},[]);const y=o.useCallback(()=>{v.current&&clearInterval(v.current),v.current=setInterval(async()=>{try{const w=await r(e,"provider_auto_fix_status",{providerType:s.type});(w==null?void 0:w.running)===!1&&a==="running"&&(i("done"),j(g=>[...g,`
|
|
61
|
-
✅ Auto-fix completed!`]),v.current&&clearInterval(v.current))}catch{}},3e3)},[e,s.type,r,a]),I=async()=>{if(u.length!==0){i("running"),j(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,d?`💬 Comment: ${d}`:"",""]),p("");try{const w=await r(e,"provider_auto_fix",{providerType:s.type,functions:u,agent:c,...d?{comment:d}:{}});w!=null&&w.success&&(w!=null&&w.started||w!=null&&w.running)?(j(g=>[...g,"✅ Agent started. Monitoring progress..."]),y()):(i("error"),p((w==null?void 0:w.error)||"Failed to start auto-fix"))}catch(w){i("error"),p((w==null?void 0:w.message)||"Connection failed")}}},k=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),j(w=>[...w,`
|
|
62
|
-
⚠️ Auto-fix cancelled.`]),i("done"),v.current&&clearInterval(v.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:w=>w.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:s.icon||"🔧"}),t.jsxs("div",{children:[t.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",s.displayName]}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),t.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),t.jsx("div",{className:"flex gap-2",children:yx.map(w=>t.jsxs("button",{onClick:()=>l(w.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===w.value?w.color+"66":"var(--border-subtle)",background:c===w.value?w.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===w.value?w.color:"var(--text-primary)"},children:w.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:w.desc})]},w.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:C,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:A,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:si.map(w=>t.jsxs("button",{onClick:()=>b(w),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(w)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(w)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(w)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(w)?"☑ ":"☐ ",w]},w))})]}),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:w=>h(w.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[m.map((w,g)=>t.jsx("div",{className:w.startsWith("✅")?"text-green-400":"",style:w.startsWith("❌")||w.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:w},g)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:x})]}),S&&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:S})]})]}),t.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[t.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&u.length>0&&`${u.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),t.jsxs("div",{className:"flex gap-2",children:[a==="config"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:I,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"})]}),a==="running"&&t.jsx("button",{onClick:k,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{i("config"),j([]),p("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function wx({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var y;const i=s.filter(I=>I.category==="ide"),[c,l]=o.useState(((y=i[0])==null?void 0:y.type)||""),[u,f]=o.useState(""),[d,h]=o.useState(""),[m,j]=o.useState(!1),[S,p]=o.useState(""),[x,v]=o.useState(!1),b=I=>{const k=I.toLowerCase().replace(/[^a-z0-9-]/g,"");f(k),(!d||d===C(u))&&h(C(k))},C=I=>I.split("-").map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join(" "),A=async()=>{if(!(!u||!d||!c)){j(!0),p("");try{const I=await r(e,"provider_clone",{type:u,name:d,category:"ide",location:"user",cloneFrom:c});I!=null&&I.success||I!=null&&I.created?(v(!0),a==null||a(u)):p((I==null?void 0:I.error)||"Failed to create provider")}catch(I){p((I==null?void 0:I.message)||"Connection failed")}j(!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:I=>I.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:x?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(I=>t.jsxs("button",{onClick:()=>l(I.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===I.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===I.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:I.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===I.type?"#a78bfa":"var(--text-secondary)"},children:I.displayName})]},I.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:I=>b(I.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:I=>h(I.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"})]}),S&&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:S})]})}),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:x?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:A,disabled:!u||!d||m,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||m?.4:1},children:m?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function jx({machineId:e,providers:s,sendDaemonCommand:r}){var T;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[f,d]=o.useState("all"),[h,m]=o.useState(null),[j,S]=o.useState(!1),[p,x]=o.useState(null),[v,b]=o.useState("normal"),[C,A]=o.useState(""),[y,I]=o.useState(!1),k=o.useCallback(async()=>{if(e)try{const M=await r(e,"get_provider_source_config",{}),P=ti(M);P&&(x(P),b(P.sourceMode),A(P.explicitProviderDir||""))}catch{}},[e,r]),w=o.useCallback(async()=>{if(e){c(!0);try{const M=await r(e,"get_provider_settings",{}),P=xx(M);if(P){const K=bx(P,s);K.sort((U,L)=>U.category.localeCompare(L.category)||U.displayName.localeCompare(L.displayName)),a(K)}}catch{}c(!1)}},[e,s,r]);o.useEffect(()=>{n.length===0&&w(),p||k()},[]);const g=async(M,P,K)=>{u(`${M}.${P}`),a(U=>U.map(L=>L.type===M?{...L,values:{...L.values,[P]:K}}:L));try{const U=await r(e,"set_provider_setting",{providerType:M,key:P,value:K});U!=null&&U.success||w()}catch{w()}u(null)},E=async()=>{I(!0);try{const M=await r(e,"set_provider_source_config",{providerSourceMode:v,providerDir:gx(C)}),P=ti(M);P?(x(P),b(P.sourceMode),A(P.explicitProviderDir||"")):await k(),await w()}catch{await k()}I(!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(M=>t.jsx("button",{onClick:()=>d(M),className:`machine-btn text-[10px] px-2 py-0.5 ${f===M?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:M.toUpperCase()},M))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>S(!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:w,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:k,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:v,onChange:M=>b(M.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:C,onChange:M=>A(M.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void E(),disabled:y,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:y?"Applying…":"Apply + Reload"})]}),t.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(p==null?void 0:p.userDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(p==null?void 0:p.upstreamDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((T=p==null?void 0:p.providerRoots)==null?void 0:T.join(" → "))||"loading…"]})]})]}),f!=="all"&&n.filter(M=>M.category===f).length>1&&(()=>{const M=n.filter(L=>L.category===f),P=new Map;for(const L of M)for(const R of L.schema){if(R.type!=="boolean")continue;const z=P.get(R.key),$=!!(L.values[R.key]??R.default);z?(z.onCount+=$?1:0,z.total+=1):P.set(R.key,{label:R.label||R.key,onCount:$?1:0,total:1})}const K=[...P.entries()].filter(([,L])=>L.total===M.length);if(K.length===0)return null;const U=async(L,R)=>{for(const z of M)await g(z.type,L,R)};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 ",f.toUpperCase()," providers (",M.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:K.map(([L,R])=>{const z=R.onCount===R.total,$=R.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:R.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",R.onCount,"/",R.total,")"]}),t.jsx("button",{onClick:()=>void U(L,!0),disabled:z,className:`machine-btn text-[9px] px-1.5 py-px ${z?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void U(L,!1),disabled:$,className:`machine-btn text-[9px] px-1.5 py-px ${$?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},L)})})]})})(),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(M=>f==="all"||M.category===f).map(M=>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:M.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:M.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:M.category==="acp"?"rgba(139,92,246,0.08)":M.category==="cli"?"rgba(59,130,246,0.08)":M.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:M.category==="acp"?"#a78bfa":M.category==="cli"?"#60a5fa":M.category==="ide"?"#86efac":"var(--status-warning)"},children:M.category}),M.category==="ide"&&t.jsx("button",{onClick:()=>m(s.find(P=>P.type===M.type)||{type:M.type,name:M.displayName,displayName:M.displayName,icon:M.icon,category:M.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:M.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===`${M.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:()=>g(M.type,P.key,!(M.values[P.key]??P.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:M.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:M.values[P.key]??P.default?21:3}})}):P.type==="number"?t.jsx("input",{type:"number",value:Number(M.values[P.key]??P.default??0)||0,min:P.min,max:P.max,onChange:K=>{const U=parseInt(K.target.value)||0;P.min!==void 0&&U<P.min||P.max!==void 0&&U>P.max||g(M.type,P.key,U)},className:"machine-input w-20 text-center text-[11px]"}):P.type==="select"&&P.options?t.jsx("select",{value:String(M.values[P.key]??P.default??""),onChange:K=>g(M.type,P.key,K.target.value),className:"machine-input text-[11px]",children:P.options.map(K=>t.jsx("option",{value:K,children:K},K))}):t.jsx("input",{type:"text",value:String(M.values[P.key]??P.default??""),onBlur:K=>g(M.type,P.key,K.target.value),className:"machine-input w-[120px] text-[11px]"})})]},P.key))})]},M.type))}),h&&t.jsx(vx,{machineId:e,provider:h,sendDaemonCommand:r,onClose:()=>m(null)}),j&&t.jsx(wx,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>S(!1),onCreated:()=>{S(!1),w()}})]})}const kx=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Sx({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function Nx(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function Cx(e){return e.trim().toLowerCase()}function cn(e,s){const r=Cx(s);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function qa(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Qs(e,s=220){const r=qa(e);return r?r.length>s?`${r.slice(0,s)}…`:r:""}function Ix(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 il(e,s){return e.filter(r=>cn([r.level,r.message],s))}function Mx(e,s){return e.split(`
|
|
63
|
-
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>cn([r],s))}function cl(e,s){return e.filter(r=>cn([r.level,r.category,r.stage,r.interactionId,qa(r.payload)],s))}function ll(e,s){return e.filter(r=>cn([r.kind,r.topic,r.interactionId,qa(r.payload)],s))}function ri(e){return e==="warn"||e==="error"}function Ax({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){return{all:e.length+s.length+r.length+n.length,info:e.filter(a=>a.level!=="debug").length+r.filter(a=>a.level!=="debug").length+n.length,issues:e.filter(a=>ri(a.level)).length+r.filter(a=>ri(a.level)).length}}function Tx({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(i=>`${new Date(i.timestamp).toISOString()} ${i.level.toUpperCase()} ${i.message}`)].join(`
|
|
64
|
-
`)):s.length>0&&a.push(["[daemon logs]",...s].join(`
|
|
65
|
-
`)),r.length>0&&a.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${Qs(i.payload,500)}`.trim())].join(`
|
|
66
|
-
`)),n.length>0&&a.push(["[browser events]",...n.map(i=>`${new Date(i.ts).toISOString()} ${i.kind}${i.topic?` topic=${i.topic}`:""} ${Qs(i.payload,500)}`.trim())].join(`
|
|
67
|
-
`)),a.join(`
|
|
68
|
-
|
|
69
|
-
`)}function Lx({daemonLogs:e,trace:s,webEvents:r,daemonLogKind:n,daemonFetchError:a,traceFetchError:i,searchQuery:c}){const l=il(e,c),u=cl(s,c),f=ll(r,c),d=l.filter(j=>j.level==="warn"||j.level==="error").map(j=>({source:"daemon",level:j.level,timestamp:j.timestamp,label:"daemon",detail:j.message})),h=u.filter(j=>j.level==="warn"||j.level==="error").map(j=>({source:"trace",level:j.level,timestamp:j.ts,label:`${j.category}.${j.stage}`,detail:Qs(j.payload,320)||`${j.category}.${j.stage}`})),m=[...d,...h].sort((j,S)=>S.timestamp-j.timestamp);return{daemonCount:l.length,traceCount:u.length,webCount:f.length,issueCount:m.length,latestIssue:m[0]||null,hasAnyData:n==="text"||l.length>0||u.length>0||f.length>0,hasBlockingError:!!(a||i)}}function ni(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function ai(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 _n(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 Rx({machineId:e,sendDaemonCommand:s}){var he,Se;const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[u,f]=o.useState([]),[d,h]=o.useState([]),[m,j]=o.useState(0),[S,p]=o.useState(0),[x,v]=o.useState(null),[b,C]=o.useState(!0),[A,y]=o.useState("info"),[I,k]=o.useState("info"),[w,g]=o.useState("all"),[E,T]=o.useState(""),[M,P]=o.useState(!0),[K,U]=o.useState(!0),[L,R]=o.useState(""),[z,$]=o.useState(""),[_,Y]=o.useState(0),[J,pe]=o.useState({daemon:!0,trace:!1,web:!1}),ae=o.useRef(null),be=o.useRef(!1),ye=o.useMemo(()=>Nx(u,w),[u,w]),ve=o.useMemo(()=>il(r,E),[r,E]),Ie=o.useMemo(()=>Mx(c,E),[c,E]),H=o.useMemo(()=>cl(ye,E),[ye,E]),V=o.useMemo(()=>ll(d,E),[d,E]),Q=o.useMemo(()=>I==="issues"?ve.filter(N=>N.level==="warn"||N.level==="error"):I==="info"?ve.filter(N=>N.level!=="debug"):ve,[ve,I]),ue=o.useMemo(()=>I==="all"?Ie:[],[Ie,I]),re=o.useMemo(()=>I==="issues"?H.filter(N=>N.level==="warn"||N.level==="error"):I==="info"?H.filter(N=>N.level!=="debug"):H,[H,I]),le=o.useMemo(()=>I==="issues"?[]:V,[V,I]),se=o.useMemo(()=>Ax({daemonLogs:ve,daemonRawLines:Ie,trace:H,webEvents:V}),[ve,Ie,H,V]),me=o.useMemo(()=>Lx({daemonLogs:r,trace:ye,webEvents:d,daemonLogKind:a,daemonFetchError:L,traceFetchError:z,searchQuery:E}),[L,a,r,ye,E,z,d]),ne=o.useCallback(async()=>{if(!e)return;const[N,O]=await Promise.allSettled([s(e,"get_logs",{count:200,minLevel:A,since:m}),s(e,"get_debug_trace",Sx({count:120,since:S,category:w}))]);if(N.status==="fulfilled"){const G=N.value,Z=(G==null?void 0:G.result)||G,fe=Ix(Z);if(P(!1),R((G==null?void 0:G.success)===!1?String((G==null?void 0:G.error)||"Could not load daemon logs"):""),i(fe.kind),l(fe.rawText),fe.entries.length>0){n(Pe=>(m>0?[...Pe,...fe.entries]:fe.entries).slice(-300));const ge=fe.entries.reduce((Pe,Ee)=>Math.max(Pe,Number(Ee.timestamp||0)),m);ge>m&&j(ge)}else fe.kind!=="structured"&&m===0&&n([])}else P(!1),R(N.reason instanceof Error?N.reason.message:"Could not load daemon logs");if(O.status==="fulfilled"){const G=O.value,Z=(G==null?void 0:G.result)||G;if((G==null?void 0:G.success)===!1)$(String((G==null?void 0:G.error)||"Could not load daemon trace"));else if(Array.isArray(Z==null?void 0:Z.trace)){$(""),f(Z.trace.slice(-120));const fe=Z.trace.reduce((ge,Pe)=>Math.max(ge,Number(Pe.ts||0)),S);fe>S&&p(fe)}else $(""),f([]);U(!1)}else U(!1),$(O.reason instanceof Error?O.reason.message:"Could not load daemon trace");h(js.list({limit:120})),v(Date.now())},[m,S,A,e,s,w]);o.useEffect(()=>{if(!e||(ne(),!b))return;const N=setInterval(()=>{ne()},3e3);return()=>clearInterval(N)},[b,ne,e,_]),o.useEffect(()=>{if(b&&(Q.length>0||ue.length>0||re.length>0||le.length>0)){const N=be.current?"smooth":"instant";setTimeout(()=>{var O;(O=ae.current)==null||O.scrollIntoView({behavior:N}),be.current=!0},50)}},[Q.length,ue.length,re.length,le.length,b]),o.useEffect(()=>{f([]),p(0),U(!0)},[w]);const ce=((he=me.latestIssue)==null?void 0:he.level)==="error"?"danger":((Se=me.latestIssue)==null?void 0:Se.level)==="warn"?"warning":"good",oe=L||z?"danger":b?"good":"neutral",we=o.useCallback(async()=>{var O;const N=Tx({daemonLogs:Q,daemonRawLines:ue,trace:re,webEvents:le});if(!N.trim()){lt.showToast("복사할 visible logs가 없습니다.","info");return}try{await((O=navigator.clipboard)==null?void 0:O.writeText(N)),lt.showToast("Visible logs를 클립보드에 복사했습니다.","success")}catch(G){lt.showToast(G instanceof Error?G.message:"Could not copy visible logs","warning")}},[Q,ue,re,le]);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(N=>t.jsx("button",{onClick:()=>{y(N),n([]),l(""),i("empty"),j(0),P(!0)},className:`machine-btn text-[10px] px-2 py-0.5 ${A===N?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:N.toUpperCase()},N)),t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider ml-3 mr-1",children:"Trace"}),kx.map(N=>t.jsx("button",{onClick:()=>g(N.value),className:`machine-btn text-[10px] px-2 py-0.5 ${w===N.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:N.label},N.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+ (${se.info})`},{id:"issues",label:`Issues (${se.issues})`},{id:"all",label:`All (${se.all})`}].map(N=>t.jsx("button",{type:"button",onClick:()=>k(N.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${I===N.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:N.label},N.id))}),t.jsx("input",{value:E,onChange:N=>T(N.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:()=>{we()},className:"machine-btn",children:"Copy visible"}),t.jsx("button",{onClick:()=>C(N=>!N),className:`machine-btn ${b?"text-green-500 border-green-500/30":""}`,children:b?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>Y(N=>N+1),className:"machine-btn",children:"↻ Refresh"}),t.jsx("button",{onClick:()=>{n([]),l(""),i("empty"),f([]),h([]),j(0),p(0),v(null),R(""),$(""),P(!0),U(!0),js.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 ${_n(me.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 ",Q.length+ue.length," · trace ",re.length," · web ",le.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 ${_n(ce)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Attention needed"}),me.latestIssue?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[me.latestIssue.source," · ",me.latestIssue.label]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:me.latestIssue.detail}),t.jsxs("div",{className:"text-[10px] text-text-muted mt-2",children:[me.issueCount," warn/error signal(s) · ",ni(me.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 ${_n(oe)}`,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:L||z?"Needs attention":b?"Live polling every 3s":"Paused"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",ni(x)]}),(L||z)&&t.jsxs("div",{className:"text-[11px] text-red-300 mt-2 space-y-1",children:[L&&t.jsxs("div",{children:["Daemon logs: ",L]}),z&&t.jsxs("div",{children:["Daemon trace: ",z]})]})]})]}),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:()=>pe(N=>({...N,daemon:!N.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:a==="text"?`${ue.length} visible raw line(s) from file fallback`:`${Q.length} visible structured line(s)`})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:J.daemon?"Hide":"Show"})]}),J.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:[M&&!me.hasAnyData&&!L&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!M&&L&&a==="empty"&&t.jsx("div",{className:"p-6 text-center text-red-300",children:L}),!M&&a==="empty"&&!L&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),a==="text"&&ue.length===0&&c&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:I==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),a==="structured"&&Q.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."}),a==="text"&&ue.map((N,O)=>t.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:N},`raw-${O}`)),a!=="text"&&Q.map((N,O)=>t.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${ai(N.level)}`,children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(N.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:N.level==="error"?"ERR":N.level==="warn"?"WRN":N.level==="debug"?"DBG":"INF"}),t.jsx("span",{className:"break-words",children:N.message})]},`log-${O}`))]})]}),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:()=>pe(N=>({...N,trace:!N.trace})),children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",w==="session_host"?" · session_host only":""]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[re.length," visible trace event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:J.trace?"Hide":"Show"})]}),J.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:[K&&re.length===0&&!z&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!K&&z&&re.length===0&&t.jsx("div",{className:"p-6 text-center text-red-300",children:z}),!K&&re.length===0&&!z&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:E.trim()?"No trace entries match the current search.":w==="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."}),re.map(N=>t.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${ai(N.level)}`,children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(N.ts).toLocaleTimeString()}),t.jsx("span",{children:N.level.toUpperCase()}),t.jsxs("span",{children:[N.category,".",N.stage]}),N.interactionId&&t.jsxs("span",{children:["ix=",N.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Qs(N.payload,360)||"No payload"})]},N.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:()=>pe(N=>({...N,web:!N.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:[le.length," visible browser event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:J.web?"Hide":"Show"})]}),J.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:[le.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."}),le.map(N=>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(N.ts).toLocaleTimeString()}),t.jsx("span",{children:N.kind}),N.topic&&t.jsxs("span",{children:["topic=",N.topic]}),N.interactionId&&t.jsxs("span",{children:["ix=",N.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Qs(N.payload,360)||"No payload"})]},N.id))]})]})]}),t.jsx("div",{ref:ae})]})}function Px(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 dl(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 a;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=dl((i==null?void 0:i.meta)||void 0),u=((a=i==null?void 0:i.meta)==null?void 0:a.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 Dx(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Dn(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 En(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function $n(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function oi(e){if(!e)return"unknown";const s=Date.now()-e,r=Math.max(0,Math.round(s/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const a=Math.round(n/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function Ex(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function $x(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 Bx(e){var r;const s=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const a=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!a)continue;const i=`${n.providerType}::${n.workspace}::${a}`;s.set(i,(s.get(i)||0)+1)}return Array.from(s.values()).filter(n=>n>1).length}function Kx({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),f=Jf(e,{enabled:!!e,includeSessions:!0,limit:So,intervalMs:fm}),d=f.diagnostics,h=f.loading,m=f.applyDiagnostics,j=o.useMemo(()=>Px({diagnostics:d,loading:h,refreshing:l,error:n}),[d,h,l,n]),S=o.useMemo(()=>new Map(s.map(T=>[T.sessionId||T.id,T])),[s]),p=o.useCallback(async()=>{if(e){u(!0);try{const T=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:So}),M=En(T);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Could not load hosted runtime diagnostics");m(M.diagnostics||M.result||null),a("")}catch(T){const M=T instanceof Error?T.message:"Could not load hosted runtime diagnostics";a(M)}finally{u(!1)}}},[m,e,r]);o.useEffect(()=>{!e||d||h||l||p()},[d,h,e,p,l]);const x=o.useCallback(async(T,M)=>{const P=`${T}:${M.sessionId}`;if(!(T==="session_host_stop_session"&&!window.confirm(`Stop ${M.displayName}?
|
|
70
|
-
This will terminate the hosted runtime.`))){c(P);try{const K=await r(e,T,{sessionId:M.sessionId}),U=En(K);if(!(U!=null&&U.success))throw new Error((U==null?void 0:U.error)||"Session host action failed");const L=T==="session_host_resume_session"?"resumed":T==="session_host_restart_session"?"restarted":"stopped";lt.showToast(`Session host ${L}: ${M.displayName}`,"success"),await p()}catch(K){const U=K instanceof Error?K.message:"Session host action failed";lt.showToast(U,"warning"),a(U)}finally{c(K=>K===P?null:K)}}},[e,p,r]),v=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
71
|
-
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 M=await r(e,"session_host_prune_duplicate_sessions",{}),P=En(M);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const K=P.result||{},U=Array.isArray(K.prunedSessionIds)?K.prunedSessionIds.length:0,L=typeof K.duplicateGroupCount=="number"?K.duplicateGroupCount:0;lt.showToast(`Pruned ${U} duplicate runtime(s) across ${L} group(s)`,"success"),await p()}catch(M){const P=M instanceof Error?M.message:"Duplicate prune failed";lt.showToast(P,"warning"),a(P)}finally{c(M=>M==="session_host_prune_duplicate_sessions"?null:M)}}},[e,p,r]),b=o.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((T,M)=>(M.lastActivityAt||0)-(T.lastActivityAt||0)),[d==null?void 0:d.sessions]),C=o.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(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),A=C.liveRuntimes,y=C.recoverySnapshots,I=C.inactiveRecords,k=o.useMemo(()=>Bx(A),[A]),w=o.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),g=o.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(T=>T.level==="warn"||T.level==="error")||null,[d==null?void 0:d.recentLogs]),E=(T,M)=>{var Y;const P=i===`session_host_resume_session:${T.sessionId}`,K=i===`session_host_restart_session:${T.sessionId}`,U=i===`session_host_stop_session:${T.sessionId}`,L=dl(T.meta),R=S.get(T.sessionId),z=T.attachedClients.length===1?"1 client":`${T.attachedClients.length} clients`,$=M==="recovery"?"Recover":"Resume",_=Dx(M);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:T.displayName||(R==null?void 0:R.cliName)||T.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${$x(T.lifecycle)}`,children:T.lifecycle}),L&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:L})]}),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:T.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||T.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:T.runtimeKey}),T.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",T.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((Y=T.writeOwner)==null?void 0:Y.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Ex(T.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(ki,{size:11})," ",z]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",oi(T.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",_]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[M==="recovery"&&(T.lifecycle==="interrupted"||T.lifecycle==="failed"||T.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_resume_session",T)},children:P?`${$}ing…`:$}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_restart_session",T)},children:K?"Restarting…":"Restart"}),M==="live"&&(T.lifecycle==="running"||T.lifecycle==="starting"||T.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:()=>{x("session_host_stop_session",T)},children:U?"Stopping…":"Stop"})]})]})},T.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(ls,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:sf()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[k>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{v()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${k})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${j.toneClass}`,children:j.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:h||l,children:[t.jsx(er,{size:13}),h||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(qs,{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:y.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:oi(d.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:$n(d.hostStartedAt)})]})]}),g&&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(qs,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:g.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[$n(g.timestamp),g.sessionId?` · ${g.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(ba,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Dn("live")}),A.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:A.map(T=>E(T,"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(ls,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Dn("recovery")}),y.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:y.map(T=>E(T,"recovery"))})]}),I.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:Dn("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:I.map(T=>E(T,"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"}),w.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:w.map(T=>{var P;const M=b.find(K=>K.sessionId===T.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:(M==null?void 0:M.displayName)||((P=S.get(T.sessionId))==null?void 0:P.cliName)||T.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[T.action,T.lifecycle?` · ${T.lifecycle}`:"",T.detail?` · ${T.detail}`:"",T.error?` · ${T.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${T.success===!1?"text-red-300":"text-text-secondary"}`,children:$n(T.timestamp)})]},`${T.sessionId}:${T.timestamp}:${T.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 Ox({machine:e,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return t.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:t.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[t.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),t.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),t.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?t.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(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:()=>{a(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:()=>{a(null),n({cliType:s.cliType,useDefaultWorkspace:!0,argsStr:s.argsStr,model:s.model})},children:"Default workspace"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:s.cliType,useHome:!0,argsStr:s.argsStr,model:s.model})},children:"Home directory"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function Bn({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 Kn({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 Wx({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),d=Hs(e,"0.9.11");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(Bn,{icon:t.jsx(Ft,{size:13}),children:"Current Chats"}),t.jsx(Kn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(h=>{const m=Zn(h);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(h),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:rt(h)}),m>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Jr(m)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:us(h)})]},h.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Bn,{icon:t.jsx(Mi,{size:13}),children:"Recent Launches"}),t.jsx(Kn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const{metaText:m,updatedLabel:j}=Uc(h);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(h),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:h.label}),j&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:j})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:m})]},h.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Bn,{icon:t.jsx(qs,{size:13}),children:"Daemon Update"}),t.jsx(Kn,{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:a,children:[t.jsx(er,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Hx(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const Fx={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 Ir(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function On({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:f}){const d=Is(),{handleLaunchIde:h,handleStopCli:m,handleRestartIde:j,handleStopIde:S,handleDetectIdes:p,launchingIde:x,launchingAgentType:v,addLog:b}=c,[C,A]=o.useState(null),y=o.useCallback(D=>{D&&d(Vt(D))},[d]),I=Fx[e],k=e==="ide",w=e==="acp",g=o.useMemo(()=>n.filter(D=>D.category===e&&(e==="ide"||D.installed!==!1)),[e,n]),E=o.useMemo(()=>new Map(g.map(D=>[D.type,D.displayName||D.type])),[g]),[T,M]=o.useState(""),[P,K]=o.useState(""),[U,L]=o.useState([]),[R,z]=o.useState(""),[$,_]=o.useState(""),[Y,J]=o.useState([]),[pe,ae]=o.useState(!1),[be,ye]=o.useState(!1),[ve,Ie]=o.useState(""),[H,V]=o.useState(!1),[Q,ue]=o.useState(()=>pt()),[re,le]=o.useState(null),[se,me]=o.useState(f?"__custom__":u||s.defaultWorkspaceId||""),[ne,ce]=o.useState(f||""),[oe,we]=o.useState([]),[he,Se]=o.useState(!1),[N,O]=o.useState(""),[G,Z]=o.useState([]),[fe,ge]=o.useState(!1),[Pe,Ee]=o.useState(""),We=o.useRef(null),[ze,Qe]=o.useState(null),Ze=o.useRef("__home__"),[it,yt]=o.useState("__home__"),[ut,Ye]=o.useState(!1),nt=o.useRef(0),je=oe.filter(D=>!a.some(te=>te.type===D&&bt(te.status)!=="stopped")),$e=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!se&&me(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(f){me("__custom__"),ce(f);return}u&&(me(u),ce(""))},[u,f]),o.useEffect(()=>{k||T&&(g.some(D=>D.type===T)||(M(""),_("")))},[g,k,T]);const Ke=(()=>{if(se==="__custom__")return ne.trim();if(!se)return"";const D=(s.workspaces||[]).find(te=>te.id===se);return(D==null?void 0:D.path)||""})(),st=o.useCallback(D=>{const te=$e.current[D];te&&(clearTimeout(te),delete $e.current[D]),we(de=>de.includes(D)?de.filter(Le=>Le!==D):de)},[]),dt=o.useRef(new Set),mt=o.useCallback(async D=>{if(l){ge(!0),Ee("");try{const te=await rn(l,r,D);O(te.path),ce(te.path),Z(te.directories)}catch(te){Ee(te instanceof Error?te.message:"Could not load folder")}finally{ge(!1)}}},[r,l]),ee=o.useCallback(()=>{if(!l)return;me("__custom__"),Se(!0);const D=a.map(de=>de.workspace),te=sn(s.platform,tn(ne.trim(),Ke,f,D,s.defaultWorkspacePath,(s.workspaces||[]).map(de=>de.path)));mt(te)},[ne,f,mt,s.defaultWorkspacePath,s.platform,s.workspaces,a,Ke,l]),Te=o.useCallback(D=>{const te=String(D.workspace||"").trim();if(!te)return;const de=(s.workspaces||[]).find(Le=>Ir(Le.path)===Ir(te));if(de){me(de.id),ce("");return}me("__custom__"),ce(te)},[s.workspaces]),Re=o.useCallback(D=>{const te=String(D.workspace||"").trim();if(!te)return{workspaceId:null,workspacePath:"",useHome:!0};const de=(s.workspaces||[]).find(Le=>Ir(Le.path)===Ir(te));return de?{workspaceId:de.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:te,useHome:!1}},[s.workspaces]),at=o.useCallback(async D=>{if(!l||!D||e!=="cli"){J([]),ae(!1),ye(!1),Ie("");return}const te=nt.current+1;nt.current=te,ae(!0),Ie("");try{const de=await l(r,"list_saved_sessions",{providerType:D,kind:"cli",limit:30});if(nt.current!==te)return;const Le=(de==null?void 0:de.result)??de;J(Array.isArray(Le==null?void 0:Le.sessions)?Le.sessions:[])}catch(de){if(nt.current!==te)return;J([]),Ie(de instanceof Error?de.message:"Could not load saved sessions")}finally{nt.current===te&&(ae(!1),ye(!0))}},[e,r,l]),ht=o.useMemo(()=>{if(e!=="cli"||!T)return null;const D=E.get(T)||T;return{routeId:r,daemonId:r,providerSessionId:$||void 0,transport:"pty",mode:"chat",agentName:D,agentType:T,status:"idle",title:D,messages:[],ideType:T,workspaceName:Ke,displayPrimary:D,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${T}`}},[e,r,E,Ke,$,T]),vt=o.useCallback(D=>{if(e==="ide"||!D){L([]);return}L(rl(r,D))},[e,r]);o.useEffect(()=>{nt.current+=1,_(""),vt(T),ye(!1),J([]),Ie(""),ae(!1)},[e,vt,at,T]);const He=o.useMemo(()=>Y.find(D=>D.providerSessionId===$)||null,[Y,$]);o.useEffect(()=>{if(!$)return;const D=Y.find(te=>te.providerSessionId===$);D!=null&&D.canResume||_("")},[Y,$]);const It=o.useCallback((D,te)=>{We.current=te,Ze.current=D.selectedWorkspaceKey||"__home__",yt(D.selectedWorkspaceKey||"__home__"),Qe(D)},[]),B=o.useCallback(()=>{We.current&&(Ye(!0),We.current().finally(()=>{We.current=null,Ye(!1),Qe(null)}))},[]),W=o.useCallback(D=>{if(!D)return;we(de=>de.includes(D)?de:[...de,D]);const te=$e.current[D];te&&clearTimeout(te),$e.current[D]=setTimeout(()=>{we(de=>de.includes(D)?de.filter(Le=>Le!==D):de),delete $e.current[D]},2e4)},[]);o.useEffect(()=>{for(const te of a)bt(te.status)!=="stopped"&&(oe.includes(te.type)&&!dt.current.has(te.type)&&(dt.current.add(te.type),b("info",`${E.get(te.type)||te.type} launched`,!0)),st(te.type));const D=new Set(a.filter(te=>bt(te.status)!=="stopped").map(te=>te.type));dt.current.forEach(te=>{!oe.includes(te)&&!D.has(te)&&dt.current.delete(te)})},[b,st,a,oe,E]),o.useEffect(()=>()=>{Object.values($e.current).forEach(clearTimeout),$e.current={}},[]);const[F,q]=o.useState({}),[ie,ke]=o.useState(null);o.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const te=await l(r,"get_ide_extensions",{}),de=(te==null?void 0:te.result)||te;de!=null&&de.success&&(de!=null&&de.ideExtensions)&&q(de.ideExtensions)}catch{}})()},[k,r,l]);const Ce=D=>k?tt(D.type):e==="cli"?D.cliName:D.acpName,X=k?s.detectedIdes||[]:[],xe=o.useCallback(async D=>{const te=(D==null?void 0:D.type)||T,de=(D==null?void 0:D.workspacePath)??Ke;if(k){await h(te,de?{workspace:de}:void 0)&&W(te);return}const Le=await c.runLaunchCliCore({cliType:te,dir:D!=null&&D.workspaceId?void 0:de||void 0,workspaceId:(D==null?void 0:D.workspaceId)||void 0,useHome:(D==null?void 0:D.useHome)||!(D!=null&&D.workspaceId)&&!de,argsStr:(D==null?void 0:D.argsStr)??(P||void 0),model:(D==null?void 0:D.model)??(w&&R||void 0),resumeSessionId:(D==null?void 0:D.resumeSessionId)||!w&&e==="cli"&&te===T&&$||void 0});if(Le.success||Le.pending){const Ne=(D==null?void 0:D.argsStr)??P;!k&&(Ne!=null&&Ne.trim())&&(nl(r,te,Ne),vt(te)),W(te),Le.success&&Le.sessionId&&y(Le.sessionId)}},[c,h,w,k,P,R,vt,W,r,y,Ke,$,T]),Be=pc(k?"ide":w?"acp":"cli",!k&&!w&&!!$),Oe=hc(k?"ide":w?"acp":"cli",!k&&!w&&!!$),Xe=()=>{var Ne;const D=k?tt(T):E.get(T)||T,te=!k&&!w&&!!$,{options:de,selectedKey:Le}=os({machine:s,currentWorkspaceId:se&&se!=="__custom__"?se:null,currentWorkspacePath:Ke});It({title:te?Ra(D):ss("start-fresh",D),description:te?Pa():rs("start-fresh"),confirmLabel:Be,busyLabel:Oe,workspaceOptions:de,selectedWorkspaceKey:Le,details:[{label:"Mode",value:I.label},{label:"Provider",value:D},...!k&&e==="cli"&&$?[{label:"Resume",value:((Ne=Y.find(Me=>Me.providerSessionId===$))==null?void 0:Ne.title)||$}]:[],...!k&&P.trim()?[{label:"Arguments",value:P.trim()}]:[],...w&&R.trim()?[{label:"Model",value:R.trim()}]:[]]},async()=>{const Me=de.find(Ae=>Ae.key===Ze.current);Me!=null&&Me.workspaceId?(me(Me.workspaceId),ce("")):Me!=null&&Me.workspacePath?(me("__custom__"),ce(Me.workspacePath)):(me(""),ce("")),await xe({workspaceId:(Me==null?void 0:Me.workspaceId)??null,workspacePath:(Me==null?void 0:Me.workspacePath)??"",useHome:!(Me!=null&&Me.workspaceId)&&!(Me!=null&&Me.workspacePath)})})},qe=D=>{k?S(D):m(D.type,D.workspace,D.id)},Ue=o.useCallback(async(D,te,de=!1)=>{if(D.mode===te){de&&D.sessionId&&y(D.sessionId);return}if(!l||!D.sessionId){de&&D.sessionId&&y(D.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:D.sessionId,cliType:D.type,mode:te}),de&&y(D.sessionId)}catch(Le){const Ne=Ha(Le);Wa(Le)?console.warn(Ne?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Le instanceof Error?Le.message:String(Le)):console.error("Failed to switch CLI view mode:",Le)}},[r,y,l]),_e=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:se,onChange:D=>{const te=D.target.value;if(me(te),te==="__custom__"&&l){ee();return}te!=="__custom__"&&ce("")},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(D=>t.jsxs("option",{value:D.id,children:[D.id===s.defaultWorkspaceId?"⭐ ":"",Zr(D.path,D.label)]},D.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…"})]})}),se==="__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:ee,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:ne,onChange:D=>ce(D.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),t.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:se==="__custom__"?Ke?t.jsx("span",{className:"font-mono truncate block",title:Ke,children:Ke}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Ke?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:se===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:Ke,children:Ke})]}):"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 ${I.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 ",I.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?X.length>0?X.map(D=>{const te=a.find(Ae=>(Ae.type||"").toLowerCase()===(D.type||"").toLowerCase()&&bt(Ae.status)!=="stopped"),de=D.running||!!te,Le=!!te&&te.cdpConnected,Ne=oe.includes(D.type||D.id||""),Me=T===(D.type||"");return t.jsxs("button",{onClick:()=>{if(Le&&te){const Ae=te.sessionId;Ae?d(Vt(Ae),{state:{openRemoteForTabKey:Ae}}):d("/dashboard",{state:{openRemoteForTabKey:te.id}});return}Ne||M(Ae=>Ae===(D.type||"")?"":D.type||"")},disabled:!!x||Ne,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Le?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Me?"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:x&&x!==D.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(D.type)}),de&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Le?"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:D.name||tt(D.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Le?"text-green-400":Ne?"text-orange-400":Me?"text-accent-primary":"text-text-muted"}`,children:Le?"Open Session":Ne?"Starting...":Me?"Configure":"Select"})]})]},D.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:p,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(kd,{size:14})," Scan System"]})]}):g.length>0?g.map(D=>{const te=T===D.type,de=oe.includes(D.type),Ne=!!a.find(Me=>Me.type===D.type&&bt(Me.status)!=="stopped");return t.jsxs("button",{onClick:()=>M(Me=>Me===D.type?"":D.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${te?"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:D.icon}),Ne&&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:D.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${de?"text-orange-400":te?"text-accent-primary":"text-text-muted"}`,children:de?"Starting...":te?"Configure":"Select"})]})]},D.type)}):t.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",t.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),T&&(k?X.find(D=>D.type===T):g.find(D=>D.type===T))&&t.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:k?tt(T):E.get(T)||T})]}),_e,!k&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&t.jsx(ol,{busy:!!v||!!x||oe.includes(T),savedSessionsLoading:pe,savedSessionsError:ve,selectedSession:He,onRefresh:()=>void at(T),onOpenHistory:()=>{T&&(V(!0),al({hasLoadedInitialResults:be,isLoading:pe})&&at(T))},onClearSelection:()=>_("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[w&&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:R,onChange:D=>z(D.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:D=>K(D.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"}),U.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:U.map(D=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>K(D),title:D,children:D},D))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:Xe,disabled:!!v||!!x||oe.includes(T),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:v===T||x===T?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+oe.filter(D=>!a.some(te=>te.type===D&&bt(te.status)!=="stopped")).length,")"]}),a.length===0&&je.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 ",I.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[je.map(D=>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(D)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?tt(D):E.get(D)||D}),t.jsx("div",{className:"text-[11px] text-text-muted",children:v===D?"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:${D}`)),a.map(D=>{const te=k?D:null,de=!k&&!w?D:null,Le=bt(D.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(D.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ce(D),(te==null?void 0:te.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",te.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:D.workspace||"—"}),(de==null?void 0:de.mode)&&t.jsx("span",{className:de.mode==="chat"?"text-violet-400":"text-text-secondary",children:de.mode==="chat"?"Chat view":"Terminal view"})]}),de&&(de.runtimeKey||de.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[de.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 ",de.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 Ne;(Ne=navigator.clipboard)==null||Ne.writeText(`adhdev attach ${de.runtimeKey}`),A(de.runtimeKey||null),window.setTimeout(()=>{A(Me=>Me===de.runtimeKey?null:Me)},1200)},children:C===de.runtimeKey?"Copied":"Copy"})]}),de.runtimeWriteOwner&&t.jsx("span",{style:{color:de.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:de.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Hx(de.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 ${Le==="stopped"?"bg-red-500/[0.08] text-red-500":Le==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Le}),k&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Ne=D.sessionId;if(Ne){d(Vt(Ne),{state:{openRemoteForTabKey:Ne}});return}d("/dashboard",{state:{openRemoteForTabKey:D.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(Ct,{size:13})}),t.jsx("button",{onClick:()=>{const Ne=D.workspace||"",{options:Me,selectedKey:Ae}=os({machine:s,currentWorkspacePath:Ne});It({title:ss("restart-ide",tt(D.type)),description:rs("restart-ide"),confirmLabel:Ns("restart-ide"),busyLabel:Cs("restart-ide"),workspaceOptions:Me,selectedWorkspaceKey:Ae,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:tt(D.type)}]},async()=>{const ft=Me.find(Ts=>Ts.key===Ze.current),ct=(ft==null?void 0:ft.workspacePath)??"";if(ct&&ct!==Ne){await xe({type:D.type,workspacePath:ct});return}await j(D)})},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(er,{size:14})})]}),w&&t.jsx("button",{onClick:()=>{const Ne=D.sessionId;Ne&&y(Ne)},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:!D.sessionId,children:t.jsx(Ft,{size:14})}),de&&Le!=="stopped"&&t.jsxs(t.Fragment,{children:[de.mode&&t.jsx(Aa,{mode:de.mode,onChange:Ne=>void Ue(de,Ne,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Ne=D.sessionId;Ne&&y(Ne)},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:!D.sessionId,children:de.mode==="chat"?t.jsx(Ft,{size:14}):t.jsx(Ct,{size:13})})]}),Le==="stopped"?t.jsx("button",{onClick:()=>{const Ne=D.workspace||"",Me=k?tt(D.type):Ce(D),{options:Ae,selectedKey:ft}=os({machine:s,currentWorkspacePath:Ne});It({title:ss("restart-stopped",Me),description:rs("restart-stopped"),confirmLabel:Ns("restart-stopped"),busyLabel:Cs("restart-stopped"),workspaceOptions:Ae,selectedWorkspaceKey:ft,details:[{label:"Mode",value:I.label},{label:"Provider",value:Me}]},async()=>{const ct=Ae.find(Ts=>Ts.key===Ze.current);await xe({type:D.type,workspaceId:(ct==null?void 0:ct.workspaceId)??null,workspacePath:(ct==null?void 0:ct.workspacePath)??"",useHome:!(ct!=null&&ct.workspaceId)&&!(ct!=null&&ct.workspacePath)})})},disabled:oe.includes(D.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:oe.includes(D.type)?"⏳":t.jsx(ga,{size:14})}):t.jsx("button",{onClick:()=>qe(D),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(wt,{size:14})})]})]}),te&&te.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:te.aiAgents.map(Ne=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${$i(Ne.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Ne.name," · ",bt(Ne.status)]},Ne.id))}),te&&(F[te.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:(F[te.type]||[]).map(Ne=>t.jsxs("button",{disabled:ie===`${te.type}.${Ne.type}`,onClick:async()=>{const Me=`${te.type}.${Ne.type}`;ke(Me);try{await l(r,"set_ide_extension",{ideType:te.type,extensionType:Ne.type,enabled:!Ne.enabled}),q(Ae=>({...Ae,[te.type]:(Ae[te.type]||[]).map(ft=>ft.type===Ne.type?{...ft,enabled:!ft.enabled}:ft)}))}catch(Ae){console.error("Extension toggle failed:",Ae)}finally{ke(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 ${Ne.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 ${Ne.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Ne.name,t.jsx("span",{className:"text-[9px] font-normal",children:Ne.enabled?"ON":"OFF"})]},Ne.type))})]})]},D.id)})]}),he&&l&&t.jsx(an,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:N,directories:G,busy:fe,error:Pe,confirmLabel:"Use this folder",onClose:()=>Se(!1),onNavigate:D=>{mt(D)},onConfirm:D=>{ce(D),me("__custom__"),Se(!1)}}),ze&&t.jsx(Va,{title:ze.title,description:ze.description,details:ze.details,workspaceOptions:ze.workspaceOptions,selectedWorkspaceKey:it,onWorkspaceChange:D=>{Ze.current=D,yt(D)},confirmLabel:ze.confirmLabel,busyLabel:ze.busyLabel,busy:ut,onConfirm:B,onCancel:()=>{We.current=null,Qe(null)}}),H&&ht&&t.jsx(_a,{activeConv:ht,ides:[],isCreatingChat:!1,isRefreshingHistory:pe,savedSessions:Y,isSavedSessionsLoading:pe,isResumingSavedSessionId:re,savedHistoryFilters:Q,onSavedHistoryFiltersChange:ue,onClose:()=>V(!1),onNewChat:()=>{_(""),V(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{at(T)},onResumeSavedSession:D=>{if(!D.canResume||re)return;const te=Re(D);_(D.providerSessionId),Te(D),le(D.providerSessionId),V(!1),xe({type:D.providerType,workspaceId:te.workspaceId,workspacePath:te.workspacePath,useHome:te.useHome,resumeSessionId:D.providerSessionId}).finally(()=>{le(de=>de===D.providerSessionId?null:de)})}})]})}const ii=[{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 Ux({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:f,initialWorkspacePath:d,sendDaemonCommand:h}){var p;const[m,j]=o.useState(u);o.useEffect(()=>{j(u)},[u]);const S=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.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:ii.map(x=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${m===x.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>j(x.id),children:[t.jsx("span",{children:x.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${m===x.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:S[x.id]})]},x.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(p=ii.find(x=>x.id===m))==null?void 0:p.helper})]}),m==="ide"&&t.jsx(On,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d}),m==="cli"&&t.jsx(On,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d}),m==="acp"&&t.jsx(On,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d})]})}function zx({onNicknameSynced:e}={}){var le,se,me,ne,ce,oe,we,he,Se;const{id:s}=Gl(),r=Is(),n=fa(),{sendCommand:a}=jt(),i=nr(),c=Tc(),l=oc(),u=l.ides||[],f=l.initialLoaded??!0,d=u.find(N=>N.id===s&&N.type==="adhdev-daemon"),h=u.some(N=>N.type==="adhdev-daemon"),[m,j]=o.useState("workspace"),[S,p]=o.useState("ide"),x=o.useRef(null),[v,b]=o.useState(null),C=o.useRef("__home__"),[A,y]=o.useState("__home__"),[I,k]=o.useState(!1),w=o.useRef(null);o.useEffect(()=>{!s||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,d,s]),o.useEffect(()=>{if(!s||!d||m!=="overview")return;const N=d.machine;(typeof(N==null?void 0:N.cpus)!="number"||typeof(N==null?void 0:N.totalMem)!="number"||typeof(N==null?void 0:N.arch)!="string"||typeof(N==null?void 0:N.release)!="string")&&c(s,{minFreshMs:3e4}).catch(()=>{})},[m,c,d,s]),Xf(s&&m==="overview"?[s]:[],{enabled:m==="overview",intervalMs:lm});const g=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},E=px({machineId:s,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:w});o.useEffect(()=>lt.onToast(O=>{l.setToasts(Z=>{if(Z.some(Pe=>Pe.message===O.message&&O.timestamp-Pe.timestamp<3e3))return Z;const ge={id:O.id,message:O.message,type:O.type,timestamp:O.timestamp,targetKey:O.targetKey,actions:O.actions};return[...Z.slice(-4),ge]});const G=O.duration||5e3;setTimeout(()=>l.setToasts(Z=>Z.filter(fe=>fe.id!==O.id)),G)}),[l]);const T=(d==null?void 0:d.availableProviders)||[],M={};for(const N of T)M[N.type]=N.icon;const P=N=>M[N]||"",K=d?{id:d.id,hostname:Bi(d,{fallbackId:d.id}),platform:((le=d.machine)==null?void 0:le.platform)||"unknown",arch:((se=d.machine)==null?void 0:se.arch)||"",cpus:((me=d.machine)==null?void 0:me.cpus)||0,totalMem:((ne=d.machine)==null?void 0:ne.totalMem)||0,freeMem:(ce=d.machine)==null?void 0:ce.freeMem,availableMem:(oe=d.machine)==null?void 0:oe.availableMem,loadavg:(we=d.machine)==null?void 0:we.loadavg,uptime:(he=d.machine)==null?void 0:he.uptime,release:((Se=d.machine)==null?void 0:Se.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,U=u.filter(N=>N.daemonId===s&&N.type!=="adhdev-daemon").filter(N=>!Xs(N)&&!gs(N)).map(N=>({id:N.id,sessionId:N.sessionId,type:N.type,version:N.version||"",instanceId:N.instanceId||"",status:N.status,workspace:N.workspace||null,terminals:N.terminals||0,aiAgents:xu(N.aiAgents||(N.agents||[]).map(O=>({id:O.name,name:O.name,status:O.status,version:O.version}))),activeChat:N.activeChat||null,chats:N.chats||[],childSessions:N.childSessions||[],cdpConnected:N.cdpConnected||!1,daemonId:s})),L=u.filter(N=>N.daemonId===s&&Xs(N)).map(N=>({id:N.id,sessionId:N.sessionId,type:N.type,cliName:N.cliName||N.type,status:N.status,workspace:N.workspace||"",activeChat:N.activeChat||null,providerSessionId:N.providerSessionId,mode:N.mode,runtimeKey:N.runtimeKey,runtimeDisplayName:N.runtimeDisplayName,runtimeWorkspaceLabel:N.runtimeWorkspaceLabel,runtimeWriteOwner:N.runtimeWriteOwner||null,runtimeAttachedClients:N.runtimeAttachedClients||[],daemonId:s})),R=u.filter(N=>N.daemonId===s&&gs(N)).map(N=>({id:N.id,sessionId:N.sessionId,type:N.type,acpName:N.cliName||N.type,status:N.status,workspace:N.workspace||"",activeChat:N.activeChat||null,providerSessionId:N.providerSessionId,daemonId:s})),z=d?Tt(d,{fallbackId:s}):"",$="workspace",_=n.state,Y=_==null?void 0:_.initialMachineTab,J=_==null?void 0:_.initialWorkspaceCategory,pe=_==null?void 0:_.initialWorkspaceId,ae=_==null?void 0:_.initialWorkspacePath,be=Y==="ides"||Y==="clis"||Y==="acps"?"workspace":Y||$,ye=Y==="ides"?"ide":Y==="clis"?"cli":Y==="acps"?"acp":J,ve=[...U.map(N=>{var O,G,Z,fe,ge;return{id:`ide:${N.type}:${N.workspace||""}`,label:((O=N.activeChat)==null?void 0:O.title)||N.type,kind:"ide",providerType:N.type,subtitle:N.workspace||void 0,workspace:N.workspace||void 0,lastLaunchedAt:((ge=(fe=(Z=(G=N.activeChat)==null?void 0:G.messages)==null?void 0:Z.at)==null?void 0:fe.call(Z,-1))==null?void 0:ge.timestamp)||0}}),...L.map(N=>{var O,G,Z,fe,ge;return{id:`cli:${N.type}:${N.workspace||""}`,label:((O=N.activeChat)==null?void 0:O.title)||N.cliName,kind:"cli",providerType:N.type,providerSessionId:N.providerSessionId,subtitle:N.workspace||void 0,workspace:N.workspace||void 0,lastLaunchedAt:((ge=(fe=(Z=(G=N.activeChat)==null?void 0:G.messages)==null?void 0:Z.at)==null?void 0:fe.call(Z,-1))==null?void 0:ge.timestamp)||0}}),...R.map(N=>{var O,G,Z,fe,ge;return{id:`acp:${N.type}:${N.workspace||""}`,label:((O=N.activeChat)==null?void 0:O.title)||N.acpName,kind:"acp",providerType:N.type,providerSessionId:N.providerSessionId,subtitle:ds(N.summaryMetadata)||N.workspace||void 0,workspace:N.workspace||void 0,lastLaunchedAt:((ge=(fe=(Z=(G=N.activeChat)==null?void 0:G.messages)==null?void 0:Z.at)==null?void 0:fe.call(Z,-1))==null?void 0:ge.timestamp)||0}})].sort((N,O)=>(O.lastLaunchedAt||0)-(N.lastLaunchedAt||0)),Ie=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(N=>({id:N.id,label:N.title||N.providerName||N.providerType,kind:N.kind,providerType:N.providerType,providerSessionId:N.providerSessionId,subtitle:ds(N.summaryMetadata)||N.workspace||void 0,workspace:N.workspace,summaryMetadata:N.summaryMetadata,lastLaunchedAt:N.lastLaunchedAt})):ve,H=o.useMemo(()=>{var O;const N=((O=l.connectionStates)==null?void 0:O[s||""])||void 0;return u.filter(G=>G.daemonId===s&&G.type!=="adhdev-daemon").flatMap(G=>Da(G,{connectionStates:s&&N?{[s]:N}:void 0,defaultConnectionState:N})).filter(G=>!(G.transport==="pty"&&G.mode==="terminal")).sort((G,Z)=>Zn(Z)-Zn(G))},[u,l.connectionStates,s]),V=o.useCallback(N=>{const O=Ca(N);O&&r(Vt(O))},[r]),Q=o.useCallback(()=>{x.current&&(k(!0),x.current().finally(()=>{x.current=null,k(!1),b(null)}))},[]),ue=o.useCallback(N=>{if(!K)return;const{options:O,selectedKey:G}=os({machine:K,currentWorkspacePath:N.workspace}),Z=async()=>{p(N.kind),j("workspace")};x.current=async()=>{const fe=O.find(Ee=>Ee.key===C.current),ge=(fe==null?void 0:fe.workspacePath)??null,Pe=(fe==null?void 0:fe.workspaceId)??null;if(N.kind==="ide"&&N.providerType){await E.handleLaunchIde(N.providerType,ge?{workspace:ge}:void 0);return}if((N.kind==="cli"||N.kind==="acp")&&N.providerType){await E.runLaunchCliCore({cliType:N.providerType,dir:Pe?void 0:ge||"",workspaceId:Pe||void 0,model:N.kind==="acp"&&Oi(N.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:N.providerSessionId});return}await Z()},C.current=G,y(G),b({title:N.kind==="ide"?ss("restart-ide",N.label):N.providerSessionId?Ra(N.label):ss("start-fresh",N.label),description:N.kind==="ide"?rs("restart-ide"):N.providerSessionId?Pa():rs("start-fresh"),confirmLabel:N.kind==="ide"?Ns("restart-ide"):N.providerSessionId?Ur(!0):Ns("start-fresh"),busyLabel:N.kind==="ide"?Cs("restart-ide"):N.providerSessionId?Ta(!0):Cs("start-fresh"),workspaceOptions:O,details:[{label:"Mode",value:N.kind.toUpperCase()},...N.providerType?[{label:"Provider",value:N.providerType}]:[]]})},[E,K]);if(o.useEffect(()=>{j(be)},[$,be,s]),o.useEffect(()=>{ye&&p(ye)},[ye,s]),!K)return f?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:g,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 re=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ct,{size:14})," Workspace"]}),count:U.length+L.length+R.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(ls,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Yr,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Sd,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(wd,{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:g,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:N=>E.setNicknameInput(N.target.value),onKeyDown:N=>{N.key==="Enter"&&E.handleSaveNickname(),N.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(K.machineNickname||"")},title:"Click to set nickname",children:z}),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:[K.platform," · ",K.arch]}),t.jsxs("span",{children:[K.cpus," cores"]}),(d==null?void 0:d.version)&&t.jsxs("span",{children:["v",d.version]}),K.p2p.available&&t.jsxs("span",{children:["P2P ",K.p2p.state==="connected"?"connected":K.p2p.state]}),K.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:K.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:re.map(N=>t.jsxs("button",{onClick:()=>j(N.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${m===N.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[N.label,N.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${m===N.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:N.count})]},N.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:[m==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(Wx,{machineEntry:d,providers:T,recentLaunches:Ie,currentConversations:H,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:ue,onOpenConversation:V}),t.jsx(Ux,{machine:K,machineId:s,providers:T,ideSessions:U,cliSessions:L,acpSessions:R,actions:E,getIcon:P,initialCategory:S,initialWorkspaceId:pe,initialWorkspacePath:ae,sendDaemonCommand:a})]}),m==="providers"&&t.jsx(jx,{machineId:s,providers:T,sendDaemonCommand:a}),m==="overview"&&t.jsx(hx,{machineId:s,machine:K,ideSessions:U,cliSessions:L,acpSessions:R,actions:E,sendDaemonCommand:a}),m==="session-host"&&t.jsx(Kx,{machineId:s,cliSessions:L,sendDaemonCommand:a}),m==="logs"&&t.jsx(Rx,{machineId:s,sendDaemonCommand:a})]})})}),E.launchPick&&K&&t.jsx(Ox,{machine:K,launchPick:E.launchPick,actions:E}),v&&t.jsx(Va,{title:v.title,description:v.description,details:v.details,workspaceOptions:v.workspaceOptions,selectedWorkspaceKey:A,onWorkspaceChange:N=>{C.current=N,y(N)},confirmLabel:v.confirmLabel,busyLabel:v.busyLabel,busy:I,onConfirm:Q,onCancel:()=>{x.current=null,b(null)}}),t.jsx(xc,{toasts:l.toasts||[],onDismiss:N=>l.setToasts(O=>O.filter(G=>G.id!==N)),onClickToast:N=>{N.targetKey&&r(Vt(N.targetKey))}}),t.jsx("style",{children:`
|
|
72
|
-
@keyframes toast-in {
|
|
73
|
-
from { opacity: 0; transform: translateX(40px); }
|
|
74
|
-
to { opacity: 1; transform: translateX(0); }
|
|
75
|
-
}
|
|
76
|
-
`})]})}function Ya(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Vx(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=Ya();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 $t(e,s){return await fetch(Vx(e),{credentials:"same-origin",...s})}function ul(){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 Gx{constructor(){Ve(this,"adapters",new Map);Ve(this,"states",new Map);Ve(this,"runtimeListeners",new Map);Ve(this,"screenshotCallbacks",new Map);Ve(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}onScreenshot(s,r){return this.screenshotCallbacks.set(s,r),()=>{this.screenshotCallbacks.delete(s)}}emitScreenshot(s,r){this.screenshotCallbacks.forEach(n=>n(s,r))}onStatus(s){return this.statusCallbacks.add(s),()=>{this.statusCallbacks.delete(s)}}emitStatus(s,r){this.statusCallbacks.forEach(n=>n(s,r))}emitRuntimeSnapshot(s,r,n=0,a=!1,i,c){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:a,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 a=this.runtimeListeners.get(s);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(s))}}async requestRuntimeSnapshot(s,r){if(!r)return{success:!1,error:"sessionId is required"};const n=await $t(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`);if(!n.ok){let i=`Runtime snapshot unavailable (${n.status})`;try{const c=await n.json();c!=null&&c.error&&(i=c.error)}catch{}return{success:!1,error:i}}const a=await n.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof a.seq=="number"?a.seq:0,text:typeof a.text=="string"?a.text:"",truncated:!!a.truncated,cols:typeof a.cols=="number"?a.cols:void 0,rows:typeof a.rows=="number"?a.rows:void 0}),{success:!0}}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(a=>a(r))}}const Ot=new Gx;function qx(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Ya();return r?`${s}?token=${encodeURIComponent(r)}`:s}const Mr=qx(),ci=3e3,Yx=3e4;let Rt=null,Xx=0;const qr=new Map;let Jt=null,Us=null;function li(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function Es(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function Jx(e){return e==="connected"?"connected":e}async function Er(e,s,r){const n=yc(e,r||{}),a=Rt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++Xx}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{qr.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);qr.set(i,{resolve:f=>{clearTimeout(u),c(f)},reject:f=>{clearTimeout(u),l(f)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function la(e,s){const r=Rt;if(!r||r.readyState!==WebSocket.OPEN||!s||s.type!=="subscribe"&&s.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}function Qx(e,s,r){const n=Rt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=yc(e,{sessionId:s,targetSessionId:s,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}class Zx{constructor(s){Ve(this,"daemonId");Ve(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN}get connectionState(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Er(this.daemonId,s,r)}async sendInput(s,r){return Er(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Jt&&(clearInterval(Jt),Jt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Er(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Ot.emitScreenshot(this.daemonId,a)}}catch{}};r(),Jt=setInterval(r,2e3)}stopScreenshots(s){Jt&&(clearInterval(Jt),Jt=null)}}let At=null;function eb(e){return(!At||At.daemonId!==e)&&(At=new Zx(e)),At}function tb({children:e}){const s=o.useRef(Gs()),r=Gs();s.current=r;const{setUserName:n}=cs(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((p,x)=>{l(p),Us==null||Us(p,x)},[]),f=o.useRef(null),d=o.useRef(),h=o.useRef(ci),m=o.useRef(!0),j=o.useRef(!1),S=o.useRef("initial_connect");return o.useEffect(()=>{m.current=!0,j.current=!1;function p(){var b,C;if(!m.current||((b=f.current)==null?void 0:b.readyState)===WebSocket.OPEN||((C=f.current)==null?void 0:C.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Mr}...`),Es("connect_attempt",{url:Mr,reason:S.current,delayMs:h.current});let v;try{v=new WebSocket(Mr)}catch(A){console.error("[Standalone WS] Failed to create WebSocket:",A),x();return}f.current=v,v.onopen=()=>{if(!m.current){v.close();return}u("connected"),h.current=ci,Es("open",{url:Mr,reason:S.current}),Gt.resubscribeAll({sendData:la}),console.log("[Standalone WS] Connected")},Rt=v,v.onmessage=A=>{var y,I;try{const k=JSON.parse(A.data);if((k.type==="command_result"||k.type==="error")&&k.requestId){const w=qr.get(k.requestId);w&&(qr.delete(k.requestId),k.type==="error"?w.reject(new Error(((y=k.data)==null?void 0:y.message)||"Command failed")):w.resolve(k.data));return}if(k.type==="session_output"){const w=k.sessionId||k.cliId||k.cliType;w&&Ot.emitSessionOutput(w,typeof k.data=="string"?k.data:"",typeof k.seq=="number"?k.seq:void 0);return}if(k.type==="runtime_snapshot"){Ot.emitRuntimeSnapshot(k.sessionId,typeof k.text=="string"?k.text:"",typeof k.seq=="number"?k.seq:0,!!k.truncated,typeof k.cols=="number"?k.cols:void 0,typeof k.rows=="number"?k.rows:void 0);return}if(k.type==="topic_update"){const w=k.update;w&&Gt.publish(w);return}if(k.type==="status"||k.type==="initial_state"){const w=k.data;if(!w)return;const{injectEntries:g,markLoaded:E,getIdes:T}=s.current,M=w.instanceId||"standalone",P=T().find(L=>L.id===M),K=eb(M);Ot.register(M,K),Ot.setState(M,"connected"),u("connected",M),Ot.emitStatus(M,w);const U=Fr(w,{daemonId:M,existingDaemon:P,existingEntries:T()});li("ws_status",{type:k.type,daemonId:M,sessions:(w.sessions||[]).map(L=>({id:L.id,parentId:L.parentId,providerType:L.providerType,kind:L.kind,transport:L.transport,unread:L.unread,inboxBucket:L.inboxBucket,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,title:L.title})),recentLaunches:(w.recentLaunches||[]).map(L=>({id:L.id,providerType:L.providerType,kind:L.kind,workspace:L.workspace,lastLaunchedAt:L.lastLaunchedAt}))}),li("entries",{daemonId:M,entries:U.filter(L=>L.type!=="adhdev-daemon").map(L=>({id:L.id,type:L.type,unread:L.unread,inboxBucket:L.inboxBucket,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,sessionId:L.sessionId}))}),U.length>0&&g(U,{authoritativeDaemonIds:[M]}),E(),c.current!==M&&((I=i.current)==null||I.call(i),c.current=M,i.current=Gt.subscribe({sendData:la},M,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${M}`,params:{includeSessions:!0}},L=>{if(L.topic!=="daemon.metadata")return;const R=s.current.getIdes(),z=R.find(_=>_.id===M),$=Fr(L.status,{daemonId:M,existingDaemon:z,existingEntries:R,timestamp:L.timestamp});$.length>0&&s.current.injectEntries($),L.userName&&a.current&&a.current(L.userName)}))}}catch(k){console.error("[Standalone WS] Parse error:",k)}},v.onclose=A=>{m.current&&(At==null||At.stopScreenshots(),At&&Ot.setState(At.daemonId,"disconnected"),u("disconnected"),f.current=null,S.current=`close:${A.code}${A.wasClean?":clean":":unclean"}`,Es("close",{code:A.code,reason:A.reason||"",wasClean:A.wasClean}),x())},v.onerror=A=>{j.current||!m.current||(S.current="error",Es("error",{message:A instanceof Event?"event":String(A),readyState:v.readyState}),console.warn("[Standalone WS] Error, will reconnect:",A))}}function x(){if(!m.current)return;clearTimeout(d.current);const v=h.current;console.log(`[Standalone WS] Reconnecting in ${v}ms...`),Es("schedule_reconnect",{reason:S.current,delayMs:v}),d.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,Yx),p()},v)}return p(),()=>{var v;m.current=!1,j.current=!0,(v=i.current)==null||v.call(i),i.current=null,c.current=null,clearTimeout(d.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Rt=null),At&&(At.stopScreenshots(),Ot.unregister(At.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function sb({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(Us=(c,l)=>{r(c),l&&a(l)},()=>{Us=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=Jx(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(ud,{connectionOverrides:i,children:t.jsx(tb,{children:e})})}const ml="adhdev_standalone_font_preferences",is={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},ln=[{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"}],Zs=[{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"}],rb=new Set(ln.map(e=>e.id)),nb=new Set(Zs.map(e=>e.id));function Kt(e){const s=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:$r("chat",s.chat),code:$r("code",s.code),terminal:$r("terminal",s.terminal)}}function $r(e,s){const r=is[e],n=s&&typeof s=="object"&&!Array.isArray(s)?s:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?rb:nb).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function Br(e,s){var a;const r=$r(e,s);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?ln:Zs;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function ab(e){const s=Kt(e),r=Br("chat",s.chat),n=Br("code",s.code),a=Br("terminal",s.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Zt(e,s=document.documentElement){const r=Kt(e),n=ab(r);s.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))s.style.setProperty(a,i);return r}function da(e){const s=Kt(e);try{localStorage.setItem(ml,JSON.stringify(s))}catch{}return s}function ob(){try{const e=localStorage.getItem(ml);if(e)return Kt(JSON.parse(e))}catch{}return is}function ib(){return Zt(ob())}function $s(e,s){var n;const r=e==="chat"?ln:Zs;return((n=r.find(a=>a.id===s))==null?void 0:n.label)||r[0].label}const cb=[{id:"dashboard",path:"/dashboard",icon:t.jsx(ji,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(ls,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(Yr,{}),label:"Settings"}];function lb({children:e}){const s=Is(),r=fa(),n=o.useMemo(()=>cb.map(i=>({...i,active:r.pathname.startsWith(i.path),onSelect:()=>s(i.path)})),[r.pathname,s]),a=o.useMemo(()=>[{id:"docs",label:t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Docs"}),t.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:t.jsx(Si,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:t.jsx(Ni,{}),active:r.pathname==="/about",onSelect:()=>s("/about"),title:"About"}],[r.pathname,s]);return t.jsx(jf,{brand:({collapsed:i})=>t.jsxs(t.Fragment,{children:[t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&t.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:i})=>i?null:t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.11"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:i?"Expand sidebar":"Collapse sidebar",children:[t.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&t.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const db=[{icon:t.jsx(ls,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Ft,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(Ci,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Ct,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(Ys,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(Si,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],ub=[{icon:t.jsx(Cd,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(ji,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(Xr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(vd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(ki,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(jd,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],mb=[{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 fb(){return t.jsxs(kc,{icon:t.jsx(Ni,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:t.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.9.11"]}),children:[t.jsx(Nt,{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(Nt,{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:db.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(Nt,{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:vc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:jc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:wc.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(Nt,{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:ub.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(Nt,{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:mb.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(Nc,{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(Ed,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Wn(e,s,r){return{...e,[s]:r}}function Hn({surface:e,title:s,description:r,value:n,options:a,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:a.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:Br(e,n)})]})]})]})}function pb({value:e,savedValue:s,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:u}){const f=JSON.stringify(e)!==JSON.stringify(s);return t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&t.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&t.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),t.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[t.jsx(Hn,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:ln,onChange:d=>i(Wn(e,"chat",d))}),t.jsx(Hn,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Zs,onChange:d=>i(Wn(e,"code",d))}),t.jsx(Hn,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Zs,onChange:d=>i(Wn(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: ",$s("chat",e.chat.preset)," · Code: ",$s("code",e.code.preset)," · Terminal: ",$s("terminal",e.terminal.preset)]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",$s("chat",is.chat.preset)," / ",$s("code",is.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||!f,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||!f,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 hb(){const{ides:e}=cs(),s=e.find(H=>H.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=jt(),{userName:a}=cs(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[f,d]=o.useState(null),[h,m]=o.useState(is),[j,S]=o.useState(!1),[p,x]=o.useState(""),[v,b]=o.useState(""),[C,A]=o.useState("127.0.0.1"),[y,I]=o.useState(""),[k,w]=o.useState(""),[g,E]=o.useState(""),[T,M]=o.useState(""),[P,K]=o.useState(""),[U,L]=o.useState(!1),R=async()=>{const V=await(await $t("/auth/session")).json();u(V)},z=async()=>{const V=await(await $t("/api/v1/standalone/preferences")).json();d(V),A(V.standaloneBindHost);const Q=Kt(V.standaloneFontPreferences);m(Q),Zt(Q),da(Q)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([R(),z()]).catch(H=>{M(H instanceof Error?H.message:String(H))})},[]),o.useEffect(()=>{Zt(h)},[h]);const $=H=>{const V=H.target.value.trim();s!=null&&s.id&&V!==a&&n(s.id,"set_user_name",{userName:V}).catch(console.error)},[_,Y]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),J=H=>{Y(H);try{localStorage.setItem("adhdev_sound",H?"1":"0")}catch{}},pe=async()=>{x(""),b(""),S(!0);try{const H=Kt(h),V=await $t("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:H})}),Q=await V.json();if(!V.ok)throw new Error((Q==null?void 0:Q.error)||"Failed to save standalone font preferences");const ue=Kt(Q.standaloneFontPreferences);d(Q),m(ue),Zt(ue),da(ue),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(H){x(H instanceof Error?H.message:String(H))}finally{S(!1)}},ae=()=>{const H=Kt(f==null?void 0:f.standaloneFontPreferences);x(""),b(""),m(H),Zt(H)},be=()=>{x(""),b(""),m(is),Zt(is)},ye=async()=>{M(""),K(""),L(!0);try{const H=await $t("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),V=await H.json();if(!H.ok)throw new Error((V==null?void 0:V.error)||"Failed to save standalone network preference");d(V),A(V.standaloneBindHost),K(V.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(H){M(H instanceof Error?H.message:String(H))}finally{L(!1)}},ve=async()=>{if(M(""),K(""),k.trim().length<4){M("Password must be at least 4 characters.");return}if(k!==g){M("New password and confirmation do not match.");return}L(!0);try{const H=await $t("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:k})}),V=await H.json();if(!H.ok)throw new Error((V==null?void 0:V.error)||"Failed to save password");u(V),await z(),I(""),w(""),E(""),K(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),ul()}catch(H){M(H instanceof Error?H.message:String(H))}finally{L(!1)}},Ie=async()=>{M(""),K(""),L(!0);try{const H=await $t("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),V=await H.json();if(!H.ok)throw new Error((V==null?void 0:V.error)||"Failed to clear password");u(V),await z(),I(""),w(""),E(""),K("Standalone password disabled.")}catch(H){M(H instanceof Error?H.message:String(H))}finally{L(!1)}};return t.jsxs(kc,{icon:t.jsx(Yr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(gr,{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(gr,{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(Nt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:t.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[t.jsx("span",{className:"text-text-muted",children:"Version"}),t.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.11"]}),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:(f==null?void 0:f.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:(f==null?void 0:f.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(Nt,{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:C==="127.0.0.1",onChange:()=>A("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:C==="0.0.0.0",onChange:()=>A("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:()=>{ye()},disabled:U,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:U?"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 ",(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),t.jsx(Nt,{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."}),T&&t.jsx(gr,{variant:"error",children:T}),P&&t.jsx(gr,{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:y,onChange:H=>I(H.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:k,onChange:H=>w(H.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:g,onChange:H=>E(H.target.value)})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{ve()},disabled:U,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:U?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&t.jsx("button",{type:"button",onClick:()=>{Ie()},disabled:U,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(Nt,{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(H=>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 ${H.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:H.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:H.type})]},H.type))})}),t.jsx(Nt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(Lf,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Nt,{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(Df,{})]}),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(Ff,{})]}),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(pb,{value:h,savedValue:Kt(f==null?void 0:f.standaloneFontPreferences),saving:j,error:p,notice:v,onChange:m,onSave:()=>{pe()},onResetToSaved:ae,onResetToDefaults:be})]}),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(Vf,{})]})]})}),t.jsx(Nt,{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(Mf,{}),t.jsx(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Dd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:_,onChange:J})]})}),t.jsx(Nt,{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(yd,{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:H=>c(H.target.value),onBlur:$,onKeyDown:H=>{H.key==="Enter"&&H.currentTarget.blur()}})]})})})]})}vf();Wf();ib();const xb=yi({baseUrl:"",getToken:Ya});function bb({children:e}){const[s,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[f,d]=o.useState(!1),h=async()=>{a(!0),u("");try{const S=await(await $t("/auth/session")).json();r(S)}catch(j){u(j instanceof Error?j.message:String(j))}finally{a(!1)}};o.useEffect(()=>{h()},[]),o.useEffect(()=>{if(!s||s.required&&!s.authenticated)return;let j=!1;return(async()=>{try{const S=await $t("/api/v1/standalone/preferences");if(!S.ok)return;const p=await S.json();if(j)return;const x=Kt(p.standaloneFontPreferences);Zt(x),da(x)}catch{}})(),()=>{j=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const m=async j=>{j.preventDefault(),d(!0),u("");try{const S=await $t("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),p=await S.json();if(!S.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),ul()}catch(S){u(S instanceof Error?S.message:String(S))}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:m,children:[t.jsx("input",{type:"password",value:i,onChange:j=>c(j.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:f||!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:f?"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 di(){const{ides:e,initialLoaded:s}=cs();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(zn,{to:`/machines/${r.id}`,replace:!0}):t.jsx(zn,{to:"/dashboard",replace:!0})}function gb(){const e=o.useMemo(()=>({sendCommand:Er,sendData:la,sendPtyInput:Qx}),[]);return t.jsx(ql,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(pd,{client:xb,children:t.jsx(bb,{children:t.jsx(sb,{children:t.jsx(xd,{value:e,children:t.jsx(lb,{children:t.jsxs(Yl,{children:[t.jsx(Yt,{path:"/dashboard",element:t.jsx(fx,{})}),t.jsx(Yt,{path:"/machine",element:t.jsx(di,{})}),t.jsx(Yt,{path:"/machines/:id",element:t.jsx(zx,{})}),t.jsx(Yt,{path:"/machines",element:t.jsx(di,{})}),t.jsx(Yt,{path:"/about",element:t.jsx(fb,{})}),t.jsx(Yt,{path:"/settings",element:t.jsx(hb,{})}),t.jsx(Yt,{path:"*",element:t.jsx(zn,{to:"/dashboard",replace:!0})})]})})})})})})})}Bm({connectionManager:Ot});Xl(document.getElementById("root")).render(t.jsx(gb,{}));
|