@adhdev/daemon-standalone 0.8.81 → 0.8.82

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,72 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-2SYILvaH.js","assets/vendor-BRZ4K-AC.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
+ var $l=Object.defineProperty;var Bl=(e,s,r)=>s in e?$l(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var qe=(e,s,r)=>Bl(e,typeof s!="symbol"?s+"":s,r);import{r as o,j as t,M as fa,a as ha,b as gi,c as yi,u as Fs,R as rt,d as ir,t as Kl,e as Wl,D as Ol,f as Xn,g as Qn,h as xa,i as Hl,k as Ul,B as Fl,l as zl,m as os,N as Jn,n as Vl}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 Gl(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 Ds=Gl();function uo(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 Yl(e,s){if(!e)return s??null;if(!s)return e??null;const r=Array.isArray(e.messages)&&e.messages.length>0?e.messages:s.messages,n=e.activeModal||(e.status==="waiting_approval"?s.activeModal:null);return{...s,...e,messages:r,activeModal:n,inputContent:e.inputContent??s.inputContent}}function er(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:Yl(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),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 mo(e,s){if(!(s!=null&&s.length))return e;if(!(e!=null&&e.length))return s;const r=new Map(e.map(n=>[n.id,n]));return s.map(n=>{const a=r.get(n.id);return a?er(n,a):n})}const vi=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}),wi=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function po(e){var r,n;let s=0;return"activeChat"in e&&(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 jn(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 Qr(e){return Array.isArray(e)?e.map(Qr):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([s])=>s!=="timestamp"&&s!=="_lastUpdate").sort(([s],[r])=>s.localeCompare(r)).map(([s,r])=>[s,Qr(r)]))}function Xl(e,s){try{return JSON.stringify(Qr(e))===JSON.stringify(Qr(s))}catch{return!1}}function Sr(e,s,r){return Xl(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function Ql(e,s,r){var u,p,m,f,w,k,A;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return e.map(d=>({...d,_lastUpdate:n}));const i=new Map;for(const d of s)i.set(d.id,d);for(const d of e){const b=i.get(d.id);if(!b){i.set(d.id,{...d,_lastUpdate:n});continue}const y=po(d),h=po(b);if(y>h){const N=(u=d.chats)!=null&&u.length?d.chats:b.chats,_=mo(b.childSessions,d.childSessions),g=jn(b,d,{...b,...d,chats:N,childSessions:_,_lastUpdate:n});i.set(d.id,Sr(b,g,n))}else if(y<h){const N={};if(d.status&&d.status!==b.status&&(N.status=d.status),d.cdpConnected!==void 0&&(N.cdpConnected=d.cdpConnected),(p=d.chats)!=null&&p.length&&!((m=b.chats)!=null&&m.length)&&(N.chats=d.chats),d.machineNickname!==void 0&&d.machineNickname!==b.machineNickname&&(N.machineNickname=d.machineNickname),d.version!==void 0&&(N.version=d.version),d.serverVersion!==void 0&&(N.serverVersion=d.serverVersion),d.versionMismatch===!0&&(N.versionMismatch=!0),Object.keys(N).length>0){const _=jn(b,d,{...b,...N,_lastUpdate:b._lastUpdate});i.set(d.id,Sr(b,_,n))}else Sr(b,{...b,_lastUpdate:b._lastUpdate},n)}else{const N=d.timestamp||n,_=b._lastUpdate||b.timestamp||0;if(N>=_){const g=(f=d.chats)!=null&&f.length?d.chats:b.chats,I=mo(b.childSessions,d.childSessions),j=jn(b,d,{...b,...d,chats:g,childSessions:I,_lastUpdate:n});i.set(d.id,Sr(b,j,n))}else(w=d.chats)!=null&&w.length&&!((k=b.chats)!=null&&k.length)&&i.set(d.id,{...b,chats:d.chats})}}const c=new Set(e.map(d=>d.id)),l=new Set;for(const d of e){const b=d.daemonId||((A=d.id)==null?void 0:A.split(":")[0]);b&&l.add(b)}for(const[d,b]of i){const y=b.daemonId||d.split(":")[0];if(!l.has(y))continue;if(a.has(y)&&!c.has(d)){i.delete(d);continue}const h=n-(b._lastUpdate||b.timestamp||0);(b.transport==="pty"&&!c.has(d)&&h>1e4||b.transport==="acp"&&!c.has(d)&&h>1e4||b.transport==="cdp-page"&&!c.has(d)&&h>3e4)&&i.delete(d)}for(const[d,b]of i)n-(b._lastUpdate||b.timestamp||0)>3e5&&b.status!=="online"&&i.delete(d);return Array.from(i.values())}function Jl(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 Zl({children:e,connectionOverrides:s}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[u,p]=o.useState(void 0),m=o.useRef(r);o.useEffect(()=>{m.current=r},[r]);const f=o.useCallback((y,h)=>{n(N=>{let _=!1;const g=N.map(I=>I.id!==y||I.chats===h?I:(_=!0,{...I,chats:h}));return _?g:N})},[]),w=o.useCallback((y,h)=>{n(N=>{const _=N.length===0?y:Ql(y,N,h),g=!Jl(N,_);return g&&Ds.record({kind:"dashboard.entries_applied",payload:{incoming:uo(y),next:uo(_)}}),g?_:N})},[]),k=o.useCallback(()=>i(!0),[]),A=o.useMemo(()=>({injectEntries:w,markLoaded:k,getIdes:()=>m.current}),[w,k]),d=s,b=o.useMemo(()=>({ides:r,updateRouteChats:f,initialLoaded:a,toasts:c,setToasts:l,wsStatus:(d==null?void 0:d.wsStatus)??"connected",isConnected:(d==null?void 0:d.isConnected)??!0,connectionStates:(d==null?void 0:d.connectionStates)??{},connectionTransports:(d==null?void 0:d.connectionTransports)??{},showReconnected:(d==null?void 0:d.showReconnected)??!1,retryConnection:d==null?void 0:d.retryConnection,isP2PActive:(d==null?void 0:d.isP2PActive)??!1,p2pStates:(d==null?void 0:d.p2pStates)??{},userRole:d==null?void 0:d.userRole,userName:u,setUserName:p}),[r,f,a,c,d==null?void 0:d.wsStatus,d==null?void 0:d.isConnected,d==null?void 0:d.connectionStates,d==null?void 0:d.connectionTransports,d==null?void 0:d.showReconnected,d==null?void 0:d.retryConnection,d==null?void 0:d.isP2PActive,d==null?void 0:d.p2pStates,d==null?void 0:d.userRole,u]);return t.jsx(wi.Provider,{value:A,children:t.jsx(vi.Provider,{value:b,children:e})})}function gs(){return o.useContext(vi)}function Jr(){return o.useContext(wi)}function ji(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(),p=a(l),m=l.startsWith("http")?new URL(p):new URL(p,typeof window<"u"?window.location.origin:"http://localhost");return u&&m.searchParams.set("token",u),!l.startsWith("http")&&!s?`${m.pathname}${m.search}${m.hash}`:m.toString()}async function c(l,u={}){const p={"Content-Type":"application/json",...u.headers||{}},m=r==null?void 0:r();m&&(p.Authorization=`Bearer ${m}`);const f=a(l),w=new AbortController,k=setTimeout(()=>w.abort(),15e3);try{const A=await fetch(f,{...u,headers:p,signal:w.signal});if(A.status===401)throw n==null||n(),new Error("Unauthorized");if(!A.ok){const d=await A.json().catch(()=>({error:A.statusText}));throw new Error(d.error||`API Error: ${A.status}`)}return A.json()}finally{clearTimeout(k)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,u,p={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:u,payload:p})}),execTerminal:(l,u,p)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:p})}),sendAgentMessage:(l,u,p)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:p})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,u,p)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:u,action:p?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,u,p={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:p})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const ed=ji({baseUrl:"http://localhost:3847"}),td=o.createContext(ed);function sd({client:e,children:s}){return t.jsx(td.Provider,{value:e,children:s})}const rd={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},ki=o.createContext(rd);function nd({value:e,children:s}){return t.jsx(ki.Provider,{value:e,children:s})}function Pt(){return o.useContext(ki)}function ad(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 od(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Si(e){return e?ad([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),od(e.content)]):""}const We={size:18};function Ni({size:e=We.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 ba({size:e=We.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 qt({size:e=We.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 ga({size:e=We.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 id({size:e=We.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 cd({size:e=We.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 Ci({size:e=We.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 ld({size:e=We.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 cn({size:e=We.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 Ii({size:e=We.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 dd({size:e=We.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 Yt({size:e=We.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Rt({size:e=We.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 ya({size:e=We.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 ud({size:e=We.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 Es({size:e=We.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 zs({size:e=We.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 ys({size:e=We.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 cr({size:e=We.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 Ai({size:e=We.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 Mi({size:e=We.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 Ti({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function md({size:e=We.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 ln({size:e=We.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 pd({size:e=We.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 va({size:e=We.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 fd({size:e=We.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 It({size:e=We.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 hd({size:e=We.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 xd({size:e=We.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 bd({size:e=We.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 gd({size:e=We.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 dn({size:e=We.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 yd({size:e=We.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 vd({size:e=We.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 wd({size:e=We.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 jd({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),t.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function kd({size:e=We.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 Sd({size:e=We.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 Nd({size:e=We.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 Cd({size:e=We.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 Id({size:e=We.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 Ad({size:e=We.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 Md({size:e=We.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 Td({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),t.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),t.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}function fo(e){return!!e&&typeof e=="object"&&"text"in e}function wa(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:fo(i)?String(i.text||""):"").join(r):fo(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function $s(e){return wa(e,{normalizeWhitespace:!0})}const kn=new Map;function ho(e,s){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(s||""):!0}function Ld(e){if(!Array.isArray(e)||e.length===0)return"0:empty";const s=e[e.length-1];return`${e.length}:${Si(s)}`}function xo(e,s){const r=Math.max(0,e.scrollHeight-e.clientHeight-s.fromBottom);e.scrollTop=Number.isFinite(r)?r:s.top}function Li(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function _d(e,s,r){return Number(e.receivedAt||r[Ms(e,s)]||0)||0}function _i(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Rd(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function Nr(e,s){if(!e)return s;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||s}catch{return e.split(/[\\/]/).filter(Boolean).pop()||s}}function Sn(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 bo(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):_i(e)?t.jsx(fa,{remarkPlugins:[ha,gi,yi],children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function Cr({parts:e,renderAsPreformatted:s}){return t.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return t.jsx("div",{children:bo(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const a=Sn(r);return a?t.jsx("img",{src:a,alt:Nr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=Sn(r);return a?t.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=Sn(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:Nr(r.uri,"video")},`video-link-${n}`):null}if(r.type==="resource_link")return r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:r.name||Nr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=Nr(r.resource.uri,"resource");if(r.resource.text)return t.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[t.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),bo(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 Ms(e,s){const r=e,n=wa(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 Pd=o.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(fa,{remarkPlugins:[ha],children:s.text}),t.jsx("span",{className:"action-time",children:Li(s.timestamp)})]})},(e,s)=>e.log===s.log),Dd=o.memo(function({message:s,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var I,j,v;const u=(s.role||"").toLowerCase(),p=u==="user"||u==="human",m=s.kind||(u==="tool"?"tool":"standard"),f=Rd(s.content)?s.content:null,w=!!(f!=null&&f.some(x=>x.type!=="text")),k=wa(s.content,{joiner:`
4
+ `});if(m==="thought"){const x=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(bd,{size:13}),t.jsx("span",{children:x})]}),t.jsx("div",{className:"chat-msg-body",children:k})]})}if(m==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),w&&f?t.jsx("div",{className:"tool-text w-full",children:t.jsx(Cr,{parts:f,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:k})]});if(m==="terminal"){const x=(j=s.meta)!=null&&j.isRunning?"⏳":"✅",$=typeof((v=s.meta)==null?void 0:v.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:x}),t.jsx("span",{children:$})]}),w&&f?t.jsx("div",{className:"chat-msg-body",children:t.jsx(Cr,{parts:f,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:k})]})}if(m==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:w&&f?t.jsx(Cr,{parts:f,renderAsPreformatted:!1}):k.slice(0,100)});const A=s.meta,b=(typeof(A==null?void 0:A.renderMode)=="string"?A.renderMode.trim():"")==="preformatted",y=k,h=!1,N=y,_=b,g=!_&&_i(N);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${p?"self-end":"self-start"}`,children:(y||w||p)&&t.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${y||w?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:p?a||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:Li(r)})]}),(y||w)&&t.jsx("div",{className:"chat-markdown",children:w&&f?t.jsx(Cr,{parts:f,renderAsPreformatted:_}):_?t.jsx("pre",{className:"chat-preformatted",children:N}):g?t.jsx(fa,{remarkPlugins:[ha,gi,yi],children:N}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:N})}),h]})})},(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),Ed=o.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:u={},emptyState:p,onLoadMore:m,isLoadingMore:f,hasMoreHistory:w,hiddenLiveCount:k=0,loadError:A,scrollToBottomRequestNonce:d},b){const y=o.useRef(null),h=o.useRef(null),N=o.useRef(null),_=o.useRef(0),g=o.useRef(""),I=o.useRef(!1),j=o.useRef(null),v=o.useRef(!1),x=o.useRef(null),$=o.useRef(!1),[M,L]=o.useState(new Set),T=o.useRef(!1),K=o.useRef(!1),U=()=>{const X=y.current;return X?X.scrollHeight-X.scrollTop-X.clientHeight<200:!0},C=o.useCallback((X="auto")=>{const he=y.current;he&&he.scrollTo({top:he.scrollHeight,behavior:X})},[]),R=o.useCallback(()=>{var xe;const X=y.current,he=(xe=window.getSelection)==null?void 0:xe.call(window);if(!X||!he||he.rangeCount===0||he.isCollapsed){$.current=!1;return}const ke=he.anchorNode,ie=he.focusNode;$.current=!!(ke&&ie&&X.contains(ke)&&X.contains(ie))},[]),O=Ld(s),S=o.useCallback(()=>{const X=y.current;!X||!l||kn.set(l,{top:X.scrollTop,fromBottom:Math.max(0,X.scrollHeight-X.scrollTop-X.clientHeight),messageFingerprint:O})},[l,O]),D=o.useCallback((X="auto")=>{j.current!=null&&cancelAnimationFrame(j.current),j.current=requestAnimationFrame(()=>{j.current=null,C(X)})},[C]);o.useEffect(()=>{const X=!I.current,he=g.current!==l;if(g.current=l,X||he){if(I.current=!0,T.current=!1,v.current=!0,!$.current){const ie=l?kn.get(l):null;ie&&ho(ie,O)?requestAnimationFrame(()=>{const xe=y.current;xe&&(xo(xe,ie),K.current=!0)}):D("auto")}_.current=s.length;return}s.length>_.current?!T.current&&!$.current&&D("auto"):U()&&!T.current&&!$.current&&D("auto"),_.current=s.length},[O,l,c,s.length,D]),o.useEffect(()=>{d&&(T.current=!1,v.current=!0,K.current=!0,x.current!=null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{v.current=!1,x.current=null},180),$.current||D("auto"))},[D,d]),o.useEffect(()=>()=>{S(),j.current!=null&&cancelAnimationFrame(j.current),x.current!=null&&window.clearTimeout(x.current)},[S]),o.useEffect(()=>{const X=h.current;if(!X)return;const he=()=>{x.current!=null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{v.current=!1,x.current=null},180)},ke=new ResizeObserver(()=>{v.current&&($.current||(D("auto"),he()))});return ke.observe(X),()=>{ke.disconnect(),x.current!=null&&(window.clearTimeout(x.current),x.current=null)}},[D,l]),o.useImperativeHandle(b,()=>({scrollToBottom:(X="smooth")=>{C(X)}}),[C]),o.useEffect(()=>{const X=y.current;if(!X)return;let he;const ke=()=>{clearTimeout(he),he=setTimeout(()=>{T.current=!U(),S()},50)};return X.addEventListener("scroll",ke,{passive:!0}),()=>{X.removeEventListener("scroll",ke),clearTimeout(he)}},[S]),o.useEffect(()=>(document.addEventListener("selectionchange",R),()=>document.removeEventListener("selectionchange",R)),[R]);const G=o.useRef(0),q=o.useRef(!1);o.useEffect(()=>{const X=y.current;if(!X||!q.current||G.current===0)return;const he=X.scrollHeight-G.current;he>0&&(X.scrollTop=he),S(),G.current=0,q.current=!1},[s.length,S]),o.useEffect(()=>{if(K.current||!l)return;const X=kn.get(l),he=y.current;if(!(!X||!he)){if(!ho(X,O)){C("auto"),K.current=!0;return}xo(he,X),K.current=!0}},[l,O,s.length,C]);const H=()=>{const X=y.current;X&&(G.current=X.scrollHeight),q.current=!0,m==null||m()},re=o.useMemo(()=>{const X=s.map((xe,pe)=>({type:"message",data:xe,index:pe,ts:_d(xe,pe,u)}));if(!r||r.length===0)return X;const he=[...r].sort((xe,pe)=>xe.timestamp-pe.timestamp).map((xe,pe)=>({type:"action",data:xe,index:pe,ts:xe.timestamp})),ke=[];let ie=0;for(const xe of X){for(;ie<he.length&&xe.ts>0&&he[ie].ts<xe.ts;)ke.push(he[ie++]);ke.push(xe)}for(;ie<he.length;)ke.push(he[ie++]);return ke},[s,r,u]),ae=k>0||!!w,Ne=k>0?`↑ Show ${Math.min(k,80)} earlier messages${k>80?` (${k} hidden)`:""}`:A?`↻ ${A}`:"↑ Load older messages";return t.jsx("div",{ref:y,"data-chat-scroll":!0,className:"chat-container",children:t.jsxs("div",{ref:h,className:"chat-container-content",children:[f&&t.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),ae&&!f&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{onClick:H,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${A&&k===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:Ne})}),re.length===0&&!ae&&(p||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),re.map(X=>{if(X.type==="action"){const ge=X.data;return t.jsx(Pd,{log:ge},`action-${X.index}`)}const he=X.data,ke=X.index,ie=Ms(he,ke),xe=he.receivedAt||u[ie],pe=`${l}-${ie}`,V=M.has(pe);return t.jsx(Dd,{message:he,receivedAt:xe,agentName:n,userName:a,isCliMode:i,isTextExpanded:V,onToggleTextExpanded:()=>L(ge=>{const ne=new Set(ge);return V?ne.delete(pe):ne.add(pe),ne})},`msg-${ie}`)}),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:N})]})})}),$d=o.memo(Ed,(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),Bd="modulepreload",Kd=function(e){return"/"+e},go={},Wd=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=Kd(u),u in go)return;go[u]=!0;const p=u.endsWith(".css"),m=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${m}`))return;const f=document.createElement("link");if(f.rel=p?"stylesheet":Bd,p||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),p)return new Promise((w,k)=>{f.addEventListener("load",w),f.addEventListener("error",()=>k(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 yo=!1;const Ri=o.forwardRef(({onInput:e,fontSize:s=13,readOnly:r=!1,sizingMode:n="measured"},a)=>{const i=o.useRef(null),[c,l]=o.useState(null),u=o.useRef([]),p=o.useRef(!1),m=o.useRef(!1),f=o.useRef(!1),w=()=>{const k=i.current;if(k){p.current&&(k.clear(),p.current=!1);for(const A of u.current)k.write(A);u.current=[],m.current&&(k.fit(),m.current=!1),f.current&&(k.bumpResize(),f.current=!1)}};return o.useImperativeHandle(a,()=>({write:k=>{i.current?i.current.write(k):u.current.push(k)},clear:()=>{i.current?i.current.clear():(u.current=[],p.current=!0)},reset:()=>{i.current&&typeof i.current.reset=="function"?i.current.reset():(u.current=[],p.current=!0)},resize:(k,A)=>{i.current&&typeof i.current.resize=="function"&&i.current.resize(k,A)},fit:()=>{i.current?i.current.fit():m.current=!0},bumpResize:()=>{i.current?i.current.bumpResize():f.current=!0}}),[]),o.useEffect(()=>{if(!c)return;const k=requestAnimationFrame(()=>{w()});return()=>cancelAnimationFrame(k)},[c]),o.useEffect(()=>{let k=!1;return Wd(()=>import("./terminal-2SYILvaH.js"),__vite__mapDeps([0,1,2])).then(A=>{yo||(yo=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),k||l(()=>A.GhosttyTerminalView)}).catch(A=>{console.error("[CliTerminal] failed to load terminal renderer",A)}),()=>{k=!0}},[]),c?t.jsx(c,{ref:i,onInput:e,fontSize:s,readOnly:r,sizingMode:n,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 Ir({label:e,value:s,sub:r,icon:n}){return t.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[t.jsx("span",{className:"text-base flex items-center",children:n}),t.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),t.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:s}),r&&t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function vo({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 Od({cursorPos:e,viewportRef:s,imgRef:r}){var h;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(h=s.current)==null?void 0:h.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,u=c/l,p=a.width/a.height;let m,f,w,k;u>p?(m=a.width,f=a.width/u,w=0,k=(a.height-f)/2):(f=a.height,m=a.height*u,w=(a.width-m)/2,k=0);const A=a.left-i.left+w+m*e.nx,d=a.top-i.top+k+f*e.ny,b=Math.max(8,Math.min(i.width-8,A)),y=Math.max(8,Math.min(i.height-8,d));return t.jsxs("div",{style:{position:"absolute",left:b-8,top:y-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 Hd({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:u,isConnActive:p,zoom:m,isMobile:f,mobileFillZoom:w,onZoomOut:k,onZoomReset:A,onZoomIn:d,transportType:b,screenshotUsage:y,lastActionStatus:h}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:N=>N.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[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(N=>!N),i(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children: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:N=>N.stopPropagation(),onChange:N=>l(N.target.value),onKeyDown:N=>{u(N)},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(N=>!N),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children: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:p?"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:p?"#22c55e":"#eab308",boxShadow:p?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:p?"#22c55e":"#eab308"},children:p?"Connected":"WS"})]}),m>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(m*100),"%"]}),b==="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"}),b==="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"}),y&&y.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:y.budgetExhausted?"#ef4444":"#c4b5fd",background:y.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:y.budgetExhausted?"TURN blocked":`TURN ${y.dailyUsedMinutes}/${y.dailyBudgetMinutes}m`}),h&&t.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:h})]})]}),a&&t.jsxs("div",{onTouchStart:N=>N.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[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: ",m<=(f?w:1)+.01?f?"FILL":"FIT":`${Math.round(m*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:N=>{N.stopPropagation(),k()},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:N=>{N.stopPropagation(),A()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:f?"FILL":"FIT"}),t.jsx("button",{onClick:N=>{N.stopPropagation(),d()},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 Ud({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 Fd(){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 wo(e){return e==null||typeof e=="number"||typeof e=="boolean"?e:typeof e=="string"?e.length>64?`${e.slice(0,61)}...`:e:Array.isArray(e)?`Array(${e.length})`:typeof e=="object"?"Object":typeof e}function pr(e,s){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!Fd())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,wo(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,wo(s[c])]))}),r.current=s})}function zd({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:u,setPanX:p,setPanY:m,setZoom:f,lastWheelTimeRef:w,onAction:k,setLastActionStatus:A,spawnRippleFromNormalized:d,clampPan:b,isMobile:y,mobileFillZoom:h}){const[N,_]=o.useState(null),g=o.useRef(null),I=o.useRef(null),j=o.useRef(null),v=o.useRef(!1),x=o.useRef(null),$=o.useRef(0),M=o.useRef(null),L=o.useRef(1),T=o.useRef({x:0,y:0}),K=o.useRef(!1),U=o.useRef(n),C=o.useRef(k),R=30,O=550,S=18,D=60,G=400,q=12,H=()=>{if(g.current)return;const Ne={nx:.5,ny:.5};g.current=Ne,_(Ne)};return o.useEffect(()=>{U.current=n,n==="mouse"&&H()},[n]),o.useEffect(()=>{C.current=k},[k]),o.useEffect(()=>{const Ne=e.current;if(!Ne)return;const X=V=>{if(!r.current)return null;const ge=r.current.getBoundingClientRect();return!ge.width||!ge.height?null:{nx:Math.max(0,Math.min(1,(V.clientX-ge.left)/ge.width)),ny:Math.max(0,Math.min(1,(V.clientY-ge.top)/ge.height))}},he=(V,ge)=>{if(!r.current)return{dnx:0,dny:0};const ne=r.current,ce=ne.getBoundingClientRect(),Z=ne.naturalWidth||ce.width,le=ne.naturalHeight||ce.height,ee=Z/le,ye=ce.width/ce.height;let be,B;return ee>ye?(be=ce.width,B=ce.width/ee):(B=ce.height,be=ce.height*ee),{dnx:V/be,dny:ge/B}},ke=(V,ge,ne)=>{if(ne<=1.05)return;const ce=-(V-.5)*100,Z=-(ge-.5)*100,le=b(ce,Z,ne);(Math.abs(le.x-l.current)>.1||Math.abs(le.y-u.current)>.1)&&(p(le.x),m(le.y),l.current=le.x,u.current=le.y)},ie=V=>{const ge=s.current;if(ge&&V.target instanceof Node&&ge.contains(V.target))V.preventDefault();else return;if(V.touches.length===1){const ne=V.touches[0];I.current={x:ne.clientX,y:ne.clientY,time:Date.now()},j.current={x:ne.clientX,y:ne.clientY},K.current||(v.current=!1),x.current=setTimeout(()=>{if(!v.current&&!K.current)if(v.current=!0,U.current==="mouse"){const ce=g.current||{nx:.5,ny:.5};A("Right Click"),d(ce.nx,ce.ny,"right"),C.current("input_click",{...ce,button:"right"}).catch(()=>{})}else{const ce=X(ne);ce&&(A("Right Click"),d(ce.nx,ce.ny,"right"),C.current("input_click",{...ce,button:"right"}).catch(()=>{}))}},500);return}if(V.touches.length===2){x.current&&clearTimeout(x.current),v.current=!0,K.current=!0;const ne=V.touches[1].clientX-V.touches[0].clientX,ce=V.touches[1].clientY-V.touches[0].clientY;M.current=Math.sqrt(ne*ne+ce*ce),L.current=c.current,T.current={x:(V.touches[0].clientX+V.touches[1].clientX)/2,y:(V.touches[0].clientY+V.touches[1].clientY)/2}}},xe=V=>{const ge=s.current;if(ge&&V.target instanceof Node&&ge.contains(V.target)&&V.preventDefault(),V.touches.length===1&&j.current){const ne=V.touches[0],ce=ne.clientX-j.current.x,Z=ne.clientY-j.current.y;if(!v.current&&I.current){const le=ne.clientX-I.current.x,ee=ne.clientY-I.current.y;Math.sqrt(le*le+ee*ee)>8&&(v.current=!0,x.current&&clearTimeout(x.current))}if(v.current)if(U.current==="mouse"){const le=he(ce,Z),ee=g.current||{nx:.5,ny:.5},ye=Math.max(0,Math.min(1,ee.nx+le.dnx)),be=Math.max(0,Math.min(1,ee.ny+le.dny));g.current={nx:ye,ny:be},_({nx:ye,ny:be}),A(`Cursor: ${Math.round(ye*100)}%, ${Math.round(be*100)}%`),ke(ye,be,c.current);const B=Date.now();B-w.current>=30&&(w.current=B,C.current("input_mouseMoved",{nx:ye,ny:be}).catch(()=>{}))}else if(c.current>1){const le=s.current;if(le){const ee=le.clientWidth,ye=le.clientHeight,be=l.current+ce/ee*100,B=u.current+Z/ye*100,ve=b(be,B,c.current);p(ve.x),m(ve.y),l.current=ve.x,u.current=ve.y}}else{const le=X(ne);if(le){const ee=Date.now();ee-w.current>=40&&(w.current=ee,A("Scroll"),C.current("input_wheel",{nx:le.nx,ny:le.ny,deltaX:Math.round(-ce*2.5),deltaY:Math.round(-Z*2.5)}).catch(()=>{}))}}j.current={x:ne.clientX,y:ne.clientY};return}if(V.touches.length===2&&M.current!==null){const ne=V.touches[1].clientX-V.touches[0].clientX,ce=V.touches[1].clientY-V.touches[0].clientY,le=Math.sqrt(ne*ne+ce*ce)/M.current,ee=(V.touches[0].clientX+V.touches[1].clientX)/2,ye=(V.touches[0].clientY+V.touches[1].clientY)/2,be=ee-T.current.x,B=ye-T.current.y,ve=Math.abs(le-1)>.03;if(U.current==="mouse"){if(ve){const Ce=Math.max(i,Math.min(5,L.current*le));f(Ce),c.current=Ce}else if(Math.abs(be)>2||Math.abs(B)>2){const Ce=g.current||{nx:.5,ny:.5},Ae=Date.now();Ae-w.current>=30&&(w.current=Ae,A("Scroll"),C.current("input_wheel",{nx:Ce.nx,ny:Ce.ny,deltaX:Math.round(-be*3),deltaY:Math.round(-B*3)}).catch(()=>{}))}}else{const Ce=Math.max(i,Math.min(5,L.current*le));f(Ce),c.current=Ce;const Ae=s.current;if(Ae&&Ce>1){const Q=Ae.clientWidth,Pe=Ae.clientHeight,He=l.current+be/Q*100,$e=u.current+B/Pe*100,Be=b(He,$e,Ce);p(Be.x),m(Be.y),l.current=Be.x,u.current=Be.y}}T.current={x:ee,y:ye}}},pe=V=>{var ge;if(x.current&&clearTimeout(x.current),M.current=null,V.touches.length===1&&K.current){const ne=V.touches[0];I.current={x:ne.clientX,y:ne.clientY,time:Date.now()},j.current={x:ne.clientX,y:ne.clientY},v.current=!0;return}if(V.touches.length===0){if(K.current){K.current=!1,v.current=!1;return}if(V.changedTouches.length===1){const ne=V.changedTouches[0],ce=Date.now(),Z=ce-(((ge=I.current)==null?void 0:ge.time)||0),le=I.current?ne.clientX-I.current.x:0,ee=I.current?ne.clientY-I.current.y:0,ye=Math.sqrt(le*le+ee*ee);if(U.current==="mouse"){if(Z<R||Z>O||ye>S){v.current=!1;return}const be=g.current||X(ne);be&&(A(`Click: ${Math.round(be.nx*100)}%, ${Math.round(be.ny*100)}%`),d(be.nx,be.ny,"left"),C.current("input_click",{...be}).catch(()=>{}))}else{if(v.current){v.current=!1;return}if(Z<D||Z>G||ye>q){v.current=!1;return}const be=X(ne);if(!be)return;ce-$.current<300?(A("Double tap"),d(be.nx,be.ny,"double"),C.current("input_click",{...be,clickCount:2}).catch(()=>{}),$.current=0):(A(`Tap: ${Math.round(be.nx*100)}%, ${Math.round(be.ny*100)}%`),d(be.nx,be.ny,"left"),C.current("input_click",{...be}).catch(()=>{}),$.current=ce)}}v.current=!1}};return Ne.addEventListener("touchstart",ie,{passive:!1}),Ne.addEventListener("touchmove",xe,{passive:!1}),Ne.addEventListener("touchend",pe,{passive:!1}),()=>{Ne.removeEventListener("touchstart",ie),Ne.removeEventListener("touchmove",xe),Ne.removeEventListener("touchend",pe),x.current&&clearTimeout(x.current)}},[e,s,r,i,c,l,u,p,m,f,w,A,d,b]),{cursorPos:N,cursorPosRef:g,handleToggleInputMode:()=>{a(Ne=>{const X=Ne==="touch"?"mouse":"touch";return X==="mouse"&&H(),X})},handleZoomReset:()=>{const Ne=y?h:1;f(Ne),c.current=Ne,p(0),m(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),[p,m]=o.useState(null),[f,w]=o.useState(""),[,k]=o.useState(!1),[A,d]=o.useState([]),b=o.useRef(0),[y,h]=o.useState(!1),[N,_]=o.useState(!1),g=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[I,j]=o.useState(g?"mouse":"touch"),[v,x]=o.useState(1),$=o.useRef(!1),[M,L]=o.useState(1),[T,K]=o.useState(0),[U,C]=o.useState(0);pr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:I,zoom:M,panX:T,panY:U,isMenuOpen:y,isImeOpen:N});const R=o.useRef(0),O=o.useRef(M),S=o.useRef(T),D=o.useRef(U);o.useEffect(()=>{O.current=M},[M]),o.useEffect(()=>{S.current=T},[T]),o.useEffect(()=>{D.current=U},[U]),o.useEffect(()=>{var Z;(Z=c.current)==null||Z.focus()},[]);const G=r==="connected",q=n,H=G?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",re=G?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!g||$.current||!q)return;const Z=u.current,le=l.current;if(!Z||!le)return;const ee=()=>{const ye=le.clientWidth,be=le.clientHeight,B=Z.naturalWidth,ve=Z.naturalHeight;if(!B||!ve||!ye||!be)return;const Ce=Math.min(ye/B,be/ve),Q=Math.max(ye/B,be/ve)/Ce;Q>1.01&&(x(Q),L(Q),O.current=Q),$.current=!0};Z.complete&&Z.naturalWidth?ee():Z.addEventListener("load",ee,{once:!0})},[q,g]);const ae=.5;o.useEffect(()=>{M<=ae&&(K(0),C(0))},[M,ae]);const Ne=(Z,le,ee)=>{if(ee<=ae)return{x:0,y:0};const ye=(ee-1)/(2*ee)*100,be=(ee-1)/(2*ee)*100;return{x:Math.max(-ye,Math.min(ye,Z)),y:Math.max(-be,Math.min(be,le))}},X=(Z,le)=>{if(!u.current)return null;const ee=u.current.getBoundingClientRect();return!ee.width||!ee.height?null:{nx:Math.max(0,Math.min(1,(Z-ee.left)/ee.width)),ny:Math.max(0,Math.min(1,(le-ee.top)/ee.height))}},he=(Z,le,ee)=>{const ye=l.current;if(!ye)return;const be=ye.getBoundingClientRect(),B=++b.current;d(ve=>[...ve,{id:B,x:Z-be.left,y:le-be.top,type:ee}]),setTimeout(()=>d(ve=>ve.filter(Ce=>Ce.id!==B)),600)},ke=(Z,le,ee)=>{const ye=u.current,be=l.current;if(!ye||!be)return;const B=ye.getBoundingClientRect(),ve=be.getBoundingClientRect(),Ce=ye.naturalWidth||B.width,Ae=ye.naturalHeight||B.height,Q=Ce/Ae,Pe=B.width/B.height;let He,$e,Be,Ye;Q>Pe?(He=B.width,$e=B.width/Q,Be=0,Ye=(B.height-$e)/2):($e=B.height,He=B.height*Q,Be=(B.width-He)/2,Ye=0);const Ve=B.left-ve.left+Be+He*Z,ut=B.top-ve.top+Ye+$e*le,at=++b.current;d(pt=>[...pt,{id:at,x:Ve,y:ut,type:ee}]),setTimeout(()=>d(pt=>pt.filter(ze=>ze.id!==at)),600)},ie=async Z=>{var ee;const le=X(Z.clientX,Z.clientY);if(le){m(`Click: ${Math.round(le.nx*100)}%, ${Math.round(le.ny*100)}%`),he(Z.clientX,Z.clientY,"left"),(ee=c.current)==null||ee.focus();try{const ye=await e("input_click",{nx:le.nx,ny:le.ny});ye!=null&&ye.success||s(`❌ Click failed: ${ye==null?void 0:ye.error}`)}catch(ye){s(`❌ Click error: ${ye.message||ye}`)}}},xe=async(Z,le,ee,ye=0)=>{try{await e("input_key",{type:ee?"char":"keyDown",key:Z,code:le,text:ee?Z:void 0,unmodifiedText:ee?Z:void 0,modifiers:ye})}catch(be){s(`❌ Key error: ${be.message||be}`)}},pe=async Z=>{if(Z.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(Z.key)&&Z.preventDefault();let ee=0;Z.altKey&&(ee|=1),Z.ctrlKey&&(ee|=2),Z.metaKey&&(ee|=4),Z.shiftKey&&(ee|=8),m(`Key: ${Z.key}`),await xe(Z.key,Z.code,Z.key.length===1,ee)},V=async Z=>{if(Z.key==="Enter"){if(Z.nativeEvent.isComposing)return;if(f){const le=f;w(""),m(`IME Sent: ${le}`);try{const ee=await e("input_type",{text:le});ee!=null&&ee.success||s(`❌ IME error: ${ee==null?void 0:ee.error}`)}catch(ee){s(`❌ IME error: ${ee.message}`)}}else m("Key: Enter"),await xe("Enter","Enter",!1)}};o.useEffect(()=>{const Z=c.current;if(!Z)return;const le=ee=>{var ye;if((ye=u.current)!=null&&ye.contains(ee.target)){ee.preventDefault();const be=Date.now();if(be-R.current<40)return;R.current=be;const B=X(ee.clientX,ee.clientY);if(!B)return;m(`Scroll: ${Math.round(ee.deltaY)}`),e("input_wheel",{nx:B.nx,ny:B.ny,deltaX:Math.round(ee.deltaX),deltaY:Math.round(ee.deltaY)}).catch(()=>{})}};return Z.addEventListener("wheel",le,{passive:!1}),()=>Z.removeEventListener("wheel",le)},[e]);const{cursorPos:ge,handleToggleInputMode:ne,handleZoomReset:ce}=zd({containerRef:c,viewportRef:l,imgRef:u,inputMode:I,setInputMode:j,minZoom:ae,zoomRef:O,panXRef:S,panYRef:D,setPanX:K,setPanY:C,setZoom:L,lastWheelTimeRef:R,onAction:e,setLastActionStatus:m,spawnRippleFromNormalized:ke,clampPan:Ne,isMobile:g,mobileFillZoom:v});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:pe,onContextMenu:Z=>Z.preventDefault(),onFocus:()=>k(!0),onBlur:()=>k(!1),tabIndex:0,children:[t.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[q?t.jsx("img",{ref:u,src:q,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${M}) translate(${T}%, ${U}%)`,transformOrigin:"center center",cursor:I==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ie,onContextMenu:Z=>Z.preventDefault(),onDragStart:Z=>Z.preventDefault()}):t.jsx(Ud,{waitingLabel:H,waitingHint:re,transportType:i}),I==="mouse"&&q&&t.jsx(Od,{cursorPos:ge,viewportRef:l,imgRef:u}),A.map(Z=>{const ee={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[Z.type];return t.jsxs("div",{style:{position:"absolute",left:Z.x,top:Z.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ee}, 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(${ee}, 0.9)`,boxShadow:`0 0 12px rgba(${ee}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},Z.id)})]}),t.jsx(Hd,{inputMode:I,onToggleInputMode:ne,isImeOpen:N,setIsImeOpen:_,isMenuOpen:y,setIsMenuOpen:h,imeText:f,setImeText:w,handleImeSubmit:V,isConnActive:G,zoom:M,isMobile:g,mobileFillZoom:v,onZoomOut:()=>L(Z=>Math.max(.5,Z-.25)),onZoomReset:ce,onZoomIn:()=>L(Z=>Math.min(5,Z+.25)),transportType:i,screenshotUsage:a,lastActionStatus:p}),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 Ct(e){return(typeof e=="string"?e.trim():"")||void 0}function Gt(e,s){const r=Ct(s);return r?`${e}:${r}`:void 0}function es(e,s,r){const n=Gt(s,r),a=Ct(r);n&&e.push(n),a&&e.push(a)}function Ts(e){const s=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),s.push(n));return s}function Di(e){return Ct(e.providerSessionId)||Ct(e.sessionId)||Ct(e.tabKey)||Ct(e.routeId)}function ja(e){return Ts([Ct(e.providerSessionId),Ct(e.sessionId)])}function ts(e){const s=[];return es(s,"provider",e.providerSessionId),es(s,"session",e.sessionId),es(s,"tab",e.tabKey),es(s,"route",e.routeId),Ts(s)}function Vd(e){const s=[];return Ct(e.providerSessionId)?(es(s,"provider",e.providerSessionId),Ts(s)):Ct(e.sessionId)?(es(s,"session",e.sessionId),Ts(s)):Ct(e.tabKey)?(es(s,"tab",e.tabKey),Ts(s)):Ct(e.routeId)?(es(s,"route",e.routeId),Ts(s)):[]}function ka(e){return Gt("provider",e.providerSessionId)||Gt("session",e.sessionId)||Gt("tab",e.tabKey)||Gt("route",e.routeId)||"unknown:"}function fr(e){return ja(e)[0]}function Ei(e){const s=Ct(e.providerSessionId),r=Ct(e.sessionId),n=Ct(e.tabKey),a=Ct(e.routeId),i=[Gt("provider",s),Gt("session",r),Gt("tab",n),Gt("route",a)].filter(u=>typeof u=="string"),c=ts({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),l=ka({providerSessionId:s,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:s,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:Di({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),historySessionId:fr({providerSessionId:s,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function lr(e,s){const r=Ei(e);return Vd(s).some(n=>r.lookupKeys.includes(n))}function un(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 p=Math.floor(u/24);return p<7?`${p}d${r}`:new Date(e).toLocaleDateString()}const $i=e=>un(e);function Gd(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden}}function Vs(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 qd(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...Gd(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 Zr(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}}function mn(e,s,r){const n=Zr(e,s),a=Vs(e),i=ts(e).map(A=>{var d;return(d=r==null?void 0:r.notificationStateBySessionId)==null?void 0:d.get(A)}).find(A=>!!A),c=a.isReconnecting,l=a.isConnecting,u=a.isGenerating,p=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||p,f=n.inboxBucket==="working"||u,k=!!(n.inboxBucket==="task_complete"&&(i?i.unreadCount>0:n.unread)&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:k,requiresAction:m,isWorking:f,isReconnecting:c,isConnecting:l,isGenerating:u,isWaiting:p,inboxBucket:m?"needs_attention":f?"working":k?"task_complete":"idle"}}function Yd(e,s,r){return mn(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation,notificationStateBySessionId:r==null?void 0:r.notificationStateBySessionId}).unread}function Bi({activeConv:e,onModalButton:s}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Vs(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(ys,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,u)=>{const p=c(l).toLowerCase(),m=/^(run|approve|accept|yes|allow|always)/.test(p),f=/^(reject|deny|delete|remove|abort)/.test(p),w=r===l,k=r!==null;return t.jsx("button",{onClick:()=>i(l),disabled:k,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${m?"font-extrabold":f?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${k&&!w?"opacity-40":"opacity-100"} ${k?"cursor-not-allowed":"cursor-pointer"}`,style:m?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:f?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:w?"⏳ ...":c(l)},u)})})]})]})}const Sa="adhdev_controls_bar_visible",Zn="adhdev:controlsbarvisibilitychange";function Nn(e){if(!e)return!1;try{return e.getItem(Sa)==="1"}catch{return!1}}function jo(e,s){if(s)try{s.setItem(Sa,e?"1":"0")}catch{}}function ko(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Zn,{detail:{visible:e}}))}function Ki(){const[e,s]=o.useState(()=>typeof window>"u"?!1:Nn(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(Nn(window.localStorage))},i=c=>{c.key===Sa&&s(Nn(window.localStorage))};return window.addEventListener(Zn,a),window.addEventListener("storage",i),()=>{window.removeEventListener(Zn,a),window.removeEventListener("storage",i)}},[]);const r=o.useCallback(a=>{s(a),typeof window<"u"&&jo(a,window.localStorage),ko(a)},[]),n=o.useCallback(()=>{s(a=>{const i=!a;return typeof window<"u"&&jo(i,window.localStorage),ko(i),i})},[]);return{isVisible:e,setVisibility:r,toggleVisibility:n}}var Xd=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Qd(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function Nt(e,s){if(Qd(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":Xd.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 Wi(e){return Nt(e)==="generating"}function nt(e){return e?e.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" "):"IDE"}function Jd(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 Cn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function pn(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 Zd(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 eu(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function tu(e){return Zd(e.trim().replace(/\.local$/i,""))}function su(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function Oi(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&&!eu(c));if(r&&r!=="Unknown")return tu(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function _t(e,s={}){return su(e)||Oi(e,s)}function Hi(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 Ui(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 vs(e,s){return Hi(e).join(" · ")}function dr(e){return e.transport==="pty"}function Ls(e){return e.transport==="acp"}function ru(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:nt(e)}function So(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=nt(r||"").trim().toLowerCase();return n===a||n===i||n===c}function nu(e){return Nt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function au(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=Nt(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 ou(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 iu(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&&ou(s.receivedAt)||0}function cu(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ea(e){return Math.max(cu(e),iu(e.activeChat))}function lu(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 Na(e,s){return lu(ea(e),ea(s),_t(e,{fallbackId:e.id}),_t(s,{fallbackId:s.id}),e.id,s.id)}const Fi="adhdev_notification_prefs",No={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function du(){try{const e=localStorage.getItem(Fi);if(e){const s=JSON.parse(e);return{...No,...s}}}catch{}return{...No}}function uu(e){try{localStorage.setItem(Fi,JSON.stringify(e))}catch{}}let Vt=du(),Fr=[];function mu(){Fr.forEach(e=>e())}function pu(e){Vt={...Vt,...e},uu(Vt),mu()}function fu(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Fr.push(r),()=>{Fr=Fr.filter(n=>n!==r)}},[]);const s=o.useCallback(r=>{pu(r)},[]);return[{...Vt},s]}function sr(e){if(!Vt.globalEnabled)return!1;switch(e){case"disconnect":return Vt.disconnectAlert;case"completion":return Vt.completionAlert;case"approval":return Vt.approvalAlert;case"browser":return Vt.browserNotifications;default:return!0}}const hu={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function zi(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Vi(){return"Notification"in window&&Notification.permission==="granted"}let is=null;async function xu(){if(is!==null)return is;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return is=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(is=!!await e.pushManager.getSubscription(),is):(is=!1,!1)}catch{return is=!1,!1}}function ta(e,s,r){if(Vi())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 bu(e,s={}){const r={...hu,...s},n=o.useRef(new Map),a=o.useRef(0),i=o.useRef(null);o.useEffect(()=>{xu().then(l=>{i.current=l})},[]);const c=o.useCallback((l,u,p)=>{const m=Date.now();m-a.current<r.throttleMs||(a.current=m,ta(l,u,p))},[r.throttleMs]);o.useEffect(()=>{var l;if(!(!r.enabled||!Vi())&&sr("browser")&&i.current!==!0){if(document.hasFocus()){for(const u of e)n.current.set(u.id,Nt(u.status,{activeModal:u.activeModal}));return}for(const u of e){const p=n.current.get(u.id),m=Nt(u.status,{activeModal:u.activeModal}),f=u.name||u.id;if(r.onApproval&&sr("approval")&&m==="waiting_approval"&&p!=="waiting_approval"){const w=((l=u.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${f} — Approval needed`,w.slice(0,120),`approval-${u.id}`)}r.onComplete&&sr("completion")&&Wi(p)&&m==="idle"&&c(`✅ ${f} — Task complete`,"Agent has finished generating",`complete-${u.id}`),r.onError&&m==="error"&&p!=="error"&&c(`⚠️ ${f} — Error`,"Agent encountered an error",`error-${u.id}`),n.current.set(u.id,m)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const gu=/^(run|approve|accept|yes|allow|always)/,yu=/^(run|approve|accept|yes|allow|always|proceed|save)/,vu=/^(reject|deny|delete|remove|abort|cancel|no)/;function Ca(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function wu(e){const s=Ca(e).toLowerCase();return gu.test(s)?"primary":vu.test(s)?"danger":"default"}function ju(e){return yu.test(Ca(e).toLowerCase())?"approve":"reject"}function ku(e){return e.map((s,r)=>({label:Ca(s),variant:wu(s),action:ju(s),button:s,buttonIndex:r}))}function Su(e,s){const r=e||"Approval requested",n=s!=null&&s.length?s.map(a=>`[${a}]`).join(" "):"[Approve] [Reject]";return`⚡ Approval requested: ${r}
28
+ ${n}`}function Nu(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Cu(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 Iu{constructor(){qe(this,"dedupMap",new Map);qe(this,"DEDUP_WINDOW_MS",5e3);qe(this,"DEDUP_MAX_SIZE",50);qe(this,"DEDUP_CLEANUP_AGE_MS",1e4);qe(this,"toastCallbacks",[]);qe(this,"systemMessageCallbacks",[]);qe(this,"clearSystemMessageCallbacks",[]);qe(this,"resolveActionFn",null);qe(this,"viewRequestRespondFn",null);qe(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==s)}}onSystemMessage(s){return this.systemMessageCallbacks.push(s),()=>{this.systemMessageCallbacks=this.systemMessageCallbacks.filter(r=>r!==s)}}onClearSystemMessage(s){return this.clearSystemMessageCallbacks.push(s),()=>{this.clearSystemMessageCallbacks=this.clearSystemMessageCallbacks.filter(r=>r!==s)}}setResolveAction(s){this.resolveActionFn=s}setIdes(s){this.ides=s}setViewRequestRespond(s){this.viewRequestRespondFn=s}emitToast(s){for(const r of this.toastCallbacks)r(s)}showToast(s,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:s,type:r,timestamp:a,duration:5e3,...n})}emitSystemMessage(s,r){for(const n of this.systemMessageCallbacks)n(s,r)}isDuplicate(s){const r=Date.now(),n=this.dedupMap.get(s)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(s,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[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 A,d;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,p=(u==null?void 0:u.type)||"";let m=nt(p);const f=this.resolveOwningDaemon(s);if(f){const b=_t(f,{fallbackId:f.id});b&&(m=!p||p==="adhdev-daemon"?b:`${b}/${m}`)}let w="",k="info";if(s.event==="agent:generating_completed"){const b=s.duration?` (${s.duration}s)`:"";w=`✅ ${m} agent task completed${b}`,k="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(w=`⚡ ${m} approval needed`,k="warning",n&&!((A=s.modalButtons)!=null&&A.length)&&this.emitSystemMessage(n,{role:"system",timestamp:a,content:Su(s.modalMessage,s.modalButtons),_localId:`sys_approval_${a}`}),(d=s.modalButtons)!=null&&d.length&&this.resolveActionFn){const b=this.resolveActionRouteTarget(s);if(!b)return;const y=this.resolveActionFn,h=ku(s.modalButtons).map(g=>({label:g.label,variant:g.variant,onClick:()=>{y(b,"resolve_action",{action:g.action,button:g.button,buttonIndex:g.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),N=Nu(m,s.modalMessage,w),_=Date.now();this.emitToast({id:_,message:N,type:k,timestamp:_,targetKey:n||b,actions:h,duration:15e3}),w=""}}else if(s.event==="monitor:long_generating"){const b=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";w=`⚠️ ${m} agent is taking a long time${b}`,k="warning",sr("browser")&&!document.hasFocus()&&ta(`⚠️ ${m} — Long Running`,`Agent has been generating for over ${b.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const b=s.requesterName||"A team member",y=s.requestId,h=s.orgId;if(w=`👁️ ${b} wants to view your session`,k="warning",y&&h&&this.viewRequestRespondFn){const N=Date.now(),_=Cu(h,y,this.viewRequestRespondFn,(g,I)=>console.error(`[EventManager] ${g} view request failed:`,I));this.emitToast({id:N,message:w,type:k,timestamp:N,actions:_,duration:3e4}),w=""}sr("browser")&&!document.hasFocus()&&ta("👁️ View Request",`${b} wants to view your session`,`view-request-${y}`)}else s.event==="team:view_request_approved"?(w="✅ View request approved",k="success"):s.event==="team:view_request_rejected"&&(w=`❌ ${s.targetName||"Team member"} declined your view request`,k="warning");if(w){const b=Date.now();this.emitToast({id:b,message:w,type:k,timestamp:b,targetKey:n||s.daemonId,duration:5e3})}}}const it=new Iu,Co=new Map;function Bs(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function _s(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Au(e){return!Bs(e)||!Bs(e.controlResult)||!Array.isArray(e.controlResult.options)?null:e.controlResult}function Ar(e){return!Bs(e)||!Bs(e.controlResult)||typeof e.controlResult.ok!="boolean"?null:e.controlResult}function qs(e){if(!(!Bs(e)||typeof e.error!="string"||!e.error.trim()))return e.error}function Mr(e){return Bs(e)&&e.success===!1}function Mu(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";it.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";it.showToast(n.notification.body,a)}}}function Tu(e,s){return e&&_s(e.currentValue)?e.currentValue:s}function Lu(e,s){return _s(s)?_s(e)?typeof e=="string"&&e.trim()==="":!0:!1}function _u(e,s){var i,c;if((s.now??Date.now())<s.localOverrideUntil){const l=s.localValues[e];if(_s(l))return l}const n=(i=s.controlValues)==null?void 0:i[e];if(_s(n))return n;const a=(c=s.defaultValues)==null?void 0:c[e];return _s(a)?a:void 0}function zr(e,s){return e.options||s[e.id]||[]}const Ru=new Set(["antigravity","claude-code-vscode","codex"]);function Pu(e,s,r){return r.id==="new_session"&&Ru.has(s)}function Ia(e,s){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Pu(s.hostIdeType,s.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function In(e,s){return{value:s}}function Du(e,s,r){var a;return r?((a=zr(e,s).find(i=>i.value===r))==null?void 0:a.label)||r:""}const Eu={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function $u({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=Pt(),u=`${e}:${s||n}`,p=Eu[n]||"#94a3b8",[m,f]=o.useState({}),w=o.useRef({}),k=o.useRef(c);w.current=m,k.current=c;const A=o.useRef(0),d={};for(const R of i||[])R.defaultValue!==void 0&&(d[R.id]=R.defaultValue);const b={...d,...c||{},...Date.now()<A.current?m:{}};o.useEffect(()=>{c&&Date.now()>A.current&&f({})},[c]);const[y,h]=o.useState(Co.get(u)||{}),[N,_]=o.useState(null),[g,I]=o.useState(null),j=o.useCallback(async(R,O={})=>{const S={...O,...s&&{targetSessionId:s}};return await l(e,R,S)},[e,s,l]),v=o.useCallback(async(R,O={})=>{const S=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await j("invoke_provider_script",{...S,scriptName:R,...O})},[j,n,r,s]),x=o.useCallback((R,O,S)=>{const D=Tu(S,O);f(G=>({...G,[R.id]:D})),Mu(S==null?void 0:S.effects)},[]),$=o.useCallback((R,O)=>{f(S=>{const D={...S};return O===void 0?delete D[R.id]:D[R.id]=O,D}),A.current=0},[]);if(!i||i.length===0)return null;const M=Ia(i,{hostIdeType:r,providerType:n});if(M.length===0)return null;const L=async R=>{if(N===R.id){_(null);return}if(zr(R,y).length>0){_(R.id);return}if(R.dynamic&&R.listScript){I(R.id);try{const S=await v(R.listScript,{}),D=Au(S);if(!D){const H=qs(S);H&&it.showToast(H,"warning");return}const G=D.options;h(H=>{const re={...H,[R.id]:G};return Co.set(u,re),re});const q=_u(R.id,{localOverrideUntil:A.current,localValues:w.current,controlValues:k.current,defaultValues:d});if(Lu(q,D.currentValue)){const H=D.currentValue;f(re=>({...re,[R.id]:H}))}_(R.id)}catch(S){const D=S instanceof Error?S.message:`Could not load ${R.label}`;it.showToast(D,"warning")}finally{I(null)}}},T=async(R,O)=>{_(null);const S=(c==null?void 0:c[R.id])??d[R.id];f(D=>({...D,[R.id]:O})),A.current=Date.now()+5e3;try{if(!R.setScript)return;const D=await v(R.setScript,In(R,O)),G=Ar(D);if(G&&!G.ok||Mr(D))throw new Error((G==null?void 0:G.error)||qs(D)||`Could not update ${R.label}`);x(R,O,G)}catch(D){$(R,S);const G=D instanceof Error?D.message:`Could not update ${R.label}`;it.showToast(G,"warning")}},K=async R=>{const O=zr(R,y).map(re=>re.value);if(O.length===0)return;const S=String(b[R.id]||""),G=(O.indexOf(S)+1)%O.length,q=O[G];if(typeof q!="string")return;const H=(c==null?void 0:c[R.id])??d[R.id];f(re=>({...re,[R.id]:q})),A.current=Date.now()+5e3;try{if(!R.setScript)return;const re=await v(R.setScript,In(R,q)),ae=Ar(re);if(ae&&!ae.ok||Mr(re))throw new Error((ae==null?void 0:ae.error)||qs(re)||`Could not update ${R.label}`);x(R,q,ae)}catch(re){$(R,H);const ae=re instanceof Error?re.message:`Could not update ${R.label}`;it.showToast(ae,"warning")}},U=async R=>{const S=!b[R.id],D=(c==null?void 0:c[R.id])??d[R.id];f(G=>({...G,[R.id]:S})),A.current=Date.now()+5e3;try{if(!R.setScript)return;const G=await v(R.setScript,In(R,S)),q=Ar(G);if(q&&!q.ok||Mr(G))throw new Error((q==null?void 0:q.error)||qs(G)||`Could not update ${R.label}`);x(R,S,q)}catch(G){$(R,D);const q=G instanceof Error?G.message:`Could not update ${R.label}`;it.showToast(q,"warning")}},C=async R=>{if(!R.invokeScript)return;if(R.confirmMessage){const S=[R.confirmTitle,R.confirmMessage,R.confirmLabel].filter(G=>typeof G=="string"&&G.trim().length>0);if(!window.confirm(S.join(`
29
+
30
+ `)))return}const O=(c==null?void 0:c[R.id])??d[R.id];try{const S=await v(R.invokeScript),D=Ar(S);if(D&&!D.ok||Mr(S))throw new Error((D==null?void 0:D.error)||qs(S)||`Could not run ${R.label}`);D&&x(R,O??!0,D)}catch(S){$(R,O);const D=S instanceof Error?S.message:`Could not run ${R.label}`;it.showToast(D,"warning")}};return t.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1 flex-wrap text-[10px] border-t border-border-subtle bg-surface-primary font-[var(--font)]",children:[t.jsx("span",{className:"text-[9px] font-bold tracking-wide opacity-70",style:{color:p},children:a}),t.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),M.map(R=>{const O=String(b[R.id]||""),S=Du(R,y,O),D=N===R.id,G=g===R.id,q=zr(R,y);switch(R.type){case"select":return t.jsxs("div",{className:"relative",children:[t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap max-w-40 overflow-hidden text-ellipsis",style:{borderColor:D?`${p}55`:"transparent",border:"1px solid",color:O?"var(--text-primary)":"var(--text-muted)"},onClick:()=>L(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),G?"...":S||R.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),D&&q.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>_(null)}),t.jsxs("div",{className:"absolute bottom-full left-0 z-[60] bg-[var(--surface-primary)] border border-border-subtle rounded-lg mb-1 max-h-[220px] overflow-y-auto min-w-40 shadow-[0_-4px_16px_rgba(0,0,0,0.3)]",children:[t.jsx("div",{className:"px-3 py-1.5 text-[9px] font-bold text-text-muted tracking-wider border-b border-border-subtle",children:R.label.toUpperCase()}),q.map(H=>t.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:H.value===O?`${p}18`:"transparent",color:H.value===O?p:"var(--text-secondary)",fontWeight:H.value===O?600:400,borderLeft:H.value===O?`2px solid ${p}`:"2px solid transparent"},title:H.description||H.label,onMouseEnter:re=>{re.currentTarget.style.background=`${p}12`},onMouseLeave:re=>{re.currentTarget.style.background=H.value===O?`${p}18`:"transparent"},onClick:()=>T(R,H.value),children:H.label},H.value))]})]})]},R.id);case"cycle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap",style:{border:"1px solid transparent",color:O?"var(--text-primary)":"var(--text-muted)"},onClick:()=>K(R),title:`Click to cycle: ${q.map(H=>H.label).join(" → ")}`,children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),S||R.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},R.id);case"toggle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all whitespace-nowrap",style:{border:"1px solid",borderColor:O?`${p}44`:"transparent",background:O?`${p}14`:"var(--surface-tertiary)",color:O?p:"var(--text-muted)"},onClick:()=>U(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),R.label]},R.id);case"action":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all hover:bg-[var(--surface-tertiary-hover)] whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>C(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),R.resultDisplay==="inline"&&O?`${R.label}: ${O}`:R.label]},R.id);case"display":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:O?"var(--text-primary)":"var(--text-muted)"},children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),O?`${R.label}: ${O}`:R.label]},R.id);default:return null}})]})}function Bu({isActive:e=!0,isCliTerminal:s=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:p}=Ki(),m=Ia(l,{hostIdeType:a,providerType:i});return!e||s||m.length===0||!p?null:t.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:t.jsx($u,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:m,controlValues:u})})}function Gi({hasDraft:e,isBusy:s=!1}){return!e||s}const Ku=o.memo(function({contextKey:s,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:u=!1}){const p=o.useRef(null),[m,f]=o.useState(""),{isVisible:w,toggleVisibility:k}=Ki();o.useEffect(()=>{f("")},[s]),o.useEffect(()=>{var d;l&&((d=p.current)==null||d.focus())},[s,l]);const A=async()=>{const d=m.trim();if(!d||a)return;await c(d)!==!1&&f("")};return t.jsxs("div",{className:"dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden transition-all duration-200 ease-out",style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[t.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[u&&t.jsx("button",{type:"button",onClick:k,"aria-label":w?"Hide controls":"Show controls","aria-pressed":w,title:w?"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:p,type:"text",placeholder:i||`Send message to ${r}...`,value:m,onChange:d=>f(d.target.value),onPaste:d=>{const b=d.clipboardData.getData("text");b&&f(y=>y+b),d.preventDefault()},onKeyDown:d=>{if(d.key==="Enter"){if(d.nativeEvent.isComposing){d.preventDefault();return}d.preventDefault(),A()}},onBlur:d=>{if(window.innerWidth<768){const b=d.relatedTarget;if((b==null?void 0:b.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:()=>{A()},disabled:Gi({hasDraft:!!m.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${m.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:m.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:m.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})]})}),Ze=e=>e.transport==="pty",Ks=(e,s)=>Ze(e)?e.mode||"terminal":"chat",qi=(e,s)=>Ze(e)&&Ks(e)==="terminal",Xe=e=>e.transport==="acp";function ss(e){return e.streamSource!=="agent-stream"}function as(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function Yi(e){return e.machineName||""}function hr(e){return as(e)}function Bt(e){return e.agentType||""}function en(e){return e.hostIdeType||""}function Aa(e){return e.displayPrimary||e.agentName||"Agent"}function Xi(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Wu(e){return e.lastMessagePreview||e.displaySecondary||""}function Qi(e){return[e.displaySecondary,Yi(e)].filter(Boolean)}function Ws(e){return e.agentName||nt(Bt(e))}function Ou(e){var s,r;if(!ss(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return nt(en(e)||Bt(e))}function Ji(e){return ss(e)?e.sessionId:e.nativeSessionId}function Io(e){return ss(e)?"native":e.tabKey}function Hu(e){return e.sessionId}function Uu(e,s){if(s)return ss(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function Fu(e,s){const r=Bt(e),n=ss(e),a=Ze(e)||Xe(e),i=n?a?Ws(e)||(s==null?void 0:s.cliName)||nt(en(e)||r):s!=null&&s.type?nt(s.type):nt(en(e)||r):Ws(e);return{isNativeConversation:n,isCli:Ze(e),isAcp:Xe(e),isCliTerminal:qi(e),providerType:r,displayLabel:i,targetEntry:Uu(e,s)}}function zu(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 ds(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||zu(s==null?void 0:s.receivedAt)||0}function sa(e,s=0){return ds(e)||e.lastUpdated||s||0}function Zi(e){return ds(e)||e.lastUpdated||0}function ec(e,s,r=Zi){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 ra(e){var r;const s=Nt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function Vu(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!ra(e)&&!e.title.trim()}function Gu(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(ra(r))-Number(ra(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:ec(s,r)})[0]||null}function Wt(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=Gu(a);return n?i&&Vu(n)?i:n:i||r[0]||null}function rs(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ma(e){return fr(e)||e.tabKey||e.routeId||null}function tc(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=Wt(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?Ma(a):null}function sc({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Fs(),c=as(e),l=Yi(e),u=e.transport==="cdp-page"||e.transport==="cdp-webview",p=e.streamSource==="agent-stream"&&!!e.agentName,m=!p&&(e.transport==="pty"||e.transport==="acp"),f=Ws(e),w=Ou(e),k=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),A=o.useCallback(()=>{if(r){r();return}const d=Ma(e);d&&i(rs(d))},[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:A,title:w,children:[t.jsx(Rt,{size:12}),t.jsx("span",{children:w})]}):t.jsxs("span",{className:"conversation-meta-chip",title:w,children:[t.jsx(Rt,{size:12}),t.jsx("span",{children:w})]})),p&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(cr,{size:12}),t.jsx("span",{children:f})]}),m&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(cr,{size:12}),t.jsx("span",{children:f})]}),l&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:k,title:l,children:[t.jsx(qt,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(qt,{size:12}),t.jsx("span",{children:l})]}))]})}function An(e,s){return`${e}:${s}`}function qu(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Tr(e,s){qu()&&console.debug(`[subscription-manager] ${e}`,s)}class Yu{constructor(){qe(this,"active",new Map)}subscribe(s,r,n,a){var p;const i=An(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 m={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,m),Tr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((p=s.sendData)==null?void 0:p.call(s,r,n))??!1}const u=()=>{var w;const m=this.active.get(i);if(!m||(m.handlers.delete(a),m.handlers.size>0))return;this.active.delete(i);const f={type:"unsubscribe",topic:n.topic,key:n.key};Tr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(w=s.sendData)==null||w.call(s,r,f)};return u.initialSendAccepted=l,u}publish(s){const r=An(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,Ds.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),Ds.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=An(s,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(s){var r;Tr("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=s.sendData)==null||r.call(s,n.daemonId,n.request)}resubscribeForDaemon(s,r){var a;const n=Array.from(this.active.values()).filter(i=>i.daemonId===s);Tr("resubscribe_daemon",{daemonId:s,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(a=r.sendData)==null||a.call(r,i.daemonId,i.request)}}const ns=new Yu;function Xu(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});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 Qu(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 tn(e,s){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=s,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:p,childrenByParent:m}=Qu(u),f=Xu(i,n),w=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,k=p.filter(b=>b.kind==="workspace"&&b.transport==="cdp-page"),A=p.filter(b=>b.kind==="agent"&&b.transport==="pty"),d=p.filter(b=>b.kind==="agent"&&b.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...w&&{machine:w,platform:w.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:k.some(b=>!!b.cdpConnected)});for(const b of k){const y=f.get(b.id),h=er(b,y),N=(m.get(b.id)||[]).map(_=>er(_,f.get(_.id)));r.push({id:`${n}:ide:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,status:h.cdpConnected?"online":"detected",daemonId:n,instanceId:b.id,workspace:h.workspace,terminals:0,childSessions:N,agents:N.map(_=>({id:_.id,name:_.providerName||_.providerType,type:_.providerType,status:_.status})),activeChat:h.activeChat,chats:[],cdpConnected:h.cdpConnected,...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l})}for(const b of A){const y=f.get(b.id),h=er(b,y);r.push({id:`${n}:cli:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:b.id,cliName:h.providerName||h.providerType,mode:h.mode||(y==null?void 0:y.mode)||"terminal",workspace:h.workspace||"",activeChat:h.activeChat,...h.resume!==void 0&&{resume:h.resume},...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l,_isCli:!0})}for(const b of d){const y=f.get(b.id),h=er(b,y);r.push({id:`${n}:acp:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:b.id,cliName:h.providerName||h.providerType,mode:"chat",workspace:h.workspace||"",activeChat:h.activeChat,...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const Mn=new Map,Tn=new Map,Ln=new Set,rr=new Map,Ju=1200;function Zu(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 Ao(e,s){const r=rr.get(e);!r||r.size===0||(rr.delete(e),r.forEach(n=>n(s)))}function em(e,s){return new Promise(r=>{const n=rr.get(e)||new Set;rr.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&rr.delete(e),r(c)},i=setTimeout(()=>a(!1),s);n.add(a)})}function xr(){const{sendCommand:e,sendData:s}=Pt(),{injectEntries:r,getIdes:n}=Jr();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??6e4,l=Tn.get(a)||0;if(!(i!=null&&i.force)&&Ln.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=Mn.get(a);if(u)return u;const p=(async()=>{if(s&&!Ln.has(a)&&(Ln.add(a),ns.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},d=>{const b=n(),y=b.find(N=>N.id===a),h=tn(d.status,{daemonId:a,existingDaemon:y,existingEntries:b,timestamp:d.timestamp});h.length>0&&r(h),Tn.set(a,Date.now()),Ao(a,!0)}),!(i!=null&&i.force)&&await em(a,Ju)))return;const m=await e(a,"get_status_metadata"),f=Zu(m);if(!f)return;const w=n(),k=w.find(d=>d.id===a),A=tn(f,{daemonId:a,existingDaemon:k,existingEntries:w,timestamp:f.timestamp||Date.now()});A.length>0&&r(A,{authoritativeDaemonIds:[a]}),Tn.set(a,Date.now()),Ao(a,!0)})().finally(()=>{Mn.delete(a)});return Mn.set(a,p),p},[n,r,e,s])}function Xt(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function Ta(e,s){if(!e||!s)return!1;if(e===s||e.id&&s.id&&String(e.id)===String(s.id)||e._localId&&s._localId&&String(e._localId)===String(s._localId))return!0;const r=String(e.role||"").toLowerCase(),n=String(s.role||"").toLowerCase();if(r!==n)return!1;const a=$s(e.content),i=$s(s.content);if(!a||!i||!(a===i||ur(a,i)||ur(i,a)))return!1;const l=Xt(e),u=Xt(s);return l&&u?Math.abs(l-u)<=15e3:!!e._localId!=!!s._localId}function Mo(e){let s=0;return e!=null&&e._localId||(s+=4),e!=null&&e.id&&(s+=3),e!=null&&e._turnKey&&(s+=2),Xt(e)&&(s+=1),s}function Os(e){return $s(e==null?void 0:e.content)}function ur(e,s){if(!e||!s||e.length<=s.length)return!1;const r=Math.max(12,Math.min(80,Math.floor(e.length*.4)));return s.length<r?!1:e.startsWith(s)||e.includes(s)}function tm(e,s){const r=Os(e),n=Os(s);return!r||!n||r===n?null:ur(r,n)?e:ur(n,r)?s:null}function sm(e,s){const r=tm(e,s);if(r)return r;const n=Mo(e),a=Mo(s);return a!==n?a>n?s:e:Os(s).length>=Os(e).length?s:e}function us(e){const s=[];for(const r of e){const n=s.findIndex(a=>Ta(a,r));if(n>=0){s.splice(n,1,sm(s[n],r));continue}s.push(r)}return s}function rm(e,s){const r=Array.isArray(e)?e:[],n=Array.isArray(s)?s:[];return r.length===0?n:n.length===0?r:us([...r,...n])}function To(e){return[...e].sort((s,r)=>{const n=Xt(s),a=Xt(r);return n&&a&&n!==a?n-a:0})}function Lo(e,s){const r=e.filter(n=>String((n==null?void 0:n.role)||"").toLowerCase()==="user").slice();return s.filter(n=>{const a=r.findIndex(i=>Ta(i,n));return a>=0?(r.splice(a,1),!1):!0})}function nm(e,s){return e.filter(r=>{const n=Os(r),a=String((r==null?void 0:r.role)||"").toLowerCase(),i=Xt(r);return!s.some(c=>{if(Ta(r,c))return!0;const l=String((c==null?void 0:c.role)||"").toLowerCase();if(!n||!a||a!==l)return!1;const u=Os(c);if(!ur(u,n)&&u!==n)return!1;const p=Xt(c);return i&&p?Math.abs(i-p)<=15e3:!0})})}function Rs(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:Ze(e)||Xe(e)?{agentType:Bt(e)}:e.streamSource==="agent-stream"?{agentType:Bt(e)}:s}function mr(e){return e?hr(e):""}function Ys(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function La(e){if(!e)return null;if(Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return"Resolve the pending approval prompt before sending another message.";switch(e.status){case"waiting_approval":case"waiting_for_user_input":return"Resolve the pending approval prompt before sending another message.";default:return null}}function am(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 om=60,im=1e3;function rc(e={}){return e.isCliLike?im:om}function cm(e={}){return rc(e)}const br=60,_a=12e4,lm=new Set(["generating","waiting_approval","starting","streaming","working"]),_o=new Map;function nc(e,s){return`${e}::${s}`}function na(e=br){return{liveMessages:[],cursor:oc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function ac(e){return Si(e)}function oc(e,s=br){return{knownMessageCount:e.length,lastMessageSignature:ac(e[e.length-1]),tailLimit:s}}function Lr(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 dm(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return us([...e,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return us([...e.slice(0,n),...r])}case"full":{const n=Math.max(Number(s.totalMessages||0),r.length);if(n>r.length&&e.length>r.length){const a=Math.max(0,n-r.length);return us([...e.slice(0,a),...r])}return r}default:return r}}class um{constructor(s){qe(this,"manager");qe(this,"sendData");qe(this,"daemonId");qe(this,"sessionId");qe(this,"historySessionId");qe(this,"subscriptionKey");qe(this,"snapshot");qe(this,"transportSubscription",null);qe(this,"listeners",new Set);qe(this,"retainCount",0);qe(this,"loadHistoryPromise",null);this.manager=s.manager||ns,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.snapshot=na(Math.max(0,s.tailLimit??br))}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=us([...r,...this.snapshot.liveMessages]);if(n.length<r.length)return;const a=oc(n,this.snapshot.cursor.tailLimit);Lr(this.snapshot.liveMessages)===Lr(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a})}subscribe(s){return this.listeners.add(s),s(this.snapshot),()=>{this.listeners.delete(s)}}retain(){this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),this.retainCount===0&&this.disconnect()}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}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,{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}:{}}},s=>{this.handleUpdate(s)}))}disconnect(){var s;(s=this.transportSubscription)==null||s.call(this),this.transportSubscription=null}dispose(){this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(s=>s(this.snapshot))}handleUpdate(s){const r=dm(this.snapshot.liveMessages,s),n={knownMessageCount:r.length,lastMessageSignature:typeof s.lastMessageSignature=="string"?s.lastMessageSignature:ac(r[r.length-1]),tailLimit:this.snapshot.cursor.tailLimit};Lr(this.snapshot.liveMessages)===Lr(r)&&this.snapshot.cursor.knownMessageCount===n.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===n.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:r,cursor:n},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:n.knownMessageCount,lastMessageSignature:n.lastMessageSignature}),this.emit())}}function ic(e){const s=nc(e.daemonId,e.sessionId),r=_o.get(s);if(r)return r.updateOptions(e),r;const n=new um(e);return _o.set(s,n),n}function mm(e,s){return{...e,loadHistoryPage:s}}function pm(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function fm(e,s={}){const r=String(e.status||"").trim().toLowerCase();if(lm.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??_a)),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 hm(e=_a){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function xm(e,s={}){const r=new Set,n=[];for(const a of e){if(!fm(a,s))continue;const i=hr(a),c=a.sessionId||"";if(!i||!c)continue;const l=nc(i,c);if(r.has(l))continue;r.add(l);const u=fr(a);n.push({daemonId:i,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(pm),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function bm(e,s){const{sendData:r,sendCommand:n}=Pt(),a=(s==null?void 0:s.enabled)!==!1,i=hr(e),c=e.sessionId||"",l=fr(e)||c,u=`daemon:${i}:session:${c}`,p=Math.max(0,(s==null?void 0:s.tailLimit)??br),m=o.useMemo(()=>!a||!i||!c?null:ic({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:p}),[i,a,l,r,c,u,p]),[f,w]=o.useState(()=>(m==null?void 0:m.getSnapshot())||na(p));o.useEffect(()=>{if(!m){w(na(p));return}m.hydrateLiveMessages(e.messages),m.retain(),w(m.getSnapshot());const A=m.subscribe(d=>{w(d)});return()=>{A(),m.release()}},[e.messages,m,p]);const k=o.useCallback(async()=>{!m||!i||!c||await m.loadHistoryPage(async()=>{const A=e.agentType,d=await n(i,"chat_history",{agentType:A,offset:m.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),b=d&&typeof d=="object"&&"result"in d?d.result||{}:d||{};return{messages:Array.isArray(b.messages)?b.messages:[],hasMore:b.hasMore===!0}})},[e.agentType,m,i,l,n,c]);return o.useMemo(()=>mm(f,k),[k,f])}function gm(e,s){const{sendData:r}=Pt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,(s==null?void 0:s.tailLimit)??br),i=Math.max(0,Number((s==null?void 0:s.recentActivityMs)??_a)),c=hm(i),[l,u]=o.useState(0);o.useEffect(()=>{if(!n||e.length===0)return;const m=setInterval(()=>{u(f=>f+1)},c);return()=>{clearInterval(m)}},[e.length,n,c]);const p=o.useMemo(()=>xm(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||p.descriptors.length===0)return;const m=p.descriptors.map(f=>ic({...f,sendData:r,tailLimit:a}));return m.forEach(f=>f.retain()),()=>{m.forEach(f=>f.release())}},[p.signature,n,r,a])}function ym(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function vm(e){return ym(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const wm=60;function aa({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:p=!1,scrollToBottomRequestNonce:m,isInputActive:f=!0}){var ae,Ne,X,he,ke;const w=o.useRef(new Map),k=xr();pr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const A=rt.useMemo(()=>Vs(e),[e.status,e.connectionState]),d=o.useMemo(()=>Fu(e,s),[e,s]),b=o.useMemo(()=>{var ie;return Ia((ie=d.targetEntry)==null?void 0:ie.providerControls,{hostIdeType:e.hostIdeType,providerType:d.providerType})},[e.hostIdeType,d.providerType,(ae=d.targetEntry)==null?void 0:ae.providerControls]),y=rc({isCliLike:d.isCli||d.isAcp}),h=cm({isCliLike:d.isCli||d.isAcp}),N=bm(e,{enabled:!!e.sessionId,tailLimit:h}),[_,g]=o.useState(y),I=e.tabKey,j=N.historyMessages,v=N.hasMoreHistory,x=N.historyError,$=rm(N.liveMessages,e.messages);o.useEffect(()=>{g(y)},[y,I]);const M=Math.max(0,$.length-_),L=Aa(e),T=hr(e),K=vm(e),U=La(e),C=a||U,R=!!U,[O,S]=o.useState(!1);o.useEffect(()=>{const ie=d.targetEntry;T&&(!ie||ie.providerControls===void 0||ie.controlValues===void 0)&&k(T,{minFreshMs:3e4}).catch(()=>{})},[T,d.isAcp,(Ne=d.targetEntry)==null?void 0:Ne.providerControls,(X=d.targetEntry)==null?void 0:X.controlValues,k]);const D=o.useCallback(async()=>{if(!O){if($.length>_){g(ie=>Math.min($.length,ie+wm));return}S(!0);try{await N.loadHistoryPage()}finally{S(!1)}}},[N,O,$.length,_]),{allMessages:G,receivedAtMap:q}=o.useMemo(()=>{const ie=M>0?$.slice(-_):$;if(j.length===0){const ge=To(us(ie)),ne={};return ge.forEach((ce,Z)=>{const le=`${e.tabKey}:${Ms(ce,Z)}`;let ee=Xt(ce)||w.current.get(le)||0;ee||(ee=Date.now(),w.current.set(le,ee)),ne[Ms(ce,Z)]=ee}),{allMessages:ge,receivedAtMap:ne}}const xe=nm(j,ie),pe=To(us([...xe,...ie])),V={};return pe.forEach((ge,ne)=>{const ce=`${e.tabKey}:${Ms(ge,ne)}`;let Z=Xt(ge)||w.current.get(ce)||0;Z||(Z=Date.now(),w.current.set(ce,Z)),V[Ms(ge,ne)]=Z}),{allMessages:pe,receivedAtMap:V}},[e.tabKey,M,j,$,_]),H=o.useMemo(()=>l.filter(ie=>ie.routeId===e.tabKey).sort((ie,xe)=>ie.timestamp-xe.timestamp),[l,e.tabKey]),re=o.useMemo(()=>{if($.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((A.isGenerating||e.status==="streaming")&&S(!1),e.status==="not_monitored"&&K)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(cr,{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(Es,{size:14})," Open ",L," 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"&&K)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(Ai,{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(Es,{size:14})," Open ",L," 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"&&!O)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,K,i,c,O,$.length,L,A.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[p&&t.jsx(sc,{conversation:e,className:"chat-pane-meta-row"}),t.jsx($d,{messages:G,actionLogs:H,agentName:Ws(e)||L||"Agent",userName:u,isCliMode:d.isCli||d.isAcp,isWorking:A.isGenerating,contextKey:e.tabKey,receivedAtMap:q,onLoadMore:D,isLoadingMore:O,hasMoreHistory:v,hiddenLiveCount:M,loadError:x??void 0,emptyState:re,scrollToBottomRequestNonce:m}),t.jsx(Bu,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:d.providerType,displayLabel:d.displayLabel,controls:(he=d.targetEntry)==null?void 0:he.providerControls,controlValues:(ke=d.targetEntry)==null?void 0:ke.controlValues,isActive:f,isCliTerminal:d.isCliTerminal}),!d.isCliTerminal&&t.jsx(Ku,{contextKey:e.tabKey,panelLabel:L,isSending:n,isBusy:R,statusMessage:C,onSend:r,isActive:f,showControlsToggle:b.length>0})]})}let cc=gs;function lc(){return cc()}class jm{constructor(){qe(this,"listeners",new Map)}send(s){}isConnected(){return!1}on(s,r){return this.listeners.has(s)||this.listeners.set(s,new Set),this.listeners.get(s).add(r),()=>{var n;(n=this.listeners.get(s))==null||n.delete(r)}}emit(s,...r){var n;(n=this.listeners.get(s))==null||n.forEach(a=>a(...r))}}let dc=new jm;class km{sendPtyInput(s,r,n){return!1}retryConnection(s){}getState(s){return"disconnected"}sendData(s,r){return!1}get(s){}onScreenshot(s,r){return()=>{}}onRuntimeEvent(s,r){return()=>{}}requestRuntimeSnapshot(s,r){return Promise.resolve()}}let mt=new km;function Sm(e){e.dashboardWS&&(dc=e.dashboardWS),e.connectionManager&&(mt=e.connectionManager),e.useDaemonsHook&&(cc=e.useDaemonsHook)}const uc=.6,Nm=1.15;function Cm(e,s={}){const r=typeof s.minScale=="number"?s.minScale:uc;return!Number.isFinite(e)||e<=0?1:e<=480?r:1}function ct(e){return Aa(e)}function ws(e){return Qi(e).join(" · ")}function mc(e){if(e.lastMessagePreview)return e.lastMessagePreview;const s=[...e.messages].reverse().find(n=>!(n!=null&&n._localId))||e.messages[e.messages.length-1],r=$s(s==null?void 0:s.content);return r||(e.title?e.title:ws(e)||"No messages yet")}function pc(e,s){const{isReconnecting:r,isConnecting:n}=Vs(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function Im(e,s){const r=["Chat",...Qi(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function ms(e){return pc(e)||ws(e)}function Am(e){return`${ct(e)} · ${mc(e)}`}function Mm(e){const s=en(e),r=s?nt(s):Ws(e);return`${ct(e)} — ${r||"Agent"}`}function Tm(e){return Ws(e)||"CLI"}function fc(e){return Xi(e)}function hc(e){return e?`Remote · ${ct(e)||e.workspaceName||"Session"}`:"Remote"}function Lm({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0}){var q;const{ides:l}=gs(),u=o.useRef(null),{sendData:p}=Pt(),[m,f]=o.useState(""),[w,k]=o.useState(!1),[A,d]=o.useState(1),b=o.useRef(!1),y=o.useRef(0),h=o.useRef(!1),N=o.useRef(""),_=o.useRef(null),g=o.useRef(!1),I=o.useRef(null),j=e.tabKey,v=e.sessionId||"",x=e.daemonId||((q=e.routeId)==null?void 0:q.split(":")[0])||e.routeId||"",$=l.find(H=>H.id===x&&H.type==="adhdev-daemon"),M=($==null?void 0:$.terminalSizingMode)==="fit"?"fit":"measured",L=La(e),T=i||L,K=uc,U=Nm,C=()=>typeof window>"u"?1:Cm(window.innerWidth||0,{minScale:K}),R=()=>{var H,re;y.current=0,h.current=!1,N.current="",_.current=null,g.current=!1,I.current!==null&&(cancelAnimationFrame(I.current),I.current=null),k(!1),(re=(H=r.current)==null?void 0:H.reset)==null||re.call(H)},O=()=>{var H,re;y.current=0,h.current=!1,N.current="",_.current=null,g.current=!1,I.current!==null&&(cancelAnimationFrame(I.current),I.current=null),k(!0),(re=(H=r.current)==null?void 0:H.reset)==null||re.call(H)},S=()=>{var re;if(I.current=null,!c)return;const H=N.current;H&&(N.current="",(re=r.current)==null||re.write(H))},D=H=>{H&&(N.current+=H,c&&I.current===null&&(I.current=requestAnimationFrame(S)))},G=(H,re=0,ae,Ne)=>{var X,he,ke,ie,xe;re>0&&y.current>=re||re===0&&h.current||(y.current=re,k(!0),typeof ae=="number"&&typeof Ne=="number"&&ae>0&&Ne>0&&((he=(X=r.current)==null?void 0:X.resize)==null||he.call(X,ae,Ne)),(ie=(ke=r.current)==null?void 0:ke.reset)==null||ie.call(ke),H&&((xe=r.current)==null||xe.write(H)))};return o.useEffect(()=>{R()},[v]),o.useEffect(()=>{var re;if(!v)return;const H=((re=mt.onRuntimeEvent)==null?void 0:re.call(mt,v,ae=>{if(!(!ae||ae.sessionId!==v)){if(ae.type==="runtime_snapshot"){if(!c){_.current={text:ae.text||"",seq:ae.seq||0,cols:ae.cols,rows:ae.rows};return}G(ae.text||"",ae.seq||0,ae.cols,ae.rows);return}if(ae.type==="session_output"){h.current=!0,typeof ae.seq=="number"&&(y.current=Math.max(y.current,ae.seq)),w||k(!0),typeof ae.data=="string"&&D(ae.data);return}if(ae.type==="session_cleared"){if(!c){g.current=!0,N.current="",_.current=null;return}O()}}}))||(()=>{});return()=>{H()}},[x,v,r,c,w]),o.useEffect(()=>{var re,ae,Ne;if(!v)return;x&&((re=mt.getState)==null?void 0:re.call(mt,x))==="connected"&&(k(!0),(ae=mt.requestRuntimeSnapshot)==null||ae.call(mt,x,v).catch(()=>{}));const H=(Ne=mt.onStateChange)==null?void 0:Ne.call(mt,(X,he)=>{var ke;X!==x||he!=="connected"||(k(!0),(ke=mt.requestRuntimeSnapshot)==null||ke.call(mt,x,v).catch(()=>{}))});return()=>{H==null||H()}},[x,v,r]),o.useEffect(()=>{s&&R()},[s,j,r]),o.useEffect(()=>{f("")},[e.tabKey]),o.useEffect(()=>{const H=()=>{b.current||d(C())};return H(),window.addEventListener("resize",H),()=>window.removeEventListener("resize",H)},[]),o.useEffect(()=>{var re;if(!c){(re=u.current)==null||re.blur();return}g.current&&(g.current=!1,O());const H=_.current;H&&(_.current=null,G(H.text,H.seq,H.cols,H.rows)),N.current&&I.current===null&&(I.current=requestAnimationFrame(S)),requestAnimationFrame(()=>{var ae;(ae=r.current)==null||ae.bumpResize()})},[c]),o.useEffect(()=>()=>{I.current!==null&&(cancelAnimationFrame(I.current),I.current=null)},[]),o.useEffect(()=>{const H=re=>{var Ne;const ae=re.detail;ae!=null&&ae.sessionId&&ae.sessionId!==v||w&&((Ne=r.current)==null||Ne.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",H),()=>{window.removeEventListener("adhdev:fit-cli-terminal",H)}},[w,v,r]),t.jsxs(t.Fragment,{children:[t.jsxs("div",{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:()=>{b.current=!0,d(H=>Math.max(K,Number((H-.1).toFixed(2))))},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:()=>{b.current=!0,d(H=>Math.min(U,Number((H+.1).toFixed(2))))},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{className:"w-full h-full overflow-x-auto overflow-y-hidden rounded-lg overscroll-contain",children:t.jsx("div",{style:{width:`${100/A}%`,height:`${100/A}%`,transform:`scale(${A})`,transformOrigin:"top left"},children:t.jsx(Ri,{ref:r,readOnly:!w||!c,sizingMode:M,onInput:H=>{w&&(p==null||p(x,{type:"pty_input",sessionId:v,targetSessionId:v,data:H}))}})})}),!w&&t.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:"Runtime terminal unavailable"})]}),t.jsxs("div",{className:"px-3 py-2 bg-[var(--surface-primary)] border-t border-border-subtle shrink-0",children:[t.jsxs("div",{className:"flex gap-2.5 items-center",children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:u,type:"text",placeholder:T||`Send message to ${ct(e)}...`,value:m,disabled:!w||!c,onChange:H=>f(H.target.value),onPaste:H=>{const re=H.clipboardData.getData("text");re&&f(ae=>ae+re),H.preventDefault()},onKeyDown:H=>{if(H.key!=="Enter")return;if(H.nativeEvent.isComposing){H.preventDefault();return}H.preventDefault();const re=m.trim();!w||!re||L||n(re).then(ae=>{ae!==!1&&f("")})},className:"w-full h-9 rounded-[18px] px-4 bg-bg-secondary text-[13px] text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:()=>{const H=m.trim();!w||!H||L||n(H).then(re=>{re!==!1&&f("")})},disabled:!w||!c||Gi({hasDraft:!!m.trim(),isBusy:!!L}),className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${m.trim()&&!L?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:m.trim()&&!L?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:m.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),T&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:T})]})]})}function _m({wsStatus:e,showReconnected:s,loginUrl:r}){const n=e==="disconnected"||e==="reconnecting"||e==="offline"||e==="auth_failed",a=e==="auth_failed"?"red":e==="offline"?"orange":"accent",i={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))"},c={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)"},l={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"};return t.jsxs(t.Fragment,{children:[n&&t.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5 justify-center",style:{background:i[a],borderBottom:c[a],color:l[a]},children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),e==="offline"&&"Network offline — waiting for connection...",e==="disconnected"&&"Reconnecting to server...",e==="reconnecting"&&"Reconnecting to server...",e==="auth_failed"&&(r?t.jsxs(t.Fragment,{children:["Session expired."," ",t.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — please restart the server.")]}),s&&e==="connected"&&t.jsxs("div",{className:"py-2 px-4 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-b border-green-500/15 animate-[fadeIn_0.3s_ease]",children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})]})}function Rm({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 Ra({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(ln,{size:n}):t.jsx(Yt,{size:n})})}function Ro({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Po({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=un(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 Pm({activeConv:e,agentCount:s,wsStatus:r,isConnected:n,conversations:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetCliViewMode:p,onHideConversation:m,hiddenConversations:f=[],onShowConversation:w,onShowAllHidden:k,onResetPanelsToMain:A,inboxOpen:d,onInboxOpenChange:b,hiddenOpen:y,onHiddenOpenChange:h,onOpenNewSession:N,actionShortcuts:_,notifications:g,notificationUnreadCount:I,onOpenNotification:j,onMarkNotificationRead:v,onMarkNotificationUnread:x,onDeleteNotification:$}){const{ides:M,p2pStates:L={}}=gs(),T=!!e&&Ze(e)&&!Xe(e),K=!!e&&Xe(e),U=u||(e?qi(e)?"terminal":"chat":null),[C,R]=o.useState(!1),O=o.useRef(null),S=o.useRef(null),D=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",G=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",q=M.filter(V=>V.type==="adhdev-daemon"),H=Object.values(L),re=H.filter(V=>V==="connected").length,ae=H.filter(V=>V==="connecting"||V==="new"||V==="checking").length,X=r!=="connected"||q.length===0?null:ae>0&&re===0?"P2P connecting...":re>0&&s===0?"Waiting for IDE...":null,he=o.useMemo(()=>g.filter(V=>!V.readAt),[g]),ke=o.useMemo(()=>g.filter(V=>!!V.readAt),[g]),ie=o.useMemo(()=>he.slice(0,9),[he]),xe=I;o.useEffect(()=>{if(!d)return;const V=ge=>{var ne;(ne=O.current)!=null&&ne.contains(ge.target)||b(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[d,b]),o.useEffect(()=>{if(!y)return;const V=ge=>{var ne;(ne=S.current)!=null&&ne.contains(ge.target)||h(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[y,h]),o.useEffect(()=>{if(!y&&!d)return;const V=ge=>{if(!ge.altKey)return;const ne=ge.code.match(/^Digit([1-9])$/);if(!ne)return;const ce=Number(ne[1])-1,Z=y?f[ce]:void 0,le=d?ie[ce]:void 0;if(!(!Z&&!le)){if(ge.preventDefault(),ge.stopPropagation(),Z){w==null||w(Z),h(!1);return}le&&(j(le),b(!1))}};return window.addEventListener("keydown",V,!0),()=>window.removeEventListener("keydown",V,!0)},[f,y,d,ie,h,b,j,w]);const pe=V=>{if(!V)return;const ge=a.find(ne=>ne.tabKey===V);ge&&(m==null||m(ge))};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(Yt,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?ct(e):"Dashboard"}),t.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:t.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:D,boxShadow:G}})})]}),t.jsxs("div",{className:"header-subtitle flex items-center",children:[t.jsx("span",{title:n?"Connected":r==="connected"?"Partial":"Disconnected",className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:D,boxShadow:G}}),X&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",X]}),N&&t.jsx("button",{type:"button",onClick:N,className:"btn btn-secondary btn-sm ml-2",title:"Start or recover a session","aria-label":"Start or recover a session",children:t.jsx(fd,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(T||K||!Xe(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:ws(e)||ct(e),children:ct(e)}),(T||K)&&l&&t.jsxs(t.Fragment,{children:[T&&p&&U&&t.jsx(Ra,{mode:U,onChange:p,compact:!0}),t.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:K?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(It,{size:14})})]}),!Xe(e)&&t.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(ya,{size:14})}),!T&&!Xe(e)&&t.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(Rt,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:O,children:[t.jsxs("div",{className:`dashboard-header-hidden${C?" is-drop-target":""}`,ref:S,onDragEnter:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),R(!0))},onDragOver:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),V.dataTransfer.dropEffect="move",R(!0))},onDragLeave:V=>{V.currentTarget.contains(V.relatedTarget)||R(!1)},onDrop:V=>{const ge=V.dataTransfer.getData("text/tab-key");V.preventDefault(),R(!1),pe(ge)},children:[t.jsxs("button",{type:"button",onClick:()=>h(!y),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${_!=null&&_.toggleHiddenTabs?` (${_.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(Mi,{size:16}),f.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:f.length})]}),y&&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(Ro,{value:_==null?void 0:_.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[A&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:A,children:"Reset panels"}),f.length>0&&k&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{k(),h(!1)},children:"Restore all"})]})]}),e&&m&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[t.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[t.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),t.jsx(Ro,{value:_==null?void 0:_.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:ct(e)})]}),f.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:f.map(V=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{w==null||w(V),h(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:ct(V)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[f.indexOf(V)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",f.indexOf(V)+1]}):null,ws(V)]})]},V.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>b(!d),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(dn,{size:16}),xe>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:xe})]}),d&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[he.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),he.map(V=>t.jsx(Po,{notification:V,shortcutIndex:ie.indexOf(V)>=0?ie.indexOf(V)+1:void 0,onOpen:()=>j(V),onMarkRead:()=>v(V.id),onMarkUnread:()=>x(V.id),onDelete:()=>$(V.id)},V.id))]}),ke.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),ke.map(V=>t.jsx(Po,{notification:V,onOpen:()=>j(V),onMarkRead:()=>v(V.id),onMarkUnread:()=>x(V.id),onDelete:()=>$(V.id)},V.id))]}),g.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function vt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Dm(e,s){return String(e||"")!==String(s||"")}function Em(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(`
31
+ `).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!Hi(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
32
+ `).includes(a)))}function $m(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 xc(e,s={}){return $m(Em(e,s),s.sortMode||"recent")}function sn(e){return e?"Resume saved history":"Start fresh"}function Pa(e){return e?"Resuming saved history…":"Starting fresh…"}function Bm(){return"Start fresh"}function bc(e,s=!1){return e==="cli"?sn(s):e==="ide"?"Start IDE":"Start ACP session"}function gc(e,s=!1){return e==="cli"?Pa(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Km(){return"Recover hosted runtime"}function Wm(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Om(){return"Open saved history"}function Hm(){return"Saved History"}function Da(){return"Use saved history when you want continuity in the same provider conversation."}function Um(){return"No saved history found yet."}function Fm(){return"Refresh saved history"}function zm(){return"Refreshing saved history…"}function ps(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function fs(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 Hs(e){return e==="start-fresh"?"Start fresh":"Restart"}function Us(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Ea(e){return`Resume saved history with ${e}?`}function $a(){return"Review or change the target workspace before resuming saved history."}function Vm(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 Ba({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:p,onNewChat:m,onSwitchSession:f,onRefreshHistory:w,onResumeSavedSession:k}){var v;const A=s.find(x=>x.id===e.routeId),d=(A==null?void 0:A.chats)||[],b=(v=A==null?void 0:A.activeChat)==null?void 0:v.id,y=Ze(e)&&!Xe(e),[h,N]=o.useState(()=>vt()),_=l||h,g=x=>{if(u){u(x);return}N(x)},I=o.useMemo(()=>xc(a,{textQuery:_.textQuery,workspaceQuery:_.workspaceQuery,modelQuery:_.modelQuery,resumableOnly:_.resumableOnly,sortMode:_.sortMode}),[_.modelQuery,_.resumableOnly,_.sortMode,_.textQuery,_.workspaceQuery,a]),j=t.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[t.jsx("div",{onClick:p,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:y?Hm():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Mm(e)}),y&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Da()})]}),t.jsx("button",{onClick:p,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(It,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!y&&t.jsx("button",{onClick:m,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"}),y?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:_.textQuery,onChange:x=>g({..._,textQuery:x.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:_.workspaceQuery,onChange:x=>g({..._,workspaceQuery:x.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:_.modelQuery,onChange:x=>g({..._,modelQuery:x.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:_.sortMode,onChange:x=>g({..._,sortMode:x.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:_.resumableOnly,onChange:x=>g({..._,resumableOnly:x.target.checked})}),"Resume-ready only"]})]}),I.map(x=>{const $=e.providerSessionId===x.providerSessionId,M=$||!x.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{M||!k||k(x)},disabled:M,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${$?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${M?"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 ${$?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:x.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:x.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Vm(x.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:x.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:[x.workspace||"Workspace unknown",vs(x.summaryMetadata)?` · ${vs(x.summaryMetadata)}`:"",x.messageCount>0?` · ${x.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:$?"ACTIVE":x.canResume?c===x.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},x.id)})]}):d.map(x=>t.jsxs("div",{onClick:()=>{f(e.routeId,x.id),p()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===x.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 ${b===x.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:x.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:[x.id.substring(0,12),"..."]}),b===x.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},x.id)),(y&&!i&&I.length===0||!y&&d.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(gd,{size:32})}),t.jsx("div",{className:"text-[13px]",children:y?a.length>0?"No saved history matches these filters.":Um():"No recent chat sessions found."})]}),y&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:zm()})})]}),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:w,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(zs,{size:13})," ",y?Fm():"Refresh History"]})})})]})]});return typeof document>"u"?j:ir.createPortal(j,document.body)}const Do={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 yc({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=Do[n.type]||Do.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(It,{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 Gm=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function qm(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function Ym(e){return e.sessionId||e.instanceId||e.agentType}function _n(e,s){return e||s}function Eo(e,s){const r=new Set,n=[];for(const a of s)if(a)for(const i of e[a]||[]){const c=i._localId||`${i.role}:${i.timestamp}:${i.content}`;r.has(c)||(r.add(c),n.push(i))}return n.sort((a,i)=>a.timestamp-i.timestamp)}function vc(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=_t(r,{fallbackId:r.id}));return s}function wc(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 Ka(e,s,r={}){return Xm(e,s,wc(e,r))}function Xm(e,s,r={}){var f,w,k,A,d,b;const n=[],a=r.machineName,i=r.connectionState,c=qm(e),l=ru(e.type,{agentName:e.cliName}),u=Ze(e)||Xe(e)?l:nt(e.type),p=Array.isArray(e.childSessions)?e.childSessions.map(y=>{var h,N;return{sessionId:y.id,instanceId:y.id,providerSessionId:y.providerSessionId,transport:y.transport,sessionCapabilities:y.capabilities,agentType:y.providerType,agentName:y.providerName||nt(y.providerType),status:y.status,title:y.title,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,messages:((h=y.activeChat)==null?void 0:h.messages)||[],activeModal:((N=y.activeChat)==null?void 0:N.activeModal)||void 0,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,inboxBucket:y.inboxBucket,surfaceHidden:y.surfaceHidden}}):[],m=Gm(e);if(m){const y=e.sessionId||e.instanceId,h=l,N=(f=e.activeChat)==null?void 0:f.activeModal,_=N&&Array.isArray(N.buttons)&&N.buttons.length>0,g=Nt((w=e.activeChat)==null?void 0:w.status,{activeModal:(k=e.activeChat)==null?void 0:k.activeModal})||Nt((d=(A=e.agents)==null?void 0:A[0])==null?void 0:d.status)||"idle",I=e.activeChat||{title:"",messages:[]};let j=I.title&&String(I.title).trim()?String(I.title).trim():"";const v=(b=e.activeChat)==null?void 0:b.id,x=e.chats;if(v&&Array.isArray(x)&&x.length>0){const U=x.find(C=>C.id===v||C.id&&String(C.id)===String(v));U!=null&&U.title&&String(U.title).trim()&&(j=String(U.title).trim())}const $=(Ze(e)||Xe(e),e.type),M=(Ze(e)||Xe(e))&&So(j,h,$)?"":j,L=I.messages||[],T=Eo(s,[e.id,y]),K=Lo(L,T);n.push({routeId:e.id,sessionId:y,providerSessionId:e.providerSessionId,nativeSessionId:y,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:Ze(e)?e.mode||"terminal":"chat",agentName:h,agentType:$,status:g,title:M,messages:[...L,...K],resume:e.resume,hostIdeType:!Ze(e)&&!Xe(e)?e.type:void 0,workspaceName:c,displayPrimary:M||c||(Ze(e)?e.mode==="chat"?h:"Terminal":h),displaySecondary:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:_?N.buttons:void 0,modalMessage:_?N.message:void 0,streamSource:"native",tabKey:_n(y,e.id),machineName:a,connectionState:i})}if(m&&(Ze(e)||Xe(e)))return n;for(const y of p){const h=y.activeModal&&Array.isArray(y.activeModal.buttons)&&y.activeModal.buttons.length>0,N=nu(y),_=Ym(y),g=`${e.id}:${_}`,I=y.title&&String(y.title).trim()||"",j=So(I,y.agentName,y.agentType)?"":I,v=y.messages||[],x=Eo(s,[g,y.sessionId,y.instanceId]),$=Lo(v,x);(y.transport==="cdp-webview"||y.sessionId||y.providerSessionId||v.length>0||$.length>0||h||j||!["idle","panel_hidden","disconnected","not_monitored"].includes(N))&&n.push({routeId:e.id,sessionId:y.sessionId||y.instanceId,providerSessionId:y.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:y.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:y.sessionCapabilities,mode:"chat",agentName:y.agentName,agentType:y.agentType,status:N,title:j,messages:[...v,...$],hostIdeType:e.type,workspaceName:c,displayPrimary:j||c||y.agentName||u,displaySecondary:`${u} · ${y.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,lastUpdated:y.lastUpdated||e.lastUpdated,modalButtons:h?y.activeModal.buttons:void 0,modalMessage:h?y.activeModal.message:void 0,streamSource:"agent-stream",tabKey:_n(y.sessionId||y.instanceId,g),machineName:a,connectionState:i})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:c,displayPrimary:c||u,displaySecondary:u,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:_n(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function Qm(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 Jm(e,s){const r=Qm(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const jc=[{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:"🏄"}],kc=[{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:"🧩"}],Sc=[{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:"🟠"}],Zm=jc,ep=kc,tp=Sc;function js(...e){return Kl(Wl(e))}function sp({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:js("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 Nc({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(sp,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:js("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Lt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:js("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 Cc({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:js("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 rp={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"},np={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function _r({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:js("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",rp[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:np[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 ap={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"},op={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function ip({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:js("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",ap[e],r),children:[t.jsx("span",{className:js("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",op[e])}),n]})}const oa="adhdev:themechange";function cp(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Is(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function As(e){return e==="system"?cp():e}function Ic(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Vr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(oa,{detail:{preference:e,theme:s}}))}function lp(){const e=Is(),s=As(e);Ic(s),Vr(e,s)}function Wa(){const[e,s]=o.useState(Is),[r,n]=o.useState(()=>As(Is()));o.useEffect(()=>{Ic(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const p=u.matches?"light":"dark";n(p),Vr("system",p)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const p=u.detail||{},m=p.preference,f=p.theme;s(m==="dark"||m==="light"||m==="system"?m:Is()),n(f==="dark"||f==="light"?f:As(Is()))},l=u=>{if(u.key!=="theme")return;const p=Is(),m=As(p);s(p),n(m)};return window.addEventListener(oa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(oa,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=As(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}Vr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=As(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Vr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const $o={dark:"Dark",light:"Light",system:"System"};function dp({collapsed:e}){const{preference:s,cycleTheme:r}=Wa(),n=s==="dark"?t.jsx(vd,{size:16}):s==="light"?t.jsx(yd,{size:16}):t.jsx(wd,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${$o[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:$o[s]})]})}function ls({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 up({onPrefChange:e}){const[s,r]=fu(),[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(ls,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(dn,{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(ls,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Rt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:c=>i("browserNotifications",c)}),s.globalEnabled&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&t.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[t.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),t.jsx("button",{onClick:()=>{zi().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(ls,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(jd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:c=>i("completionAlert",c)}),t.jsx(ls,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(kd,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:c=>i("approvalAlert",c)}),t.jsx(ls,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(cr,{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 rn(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function mp(e,s){const r=rn(e),n=rn(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 Ac(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function nr(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||mp(r,s)>=0)return!1;const n=rn(r),a=rn(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function pp(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Rn(e,s){return e instanceof Error?e.message:s}function fp({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(Cc,{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(xp,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Bo({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 ir.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 hp(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Zm,...ep,...tp].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 xp({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var K,U;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[p,m]=o.useState(null),[f,w]=o.useState("idle"),[k,A]=o.useState(""),d=e.version||null,b=((K=e.machine)==null?void 0:K.platform)||((U=e.system)==null?void 0:U.platform)||"",y=_t(e,{fallbackId:e.id}),h=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",N=s.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),_=s.filter(C=>C.daemonId===e.id&&C.transport==="pty"),g=s.filter(C=>C.daemonId===e.id&&C.transport==="acp"),I=e.p2p,j=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const C=pp(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),u(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),u(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(C.error||"Upgrade failed"))}catch(C){c("error"),u(Rn(C,"Connection lost during upgrade"))}}},v=async()=>{if(m(null),!!n){w("loading");try{await n(e.id),w("done"),A("Machine disconnected.")}catch(C){w("error"),A(Rn(C,"Failed to disconnect"))}}},x=async()=>{if(m(null),!!a){w("loading");try{await a(e.id),w("done"),A("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){w("error"),A(Rn(C,"Failed to revoke token"))}}},$="0.8.82",M=Ac(e,$),L=nr(e,$),T=N.length+_.length+g.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:h}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:y}),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),"…"]}),d&&t.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${M?"":"bg-bg-secondary"}`,style:M?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",d,!M&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&M&&t.jsx("button",{onClick:j,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${$}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${L?"↑ Update now":`↑ Update${` to v${$}`}`}`}),n&&t.jsx("button",{onClick:()=>m("disconnect"),disabled:f==="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:()=>m("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(ip,{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&&T>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),T>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(C=>{const R=hp(C.type),O=C.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}),O!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${O?"bg-green-400":"animate-pulse"}`,style:O?void 0:{background:"var(--status-warning)"},title:O?"CDP connected":"CDP connecting..."})]},C.id)}),_.map(C=>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:C.cliName||"CLI"})]},C.id)),g.map(C=>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:C.cliName||"ACP"})]},C.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||k)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-red-400":i==="done"||f==="done"?"text-green-400":"text-text-muted"}`,children:k||l})]}),p==="disconnect"&&t.jsx(Bo,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
33
+
34
+ This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
35
+
36
+ Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:v,onCancel:()=>m(null)}),p==="revoke"&&t.jsx(Bo,{title:"⚠️ Remove Machine",message:`Remove "${y}" from your dashboard?
37
+
38
+ This will:
39
+ • Immediately disconnect the machine
40
+ • Delete the machine registration
41
+ • Require restarting ADHDev on that machine
42
+
43
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:x,onCancel:()=>m(null)})]})}const bp=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function gp(){const{preference:e,setPreference:s}=Wa();return t.jsx("div",{className:"flex gap-2",children:bp.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 yp(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 vp(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Pn(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function Ko(e){const{r:s,g:r,b:n}=vp(e);return .2126*Pn(s)+.7152*Pn(r)+.0722*Pn(n)}function Wo(e,s){const r=Ko(e),n=Ko(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function Mc(e){const s=yp(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return Wo(s,r)>=Wo(s,n)?r:n}const ia={bgPrimary:"#0a0e1a",bgSecondary:"#0f1320",surfacePrimary:"#111726",textPrimary:"#f0f0f5",textSecondary:"#9ca3af",textMuted:"#6b7280",borderSubtle:"#1d2536",borderDefault:"#313c52",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#111726",assistantText:"#f0f0f5",containerBg:"#0f1320",sendButton:"#d97706",inputBorder:"#313c52",bubbleRadius:16},ca={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},wp=[{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"}}}],Tc="adhdev-chat-theme",Lc="adhdev-chat-theme-custom";function Gr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Tc)||"ember"}catch{return"ember"}}function Kt(e){try{const s=localStorage.getItem(Lc);if(s){const r=JSON.parse(s);return{...e==="dark"?ia:ca,...r[e]}}}catch{}return e==="dark"?ia:ca}function Rr(e,s){try{localStorage.setItem(Lc,JSON.stringify({dark:e,light:s}))}catch{}}function Et(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 nn(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 jp={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function ar(e,s){var a;const r=(a=jp[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",nn(r,24)),n.style.setProperty("--accent-on-primary",Mc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${nn(r,18)})`),n.style.setProperty("--border-accent",Et(r,.35)),n.style.setProperty("--nav-active-bg",Et(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Et(r,.06)}`)}function hs(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Et(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Et(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Et(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",Et(e.borderSubtle,.5)),s.style.setProperty("--border-default",Et(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",nn(e.accentColor,30)),s.style.setProperty("--accent-on-primary",Mc(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${nn(e.accentColor,40)})`),s.style.setProperty("--border-accent",Et(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Et(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Et(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 ${Et(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 Oa(){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 kp(e){try{localStorage.setItem(Tc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=xs()?"dark":"light";hs(Kt(s))}else Oa(),ar(e,xs()?"dark":"light")}function Sp(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Gr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=xs()?"dark":"light";hs(Kt(s))}else Oa(),ar(e,xs()?"dark":"light")}function xs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function St({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 Xs({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 Np({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>Kt(r));o.useEffect(()=>{a(Kt(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const p={...u,[c]:l},f=Kt(r==="dark"?"light":"dark");return r==="dark"?Rr(p,f):Rr(f,p),hs(p),s(p),p})},[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(Xs,{title:"App Background",children:[t.jsx(St,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(St,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(St,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs(Xs,{title:"App Text",children:[t.jsx(St,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(St,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(St,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs(Xs,{title:"Borders & Accent",children:[t.jsx(St,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(St,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(St,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs(Xs,{title:"Chat Bubbles",children:[t.jsx(St,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(St,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(St,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(St,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs(Xs,{title:"Chat Layout",children:[t.jsx(St,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(St,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(St,{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?ia:ca,u=Kt(e?"light":"dark");e?Rr(c,u):Rr(u,c),a(c),hs(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 Cp(){const[e,s]=o.useState(Gr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Kt("dark"));o.useEffect(()=>{n(xs());const u=new MutationObserver(()=>{const f=xs();n(f);const w=Gr();w==="custom"?hs(Kt(f?"dark":"light")):ar(w,f?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=xs();n(f);const w=Gr();w==="custom"?hs(Kt(f?"dark":"light")):ar(w,f?"dark":"light")};return p.addEventListener("change",m),()=>{u.disconnect(),p.removeEventListener("change",m)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?hs(Kt(r?"dark":"light")):(Oa(),ar(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Kt(r?"dark":"light"))},[r]);const c=u=>{s(u),kp(u)},l=[...wp,{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 p=e===u.id,m=r?u.preview.dark:u.preview.light,f=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:p?"var(--bg-glass-hover)":"var(--bg-glass)",border:p?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:p?1:.75},children:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.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:m.userBubble,color:f},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:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[p&&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(Np,{dark:r,onColorsChange:u=>i(u)})]})}const Ha="adhdev_mobileDashboardMode_v1",la="adhdev:mobile-dashboard-mode-change";function Ua(){try{return localStorage.getItem(Ha)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Ip(e){if(typeof window>"u")return()=>{};const s=a=>{e(a??Ua())},r=a=>{const i=a.detail;s(i)},n=a=>{a.key&&a.key!==Ha||s()};return window.addEventListener(la,r),window.addEventListener("storage",n),()=>{window.removeEventListener(la,r),window.removeEventListener("storage",n)}}function Ap(e){try{localStorage.setItem(Ha,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(la,{detail:e}))}function Mp(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(Ua()==="chat")},[]),t.jsx(ls,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Yt,{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),Ap(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function Tp(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 Lp(e,s){const{sendData:r}=Pt(),{injectEntries:n,getIdes:a}=Jr(),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=>ns.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:s==null?void 0:s.intervalMs}},p=>{const m=a().find(w=>w.id===u),f=Tp(m,u,p);n([f])}));return()=>{l.forEach(u=>u())}},[i,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}const _p=4e3;function _c(e,s){const{sendData:r}=Pt(),[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=ns.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}:{}}},p=>{l&&(clearTimeout(l),l=null),a(p.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},_p):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 Rp(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Rc(e){const{sendData:s}=Pt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=Rp(e);if(!a||!e.sessionId||!s){n({});return}const i=ns.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}),Ds.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()}},[e.daemonId,e.routeId,e.sessionId,s]),r}const Pc="adhdev_hiddenTabs";function Pp(){try{const e=localStorage.getItem(Pc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function Ns(e){try{localStorage.setItem(Pc,JSON.stringify([...e]))}catch{}}function Pr(e){return ka(e)}function Fa(e,s){return ts(s).some(r=>e.has(r))}function Dp(){const[e,s]=o.useState(Pp),r=o.useCallback(p=>{s(m=>{const f=new Set(m);return f.has(p)?f.delete(p):f.add(p),Ns(f),f})},[]),n=o.useCallback(p=>{s(m=>{if(m.has(p))return m;const f=new Set(m);return f.add(p),Ns(f),f})},[]),a=o.useCallback(p=>{s(m=>{if(!m.has(p))return m;const f=new Set(m);return f.delete(p),Ns(f),f})},[]),i=o.useCallback(()=>{s(p=>{if(p.size===0)return p;const m=new Set;return Ns(m),m})},[]),c=o.useCallback((p,m)=>{s(f=>{const w=new Set(f);for(const k of m)w.add(k);return Ns(w),w})},[]),l=o.useCallback((p,m)=>{s(f=>{const w=new Set(f);for(const k of m)w.delete(k);return Ns(w),w})},[]),u=o.useCallback(p=>Fa(e,p),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function Dc(e){return e instanceof Error?e.message:String(e||"")}function za(e){const s=Dc(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 Va(e){const s=Dc(e);return s.includes("P2P command timeout")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function Oo(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 Ep(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=Oo(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>Oo(u,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Ec(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 $p(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))Ec(s,a)===i&&(delete n[a],r=!0);return r?n:e}function Bp({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{zi()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:fc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return bu(a),o.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),p={};for(const[m,f]of Object.entries(l))u-f<5e3&&(p[m]=f);return Object.keys(p).length===Object.keys(l).length?l:p})},5500);return()=>clearTimeout(c)},[s,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const u=l.filter(p=>p.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(i)},[n]),null}function Kp(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 Dn(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 Wp(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 Ho(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?Wp($s(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.lastUpdated||""),Ho(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),Ho(r.activeChat)].join(":"))].join("|")}function Hp(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 Up(e,s){const r=[],n=e.sessionId||e.instanceId;r.push({key:e.id,ref:s[e.id]}),n&&r.push({key:n,ref:s[n]});for(const a of e.childSessions||[]){const i=a.id||a.providerType,c=`${e.id}:${i}`;r.push({key:c,ref:s[c]}),r.push({key:a.id,ref:s[a.id]})}return r}function Fp(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r].key!==s[r].key||e[r].ref!==s[r].ref)return!1;return!0}function zp(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const i of ts({routeId:n.routeId}))r.set(i,a);for(const i of ts({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of ts({tabKey:n.tabKey}))r.set(i,n)}return r}function Vp(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function Gp(e){const s=Vp(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=$s(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function qp({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:a}){const i=o.useMemo(()=>Kp(e),[e]),c=o.useMemo(()=>vc(e),[e]),l=o.useRef([]),u=o.useRef([]),p=o.useRef([]),m=o.useRef(new Map),f=o.useRef(new Map),w=o.useMemo(()=>{const g=new Map,I=[];for(const $ of i){const{connectionState:M="new",machineName:L}=wc($,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),T=Up($,r),K=Op($),U=m.current.get($.id);if(U&&U.ide===$&&U.sourceSignature===K&&U.connectionState===M&&U.machineName===L&&Fp(U.localRefs,T)){g.set($.id,U),I.push(...U.conversations);continue}const C=Ka($,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),R={ide:$,sourceSignature:K,connectionState:M,machineName:L,localRefs:T,conversations:C};g.set($.id,R),I.push(...C)}m.current=g;const j=new Map,v=$=>{const M=Gp($),L=f.current.get($.tabKey);if(L&&L.signature===M)return j.set($.tabKey,L),L.timestamp;const T={signature:M,timestamp:Zi($)||(L==null?void 0:L.timestamp)||0};return j.set($.tabKey,T),T.timestamp},x=[...I].sort(($,M)=>ec($,M,v));return f.current=j,x},[i,r,s,c]),k=o.useMemo(()=>{const g=Hp(w,n);return Dn(l.current,g)?l.current:(l.current=g,g)},[w,n]),A=o.useMemo(()=>{const g=new Map,I=Array.from(new Set(k.map(j=>j.routeId)));for(const j of I){const v=Wt(k,j);v&&g.set(j,v)}return g},[k]),d=o.useMemo(()=>{const g=new Map;for(const I of k){const j=A.get(I.routeId),v=I.streamSource==="native"&&j?j:I;for(const x of ts({providerSessionId:I.providerSessionId,sessionId:I.sessionId}))g.set(x,v)}return g},[k,A]),b=o.useMemo(()=>zp(k,A),[k,A]),y=o.useCallback(g=>{if(g)return d.get(g)},[d]),h=o.useCallback(g=>{if(g)return b.get(g)},[b]),N=o.useMemo(()=>{const g=k.filter(I=>!Fa(a,I));return Dn(u.current,g)?u.current:(u.current=g,g)},[k,a]),_=o.useMemo(()=>{const g=N.map(I=>I.tabKey);return Dn(p.current,g)?p.current:(p.current=g,g)},[N]);return{chatIdes:i,conversations:k,visibleConversations:N,visibleTabKeys:_,resolveConversationBySessionId:y,resolveConversationByTarget:h}}function Yp({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 Xp({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:a}){o.useEffect(()=>{it.setIdes(e)},[e]),o.useEffect(()=>{it.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),o.useEffect(()=>{const i=it.onToast(u=>{r(m=>m.some(w=>w.message===u.message&&u.timestamp-w.timestamp<3e3)?m:[...m.slice(-4),{id:u.id,message:u.message,type:u.type,timestamp:u.timestamp,targetKey:u.targetKey,actions:u.actions}]);const p=u.duration||5e3;setTimeout(()=>r(m=>m.filter(f=>f.id!==u.id)),p)}),c=it.onSystemMessage((u,p)=>{var k,A;const m=a(u),f=(k=p._localId)==null?void 0:k.startsWith("sys_approval_"),w=!!(m&&(m.status==="waiting_approval"||(A=m.modalButtons)!=null&&A.length||m.modalMessage));f&&w||n(d=>({...d,[u]:[...d[u]||[],p]}))}),l=it.onClearSystemMessage((u,p)=>{n(m=>{var f;return(f=m[u])!=null&&f.length?{...m,[u]:m[u].filter(w=>{var k;return!(w.role==="system"&&((k=w._localId)!=null&&k.startsWith(p)))})}:m})});return()=>{i(),c(),l()}},[r,n]),o.useEffect(()=>{const i=dc.on("status_event",c=>{it.handleRawEvent(c,"ws")});return()=>{i()}},[]),o.useEffect(()=>{var c;const i=l=>{var b;const u=l.data;if((u==null?void 0:u.type)!=="notification_action"||typeof u.action!="string"||!u.action.startsWith("approval_")||!(u.daemonId||u.targetSessionId||u.targetKey))return;const p=u.targetSessionId||u.targetKey||u.daemonId,m=a(p),f=(m==null?void 0:m.routeId)||u.daemonId;if(!f)return;const w=Number(u.buttonIndex),k=u.button||((b=m==null?void 0:m.modalButtons)==null?void 0:b[w])||"Approve",A=String(k).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),d=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(A);s(f,"resolve_action",{action:d?"approve":"reject",button:k,...Number.isFinite(w)&&{buttonIndex:w},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...u.targetSessionId&&{targetSessionId:u.targetSessionId}}).catch(y=>console.error("[SW Action] approval failed:",y))};return(c=navigator.serviceWorker)==null||c.addEventListener("message",i),()=>{var l;return(l=navigator.serviceWorker)==null?void 0:l.removeEventListener("message",i)}},[a,s])}const Qp="adhdev_dashboardLayout_v1",Jp="adhdev_dashboardDockview_v1",Zp="adhdev_dashboardDockviewHiddenRestore_v1",Qs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Ga(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function $c(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Bc(e){return`${Qp}:${e}`}function ef(e){const s=Bc(e);return Ga(s,null)}function tf(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=Bc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function Kc(e){return`${Jp}:${e}`}function sf(e){const s=Kc(e);return Ga(s,null)}function rf(e,s){try{const r=Kc(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Wc(e){return`${Zp}:${e}`}function nf(e){const s=Wc(e);return Ga(s,{})}function af(e,s){try{const r=Wc(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function of(){return{groupAssignments:[...Qs.groupAssignments],focusedGroup:Qs.focusedGroup,groupActiveTabIds:{...Qs.groupActiveTabIds},groupTabOrders:{...Qs.groupTabOrders},groupSizes:[...Qs.groupSizes]}}function cf(){const[e]=o.useState(()=>$c(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({}),[p,m]=o.useState([]),[f,w]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[k,A]=o.useState(!1),d=o.useCallback(()=>{if(k)return;const b=ef(e)??of();r(new Map(b.groupAssignments)),a(b.focusedGroup),c(b.groupActiveTabIds),u(b.groupTabOrders),m(b.groupSizes),A(!0)},[k,e]);return o.useEffect(()=>{k&&tf(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:p})},[k,e,s,n,i,l,p]),o.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),y=h=>w(h.matches);return b.addEventListener("change",y),()=>b.removeEventListener("change",y)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:a,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:u,groupSizes:p,setGroupSizes:m,isMobile:f,hasHydratedStoredLayout:k,hydrateStoredLayout:d}}function lf(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=ja(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function df({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:l,setSearchParams:u,historyModalOpen:p,activeConv:m,isRefreshingHistory:f,ides:w,handleRefreshHistory:k}){const A=o.useRef(!1),d=o.useRef(!1),b=o.useRef(null),y=o.useRef(!1);o.useEffect(()=>{if(!e||A.current||s.length===0)return;if(!a){i();return}const h=r(e);if(!h)return;const N=n.get(h.tabKey)??0;c(_=>({..._,[N]:h.tabKey})),l(N),A.current=!0,d.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),u(_=>{const g=new URLSearchParams(_);return g.delete("activeTab"),g},{replace:!0})},[e,s,r,n,a,i,c,l,u]),o.useEffect(()=>{if(!(d.current||a)&&s.length!==0){if(!e){i(),d.current=!0;return}if(A.current){d.current=!0;return}if(b.current==null)return b.current=window.setTimeout(()=>{b.current=null,!(d.current||a)&&(i(),d.current=!0)},1500),()=>{b.current!=null&&(window.clearTimeout(b.current),b.current=null)}}},[e,s.length,a,i]),o.useEffect(()=>{if(!p){y.current=!1;return}if(!m||y.current||f)return;const h=w.find(N=>N.id===m.routeId);h&&(!h.chats||h.chats.length===0||lf(h.chats,m))&&(y.current=!0,k())},[p,m,f,w,k]),o.useEffect(()=>{if(!m)return;let h=null,N=0,_=-1,g=0;const I=()=>{h=null;const j=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(x=>x.offsetParent!==null);if(j.length===0){N<18&&(N+=1,h=requestAnimationFrame(I));return}let v=0;for(const x of j)x.scrollTop=x.scrollHeight,v+=x.scrollHeight;v===_?g+=1:(g=0,_=v),N+=1,!(g>=2||N>=18)&&(h=requestAnimationFrame(I))};return h=requestAnimationFrame(I),()=>{h!=null&&cancelAnimationFrame(h)}},[m==null?void 0:m.tabKey])}function uf({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,p]=o.useState(null),[m,f]=o.useState(null),w=o.useMemo(()=>{if(e||!n)return null;const y=l(n);return y&&!Ze(y)&&!Xe(y)?y:null},[e,n,l]),k=o.useMemo(()=>{const y=u==null?void 0:u.routeId;if(!y)return null;const h=u!=null&&u.tabKey?i.find(N=>N.tabKey===u.tabKey):a?i.find(N=>N.tabKey===a):null;return(h==null?void 0:h.routeId)===y?h:Wt(i,y)},[i,u,a]),A=o.useMemo(()=>{if(k)return c.find(y=>y.id===k.routeId)},[c,k]);o.useEffect(()=>{w&&(p({routeId:w.routeId,tabKey:Io(w)}),f(w),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,w]);const d=o.useCallback(y=>{y&&(p({routeId:y.routeId,tabKey:Io(y)}),f(y))},[]),b=o.useCallback(()=>{p(null),f(null)},[]);return{remoteDialogConv:k,remoteDialogIdeEntry:A,remoteDialogActiveConv:m,setRemoteDialogActiveConv:f,openRemoteDialog:d,closeRemoteDialog:b}}function En(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=ja(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Uo({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setLocalUserMessages:i,setClearedTabs:c}){const[l,u]=o.useState(!1),[p,m]=o.useState(!1),f=o.useCallback(async d=>{try{await e("standalone","launch_ide",{ideType:d,enableCdp:!0})}catch(b){console.error("Launch failed",b)}},[e]),w=o.useCallback(async(d,b)=>{try{const y=d||(s==null?void 0:s.daemonId)||"",h=await e(y,"switch_chat",{id:b,sessionId:b,...Rs(s)}),N=h==null?void 0:h.result;if((h==null?void 0:h.success)===!0||N==="switched"||N==="switched-by-title")return;N===!1||N==="not_found"?Ys(a,"⚠️ Session tab not found — try refreshing history"):typeof N=="string"&&N.startsWith("error:")?Ys(a,`⚠️ Switch error: ${N}`):Ys(a,"⚠️ Session switch failed")}catch(y){console.error("Switch failed",y),Ys(a,`❌ Switch failed: ${y.message||"connection error"}`)}},[s,e,a]),k=o.useCallback(async()=>{if(!(!s||l)){u(!0);try{const d=mr(s);await e(d,"new_chat",{...Rs(s)}),c(b=>({...b,[s.tabKey]:Date.now()})),i(b=>({...b,[s.tabKey]:[]}))}catch(d){console.error("New chat failed",d)}finally{u(!1)}}},[s,l,e,c,i]),A=o.useCallback(async()=>{var d,b;if(!(!s||p)){m(!0);try{const y=mr(s),h=async()=>e(y,"list_chats",{forceExpand:!0,...Rs(s)});let N=await h(),_=(N==null?void 0:N.chats)||((d=N==null?void 0:N.result)==null?void 0:d.chats);En(_,s)&&(await new Promise(g=>setTimeout(g,450)),N=await h(),_=(N==null?void 0:N.chats)||((b=N==null?void 0:N.result)==null?void 0:b.chats)),N!=null&&N.success&&Array.isArray(_)&&(n(s.routeId,_),En(_,s)&&!En(r,s)&&Ys(a,"⚠️ History dialog did not fully open — try once more"))}catch(y){console.error("Refresh history failed",y)}finally{m(!1)}}},[s,r,p,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:p,handleLaunchIde:f,handleSwitchSession:w,handleNewChat:k,handleRefreshHistory:A}}function mf(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 pf(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function Fo(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 Dr(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 zo(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 ff(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 hf(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 Vo(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 Go(e){return Array(e).fill(100/e)}function xf({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:a,groupSizes:i,setGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:p}){const m=o.useRef(null),f=o.useMemo(()=>Dr(e,p),[e,p]),w=f.assignments,k=o.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),A=k>1,d=o.useCallback((g,I)=>{s(j=>{const v=new Map(Dr(j,p).assignments);return I===0?v.delete(g):v.set(g,I),v}),n(j=>({...j,[I]:g})),r(I)},[s,p,n,r]),b=o.useCallback(g=>{s(I=>{const j=Dr(I,p).assignments,v=new Map;for(const[x,$]of j)$!==g&&($>g?v.set(x,$-1):v.set(x,$));return v}),c(I=>{if(I.length<=1)return[];const j=[...I];j.splice(g,1);const v=j.reduce((x,$)=>x+$,0);return v>0?j.map(x=>x/v*100):[]}),r(0)},[s,p,c,r]),y=o.useCallback((g,I)=>{I.preventDefault();const j=m.current;if(!j)return;const v=I.clientX,x=j.offsetWidth,$=i.length===k?[...i]:Go(k),M=T=>{const U=(T.clientX-v)/x*100,C=[...$];C[g]=Math.max(15,$[g]+U),C[g+1]=Math.max(15,$[g+1]-U),c(C)},L=()=>{document.removeEventListener("mousemove",M),document.removeEventListener("mouseup",L),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",M),document.addEventListener("mouseup",L)},[i,k,c]),h=o.useCallback((g,I,j)=>{if(k>=4)return;const v=j==="left"?I:I+1;s(x=>{const $=Dr(x,p).assignments,M=new Map;for(const L of u){const T=$.get(L.tabKey)??0,K=T>=v?T+1:T;K>0&&M.set(L.tabKey,K)}return v>0&&M.set(g,v),M}),c(x=>{const $=x.length===k?[...x]:Go(k),M=$[I]??100/k,L=Math.max(15,M/2),T=Math.max(15,M/2),K=[...$];K[I]=L,K.splice(v,0,T);const U=K.reduce((C,R)=>C+R,0);return K.map(C=>C/U*100)}),n(x=>{const $=Vo(x,v);return $[v]=g,$}),a(x=>{const $=Vo(x,v);return $[v]=[g],$}),r(v)},[k,s,p,u,c,n,a,r]);o.useEffect(()=>{mf(e,w)||s(w)},[e,w,s]),o.useEffect(()=>{const{mapping:g,usedGroups:I}=f;n(j=>{const v=zo(j,g);return Fo(j,v)?j:v}),a(j=>{const v=zo(j,g);return Fo(j,v)?j:v}),r(j=>{const v=l?0:ff(j,I,g);return j===v?j:v}),c(j=>{const v=l?[]:hf(j,I,f.groupCount);return pf(j,v)?j:v})},[f,l,n,a,r,c]);const N=o.useMemo(()=>{const g=Array.from({length:k},()=>[]);for(const I of u){const j=w.get(I.tabKey)??0,v=Math.min(j,k-1);g[v].push(I)}return g},[u,w,k]),_=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:m,normalizedGroupAssignments:w,numGroups:k,isSplitMode:A,groupedConvs:N,moveTabToGroup:d,closeGroup:b,handleResizeStart:y,splitTabRelative:h,clearAllSplits:_}}function bf({ides:e,sendDaemonCommand:s}){const r="0.8.82",n=o.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:Ac(m,r)).sort((m,f)=>Number(nr(f,r))-Number(nr(m,r))),[r,e]),a=o.useMemo(()=>n.some(m=>nr(m,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),p=o.useCallback(async m=>{var f,w;u(k=>({...k,[m]:"upgrading"}));try{const k=await s(m,"daemon_upgrade",{});(f=k==null?void 0:k.result)!=null&&f.upgraded||(w=k==null?void 0:k.result)!=null&&w.success?u(A=>({...A,[m]:"done"})):u(A=>({...A,[m]:"error"}))}catch{u(k=>({...k,[m]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:p}}const da="adhdev_dashboard_notifications_v2",ua="adhdev_dashboard_notifications_v1",gr=80;function qr(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function qa(e){return{...e,createdAt:qr(e.createdAt),updatedAt:qr(e.updatedAt,e.createdAt),lastEventAt:qr(e.lastEventAt,e.updatedAt||e.createdAt)}}function gf(e){const s=ka(e);return s==="unknown:"?e.id:s}function qo(e){return[e.type,Di(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function yf(e,s,r,n){var c;const a=Date.now(),i=[];for(const l of e){const u=l.sessionId?s.get(l.sessionId):void 0;if(u!=null&&u.surfaceHidden)continue;const p=qo({type:"task_complete",sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,lastMessageHash:l.lastMessageHash,lastMessageAt:l.lastMessageAt,lastUpdated:(u==null?void 0:u.lastUpdated)||l.lastUpdated}),m=!!((c=n==null?void 0:n.get(p))!=null&&c.forceUnread),f=mn(l,s,{notificationStateBySessionId:r}),w=f.inboxBucket==="needs_attention"?"needs_attention":f.inboxBucket==="task_complete"&&f.unread||(u==null?void 0:u.inboxBucket)==="task_complete"&&m?"task_complete":null;if(!w)continue;const k=qr(l.lastMessageAt||(u==null?void 0:u.lastUpdated)||l.lastUpdated,a),A=w==="task_complete"?p:qo({type:w,sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,lastMessageHash:l.lastMessageHash,lastMessageAt:l.lastMessageAt,lastUpdated:(u==null?void 0:u.lastUpdated)||l.lastUpdated});i.push(qa({id:A,dedupKey:A,type:w,routeId:l.routeId,machineId:l.daemonId||l.routeId,sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,title:Xi(l),preview:Wu(l),createdAt:k,updatedAt:k,lastEventAt:k}))}return i.sort((l,u)=>u.updatedAt-l.updatedAt)}function vf(e,s=gr){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=gf(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 wf(e){return e.filter(s=>typeof s.readAt=="number"||typeof s.deletedAt=="number").map(s=>({id:s.id,...typeof s.readAt=="number"?{readAt:s.readAt}:{},...typeof s.deletedAt=="number"?{deletedAt:s.deletedAt}:{}}))}function jf(e){return new Map(e.map(s=>[s.id,s]))}function Oc(e,s,r=gr){const n=new Map;for(const i of s)n.set(i.id,i);const a=e.map(i=>{const c=qa(i),l=n.get(c.id);return{...c,...typeof(l==null?void 0:l.readAt)=="number"?{readAt:l.readAt}:{},...typeof(l==null?void 0:l.deletedAt)=="number"?{deletedAt:l.deletedAt}:{}}});return vf(a,r)}function kf(e,s,r=gr){const n=new Set(Oc(s,[],r).map(a=>a.id));return e.filter(a=>n.has(a.id)).slice(0,Math.max(0,r))}function Sf(e,s,r=Date.now()){const n=e.filter(a=>a.id!==s);return n.push({id:s,readAt:r}),n}function Nf(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,forceUnread:!0}),r}function Cf(e,s,r,n=Date.now()){const a=e.filter(i=>{const c=s.find(l=>l.id===i.id);return!c||!lr(c,r)});for(const i of s)lr(i,r)&&a.push({id:i.id,readAt:n});return a}function If(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,deletedAt:Date.now()}),r}function Af(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function Mf(e){const s=new Map;for(const r of e){if(r.deletedAt)continue;const n=ts(r);if(n.length===0)continue;const a=r.readAt?0:1;for(const i of n){const c=s.get(i);if(!c){s.set(i,{unreadCount:a,latestNotificationAt:r.updatedAt,latestRecordId:r.id});continue}s.set(i,{unreadCount:c.unreadCount+a,latestNotificationAt:Math.max(c.latestNotificationAt,r.updatedAt),latestRecordId:c.latestNotificationAt>=r.updatedAt?c.latestRecordId:r.id})}}return s}function Tf(){if(typeof window>"u")return[];const e=s=>{if(!s||typeof s!="object")return null;const r=s;if(typeof r.id!="string"||r.id.length===0)return null;const n=typeof r.readAt=="number"&&Number.isFinite(r.readAt)?r.readAt:void 0,a=typeof r.deletedAt=="number"&&Number.isFinite(r.deletedAt)?r.deletedAt:void 0,i=r.forceUnread===!0;return typeof n!="number"&&typeof a!="number"&&!i?null:{id:r.id,...typeof n=="number"?{readAt:n}:{},...typeof a=="number"?{deletedAt:a}:{},...i?{forceUnread:!0}:{}}};try{const s=window.localStorage.getItem(da),r=s?JSON.parse(s):[];if(Array.isArray(r))return r.map(e).filter(n=>!!n)}catch{}try{const s=window.localStorage.getItem(ua),r=s?JSON.parse(s):[];return Array.isArray(r)?wf(r.map(n=>qa(n)).filter(n=>!n.deletedAt)):[]}catch{return[]}}function Lf(e){if(!(typeof window>"u"))try{const s=e.filter(r=>typeof r.readAt=="number"||typeof r.deletedAt=="number"||r.forceUnread===!0).slice(0,gr);if(s.length===0){window.localStorage.removeItem(da),window.localStorage.removeItem(ua);return}window.localStorage.setItem(da,JSON.stringify(s)),window.localStorage.removeItem(ua)}catch{}}function _f(e,s){return e===s?!0:e.length!==s.length?!1:e.every((r,n)=>{const a=s[n];return a?r.id===a.id&&r.readAt===a.readAt&&r.deletedAt===a.deletedAt&&r.forceUnread===a.forceUnread:!1})}function Rf(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=gr}=e,[a,i]=o.useState(()=>Tf()),c=o.useMemo(()=>jf(a),[a]),l=o.useMemo(()=>yf(s,r,void 0,c),[s,r,c]),u=o.useMemo(()=>Oc(l,a,n),[l,a,n]),p=o.useMemo(()=>Mf(u),[u]);o.useEffect(()=>{i(d=>{const b=kf(d,l,n);return _f(d,b)?d:b})},[l,n]),o.useEffect(()=>{Lf(a)},[a]);const m=o.useMemo(()=>Af(u),[u]),f=o.useCallback((d,b)=>{i(y=>Sf(y,d,b))},[]),w=o.useCallback(d=>{i(b=>Nf(b,d))},[]),k=o.useCallback((d,b)=>{i(y=>Cf(y,u,d,b))},[u]),A=o.useCallback(d=>{i(b=>If(b,d))},[]);return{notifications:u,unreadCount:m,notificationStateBySessionId:p,markRead:f,markUnread:w,markTargetRead:k,deleteNotification:A}}function Hc(){return"select_session"}function Pf(){return"open_panel"}function Df({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function Ef(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function Yo(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function Xo(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Ya(e){return e instanceof Error?e.message:String(e||"")}function Qo(e){const s=Ya(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Jo(e,s){const r=Ya(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function fn({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:a}){const[i,c]=o.useState(!1),[l,u]=o.useState(!1),[p,m]=o.useState(null),f=o.useRef(!1),w=o.useRef(null);o.useEffect(()=>{m(null)},[s==null?void 0:s.tabKey]);const k=o.useCallback(async y=>{if(!s)return!1;const h=y.trim(),N=La(s);if(Df({hasMessage:!!h,blockedMessage:N,sendInFlight:f.current}))return N&&m(N),!1;const _=Date.now(),g={tabKey:s.tabKey,message:h,timestamp:_};if(Ef(w.current,g))return m(null),!0;f.current=!0,u(!0),m(null),w.current=g;const I=`${_}-${Math.random().toString(36).slice(2,8)}`,j={role:"user",content:h,timestamp:_,_localId:I},v=!0;r(x=>({...x,[g.tabKey]:[...x[g.tabKey]||[],j]}));try{const x=mr(s);if(!x)return w.current=Yo(w.current,g),v&&r(L=>({...L,[g.tabKey]:(L[g.tabKey]||[]).filter(T=>T._localId!==I)})),m("Unable to send message right now."),!1;const $=await e(x,"send_chat",{message:h,...Rs(s)}),M=Xo($);if(v&&(M!=null&&M.deduplicated))return r(L=>({...L,[g.tabKey]:(L[g.tabKey]||[]).filter(T=>T._localId!==I)})),m(null),!0;if((M==null?void 0:M.sent)===!1)throw new Error((M==null?void 0:M.error)||"Send failed");if((M==null?void 0:M.success)===!1)throw new Error((M==null?void 0:M.error)||"Send failed");return setTimeout(()=>{const L=Date.now()-6e4;r(T=>{const K=T[g.tabKey];if(!K)return T;const U=K.filter(C=>C.timestamp>L);return U.length===K.length?T:{...T,[g.tabKey]:U}})},6e4),m(null),!0}catch(x){const $=Ya(x);return $.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",$):console.warn("Send blocked/failed",x),w.current=Yo(w.current,g),r(M=>({...M,[g.tabKey]:(M[g.tabKey]||[]).filter(L=>L._localId!==I)})),m(am(x)),!1}finally{f.current=!1,u(!1)}},[s,e,n,r]),A=o.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(y){console.error("Relaunch failed",y)}},[s,e]),d=o.useCallback(async y=>{if(s)try{const N=(s.modalButtons||[]).indexOf(y),_=y.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),g=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(_),I=mr(s);if(!I)return;const j=await e(I,"resolve_action",{button:y,action:g?"approve":"reject",...N>=0&&{buttonIndex:N},...Rs(s)}),v=Xo(j);v.success||n(x=>[...x,{routeId:s.tabKey,text:Jo(y,v==null?void 0:v.error),timestamp:Date.now()}])}catch(h){Qo(h)||console.error("[ModalButton] Error:",h),n(N=>[...N,{routeId:s.tabKey,text:Qo(h)?Jo(y,h):`❌ **${y}** error`,timestamp:Date.now()}])}},[s,e,n]),b=o.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,Pf(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(y){console.error("Focus agent failed",y)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,sendFeedbackMessage:p,isFocusingAgent:i,handleSendChat:k,handleRelaunch:A,handleModalButton:d,handleFocusAgent:b}}const Xa=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:w,actionLogs:k,userName:A,scrollToBottomRequestNonce:d,isInputActive:b=!0}){const y=Rc(s),h=y.status||y.modalMessage||y.modalButtons?{...s,...y.status?{status:y.status}:{},...y.modalMessage!==void 0?{modalMessage:y.modalMessage}:{},...y.modalButtons!==void 0?{modalButtons:y.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(Bi,{activeConv:h,onModalButton:c}),h.transport!=="pty"&&h.transport!=="acp"&&h.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(ys,{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,h.transport==="pty"?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{display:n?"flex":"none",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(Lm,{activeConv:h,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(aa,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:w,actionLogs:k,userName:A,scrollToBottomRequestNonce:d,isInputActive:b})})]}):t.jsx(aa,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:w,actionLogs:k,userName:A,scrollToBottomRequestNonce:d,isInputActive:b})]})},(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 $f({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:p,onOpenNativeConversation:m,onOpenMachine:f,onOpenHistory:w,onOpenRemote:k,onHideConversation:A,onStopCli:d,cliViewMode:b,onSetCliViewMode:y,handleSendChat:h,handleFocusAgent:N,handleModalButton:_,handleRelaunch:g}){const I=o.useRef(null),j=Ze(e)&&!s,v=j&&b==="terminal",x=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 ${x} 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:p,type:"button","aria-label":"Back",children:t.jsx(ba,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:ct(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(sc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>m(e),onOpenMachine:()=>f(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[j&&b&&t.jsx(Ra,{mode:b,onChange:y,compact:!0}),j&&d&&t.jsx("button",{onClick:()=>{d(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(It,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:t.jsx(ya,{size:14})}),!s&&!j&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",children:t.jsx(Rt,{size:14})}),A&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>A(e),type:"button",title:"Close chat",children:t.jsx(It,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(Xa,{activeConv:e,clearToken:0,isCliTerminal:v,ideEntry:n,terminalRef:I,handleModalButton:_,handleRelaunch:g,handleSendChat:h,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:N,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const $n={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 Bf(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Uc(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(Bf())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText($n[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:$n[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:$n[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 Fc({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Rt},{key:"chats",label:"Chats",icon:Yt}];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 Er({title:e,className:s=""}){return t.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:t.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function Cs({children:e,className:s=""}){return t.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${s}`,children:e})}function Js({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 $r({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:p}=Vs(e.conversation),m=ct(e.conversation),f=ws(e.conversation),w=pc(e.conversation,{requiresAction:s==="needs_attention"}),k=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",A=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",d=c?"text-text-secondary":"text-text-primary",b=c?"text-text-muted":"text-text-secondary",y=c?"text-text-secondary opacity-80":"text-text-muted",h=c?"text-text-muted opacity-80":"text-text-muted",N="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] ${k}`,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 ${A}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(m)}),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 ${d}`,children:m}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${h}`,children:$i(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[f,u?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${N} animate-pulse`,children:"Reconnecting…"})]}):p?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):w==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:N,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${y}`,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 Zo({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 Kf({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:p,onShowAllHidden:m,onOpenNewSession:f,onOpenMachine:w,onOpenSettings:k,onSectionChange:A,wsStatus:d="connected",isStandalone:b=!1}){const y=d==="disconnected"||d==="reconnecting"||d==="offline"||d==="auth_failed",h=c.length>0,N=s.length>0||r.length>0||n.length>0||a.length>0,_=e==="machines"?"Machines":"Chats",g=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",I=b?"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 ${g}`,children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:_}),t.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(dn,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:k,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(cn,{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:y?t.jsx(Js,{icon:t.jsx(Zo,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:d==="offline"?"Your device appears to be offline. Waiting for network…":d==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?t.jsx(Js,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:b?"Waiting for your daemon":"Connect your machines",subtitle:b?"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:!b&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(Uc,{})})}):t.jsx(Cs,{children:c.map((j,v)=>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] ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>w(j.id),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(j.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:j.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:j.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[j.unread," new"]}):j.total>0?`${j.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:j.subtitle}),j.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[j.total," chat",j.total!==1?"s":"",j.unread>0?` · ${j.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},j.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Er,{title:"Needs attention",className:"mb-0"}),t.jsx(Cs,{children:s.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx($r,{item:j,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Er,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(Cs,{children:r.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx($r,{item:j,type:"task_complete",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Er,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(Cs,{children:n.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx($r,{item:j,type:"working",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&t.jsx(Er,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(Cs,{children:a.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx($r,{item:j,type:"earlier",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))}):N?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):y?t.jsx(Js,{icon:t.jsx(Zo,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):h?t.jsx(Js,{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(Yt,{size:20})}),title:"No conversations yet",subtitle:"Your machines are available. Open a machine, wait for P2P to connect, then launch your first IDE, CLI, or ACP session."}):t.jsx(Js,{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:m,children:"Restore all"})]}),t.jsx(Cs,{className:"bg-bg-secondary/25",children:i.map((j,v)=>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 ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(j),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:l(ct(j))}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:ct(j)}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:ws(j)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},j.tabKey))})]})]}),e==="chats"&&f&&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:f,"aria-label":"Start new session",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(Fc,{section:e,onSectionChange:A})]})}function Wf(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 zc(e){const s=[e.workspace||"Workspace unknown"],r=vs(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=Wf(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function hn(...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 Of(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 xn(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=Of(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 Hf(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 Uf(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function bn(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=Uf(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=(p,m)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${m}`:p==="/"||p==="\\"?`${c}${m}`:`${p.replace(/[\\/]+$/,"")}${c}${m}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:l(i,p.name)})).sort((p,m)=>p.name.localeCompare(m.name)):[];return{path:i,directories:u}}function gn({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:p}){const[m,f]=o.useState(r);o.useEffect(()=>{f(r)},[r]);const w=Hf(r),k=m.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(It,{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:()=>{!w||a||u(w)},disabled:!w||a,children:[t.jsx(ba,{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:m,onChange:A=>f(A.target.value),onKeyDown:A=>{A.key!=="Enter"||!k||a||(A.preventDefault(),u(k))},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:()=>{!k||a||u(k)},disabled:!k||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(A=>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(A.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(Es,{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:A.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:A.path})]})]},A.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:()=>p(k||r),disabled:!k&&!r||a,children:c})]})]})})}function Qa({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:p,argsValue:m,onArgsChange:f,showModelInput:w,modelValue:k,onModelChange:A,historyProviderNode:d,onConfirm:b,onCancel:y}){const h=n==null?void 0:n.find(N=>N.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:y,"aria-label":"Close launch confirmation",children:t.jsx(It,{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:N=>i(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:n.map(N=>t.jsx("option",{value:N.key,children:N.label},N.key))}),(h==null?void 0:h.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h.description})]}),d,r.map(N=>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:N.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:N.value})]},`${N.label}:${N.value}`)),w&&A&&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:k||"",onChange:N=>A(N.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),p&&f&&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:m||"",onChange:N=>f(N.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled: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:y,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:b,disabled:u,children:[t.jsx(va,{size:14}),u?l:c]})]})]})})}function ei(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function bs(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?"⭐ ":""}${ei(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:ei(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(p=>p.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 Ff(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function zf(e){return[Ff(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Vf(e){return e.lastLaunchedAt?un(e.lastLaunchedAt):""}function Vc(e){return{metaText:zf(e),updatedLabel:Vf(e)}}function Bn(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function Gf({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var ze,ft,xt,ot;const c=xr(),[l,u]=o.useState(!1),p=(((ze=e.detectedIdes)==null?void 0:ze.length)||0)>0,m=o.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),f=e.defaultWorkspaceId||null,[w,k]=o.useState(f||((ft=m[0])==null?void 0:ft.id)||""),[A,d]=o.useState(""),[b,y]=o.useState(""),[h,N]=o.useState([]),[_,g]=o.useState(!1),[I,j]=o.useState(""),[v,x]=o.useState(!1),[$,M]=o.useState(Bn(p,s.length,r.length)),L=o.useRef(null),[T,K]=o.useState(null),U=o.useRef("__home__"),[C,R]=o.useState("__home__"),[O,S]=o.useState(""),[D,G]=o.useState(""),[q,H]=o.useState(""),[re,ae]=o.useState([]),[Ne,X]=o.useState(()=>vt().textQuery),[he,ke]=o.useState(()=>vt().workspaceQuery),[ie,xe]=o.useState(()=>vt().modelQuery),[pe,V]=o.useState(()=>vt().resumableOnly),[ge,ne]=o.useState(()=>vt().sortMode),[ce,Z]=o.useState(!1),[le,ee]=o.useState(!1),ye=o.useRef(null),be=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const B=w==="__custom__"?A.trim():((xt=m.find(Te=>Te.id===w))==null?void 0:xt.path)||"",ve=w==="__custom__"&&!!B&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),Ce=w!=="__custom__"&&((ot=m.find(Te=>Te.id===w))==null?void 0:ot.path)||"",Ae=o.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),Q=o.useCallback(async Te=>{g(!0),j("");try{const Ge=await a(Te);y(Ge.path),d(Ge.path),N(Ge.directories)}catch(Ge){j(Ge instanceof Error?Ge.message:"Could not load folder")}finally{g(!1)}},[a]),Pe=o.useCallback(()=>{var Ge;k("__custom__"),x(!0);const Te=xn(e.platform,hn(A.trim(),Ce,Ae,e.defaultWorkspacePath,(Ge=m.find(Oe=>Oe.id===f))==null?void 0:Ge.path,m.map(Oe=>Oe.path)));Q(Te)},[A,f,Q,Ae,Ce,e.platform,m]),He=o.useCallback(Te=>{if(Te!=null&&Te.workspaceId){k(Te.workspaceId),d("");return}if(Te!=null&&Te.workspacePath){k("__custom__"),d(Te.workspacePath);return}k(""),d("")},[]),$e=o.useCallback(Te=>{if(k(Te),Te==="__custom__"){Pe();return}d("")},[Pe]),Be=o.useCallback(Te=>{k("__custom__"),d(Te)},[]),Ye=o.useCallback((Te,Ge)=>{L.current=Ge,U.current=Te.selectedWorkspaceKey||"__home__",R(Te.selectedWorkspaceKey||"__home__"),S(Te.initialArgs||""),G(Te.initialModel||""),H(""),ae([]);const Oe=Te.providerType?`${e.id}:${Te.providerType}`:null;if(Dm(be.current,Oe)){const Ue=vt();X(Ue.textQuery),ke(Ue.workspaceQuery),xe(Ue.modelQuery),V(Ue.resumableOnly),ne(Ue.sortMode)}be.current=Oe,K(Te),Te.providerType&&i&&(Z(!0),i(Te.providerType).then(Ue=>ae(Ue||[])).catch(Ue=>console.warn("Failed to load saved sessions",Ue)).finally(()=>Z(!1)))},[i,e.id]),Ve=o.useMemo(()=>xc(re,{textQuery:Ne,workspaceQuery:he,modelQuery:ie,resumableOnly:pe,sortMode:ge}),[ie,pe,re,ge,Ne,he]);o.useEffect(()=>{q&&(Ve.some(Te=>Te.providerSessionId===q)||H(""))},[Ve,q]);const ut=o.useCallback(()=>{L.current&&(ee(!0),L.current().finally(()=>{L.current=null,ee(!1),K(null)}))},[]),at=o.useCallback(()=>{L.current=null,K(null)},[]),pt=o.useCallback(Te=>{U.current=Te,R(Te)},[]);return o.useEffect(()=>{var Te;ye.current!==e.id&&(ye.current=e.id,k(f||((Te=m[0])==null?void 0:Te.id)||"__custom__"),d(""),y(""),N([]),j(""),x(!1),X(vt().textQuery),ke(vt().workspaceQuery),xe(vt().modelQuery),V(vt().resumableOnly),ne(vt().sortMode),be.current=null,M(Bn(p,s.length,r.length)))},[r.length,s.length,f,p,e.id,m]),o.useEffect(()=>{var Te;w!=="__custom__"&&(w&&m.some(Ge=>Ge.id===w)||k(f||((Te=m[0])==null?void 0:Te.id)||"__custom__"))},[f,w,m]),o.useEffect(()=>{$==="ide"&&p||$==="cli"&&s.length>0||$==="acp"&&r.length>0||M(Bn(p,s.length,r.length))},[$,r.length,s.length,p]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:m,defaultWorkspaceId:f,workspaceChoice:w,customWorkspacePath:A,browseCurrentPath:b,browseDirectories:h,browseBusy:_,browseError:I,browseDialogOpen:v,activeLauncherKind:$,launchConfirm:T,launchConfirmWorkspaceKeyRef:U,launchConfirmWorkspaceKey:C,launchConfirmArgs:O,launchConfirmModel:D,launchConfirmResumeId:q,launchConfirmSavedSessions:re,launchConfirmTextFilter:Ne,launchConfirmWorkspaceFilter:he,launchConfirmModelFilter:ie,launchConfirmResumableOnly:pe,launchConfirmSortMode:ge,filteredLaunchConfirmSavedSessions:Ve,launchConfirmSessionsLoading:ce,launchConfirmBusy:le,resolvedWorkspacePath:B,canCreateMissingWorkspace:ve,openBrowseDialog:Pe,loadBrowsePath:Q,handleWorkspaceChoiceChange:$e,chooseCustomWorkspacePath:Be,setCustomWorkspacePath:d,setBrowseDialogOpen:x,setActiveLauncherKind:M,openLaunchConfirm:Ye,handleConfirmLaunch:ut,closeLaunchConfirm:at,setWorkspaceSelectionFromOption:He,setLaunchConfirmWorkspaceKeyAndSync:pt,setLaunchConfirmArgs:S,setLaunchConfirmModel:G,setLaunchConfirmResumeId:H,setLaunchConfirmTextFilter:X,setLaunchConfirmWorkspaceFilter:ke,setLaunchConfirmModelFilter:xe,setLaunchConfirmResumableOnly:V,setLaunchConfirmSortMode:ne}}function qf({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:p,showBottomNav:m,onBack:f,onSectionChange:w,onOpenConversation:k,onOpenRecent:A,onOpenMachineDetails:d,onMachineUpgrade:b,onLaunchDetectedIde:y,onAddWorkspace:h,onBrowseDirectory:N,onLaunchWorkspaceProvider:_,onListSavedSessions:g}){const I=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",j=r.slice(0,4),v=s.slice(0,3),x=Gf({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:N,onListSavedSessions:g}),$=o.useMemo(()=>j.map(C=>{const{metaText:R,updatedLabel:O}=Vc(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:R,updatedLabel:O,onClick:()=>{const{options:S,selectedKey:D}=bs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspacePath:C.workspace});x.openLaunchConfirm({title:C.kind==="ide"?ps("restart-ide",C.label):C.providerSessionId?Ea(C.label):ps("start-fresh",C.label),description:C.kind==="ide"?fs("restart-ide"):C.providerSessionId?$a():fs("start-fresh"),confirmLabel:C.kind==="ide"?Hs("restart-ide"):C.providerSessionId?sn(!0):Hs("start-fresh"),busyLabel:C.kind==="ide"?Us("restart-ide"):C.providerSessionId?Pa(!0):Us("start-fresh"),workspaceOptions:S,selectedWorkspaceKey:D,details:[{label:"Mode",value:I(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const G=S.find(q=>q.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(G),await A({...C,workspace:(G==null?void 0:G.workspacePath)??null})})}}}),[x,A,j]),M=o.useMemo(()=>v.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:ct(C.conversation),secondary:Im(C.conversation,{timestampLabel:C.timestamp?$i(C.timestamp):null}),unread:C.unread,onClick:()=>k(C.conversation)})),[k,v]),L=x.showAllRecent?$:$.slice(0,4),T=$.length>0,K=M.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:f,type:"button","aria-label":"Back",children:t.jsx(ba,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:_t(e,{fallbackId:e.id})}),t.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[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:M.map(C=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),T&&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:L.map(C=>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:C.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:C.primary}),C.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:C.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),$.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:()=>x.setShowAllRecent(C=>!C),children:x.showAllRecent?"Show fewer":`Show ${$.length-4} more`})})]}),(x.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:x.workspaceChoice,onChange:C=>x.handleWorkspaceChoiceChange(C.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:x.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[x.workspaceRows.map(C=>t.jsxs("option",{value:C.id,children:[C.id===x.defaultWorkspaceId?"⭐ ":"",pn(C.path,C.label)||C.path]},C.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),x.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(Es,{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:x.resolvedWorkspacePath||x.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:x.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:()=>{x.resolvedWorkspacePath&&h(x.resolvedWorkspacePath)},disabled:!x.resolvedWorkspacePath||x.browseBusy,children:"Save as workspace"})]})]}),x.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[x.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.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:()=>x.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.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:()=>x.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.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:()=>x.setActiveLauncherKind("acp"),children:"ACP"})]}),x.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:x.activeLauncherKind==="ide"?"Choose an IDE":x.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:x.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(C=>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:O}=bs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:R,selectedWorkspaceKey:O,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const S=R.find(D=>D.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(S),y(C.type,{workspacePath:(S==null?void 0:S.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(x.activeLauncherKind==="cli"?n:a).map(C=>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=x.activeLauncherKind==="cli"?"cli":"acp",{options:O,selectedKey:S}=bs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${R.toUpperCase()}`,workspaceOptions:O,selectedWorkspaceKey:S,details:[{label:"Mode",value:R.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:R==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const D=O.find(G=>G.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(D),_(R,C.type,{workspaceId:(D==null?void 0:D.workspaceId)??null,workspacePath:(D==null?void 0:D.workspacePath)??null,args:x.launchConfirmArgs,model:x.launchConfirmModel,resumeSessionId:x.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[C.icon?`${C.icon} `:"",C.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},C.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,x.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:()=>h(x.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:b,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:d,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"})]})]})]})]}),x.browseDialogOpen&&t.jsx(gn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:x.browseCurrentPath,directories:x.browseDirectories,busy:x.browseBusy,error:x.browseError,confirmLabel:"Use this folder",onClose:()=>x.setBrowseDialogOpen(!1),onNavigate:C=>{x.loadBrowsePath(C)},onConfirm:C=>{x.chooseCustomWorkspacePath(C),x.setBrowseDialogOpen(!1)}}),x.launchConfirm&&t.jsx(Qa,{title:x.launchConfirm.title,description:x.launchConfirm.description,details:x.launchConfirm.details,workspaceOptions:x.launchConfirm.workspaceOptions,selectedWorkspaceKey:x.launchConfirmWorkspaceKey,onWorkspaceChange:x.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:x.launchConfirm.providerType?sn(!!x.launchConfirmResumeId):x.launchConfirm.confirmLabel,busyLabel:x.launchConfirm.providerType?void 0:x.launchConfirm.busyLabel,busy:x.launchConfirmBusy,showArgsInput:x.launchConfirm.showArgsInput,argsValue:x.launchConfirmArgs,onArgsChange:x.setLaunchConfirmArgs,showModelInput:x.launchConfirm.showModelInput,modelValue:x.launchConfirmModel,onModelChange:x.setLaunchConfirmModel,historyProviderNode:x.launchConfirm.providerType&&(x.launchConfirmSessionsLoading||x.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"}),x.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:Da()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:x.launchConfirmTextFilter,onChange:C=>x.setLaunchConfirmTextFilter(C.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:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmWorkspaceFilter,onChange:C=>x.setLaunchConfirmWorkspaceFilter(C.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:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmModelFilter,onChange:C=>x.setLaunchConfirmModelFilter(C.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:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsxs("select",{value:x.launchConfirmSortMode,onChange:C=>x.setLaunchConfirmSortMode(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.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:x.launchConfirmResumableOnly,onChange:C=>x.setLaunchConfirmResumableOnly(C.target.checked),disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:x.launchConfirmResumeId,onChange:C=>x.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:Bm()}),x.filteredLaunchConfirmSavedSessions.map(C=>t.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.providerSessionId))]}),!x.launchConfirmSessionsLoading&&x.launchConfirmSavedSessions.length>0&&x.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),x.launchConfirmResumeId&&(()=>{const C=x.filteredLaunchConfirmSavedSessions.find(O=>O.providerSessionId===x.launchConfirmResumeId);if(!C)return null;const R=zc(C);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:x.handleConfirmLaunch,onCancel:x.closeLaunchConfirm}),m&&t.jsx(Fc,{section:p,onSectionChange:w})]})}function Gc(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 Yf(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:vs(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,p,m;const a=dr(n)?"cli":Ls(n)?"acp":"ide",i=vs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(dr(n)?n.cliName||n.type:Ls(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ls(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((m=(p=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:p.call(u,-1))==null?void 0:m.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Xf(e,s){const r=new Map;for(const n of s){const a=as(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((f,w)=>w.timestamp-f.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=ea(n),u=a.filter(f=>f.unread||f.requiresAction).length,p=Gc(n),m=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:_t(n,{fallbackId:n.id}),subtitle:m.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?Am(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 Br(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 Qf({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:m,onRequestedMachineConsumed:f,requestedMobileSection:w,onRequestedMobileSectionConsumed:k,setSelectedTabKey:A,setScreen:d,setSelectedMachineId:b,setSection:y,setMachineBackTarget:h,resetMachineAction:N,markNotificationTargetRead:_}){const g=o.useRef(null),I=o.useCallback(j=>{if(!(j!=null&&j.sessionId))return;const v=Zr(j,c),x=Math.max(Date.now(),ds(j),v.lastUpdated||0);Br("mark_read:start",{tabKey:j.tabKey,sessionId:j.sessionId,displayPrimary:ct(j),inboxBucket:v.inboxBucket,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,activityAt:ds(j),readAt:x}),_({sessionId:j.sessionId,providerSessionId:j.providerSessionId,tabKey:j.tabKey,routeId:j.routeId},x),l(as(j)||j.routeId,"mark_session_seen",{sessionId:j.sessionId,seenAt:x}).then($=>{Br("mark_read:result",{tabKey:j.tabKey,sessionId:j.sessionId,result:$})}).catch($=>{Br("mark_read:error",{tabKey:j.tabKey,sessionId:j.sessionId,error:$ instanceof Error?$.message:String($)})})},[c,l]);return o.useEffect(()=>{var v;if(!n){d("inbox"),A(((v=e[0])==null?void 0:v.tabKey)||null),g.current=null;return}if(i!=="chat"){g.current=null;return}const j=`${n.tabKey}:${n.sessionId||""}`;g.current!==j&&(g.current=j,I(n))},[e,I,i,n,d,A]),o.useEffect(()=>{if(!u)return;const j=e.find(v=>v.tabKey===u);j&&(A(j.tabKey),d("chat"),p==null||p())},[e,p,u,d,A]),o.useEffect(()=>{if(!m)return;const j=s.find(v=>v.id===m);j&&(b(j.id),N(),y("machines"),h("inbox"),d("machine"),f==null||f())},[s,f,m,N,h,d,y,b]),o.useEffect(()=>{w&&(y(w),d("inbox"),k==null||k())},[k,w,d,y]),o.useEffect(()=>{const j=r.filter(v=>v.inboxBucket==="task_complete"||v.unread);j.length!==0&&Br("inbox_state",{screen:i,selectedTabKey:a,items:j.map(v=>{const x=Zr(v.conversation,c);return{liveState:x,tabKey:v.conversation.tabKey,sessionId:v.conversation.sessionId,displayPrimary:ct(v.conversation),serverBucket:x.inboxBucket,computedBucket:v.inboxBucket,serverUnread:x.unread,computedUnread:v.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,activityAt:ds(v.conversation)}})})},[r,c,i,a]),{markConversationRead:I}}function Jf(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function ti(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Zf(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function eh({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,p]=o.useState(null),m=o.useCallback(()=>{i("idle"),l(""),p(null)},[]),f=o.useCallback(async(h,N,_)=>{var g;try{i("loading"),l(`Launching ${N}…`);const I={ideType:N,enableCdp:!0};(g=_==null?void 0:_.workspacePath)!=null&&g.trim()&&(I.workspace=_.workspacePath.trim()),await e(h,"launch_ide",I),i("done"),l(`${N} launch requested`)}catch(I){i("error"),l(I instanceof Error?I.message:"Launch IDE failed"),console.error("Launch IDE failed",I)}},[e]),w=o.useCallback(async(h,N,_)=>{if(N.trim())try{i("loading"),l(_!=null&&_.createIfMissing?"Creating folder…":"Saving workspace…");const g=await e(h,"workspace_add",{path:N.trim(),createIfMissing:(_==null?void 0:_.createIfMissing)===!0});if(g!=null&&g.success){i("done"),l(_!=null&&_.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((g==null?void 0:g.error)||"Could not save workspace")}catch(g){i("error"),l(g instanceof Error?g.message:"Could not save workspace")}},[e]),k=o.useCallback(async h=>{var N,_,g,I,j,v;try{i("loading"),l("Starting daemon upgrade…");const x=await e(h,"daemon_upgrade",{});if((N=x==null?void 0:x.result)!=null&&N.alreadyLatest){i("done"),l(`Already on v${((_=x==null?void 0:x.result)==null?void 0:_.version)||"latest"}.`);return}if((g=x==null?void 0:x.result)!=null&&g.upgraded||(I=x==null?void 0:x.result)!=null&&I.success){i("done"),l(`Upgrade to v${((j=x==null?void 0:x.result)==null?void 0:j.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((v=x==null?void 0:x.result)==null?void 0:v.error)||"Upgrade failed")}catch(x){i("error"),l(x instanceof Error?x.message:"Upgrade failed")}},[e]),A=o.useCallback(async(h,N,_,g)=>{var v,x,$;const I=Date.now(),j={machineId:h,kind:N,providerType:_,workspaceId:(g==null?void 0:g.workspaceId)||null,workspacePath:(g==null?void 0:g.workspacePath)||null,resumeSessionId:(g==null?void 0:g.resumeSessionId)||null,startedAt:I};try{i("loading"),l(`Launching ${_}…`),p(j);const M={cliType:_};(v=g==null?void 0:g.workspacePath)!=null&&v.trim()?M.dir=g.workspacePath.trim():g!=null&&g.workspaceId&&(M.workspaceId=g.workspaceId),g!=null&&g.resumeSessionId&&(M.resumeSessionId=g.resumeSessionId),(x=g==null?void 0:g.args)!=null&&x.trim()&&(M.cliArgs=g.args.trim().split(/\s+/).filter(Boolean)),($=g==null?void 0:g.model)!=null&&$.trim()&&(M.initialModel=g.model.trim());const L=await e(h,"launch_cli",M),T=(L==null?void 0:L.result)||L,K=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);if(L!=null&&L.success&&K){p(null),i("done"),l(`${_} launched`),s(rs(K));return}if(L!=null&&L.success){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l((L==null?void 0:L.error)||(T==null?void 0:T.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(M){if(Zf(M)){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l(M instanceof Error?M.message:`Could not launch ${N.toUpperCase()} workspace`)}},[s,e]),d=o.useCallback(async(h,N)=>{try{const _=await e(h,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),g=(_==null?void 0:_.result)??_;return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]}catch(_){return console.error("Failed to list saved sessions on mobile:",_),[]}},[e]),b=o.useCallback(async(h,N)=>bn(e,h,N),[e]);o.useEffect(()=>{if(!u)return;const h=ti(u.workspacePath),N=r.find(g=>{var M,L,T,K;if(!g||g.type==="adhdev-daemon"||Jf(g.daemonId||g.id)!==u.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==u.kind||String(g.agentType||g.type||"")!==u.providerType)return!1;const x=String(g.providerSessionId||"");if(u.resumeSessionId&&x)return x===u.resumeSessionId;if(h){const U=ti(g.workspace||g.runtimeWorkspaceLabel);return U?U===h:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((K=(T=(L=(M=g.activeChat)==null?void 0:M.messages)==null?void 0:L.at)==null?void 0:T.call(L,-1))==null?void 0:K.timestamp)||0)>=u.startedAt-5e3});if(!N)return;const _=tc({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});_&&(p(null),i("done"),l(`${u.providerType} launched`),s(rs(_)))},[n,r,s,u]),o.useEffect(()=>{if(!u)return;const h=window.setTimeout(()=>{p(N=>!N||N.startedAt!==u.startedAt?N:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[u]);const y=o.useCallback(async(h,N)=>{if(N.kind==="ide"&&N.providerType){await f(h,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await A(h,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[f,A]);return{machineAction:{state:a,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:w,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:A,handleListSavedSessions:d,handleBrowseDirectory:b,handleOpenRecent:y}}function th({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:p}){const m=o.useCallback(y=>{i(y.tabKey),c("chat"),n(y)},[n,c,i]),f=o.useCallback(y=>{const h=e.find(N=>N.routeId===y.routeId&&N.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),w=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),k=o.useCallback((y,h="inbox")=>{l(y),a(),u("machines"),p(h),c("machine")},[a,p,c,u,l]),A=o.useCallback(y=>{const h=as(y);h&&k(h,"chat")},[k]),d=o.useCallback(()=>{a(),c(r)},[r,a,c]),b=o.useCallback(y=>{u(y),c("inbox")},[c,u]);return{openConversation:m,openNativeConversation:f,backFromConversation:w,openMachine:k,openConversationMachine:A,backFromMachine:d,changeMachineSection:b}}function sh(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Kr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function rh({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,userName:u,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:f,onRequestedMachineConsumed:w,requestedMobileSection:k,onRequestedMobileSectionConsumed:A,onOpenHistory:d,onOpenRemote:b,onStopCli:y,wsStatus:h,isConnected:N,onShowHiddenConversation:_,onShowAllHiddenConversations:g,onHideConversation:I,onOpenNewSession:j,notificationStateBySessionId:v,liveSessionInboxState:x,onMarkNotificationTargetRead:$}){const[M,L]=o.useState(()=>{var Q;return((Q=e[0])==null?void 0:Q.tabKey)||null}),[T,K]=o.useState(()=>e[0]?"chat":"inbox"),[U,C]=o.useState("chats"),[R,O]=o.useState(null),[S,D]=o.useState("inbox"),G=Fs(),q="0.8.82",H=o.useMemo(()=>e.find(Q=>Q.tabKey===M)||e[0]||null,[e,M]),re=o.useMemo(()=>H?r.find(Q=>Q.id===H.routeId):void 0,[r,H]),ae=o.useMemo(()=>!H||Xe(H)||!Ze(H)?null:Ks(H),[H]),Ne=o.useMemo(()=>r.filter(Q=>Q.type==="adhdev-daemon").sort(Na),[r]),X=o.useMemo(()=>Ne.find(Q=>Q.id===R)||null,[Ne,R]),he=fn({sendDaemonCommand:a,activeConv:H||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),ke=eh({sendDaemonCommand:a,navigate:G,ides:r,conversations:e}),ie=o.useMemo(()=>e.map(Q=>{const Pe=T==="chat"&&(H==null?void 0:H.tabKey)===Q.tabKey,He=mn(Q,x,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Pe,notificationStateBySessionId:v}),$e=ds(Q),Be=mc(Q);return{conversation:Q,timestamp:$e,preview:Be,unread:He.unread,requiresAction:He.requiresAction,isWorking:He.isWorking,inboxBucket:He.inboxBucket}}),[e,x,v,T,H]),{markConversationRead:xe}=Qf({conversations:e,machineEntries:Ne,items:ie,selectedConversation:H,selectedTabKey:M,screen:T,liveSessionInboxState:x,sendDaemonCommand:a,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:f,onRequestedMachineConsumed:w,requestedMobileSection:k,onRequestedMobileSectionConsumed:A,setSelectedTabKey:L,setScreen:K,setSelectedMachineId:O,setSection:C,setMachineBackTarget:D,resetMachineAction:ke.resetMachineAction,markNotificationTargetRead:$}),pe=th({conversations:e,selectedConversation:H,machineBackTarget:S,markConversationRead:xe,resetMachineAction:ke.resetMachineAction,setSelectedTabKey:L,setScreen:K,setSelectedMachineId:O,setSection:C,setMachineBackTarget:D}),V=o.useMemo(()=>Kr(ie.filter(Q=>Q.requiresAction)),[ie]),ge=o.useMemo(()=>Kr(ie.filter(Q=>Q.unread&&!Q.requiresAction)),[ie]),ne=o.useMemo(()=>Kr(ie.filter(Q=>!Q.unread&&!Q.requiresAction&&Q.isWorking)),[ie]),ce=o.useMemo(()=>Kr(ie.filter(Q=>!Q.unread&&!Q.requiresAction&&!Q.isWorking)),[ie]),Z=o.useMemo(()=>X?ie.filter(Q=>as(Q.conversation)===X.id):[],[ie,X]),le=o.useMemo(()=>Yf(X,r),[r,X]),ee=(X==null?void 0:X.version)||null,ye=!!X&&!!ee&&!0&&ee!==q,be=o.useMemo(()=>(X==null?void 0:X.availableProviders)||[],[X]),B=o.useMemo(()=>be.filter(Q=>Q.category==="cli"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[be]),ve=o.useMemo(()=>be.filter(Q=>Q.category==="acp"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[be]),Ce=o.useMemo(()=>Xf(Ne,ie),[ie,Ne]),Ae=o.useCallback(async Q=>{X&&await ke.handleOpenRecent(X.id,Q)},[ke,X]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:T==="chat"&&H?t.jsx($f,{selectedConversation:H,isAcp:Xe(H),isStandalone:l,selectedIdeEntry:re,actionLogs:n,userName:u,isSendingChat:he.isSendingChat,sendFeedbackMessage:he.sendFeedbackMessage,isFocusingAgent:he.isFocusingAgent,handleModalButton:he.handleModalButton,handleRelaunch:he.handleRelaunch,onBack:pe.backFromConversation,onOpenNativeConversation:pe.openNativeConversation,onOpenMachine:pe.openConversationMachine,onHideConversation:I,onOpenHistory:d,onOpenRemote:b,onStopCli:y,cliViewMode:ae,onSetCliViewMode:async Q=>{if(H&&ae!==Q)try{await a(as(H)||H.routeId,"set_cli_view_mode",{targetSessionId:H.sessionId,cliType:Bt(H),mode:Q})}catch(Pe){const He=Va(Pe);za(Pe)?console.warn(He?"CLI view mode result was lost after send; keeping optimistic mobile mode override:":"Skipped CLI view mode switch:",Pe instanceof Error?Pe.message:String(Pe)):console.error("Failed to switch CLI view mode:",Pe)}},handleSendChat:he.handleSendChat,handleFocusAgent:he.handleFocusAgent}):T==="machine"&&X?t.jsx(qf,{selectedMachineEntry:X,selectedMachineConversations:Z,selectedMachineRecentLaunches:le,cliProviders:B,acpProviders:ve,selectedMachineNeedsUpgrade:ye,appVersion:q,machineAction:ke.machineAction,isStandalone:l,section:U,showBottomNav:S==="inbox",onBack:pe.backFromMachine,onSectionChange:pe.changeMachineSection,onOpenConversation:pe.openConversation,onOpenRecent:Ae,onOpenMachineDetails:()=>G(`/machines/${X.id}`),onMachineUpgrade:()=>ke.handleMachineUpgrade(X.id),onLaunchDetectedIde:(Q,Pe)=>ke.handleLaunchDetectedIde(X.id,Q,Pe),onAddWorkspace:(Q,Pe)=>ke.handleAddWorkspace(X.id,Q,Pe),onBrowseDirectory:Q=>ke.handleBrowseDirectory(X.id,Q),onLaunchWorkspaceProvider:(Q,Pe,He)=>ke.handleLaunchWorkspaceProvider(X.id,Q,Pe,He),onListSavedSessions:Q=>ke.handleListSavedSessions(X.id,Q)}):t.jsx(Kf,{section:U,attentionItems:V,unreadItems:ge,workingItems:ne,completedItems:ce,hiddenConversations:s,machineCards:Ce,getAvatarText:sh,onOpenConversation:pe.openConversation,onShowConversation:_,onShowAllHidden:g,onOpenNewSession:j,onOpenMachine:pe.openMachine,onOpenSettings:()=>G("/settings"),onSectionChange:C,wsStatus:h,isConnected:N,isStandalone:l})})}function Kn(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function nh({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[p,m]=o.useState(null),f=o.useCallback(()=>{c.current=0,u(!1),m(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",f),window.addEventListener("drop",f),()=>{window.removeEventListener("dragend",f),window.removeEventListener("drop",f)}),[f]);const w=o.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),k=o.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!Kn(s,r)){m("merge");return}const y=b.currentTarget.getBoundingClientRect(),h=b.clientX-y.left,N=y.width/3;h<N?m("split-left"):h>N*2?m("split-right"):m("merge")},[s,r]),A=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),m(null))},[]),d=o.useCallback(b=>{c.current=0,u(!1);const y=b.dataTransfer.getData("text/tab-key"),h=y?e.some(_=>_.tabKey===y):!1,N=p;if(m(null),i(),!!y){if(b.preventDefault(),N==="split-left"&&Kn(s,r)){r==null||r(y,"split-left");return}if(N==="split-right"&&Kn(s,r)){r==null||r(y,"split-right");return}if(h){a(y);return}n==null||n(y)}},[e,p,s,r,n,a,i]);return{dragOver:l,dropAction:p,resetDragState:f,handleDragEnter:w,handleDragOver:k,handleDragLeave:A,handleDrop:d}}function ah(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 oh({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(s??null),[l,u]=o.useState(r??[]),[p,m]=o.useState(null),f=o.useRef(null),w=o.useRef(null),k=o.useRef(n),A=o.useRef(a);o.useEffect(()=>{k.current=n},[n]),o.useEffect(()=>{A.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{u(j=>{const v=ah(j,e);return v.length===j.length&&v.every((x,$)=>x===j[$])?j:v})},[e]);const d=o.useMemo(()=>{const j=p??l;if(j.length===0)return e;const v=new Map(j.map((x,$)=>[x,$]));return[...e].sort((x,$)=>{const M=v.get(x.tabKey)??999,L=v.get($.tabKey)??999;return M-L})},[e,p,l]);o.useEffect(()=>{var v,x;if(d.length===0){i!==null&&(c(null),(v=k.current)==null||v.call(k,null));return}if(i&&d.some($=>$.tabKey===i))return;const j=d[0].tabKey;j!==i&&(c(j),(x=k.current)==null||x.call(k,j))},[d,i]);const b=o.useMemo(()=>d.find(j=>j.tabKey===i),[d,i]),y=o.useCallback(j=>{var v;c(j),(v=k.current)==null||v.call(k,j)},[]),h=o.useCallback((j,v,x)=>{u($=>{var K;const M=$.filter(U=>U!==j),L=M.indexOf(v);if(L<0)return $;const T=x==="left"?L:L+1;return M.splice(T,0,j),(K=A.current)==null||K.call(A,M),M}),m(null)},[]),N=o.useCallback((j,v,x)=>{const M=(l.length>0?l:e.map(K=>K.tabKey)).filter(K=>K!==j),L=M.indexOf(v);if(L<0)return;const T=x==="left"?L:L+1;M.splice(T,0,j),f.current=M,m(M)},[l,e]),_=o.useCallback(()=>{var v;const j=f.current;j&&(u(j),(v=A.current)==null||v.call(A,j))},[]),g=o.useCallback(()=>{f.current=null,m(null)},[]),I=o.useCallback(j=>{u(v=>{var $;const x=v.filter(M=>M!==j);return x.push(j),($=A.current)==null||$.call(A,x),x})},[]);return{activeTabId:i,activeConv:b,sortedConversations:d,previewOrderRef:f,draggingTabRef:w,selectTab:y,handleTabReorder:h,updatePreviewOrder:N,commitPreviewOrder:_,clearPreviewOrder:g,moveTabToEnd:I,setDraggingTabKey:j=>{w.current=j}}}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 Ja({conversationsCount:e,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1}){if(a)return t.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const i=!r&&!n,c=r?"Waiting for your daemon":n?"No conversations yet":"Connect your machines",l=r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":n?"Your machines are connected. Open a machine, choose a workspace, then launch an IDE, CLI, or ACP session.":"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:c}),t.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:l}),i&&t.jsx(Uc,{}),i&&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 qc="adhdev-tab-shortcuts";function Yc(){try{return JSON.parse(localStorage.getItem(qc)||"{}")}catch{return{}}}function Xc({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>Yc()),[l,u]=o.useState(null),p=o.useCallback(f=>{const w=[];return f.metaKey&&w.push(a?"⌘":"Meta"),f.ctrlKey&&w.push("Ctrl"),f.altKey&&w.push(a?"⌥":"Alt"),f.shiftKey&&w.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(w.push(f.key.length===1?f.key.toUpperCase():f.key),w.join("+"))},[a]),m=o.useCallback(f=>{c(f);try{localStorage.setItem(qc,JSON.stringify(f))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const f=w=>{if(w.preventDefault(),w.stopPropagation(),w.key==="Escape"){u(null);return}const k=p(w);if(!k)return;const A={...i};for(const[d,b]of Object.entries(A))b===k&&delete A[d];A[l]=k,m(A),u(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[e,l,i,m,p]),o.useEffect(()=>{if(!e)return;const f=w=>{if(!(!w.ctrlKey&&!w.metaKey&&!w.altKey)){for(const[k,A]of Object.entries(i))if(s.includes(k)&&p(w)===A){w.preventDefault(),r(),n(k);return}}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,i,s,r,n,p]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:m}}const ch=o.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:p,onConversationActivated:m,onPreviewReorder:f,onReorderTab:w,onCommitPreviewOrder:k,onClearPreviewOrder:A,onDragStateReset:d,onDragTabKeyChange:b,onReceiveTab:y,onOpenContextMenu:h,longPressTimer:N,isGroupActive:_}){const g=Vs(s),I=g.isGenerating?"agent-tab-generating":g.isWaiting?"agent-tab-waiting":"",j=g.isReconnecting,v=o.useCallback(R=>{l.current=s.tabKey,b(s.tabKey),R.dataTransfer.setData("text/tab-key",s.tabKey),R.dataTransfer.effectAllowed="move"},[s.tabKey,l,b]),x=o.useCallback(()=>{l.current=null,b(null),k(),A(),d()},[l,b,k,A,d]),$=o.useCallback(R=>{const O=l.current;if(!(!O||O===s.tabKey)&&R.dataTransfer.types.includes("text/tab-key")){R.preventDefault(),R.stopPropagation();const S=R.currentTarget.getBoundingClientRect(),D=R.clientX<S.left+S.width/2?"left":"right";f(O,s.tabKey,D)}},[s.tabKey,l,f]),M=o.useCallback(R=>{R.preventDefault(),R.stopPropagation();const O=R.dataTransfer.getData("text/tab-key");if(O&&O!==s.tabKey){const S=R.currentTarget.getBoundingClientRect(),D=R.clientX<S.left+S.width/2?"left":"right";c.includes(O)?w(O,s.tabKey,D):y&&y(O)}A()},[s.tabKey,c,w,y,A]),L=o.useCallback(R=>{R.stopPropagation(),u(),p(s.tabKey),m(s)},[s,m,u,p]),T=o.useCallback(R=>{R.preventDefault(),h(R.clientX,R.clientY,s.tabKey)},[s.tabKey,h]),K=o.useCallback(R=>{const O=R.touches[0];N.current=setTimeout(()=>{h(O.clientX,O.clientY,s.tabKey)},600)},[s.tabKey,N,h]),U=o.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),C=["adhdev-dockview-tab",I,r&&"is-active",_&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:C,draggable:!0,onDragStart:v,onDragEnd:x,onDragOver:$,onDrop:M,onClick:L,onContextMenu:T,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:g.isGenerating?t.jsx("div",{className:"tab-spinner"}):g.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):g.isConnecting?t.jsx("div",{className:"tab-connecting-spinner"}):s.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("span",{className:"adhdev-dockview-tab-primary",title:ct(s),children:ct(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ms(s)}):g.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ms(s),t.jsx("span",{className:"connecting-dots"})]}):ms(s)})]}),i&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(e,s)=>e.conv===s.conv&&e.isActive===s.isActive&&e.isDraggedTab===s.isDraggedTab&&e.isTaskCompleteUnread===s.isTaskCompleteUnread&&e.shortcut===s.shortcut&&e.conversationKeys===s.conversationKeys&&e.isGroupActive===s.isGroupActive);function lh({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:f,onDragStateReset:w,onDragTabKeyChange:k,onReceiveTab:A,onHideTab:d,isGroupActive:b,allowTabShortcuts:y=!0}){const[h,N]=o.useState(null),_=o.useRef(null),g=o.useRef(null),I=o.useMemo(()=>e.map(T=>T.tabKey),[e]);pr("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:j,tabShortcuts:v,shortcutListening:x,setShortcutListening:$,saveShortcuts:M}=Xc({enabled:y,sortedTabKeys:e.map(T=>T.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const T=K=>{const U=document.querySelector("[data-pane-context-menu]");U&&U.contains(K.target)||N(null)};return window.addEventListener("mousedown",T,!0),()=>window.removeEventListener("mousedown",T,!0)},[h]),o.useEffect(()=>{const T=g.current;if(!T)return;const K=U=>{Math.abs(U.deltaY)<=Math.abs(U.deltaX)||(U.preventDefault(),T.scrollLeft+=U.deltaY)};return T.addEventListener("wheel",K,{passive:!1}),()=>T.removeEventListener("wheel",K)},[]);const L=o.useCallback((T,K,U)=>{N({x:T,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:g,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(T=>t.jsx(ch,{conv:T,isActive:s===T.tabKey,isDraggedTab:a.current===T.tabKey,isTaskCompleteUnread:n.has(T.tabKey),shortcut:y?v[T.tabKey]:void 0,conversationKeys:I,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:f,onDragStateReset:w,onDragTabKeyChange:k,onReceiveTab:A,onOpenContextMenu:L,longPressTimer:_,isGroupActive:b},T.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),h&&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:h.x,top:h.y},children:[y&&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:T=>{T.stopPropagation(),$(h.tabKey),N(null)},children:["⌨ ",v[h.tabKey]?`Change shortcut (${v[h.tabKey]})`:"Set shortcut"]}),v[h.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 T={...v};delete T[h.tabKey],M(T),N(null)},children:"✕ Remove shortcut"})]}),d&&t.jsxs(t.Fragment,{children:[y&&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:()=>{d(h.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&x&&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:()=>$(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:T=>T.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",j?"⌘+1":"Ctrl+1",", ",j?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function dh({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,userName:p,groupIndex:m,onFocus:f,isSplitMode:w,numGroups:k,onMoveTab:A,onReceiveTab:d,style:b,onActiveTabChange:y,initialActiveTabId:h,initialTabOrder:N,onTabOrderChange:_,onHideTab:g,isFocused:I,allowTabShortcuts:j=!0,notificationStateBySessionId:v,liveSessionInboxState:x}){const{sendCommand:$}=Pt(),M=o.useRef(null),{activeTabId:L,activeConv:T,sortedConversations:K,draggingTabRef:U,selectTab:C,handleTabReorder:R,updatePreviewOrder:O,commitPreviewOrder:S,clearPreviewOrder:D,moveTabToEnd:G,setDraggingTabKey:q}=oh({conversations:e,initialActiveTabId:h,initialTabOrder:N,onActiveTabChange:y,onTabOrderChange:_}),H=fn({sendDaemonCommand:a,activeConv:T,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:re,dropAction:ae,resetDragState:Ne,handleDragEnter:X,handleDragOver:he,handleDragLeave:ke,handleDrop:ie}=nh({conversations:e,numGroups:k,onMoveTab:A,onReceiveTab:d,onOwnTabDrop:G,onClearPreviewOrder:D}),xe=T&&!Xe(T)&&Ks(T)==="terminal",pe=o.useMemo(()=>T?s.find(ce=>ce.id===T.routeId):void 0,[s,T]),V=o.useMemo(()=>T?n.filter(ce=>ce.routeId===T.tabKey):[],[n,T]),ge=o.useMemo(()=>new Set(K.filter(ce=>Yd(ce,x,{isOpenConversation:ce.tabKey===L,notificationStateBySessionId:v})).map(ce=>ce.tabKey)),[L,x,K]);pr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:L,dragOver:re});const ne=o.useCallback(ce=>{ce.streamSource==="agent-stream"&&ce.agentType&&$(ce.routeId,Hc(),{agentType:ce.agentType,...ce.sessionId&&{targetSessionId:ce.sessionId}}).catch(()=>{})},[$]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:f,style:{...b,outline:re?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(lh,{conversations:K,activeTabId:L,groupIndex:m,numGroups:k,unreadTabKeys:ge,draggingTabRef:U,onFocus:f,onSelectTab:C,onConversationActivated:ne,onPreviewReorder:O,onReorderTab:R,onCommitPreviewOrder:S,onClearPreviewOrder:D,onDragStateReset:Ne,onDragTabKeyChange:q,onMoveTab:A,onReceiveTab:d,onHideTab:g,isGroupActive:I??!1,allowTabShortcuts:j}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:X,onDragOver:he,onDragLeave:ke,onDrop:ie,children:[re&&t.jsx(ih,{dropAction:ae,canSplit:!!(k<4&&A)}),T?t.jsx(Xa,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!xe,ideEntry:pe,terminalRef:M,handleModalButton:H.handleModalButton,handleRelaunch:H.handleRelaunch,handleSendChat:H.handleSendChat,isSendingChat:H.isSendingChat,sendFeedbackMessage:H.sendFeedbackMessage,handleFocusAgent:H.handleFocusAgent,isFocusingAgent:H.isFocusingAgent,actionLogs:V,userName:p,isInputActive:!w||!!I}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(Ja,{conversationsCount:e.length,isSplitMode:w,isStandalone:l,hasRegisteredMachines:u})})]})]})}function uh({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:f,hasRegisteredMachines:w,userName:k,focusedGroup:A,setFocusedGroup:d,moveTabToGroup:b,splitTabRelative:y,closeGroup:h,handleResizeStart:N,groupActiveTabIds:_,setGroupActiveTabIds:g,groupTabOrders:I,setGroupTabOrders:j,toggleHiddenTab:v,allowTabShortcuts:x=!0,notificationStateBySessionId:$,liveSessionInboxState:M}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map((L,T)=>{const K=s&&n.length===r?`${n[T]}%`:void 0;return t.jsxs(rt.Fragment,{children:[s&&T>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:U=>N(T-1,U),onDoubleClick:()=>h(T),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(dh,{style:s?{flexBasis:K??`${100/r}%`,flexGrow:K?0:1,flexShrink:K?0:1}:void 0,conversations:L,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:f,hasRegisteredMachines:w,userName:k,groupIndex:T,isFocused:s&&A===T,onFocus:()=>d(T),isSplitMode:s,numGroups:r,onMoveTab:(U,C)=>{C==="left"&&T>0?b(U,T-1):C==="right"&&T<r-1?b(U,T+1):C==="split-left"&&r<4?y(U,T,"left"):C==="split-right"&&r<4&&y(U,T,"right")},onReceiveTab:U=>b(U,T),onActiveTabChange:U=>g(C=>(C[T]??null)===(U??null)?C:{...C,[T]:U}),initialActiveTabId:_[T],initialTabOrder:I[T],onTabOrderChange:U=>j(C=>{const R=C[T]||[];return R.length===U.length&&R.every((O,S)=>O===U[S])?C:{...C,[T]:U}}),onHideTab:v,allowTabShortcuts:x,notificationStateBySessionId:$,liveSessionInboxState:M})]},T)})})}function Qc({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?mt.onScreenshot("ide-page",(m,f)=>{if(m!==e)return;const w=new FileReader;w.onload=()=>i(w.result),w.readAsDataURL(f)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var m;return e?((m=mt.onStatus)==null?void 0:m.call(mt,(f,w)=>{f===e&&w!=null&&w.screenshotUsage&&l(w.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const p=e?mt.get(e):null;if(!(!p||r!=="connected"))return n!=="chat"&&s?p.startScreenshots(s):p.stopScreenshots(s),()=>{p.stopScreenshots(s)}},[n,r,s,e]);const u=o.useCallback(async(p,m)=>{const f=e?mt.get(e):null;return!f||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):f.sendInput(p,m,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const Jc="adhdev-dashboard-action-shortcuts",mh=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 fh(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function st(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 Zc(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:st("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:st("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:st("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:st("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:st("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:st("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:st("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:st("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:st("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:st("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:st("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:st("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:st("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:st("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:st("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:st("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:st("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:st("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:st("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:st("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:st("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:st("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:st("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:st("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:st("toggleCliView",e)}]}function ma(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function an(e){const s=Object.fromEntries(Zc(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Jc)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(ph))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function el(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function hh({enabled:e=!0,onTrigger:s}){const r=fh(),[n,a]=o.useState(()=>an(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),p=o.useRef({parts:[],timer:null}),m=o.useCallback(d=>{const b=[];return d.metaKey&&b.push(r?"⌘":"Meta"),d.ctrlKey&&b.push("Ctrl"),d.altKey&&b.push(r?"⌥":"Alt"),d.shiftKey&&d.key.length!==1&&b.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(d.key)?null:(b.push(el(d.key)),b.join("+"))},[r]),f=o.useCallback(d=>{a(d);try{localStorage.setItem(Jc,JSON.stringify(d))}catch{}},[]);o.useEffect(()=>{const d=an(r),b=Object.entries(n),y=Object.entries(d);b.length===y.length&&b.every(([h,N])=>d[h]===N)||f(d)},[n,r,f]);const w=o.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),k=o.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},mh))},[]);o.useEffect(()=>{if(!i)return;const d=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),u([]);return}const y=m(b);if(!y)return;const N=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(y);if(l.length===0&&N){u([y]);return}const g=[...l,y].slice(0,2).join(" "),I={...n};for(const[j,v]of Object.entries(I))v===g&&delete I[j];I[i]=g,f(I),c(null),u([])};return window.addEventListener("keydown",d,!0),()=>window.removeEventListener("keydown",d,!0)},[n,m,f,i,l]),o.useEffect(()=>{if(!e||i)return;const d=b=>{if(b.defaultPrevented)return;const y=m(b);if(!y)return;const h=b.metaKey||b.ctrlKey||b.altKey;if(ma(b.target)&&!h)return;const N=p.current.parts,_=h?[y]:[...N.slice(-1),y].slice(-2),g=_.join(" "),I=_[_.length-1],j=Object.entries(n).filter(([,L])=>!!L),v=j.find(([,L])=>L===g);if(v){b.preventDefault(),w(),s(v[0]);return}if(j.some(([,L])=>L.startsWith(`${g} `))){b.preventDefault(),p.current.parts=_,k();return}const $=j.find(([,L])=>L===I);if($){b.preventDefault(),w(),s($[0]);return}if(j.some(([,L])=>L.startsWith(`${I} `))){b.preventDefault(),p.current.parts=[I],k();return}w()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,k,e,m,s,w,i]),o.useEffect(()=>()=>w(),[w]);const A=o.useMemo(()=>Zc(r),[r]);return{isMac:r,actionDefinitions:A,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:f}}function xh({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 bh(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function si({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!bh(n):!0}const tl=o.createContext(null);function yn(){const e=o.useContext(tl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Yr(e){return ct(e)||e.tabKey}function gh(e){return`remote:${e}`}function Jt(e){return e.startsWith("remote:")}function ri(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Wn(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 Wr(e,s){e.classList.remove(Xn.className,Qn.className),e.classList.add(s==="light"?Xn.className:Qn.className)}function ni(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 yh(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 vh(e,s,r){var c;const n=[s];let a;for(const l of n){let u;for(const p of l){const m=e.addPanel({id:p.tabKey,component:"conversation",title:Yr(p),params:{kind:"conversation",tabKey:p.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=m.id)}a=u??a}return r??((c=s[0])==null?void 0:c.tabKey)??null}function ai(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Jt(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!==Yr(n)&&a.api.setTitle(Yr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Yr(n),params:{kind:"conversation",tabKey:n.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function oi(e,s,r){var u,p;const n=r?gh(r):null;for(const m of[...e.panels])Jt(m.id)&&(!n||m.id!==n)&&e.removePanel(m);if(!r||!n)return;const a=Wt(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=hc(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)??((p=e.panels.find(m=>!Jt(m.id)))==null?void 0:p.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 f;const r=yn(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=fn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const w=[s.onDidActiveChange(k=>i(k.isActive)),s.onDidActiveGroupChange(k=>{if(!s.isActive&&!k.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const k of w)k.dispose()}},[s]);const u=o.useMemo(()=>c?r.ides.find(w=>w.id===c.routeId):void 0,[r.ides,c]),p=o.useMemo(()=>c?r.actionLogs.filter(w=>w.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(Ja,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const m=!Xe(c)&&Ks(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(Xa,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:m,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:p,userName:r.userName,scrollToBottomRequestNonce:((f=r.scrollToBottomRequest)==null?void 0:f.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a})})}function jh({params:e}){var u;const s=yn(),r=o.useMemo(()=>Wt([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>s.ides.find(p=>p.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?Ji(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 kh(){const e=yn();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(Ja,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function Sh(e){var k,A;yh(e);const s=yn(),r=o.useCallback(d=>{"button"in d&&d.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const d=Wt([...s.conversationsByTabKey.values()],e.params.routeId),b=((k=e.api.group.activePanel)==null?void 0:k.id)===e.api.id,y=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${y?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(d==null?void 0:d.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:d!=null&&d.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:d.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=((A=e.api.group.activePanel)==null?void 0:A.id)===e.api.id,i=e.api.isGroupActive,c=mn(n,s.liveSessionInboxState,{isOpenConversation:a,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,u=c.isConnecting,p=c.isGenerating,m=c.isWaiting,f=c.unread,w=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:ct(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:d=>{var b;d.preventDefault(),r(d),s.openTabContextMenu({x:d.clientX,y:d.clientY,tabKey:n.tabKey,sourceDocument:((b=d.target)==null?void 0:b.ownerDocument)??document})},children:[f&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:p?t.jsx("div",{className:"tab-spinner"}):m?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):u?t.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:ct(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ms(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ms(n)}):t.jsx("span",{children:ms(n)})})]}),w&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:w,children:w})]})}function Nh({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,initialDataLoaded:p,userName:m,toggleHiddenTab:f,actionShortcuts:w,registerActionHandlers:k,onActiveTabChange:A,requestedActiveTabKey:d,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:y,scrollToBottomRequest:h,notificationStateBySessionId:N,liveSessionInboxState:_}){var Mt,Y,Re;const{theme:g}=Wa(),{sendCommand:I}=Pt(),j=o.useRef(null),v=o.useRef(null),x=o.useRef(!1),$=o.useRef(!1),M=o.useRef(!1),L=o.useRef(null),T=o.useRef([]),[K,U]=o.useState(null),[C,R]=o.useState(!1),[O,S]=o.useState(!1),[D,G]=o.useState(0),q=o.useRef(null),H=o.useMemo(()=>$c(typeof window<"u"?window.innerWidth:1280),[]),re=o.useRef(typeof window>"u"?{}:nf(H)),ae=o.useMemo(()=>new Map(e.map(P=>[P.tabKey,P])),[e]),Ne=o.useMemo(()=>{const P=j.current;return P?P.groups.some(W=>{try{const F=W.model.location.type;return F!=="floating"&&F!=="popout"?!1:W.panels.some(z=>ae.has(z.id))}catch{return!1}}):!1},[ae,D,e]),X=o.useCallback(()=>{var P;(P=j.current)==null||P.focus()},[]),he=o.useCallback(P=>{const W=document,F=P.document;for(const Ie of W.querySelectorAll('link[rel="stylesheet"]')){const Ke=F.createElement("link");Ke.rel="stylesheet",Ke.href=Ie.href,Ie.crossOrigin&&(Ke.crossOrigin=Ie.crossOrigin),F.head.appendChild(Ke)}for(const Ie of W.querySelectorAll("style")){const Ke=F.createElement("style");Ke.textContent=Ie.textContent,F.head.appendChild(Ke)}const z=[];for(const Ie of W.styleSheets)try{for(const Ke of Ie.cssRules)Ke instanceof CSSStyleRule&&(Ke.selectorText===":root"||Ke.selectorText==="html")&&z.push(Ke.cssText)}catch{}if(z.length>0){const Ie=F.createElement("style");Ie.textContent=z.join(`
44
+ `),F.head.appendChild(Ie)}const te=W.documentElement.getAttribute("data-theme");te&&F.documentElement.setAttribute("data-theme",te),F.documentElement.style.colorScheme=te==="light"?"light":"dark",F.body.className=W.body.className;const Se=W.documentElement.getAttribute("style");Se&&F.documentElement.setAttribute("style",Se);const _e=F.getElementById("dv-popout-window");_e instanceof HTMLElement&&(_e.classList.add("adhdev-dockview"),Wr(_e,g))},[g]),ke=o.useCallback(()=>{var W;const P=j.current;if(P)for(const F of P.groups)try{const z=(W=F.element)==null?void 0:W.ownerDocument;if(!z||z===document)continue;const te=z.getElementById("dv-popout-window");te instanceof HTMLElement&&(te.classList.add("adhdev-dockview"),Wr(te,g));const Se=document.documentElement.getAttribute("data-theme");Se&&z.documentElement.setAttribute("data-theme",Se),z.documentElement.style.colorScheme=Se==="light"?"light":"dark",z.body.className=document.body.className;const _e=document.documentElement.getAttribute("style");_e?z.documentElement.setAttribute("style",_e):z.documentElement.removeAttribute("style")}catch{}},[g]),ie=o.useCallback(()=>{var W;const P=j.current;if(P)for(const F of P.groups)try{const z=(W=F.element)==null?void 0:W.ownerDocument;if(!z||z===document)continue;const te=z.getElementById("dv-popout-window");if(!(te instanceof HTMLElement))continue;te.classList.add("adhdev-dockview"),Wr(te,g),te.classList.toggle("is-showing-dockview-overlay",O),te.classList.toggle("is-dragging-dockview",C)}catch{}},[C,O,g]),xe=o.useCallback(P=>{const W=j.current;if(!W)return;const F=W.getPanel(P);F&&W.addPopoutGroup(F,{popoutUrl:"/popout.html",onDidOpen:({window:z})=>{he(z),ye();const te=ae.get(P);z.document.title=te?`${ct(te)} — ADHDev`:"ADHDev — Popout"}})},[ae,he]),pe=o.useCallback(P=>{const W=j.current,F=W==null?void 0:W.getPanel(P);if(!W||!F)return;const z=W.groups.filter(te=>{var Se;try{return((Se=te.element)==null?void 0:Se.ownerDocument)===document}catch{return!0}});z.length>0?F.api.moveTo({group:z[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),V=o.useCallback(P=>{var z;const W=j.current;if(!W)return!1;const F=W.getPanel(P);if(!F)return!1;try{return((z=F.group.element)==null?void 0:z.ownerDocument)!==document}catch{return!1}},[]),ge=o.useCallback(P=>{V(P)&&pe(P),f(P)},[V,pe,f]),ne=o.useCallback(P=>{const W=j.current,F=W==null?void 0:W.getPanel(P);!W||!F||W.addFloatingGroup(F,{width:600,height:500})},[]),ce=o.useCallback(P=>{var F;const W=(F=j.current)==null?void 0:F.getPanel(P);if(!W)return!1;try{return W.group.model.location.type==="floating"}catch{return!1}},[]),Z=o.useCallback(()=>{var W,F;const P=(F=(W=j.current)==null?void 0:W.activePanel)==null?void 0:F.id;return!P||Jt(P)?null:ae.has(P)?P:null},[ae]),le=o.useCallback(P=>{const W=j.current,F=W==null?void 0:W.getPanel(P);if(!W||!F)return;const z=W.groups.filter(te=>{try{return te.model.location.type==="grid"}catch{return!0}});z.length>0?F.api.moveTo({group:z[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),ee=o.useCallback(()=>{var Se;const P=j.current;if(!P)return;const F=P.groups.filter(_e=>{var Ie;try{return((Ie=_e.element)==null?void 0:Ie.ownerDocument)===document&&_e.model.location.type==="grid"}catch{return!1}})[0]||null,z=[...P.panels];for(const _e of z){const Ie=(Se=_e.group.element)==null?void 0:Se.ownerDocument,Ke=_e.group.model.location.type;Ie===document&&Ke==="grid"||(F&&F.id!==_e.group.id?_e.api.moveTo({group:F,position:"center"}):_e.api.moveTo({position:"center"}))}const te=P.activePanel;te&&(te.group.model.openPanel(te),te.api.setActive()),Wn(document)},[]),ye=o.useCallback(()=>{var W,F;const P=j.current;if(P)for(const z of P.groups){const te=(W=z.element)==null?void 0:W.ownerDocument;if(!te||te===document)continue;const Se=te.getElementById("dv-popout-window");if(!(Se instanceof HTMLElement))continue;let _e=null,Ie=te.title||"ADHDev",Ke="Popout workspace";const De=z.activePanel;if(De)if(_e=De.id,Jt(De.id)){const Me=((F=De.params)==null?void 0:F.routeId)||De.id.slice(7),Ee=Wt([...ae.values()],Me);Ie=hc(Ee),Ke=Ee!=null&&Ee.machineName?`Remote view · ${Ee.machineName}`:"Remote view"}else{const Me=ae.get(De.id);Ie=Me?ct(Me):De.title||De.id,Ke=Me?ms(Me):"Dockview panel"}te.title=`${Ie} — ADHDev`;let Qe=te.getElementById("adhdev-popout-header");Qe instanceof HTMLElement||(Qe=te.createElement("div"),Qe.id="adhdev-popout-header",te.body.appendChild(Qe)),Qe.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(";")),Qe.innerHTML=`
45
+ <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
46
+ <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
47
+ <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${ri(Ie)}</div>
48
+ <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${ri(Ke)}</div>
49
+ </div>
50
+ <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
51
+ <button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
52
+ <button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
53
+ </div>
54
+ `,Se.style.top="52px",Se.style.height="calc(100% - 52px)";const et=Qe.querySelector("[data-adhdev-popout-focus]");et&&(et.onclick=()=>{window.focus()});const se=Qe.querySelector("[data-adhdev-popout-dock]");se&&(se.disabled=!_e,se.style.opacity=_e?"1":"0.5",se.style.cursor=_e?"pointer":"default",se.onclick=()=>{var Me;_e&&pe(_e),(Me=te.defaultView)==null||Me.focus()})}},[ae,pe]),be=o.useCallback(P=>{var z;const W=j.current,F=W==null?void 0:W.getPanel(P);if(!(!W||!F)){F.group.model.openPanel(F),F.api.setActive();try{const te=F.group.model.location;te.type==="popout"?te.getWindow().focus():Wn((z=F.group.element)==null?void 0:z.ownerDocument)}catch{}}},[]),B=o.useCallback(P=>{const W=j.current,F=W==null?void 0:W.activePanel,z=(W==null?void 0:W.activeGroup)||(F==null?void 0:F.group);if(!W||!F||!z)return;const te=z.panels||[];if(te.length<=1)return;const Se=te.findIndex(Ke=>Ke.id===F.id);if(Se<0)return;const _e=(Se+P+te.length)%te.length,Ie=te[_e];Ie&&(Ie.group.model.openPanel(Ie),Ie.api.setActive())},[]),ve=o.useCallback(P=>{var se;const W=j.current,F=(W==null?void 0:W.activeGroup)||((se=W==null?void 0:W.activePanel)==null?void 0:se.group);if(!W||!F)return;const z=W.groups||[],te=z.find(Me=>Me.id===F.id);if(!te)return;const Se=te.element.getBoundingClientRect(),_e=Se.left+Se.width/2,Ie=Se.top+Se.height/2,Ke=(Me,Ee,tt,E)=>Math.max(0,Math.min(Ee,E)-Math.max(Me,tt)),De=Me=>{const Ee=Me.element.getBoundingClientRect(),tt=Ee.left+Ee.width/2,E=Ee.top+Ee.height/2;let J=0,de=0,me=0,Le=!1;if(P==="left"?(Le=tt<_e,J=Math.max(0,Se.left-Ee.right),de=Math.abs(E-Ie),me=Ke(Se.top,Se.bottom,Ee.top,Ee.bottom)):P==="right"?(Le=tt>_e,J=Math.max(0,Ee.left-Se.right),de=Math.abs(E-Ie),me=Ke(Se.top,Se.bottom,Ee.top,Ee.bottom)):P==="above"?(Le=E<Ie,J=Math.max(0,Se.top-Ee.bottom),de=Math.abs(tt-_e),me=Ke(Se.left,Se.right,Ee.left,Ee.right)):(Le=E>Ie,J=Math.max(0,Ee.top-Se.bottom),de=Math.abs(tt-_e),me=Ke(Se.left,Se.right,Ee.left,Ee.right)),!Le)return Number.POSITIVE_INFINITY;const we=me>0?0:120;return J*3+de+we};let Qe=null,et=Number.POSITIVE_INFINITY;for(const Me of z){if(Me.id===te.id)continue;const Ee=De(Me);Number.isFinite(Ee)&&(Ee>=et||(et=Ee,Qe=Me))}return Qe||void 0},[]),Ce=o.useCallback(P=>{var z;const W=ve(P);if(!W)return;const F=W.activePanel||W.panels[0];F&&(W.model.openPanel(F),F.api.setActive(),Wn((z=W.element)==null?void 0:z.ownerDocument))},[ve]),Ae=o.useCallback((P,W)=>{const F=j.current,z=F==null?void 0:F.activePanel,te=(F==null?void 0:F.activeGroup)||(z==null?void 0:z.group);if(!F||!z||!te)return;let Se=ve(P);!Se&&(W!=null&&W.createGroupIfMissing)&&(Se=F.addGroup({referenceGroup:te,direction:P})),Se&&(z.api.moveTo({group:Se,position:"center"}),z.group.model.openPanel(z),z.api.setActive())},[ve]),{isMac:Q,tabShortcuts:Pe,shortcutListening:He,setShortcutListening:$e,saveShortcuts:Be}=Xc({sortedTabKeys:e.map(P=>P.tabKey),onFocus:X,onSelectTab:be}),Ye=o.useCallback(()=>{var F;const P=j.current;if(!P)return;const W=P.activePanel;if(W){if(Jt(W.id)){const z=((F=W.params)==null?void 0:F.routeId)||W.id.slice(7),te=Wt(e,z);te!=null&&te.tabKey&&$e(te.tabKey);return}ae.has(W.id)&&$e(W.id)}},[ae,be,$e,e]),Ve=o.useCallback(P=>{const W=[];return P.metaKey&&W.push(Q?"⌘":"Meta"),P.ctrlKey&&W.push("Ctrl"),P.altKey&&W.push(Q?"⌥":"Alt"),P.shiftKey&&P.key.length!==1&&W.push(Q?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(P.key)?null:(W.push(el(P.key)),W.join("+"))},[Q]),ut=o.useCallback(P=>{var W,F;switch(P){case"splitActiveTabRight":Ae("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Ae("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const z=Z();z&&ne(z);return}case"popoutActiveTab":{const z=Z();z&&xe(z);return}case"dockActiveTab":{const z=Z();if(!z)return;V(z)?pe(z):ce(z)&&le(z);return}case"focusLeftPane":Ce("left");return;case"focusRightPane":Ce("right");return;case"focusUpPane":Ce("above");return;case"focusDownPane":Ce("below");return;case"moveActiveTabToLeftPane":Ae("left");return;case"moveActiveTabToRightPane":Ae("right");return;case"moveActiveTabToUpPane":Ae("above");return;case"moveActiveTabToDownPane":Ae("below");return;case"selectPreviousGroupTab":B(-1);return;case"selectNextGroupTab":B(1);return;case"setActiveTabShortcut":Ye();return;case"hideCurrentTab":{const z=(F=(W=j.current)==null?void 0:W.activePanel)==null?void 0:F.id;z&&!Jt(z)&&ge(z);return}default:return}},[B,le,Ce,ne,Z,ge,ce,V,pe,Ae,xe,Ye]);o.useEffect(()=>{if(!K)return;const P=K.sourceDocument,W=P.defaultView??window,F=z=>{const te=P.querySelector("[data-dockview-tab-context-menu]");te&&te.contains(z.target)||U(null)};return W.addEventListener("mousedown",F,!0),W!==window&&window.addEventListener("mousedown",()=>U(null),!0),()=>{W.removeEventListener("mousedown",F,!0),W!==window&&window.removeEventListener("mousedown",()=>U(null),!0)}},[K]);const at=o.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:ae,hasDetachedConversationPanels:Ne,ides:r,isStandalone:l,hasRegisteredMachines:u,liveSessionInboxState:_,notificationStateBySessionId:N,sendDaemonCommand:a,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:ge,userName:m,scrollToBottomRequest:h,tabShortcuts:Pe,openTabContextMenu:({x:P,y:W,tabKey:F,sourceDocument:z})=>U({x:P,y:W,tabKey:F,sourceDocument:z??document}),popoutTab:xe,moveTabBackToMain:pe,isTabInPopout:V,floatTab:ne,isTabFloating:ce}),[n,s,ae,Ne,r,l,u,_,N,a,c,i,ge,m,h,Pe,xe,pe,V,ne,ce]),pt=K?xh({isTabInPopout:V(K.tabKey),isTabFloating:ce(K.tabKey),tabShortcut:Pe[K.tabKey],actionShortcuts:w}):[],ze=o.useCallback(P=>{var z;const W=j.current;if((((z=W==null?void 0:W.activePanel)==null?void 0:z.id)??null)===P.id){P.group.model.openPanel(P);return}P.group.model.openPanel(P),P.api.setActive()},[]),ft=o.useCallback(P=>{if(!P)return!1;const W=j.current;if(!W)return!1;const F=W.getPanel(P);return F?(ze(F),y==null||y(),!0):!1},[ze,y]),xt=o.useCallback(()=>{if(M.current)return!1;const P=ft(L.current);return P&&(M.current=!0),P},[ft]),ot=o.useCallback(()=>{var W;const P=j.current;P&&rf(H,{activeTabId:((W=P.activePanel)==null?void 0:W.id)??null,layout:P.toJSON()})},[H]),Te=o.useCallback(()=>{af(H,re.current)},[H]),Ge=o.useCallback(P=>{var z,te,Se,_e;const W=j.current;if(!W)return{kind:"grid"};const F=W.toJSON();for(const Ie of F.floatingGroups||[])if((te=(z=Ie.data)==null?void 0:z.views)!=null&&te.includes(P)&&Ie.position)return{kind:"floating",position:Ie.position};for(const Ie of F.popoutGroups||[])if((_e=(Se=Ie.data)==null?void 0:Se.views)!=null&&_e.includes(P))return{kind:"popout",position:Ie.position,popoutUrl:Ie.url};return{kind:"grid"}},[]),Oe=o.useCallback(P=>{const W=j.current;if(!W)return;const F=W.getPanel(P),z=re.current[P];if(!F||!z||z.kind==="grid")return;if(F.group.model.location.type===z.kind){delete re.current[P],Te();return}if(z.kind==="floating"){W.addFloatingGroup(F,{x:z.position.left??24,y:z.position.top??24,width:z.position.width,height:z.position.height}),delete re.current[P],Te();return}delete re.current[P],Te()},[Te]);o.useEffect(()=>(k==null||k({setShortcutForActiveTab:Ye,restoreHiddenTabToSavedLocation:Oe,activateConversationTab:be,resetAllPanelsToMain:ee,activatePreviousTabInGroup:()=>B(-1),activateNextTabInGroup:()=>B(1),floatActiveTab:()=>{const P=Z();P&&ne(P)},popoutActiveTab:()=>{const P=Z();P&&xe(P)},dockActiveTab:()=>{const P=Z();P&&(V(P)?pe(P):ce(P)&&le(P))},splitActiveTabRight:()=>Ae("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Ae("below",{createGroupIfMissing:!0}),focusLeftPane:()=>Ce("left"),focusRightPane:()=>Ce("right"),focusUpPane:()=>Ce("above"),focusDownPane:()=>Ce("below"),moveActiveTabToLeftPane:()=>Ae("left"),moveActiveTabToRightPane:()=>Ae("right"),moveActiveTabToUpPane:()=>Ae("above"),moveActiveTabToDownPane:()=>Ae("below")}),()=>k==null?void 0:k(null)),[B,le,ne,Ce,Z,ce,V,Ae,pe,xe,k,ee,Oe,be,Ye]);const Ue=o.useCallback(()=>{const P=v.current;if(!P)return;const W=P.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")},[]),wt=o.useCallback(()=>{const P=v.current;if(!P)return;const W=P.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const F of W)F.removeAttribute("data-adhdev-force-hidden")},[]),bt=o.useCallback(()=>{const P=v.current;if(!P)return;const W=P.querySelectorAll(".dv-drop-target-container");for(const te of W)te.remove();const F=P.querySelectorAll(".dv-drop-target-dropzone");for(const te of F)te.remove();const z=P.querySelectorAll(".dv-drop-target");for(const te of z)te.classList.remove("dv-drop-target")},[]),yt=o.useCallback(()=>{R(!1),S(!1),wt(),Ue(),bt(),!(typeof window>"u")&&(q.current!=null&&window.clearTimeout(q.current),window.requestAnimationFrame(()=>{Ue(),bt()}),q.current=window.setTimeout(()=>{Ue(),bt(),q.current=null},80))},[wt,Ue,bt]),jt=o.useCallback(P=>{var F;j.current=P.api;const W=sf(H);if(L.current=(W==null?void 0:W.activeTabId)??null,W!=null&&W.layout&&P.api.fromJSON(W.layout,{reuseExistingPanels:!1}),$.current=si({hasStoredLayout:!!(W!=null&&W.layout),initialDataLoaded:p,visibleConversationCount:e.length,ides:r}),$.current||(ai(P.api,e),oi(P.api,e,b)),P.api.totalPanels===0&&e.length>0){const z=vh(P.api,e,d);if(z){const te=P.api.getPanel(z);te&&ze(te)}}else!$.current&&!ft(d)&&xt();x.current=!0,P.api.onDidActivePanelChange(z=>{var Se;if(L.current=(z==null?void 0:z.id)??null,M.current=!0,ye(),z&&Jt(z.id)){const _e=((Se=z.params)==null?void 0:Se.routeId)||z.id.slice(7),Ie=Wt(e,_e);A((Ie==null?void 0:Ie.tabKey)??null),ot();return}if(A((z==null?void 0:z.id)??null),ot(),!z)return;const te=ae.get(z.id);(te==null?void 0:te.streamSource)==="agent-stream"&&te.agentType&&I(te.routeId,Hc(),{agentType:te.agentType,...te.sessionId&&{targetSessionId:te.sessionId}}).catch(()=>{})}),P.api.onDidLayoutChange(()=>{ot(),ye(),G(z=>z+1)}),P.api.onWillDragPanel(()=>{R(!0),S(!1),Ue()}),P.api.onWillDragGroup(()=>{R(!0),S(!1),Ue()}),P.api.onWillShowOverlay(()=>{wt(),S(!0)}),P.api.onDidMovePanel(yt),P.api.onDidDrop(yt),P.api.onDidAddGroup(z=>{requestAnimationFrame(()=>{var te,Se;try{const _e=(te=z.element)==null?void 0:te.ownerDocument;if(!_e||_e===document)return;(Se=_e.getElementById("dv-popout-window"))==null||Se.classList.add("adhdev-dockview");const Ie=document.documentElement.getAttribute("data-theme");Ie&&_e.documentElement.setAttribute("data-theme",Ie),_e.body.className=document.body.className;const Ke=document.documentElement.getAttribute("style");Ke&&_e.documentElement.setAttribute("style",Ke)}catch{}ye(),G(_e=>_e+1)})}),A(((F=P.api.activePanel)==null?void 0:F.id)??null)},[ze,ft,yt,wt,ae,r,p,H,Ue,A,ot,d,b,I,ye,e]);o.useLayoutEffect(()=>{const P=j.current;if(!P||!x.current||$.current&&si({hasStoredLayout:!0,initialDataLoaded:p,visibleConversationCount:e.length,ides:r}))return;$.current&&($.current=!1);const W=T.current,F=new Set(W),z=e.map(De=>De.tabKey),te=new Set(z);let Se=!1;for(const De of W)te.has(De)||(re.current[De]=Ge(De),Se=!0);Se&&Te(),ai(P,e),oi(P,e,b);const _e=z.filter(De=>!F.has(De));let Ie=!1;for(const De of _e){const Qe=P.getPanel(De),et=re.current[De];if(!Qe||!et||et.kind==="grid")continue;if(Qe.group.model.location.type===et.kind){delete re.current[De],Ie=!0;continue}if(et.kind==="floating"){P.addFloatingGroup(Qe,{x:et.position.left??24,y:et.position.top??24,width:et.position.width,height:et.position.height}),delete re.current[De],Ie=!0;continue}}if(Ie&&Te(),T.current=z,d&&ft(d))return;!P.activePanel&&P.panels[0]&&ze(P.panels[0]),!!(P.activePanel&&P.getPanel(P.activePanel.id))||xt()},[ze,ft,xt,r,p,Te,Ge,d,b,e]),o.useEffect(()=>{x.current&&ft(d)},[ft,d]),o.useEffect(()=>{if(!C||typeof window>"u")return;const P=()=>yt();return window.addEventListener("pointerup",P),window.addEventListener("mouseup",P),window.addEventListener("dragend",P),()=>{window.removeEventListener("pointerup",P),window.removeEventListener("mouseup",P),window.removeEventListener("dragend",P)}},[yt,C]),o.useEffect(()=>()=>{typeof window>"u"||q.current!=null&&window.clearTimeout(q.current)},[]),o.useEffect(()=>{const P=F=>{const z=F.target;if(!z)return;const te=z.querySelector("[data-tab-key]")||z.closest("[data-tab-key]");if(te){const Se=te.getAttribute("data-tab-key");if(Se&&F.dataTransfer){const _e=z.closest(".dv-tab")||te.closest(".dv-tab")||te;F.dataTransfer.effectAllowed="move",F.dataTransfer.setData("text/tab-key",Se),_e instanceof HTMLElement&&F.dataTransfer.setDragImage(_e,Math.max(12,Math.round(_e.clientWidth/2)),Math.max(10,Math.round(_e.clientHeight/2)))}}};window.addEventListener("dragstart",P);const W=ni(j.current);for(const F of W)F.addEventListener("dragstart",P);return()=>{window.removeEventListener("dragstart",P);for(const F of W)F.removeEventListener("dragstart",P)}},[D]),o.useEffect(()=>{var W;const P=(W=v.current)==null?void 0:W.querySelector(".adhdev-dockview");P instanceof HTMLElement&&Wr(P,g),ke(),ye(),ie()},[ye,ie,ke,g]),o.useEffect(()=>{ye(),ie()},[ye,ie]),o.useEffect(()=>{const P=W=>{if(W.defaultPrevented||He)return;const F=Ve(W);if(!F)return;const z=W.metaKey||W.ctrlKey||W.altKey;ma(W.target)&&!z||an(Q).setActiveTabShortcut!==F||(W.preventDefault(),W.stopPropagation(),Ye())};return window.addEventListener("keydown",P,!0),()=>window.removeEventListener("keydown",P,!0)},[Ve,Q,He,Ye]),o.useEffect(()=>{const P=v.current;if(!P)return;const W=F=>{var Ie,Ke;if(!F.isTrusted)return;const z=(Ke=(Ie=F.target)==null?void 0:Ie.closest)==null?void 0:Ke.call(Ie,".dv-scrollable");if(!z)return;F.preventDefault(),F.stopPropagation();const te=Math.abs(F.deltaX),Se=Math.abs(F.deltaY),_e=te>Se?F.deltaX:F.deltaY;z.dispatchEvent(new WheelEvent("wheel",{deltaY:_e,deltaMode:F.deltaMode,bubbles:!1,cancelable:!0}))};return P.addEventListener("wheel",W,{passive:!1,capture:!0}),()=>P.removeEventListener("wheel",W,{capture:!0})},[]),o.useEffect(()=>{const P=ni(j.current);if(P.length===0)return;const W=P.map(F=>{let z=[],te=null;const Se=()=>{te!=null&&F.clearTimeout(te),te=null,z=[]},_e=()=>{te!=null&&F.clearTimeout(te),te=F.setTimeout(()=>{te=null,z=[]},1200)},Ie=De=>{if(!De.ctrlKey&&!De.metaKey&&!De.altKey)return;const Qe=Ve(De);if(!Qe)return;const et=Yc();for(const[se,Me]of Object.entries(et))if(e.some(Ee=>Ee.tabKey===se)&&Me===Qe){De.preventDefault(),be(se);return}},Ke=De=>{if(De.defaultPrevented||He)return;const Qe=Ve(De);if(!Qe)return;const et=De.metaKey||De.ctrlKey||De.altKey;if(ma(De.target)&&!et)return;const se=an(Q),Me=Object.entries(se).filter(([we,Je])=>!!Je&&(we==="splitActiveTabRight"||we==="splitActiveTabDown"||we==="floatActiveTab"||we==="popoutActiveTab"||we==="dockActiveTab"||we==="focusLeftPane"||we==="focusRightPane"||we==="focusUpPane"||we==="focusDownPane"||we==="moveActiveTabToLeftPane"||we==="moveActiveTabToRightPane"||we==="moveActiveTabToUpPane"||we==="moveActiveTabToDownPane"||we==="selectPreviousGroupTab"||we==="selectNextGroupTab"||we==="setActiveTabShortcut"||we==="hideCurrentTab")),Ee=et?[Qe]:[...z.slice(-1),Qe].slice(-2),tt=Ee.join(" "),E=Ee[Ee.length-1],J=Me.find(([,we])=>we===tt);if(J){De.preventDefault(),Se(),ut(J[0]);return}if(Me.some(([,we])=>we.startsWith(`${tt} `))){De.preventDefault(),z=Ee,_e();return}const me=Me.find(([,we])=>we===E);if(me){De.preventDefault(),Se(),ut(me[0]);return}if(Me.some(([,we])=>we.startsWith(`${E} `))){De.preventDefault(),z=[E],_e();return}Se()};return F.addEventListener("keydown",Ie),F.addEventListener("keydown",Ke),()=>{Se(),F.removeEventListener("keydown",Ie),F.removeEventListener("keydown",Ke)}});return()=>{for(const F of W)F()}},[Ve,Q,D,be,He,ut,e]);const Ot=g==="light"?Xn:Qn,At=((Re=(Y=(Mt=j.current)==null?void 0:Mt.activePanel)==null?void 0:Y.group.element)==null?void 0:Re.ownerDocument)??document;return t.jsxs(tl.Provider,{value:at,children:[t.jsx("div",{ref:v,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(Ol,{className:`h-full min-h-0 min-w-0 adhdev-dockview${C?" is-dragging-dockview":""}${O?" is-showing-dockview-overlay":""}`,components:{conversation:wh,remote:jh},defaultTabComponent:Sh,watermarkComponent:kh,onReady:jt,singleTabMode:"default",tabAnimation:"smooth",theme:Ot,popoutUrl:"/popout.html"})}),K&&ir.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:K.x,top:K.y},children:pt.map(P=>{if(P.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},P.id);let W=t.jsx(Ad,{size:13,className:"shrink-0 opacity-70"}),F=()=>{};switch(P.id){case"dockInWindow":case"dockBackToGrid":W=t.jsx(Td,{size:13,className:"shrink-0 opacity-70"}),F=()=>{le(K.tabKey),U(null)};break;case"moveBackToMain":W=t.jsx(Id,{size:13,className:"shrink-0 opacity-70"}),F=()=>{pe(K.tabKey),U(null)};break;case"floatAsPanel":W=t.jsx(Md,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ne(K.tabKey),U(null)};break;case"openInNewWindow":W=t.jsx(Cd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{xe(K.tabKey),U(null)};break;case"setShortcut":F=z=>{z.stopPropagation(),$e(K.tabKey),U(null)};break;case"removeShortcut":W=t.jsx(It,{size:13,className:"shrink-0 opacity-70"}),F=()=>{const z={...Pe};delete z[K.tabKey],Be(z),U(null)};break;case"hideTab":W=t.jsx(Mi,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ge(K.tabKey),U(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 ${P.tone==="muted"?"text-text-muted":""}`,onClick:F,children:[W,t.jsx("span",{className:"flex-1 min-w-0",children:P.label}),P.shortcut?t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:P.shortcut}):null]},P.id)})}),K.sourceDocument.body),He&&ir.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:()=>$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. ",Q?"⌘+1":"Ctrl+1",", ",Q?"⌥+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"})]})}),At.body)]})}const sl="adhdev-recent-launch-args-v1",Ch=8;function Ih(e){return String(e||"").trim().replace(/\s+/g," ")}function rl(e,s){return`${e.trim()}::${s.trim()}`}function nl(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(sl)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function Ah(e){if(!(typeof window>"u"))try{window.localStorage.setItem(sl,JSON.stringify(e))}catch{}}function al(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=nl().byKey[rl(r,n)])==null?void 0:i.items)||[]}function ol(e,s,r){var m;const n=String(e||"").trim(),a=String(s||"").trim(),i=Ih(r);if(!n||!a||!i)return;const c=nl(),l=rl(n,a),u=((m=c.byKey[l])==null?void 0:m.items)||[],p=[i,...u.filter(f=>f!==i)].slice(0,Ch);c.byKey[l]={items:p},Ah(c)}function Mh(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 Za(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 il(e){var a;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=Za((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 cl(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Ps(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 On(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Th(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function ii(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function ci(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 Lh(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function _h(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 Rh(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 Ph({machineCards:e,conversations:s,ides:r,initialMachineId:n,sendDaemonCommand:a,onOpenConversation:i,onClose:c}){var O;const[l,u]=o.useState(n||((O=e[0])==null?void 0:O.id)||null),[p,m]=o.useState(""),[f,w]=o.useState(null),[k,A]=o.useState(!1);o.useEffect(()=>{var S;u(n||((S=e[0])==null?void 0:S.id)||null)},[n,e]);const d=o.useMemo(()=>e.find(S=>S.id===l)||e[0]||null,[l,e]),b=o.useMemo(()=>r.filter(S=>{if(S.type==="adhdev-daemon"||S.transport!=="pty")return!1;const D=Th(S.daemonId||S.id);return!!(d!=null&&d.id)&&D===d.id}),[d==null?void 0:d.id,r]),y=_c(d==null?void 0:d.id,{enabled:!!(d!=null&&d.id),includeSessions:!0,limit:6,intervalMs:1e4}),h=y.diagnostics,N=y.loading,_=y.applyDiagnostics,g=o.useMemo(()=>{const S=new Map;for(const D of b){const G=s.find(q=>q.sessionId===D.sessionId||q.routeId===D.id);D.sessionId&&G&&S.set(D.sessionId,G)}return S},[b,s]),I=o.useCallback(async()=>{if(d!=null&&d.id){A(!0);try{const S=await a(d.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),D=On(S);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Could not load hosted runtime diagnostics");_(D.diagnostics||D.result||null),m("")}catch(S){const D=S instanceof Error?S.message:"Could not load hosted runtime diagnostics";m(D)}finally{A(!1)}}},[d==null?void 0:d.id,_,a]);o.useEffect(()=>{!(d!=null&&d.id)||h||N||k||I()},[d==null?void 0:d.id,h,N,I,k]);const j=o.useCallback(async(S,D)=>{if(!(d!=null&&d.id)||S==="session_host_stop_session"&&!window.confirm(`Stop ${D.displayName}?
55
+ This will terminate the hosted runtime.`))return;const G=`${S}:${D.sessionId}`;w(G);try{const q=await a(d.id,S,{sessionId:D.sessionId}),H=On(q);if(!(H!=null&&H.success))throw new Error((H==null?void 0:H.error)||"Session host action failed");const re=S==="session_host_resume_session"?"resumed":S==="session_host_restart_session"?"restarted":"stopped";it.showToast(`Session host ${re}: ${D.displayName}`,"success"),await I()}catch(q){const H=q instanceof Error?q.message:"Session host action failed";m(H),it.showToast(H,"warning")}finally{w(q=>q===G?null:q)}},[d==null?void 0:d.id,I,a]),v=o.useCallback(async()=>{if(!(!(d!=null&&d.id)||!window.confirm(`Prune duplicate hosted runtimes?
56
+ The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`))){w("session_host_prune_duplicate_sessions");try{const D=await a(d.id,"session_host_prune_duplicate_sessions",{}),G=On(D);if(!(G!=null&&G.success))throw new Error((G==null?void 0:G.error)||"Duplicate prune failed");const q=G.result||{},H=Array.isArray(q.prunedSessionIds)?q.prunedSessionIds.length:0,re=typeof q.duplicateGroupCount=="number"?q.duplicateGroupCount:0;it.showToast(`Pruned ${H} duplicate runtime(s) across ${re} group(s)`,"success"),await I()}catch(D){const G=D instanceof Error?D.message:"Duplicate prune failed";m(G),it.showToast(G,"warning")}finally{w(D=>D==="session_host_prune_duplicate_sessions"?null:D)}}},[d==null?void 0:d.id,I,a]),x=o.useMemo(()=>[...(h==null?void 0:h.sessions)||[]].sort((S,D)=>(D.lastActivityAt||0)-(S.lastActivityAt||0)),[h==null?void 0:h.sessions]),$=o.useMemo(()=>h!=null&&h.liveRuntimes||h!=null&&h.recoverySnapshots||h!=null&&h.inactiveRecords?{liveRuntimes:(h==null?void 0:h.liveRuntimes)||[],recoverySnapshots:(h==null?void 0:h.recoverySnapshots)||[],inactiveRecords:(h==null?void 0:h.inactiveRecords)||[]}:il(x),[h==null?void 0:h.inactiveRecords,h==null?void 0:h.liveRuntimes,h==null?void 0:h.recoverySnapshots,x]),M=$.liveRuntimes,L=$.recoverySnapshots,T=$.inactiveRecords,K=o.useMemo(()=>Rh(M),[M]),U=o.useMemo(()=>[...(h==null?void 0:h.recentLogs)||[]].reverse().find(S=>S.level==="warn"||S.level==="error")||null,[h==null?void 0:h.recentLogs]),C=o.useMemo(()=>[...(h==null?void 0:h.recentTransitions)||[]].slice(-3).reverse(),[h==null?void 0:h.recentTransitions]),R=(S,D)=>{var ie,xe;const G=g.get(S.sessionId),q=b.find(pe=>pe.sessionId===S.sessionId),H=f===`session_host_resume_session:${S.sessionId}`,re=f===`session_host_restart_session:${S.sessionId}`,ae=f===`session_host_stop_session:${S.sessionId}`,Ne=Za(S.meta),X=typeof((ie=S.meta)==null?void 0:ie.runtimeRecoveryError)=="string"?String(S.meta.runtimeRecoveryError):"",he=D==="recovery"?"Recover":"Resume",ke=cl(D);return t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-3.5",children:[t.jsx("div",{className:"flex items-start justify-between gap-3",children:t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx("div",{className:"text-[14px] font-bold text-text-primary",children:S.displayName||(q==null?void 0:q.runtimeDisplayName)||(q==null?void 0:q.cliName)||S.providerType}),t.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${_h(S.lifecycle)}`,children:S.lifecycle}),Ne&&t.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:Ne})]}),t.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:S.workspaceLabel||(q==null?void 0:q.runtimeWorkspaceLabel)||S.workspace||"No workspace"}),t.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-mono text-text-primary",children:S.runtimeKey}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:((xe=S.writeOwner)==null?void 0:xe.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Lh(S.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(ga,{size:11})," ",S.attachedClients.length]})]}),t.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",ci(S.lastActivityAt),S.osPid?` · pid ${S.osPid}`:"",` · Next: ${ke}`]}),X&&t.jsx("div",{className:"mt-2 rounded-xl border border-red-500/[0.18] bg-red-500/[0.07] px-3 py-2 text-[11px] text-red-200",children:X})]})}),t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[G&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i(G),c()},children:"Open chat"}),D==="recovery"&&(S.lifecycle==="interrupted"||S.lifecycle==="failed"||S.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!f,onClick:()=>{j("session_host_resume_session",S)},children:H?`${he}ing…`:he}),t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!f,onClick:()=>{j("session_host_restart_session",S)},children:re?"Restarting…":"Restart"}),D==="live"&&(S.lifecycle==="running"||S.lifecycle==="starting"||S.lifecycle==="interrupted")&&t.jsx("button",{type:"button",className:"machine-btn border-red-500/20 px-2.5 py-1 text-[11px] text-red-300 hover:text-red-200",disabled:!!f,onClick:()=>{j("session_host_stop_session",S)},children:ae?"Stopping…":"Stop"})]})]},S.sessionId)};return t.jsx("div",{className:"fixed inset-0 z-[115] flex items-end justify-center bg-black/55 backdrop-blur-[2px] md:items-center md:p-4",onClick:c,children:t.jsxs("div",{className:"w-full max-h-[88vh] overflow-hidden rounded-t-[28px] border border-border-subtle bg-bg-primary shadow-[0_-20px_60px_rgba(0,0,0,0.35)] md:max-w-3xl md:rounded-[28px] md:shadow-[0_20px_60px_rgba(0,0,0,0.35)]",onClick:S=>S.stopPropagation(),children:[t.jsx("div",{className:"mx-auto mt-3 h-1.5 w-12 rounded-full bg-border-subtle"}),t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 pt-4 pb-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[t.jsx(qt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"mt-1 text-[18px] font-black tracking-tight text-text-primary",children:(d==null?void 0:d.label)||"No machine selected"}),t.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:"Live runtime status, next actions, and explicit recover/restart controls."})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t.jsx("button",{type:"button",className:"flex h-9 w-9 items-center justify-center rounded-full border border-border-subtle bg-bg-secondary text-text-secondary",onClick:()=>{I()},disabled:N||k,"aria-label":"Refresh hosted runtime recovery",children:t.jsx(zs,{size:16})}),t.jsx("button",{type:"button",className:"flex h-9 w-9 items-center justify-center rounded-full border border-border-subtle bg-bg-secondary text-text-secondary",onClick:c,"aria-label":"Close hosted runtime recovery",children:t.jsx(It,{size:16})})]})]}),e.length>1&&t.jsx("div",{className:"flex gap-2 overflow-x-auto px-5 pb-3 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:e.map(S=>t.jsx("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[12px] font-semibold transition-colors ${S.id===(d==null?void 0:d.id)?"border-accent-primary/40 bg-accent-primary/12 text-accent-primary":"border-border-subtle bg-bg-secondary text-text-secondary"}`,onClick:()=>u(S.id),children:S.label},S.id))}),t.jsxs("div",{className:"flex max-h-[calc(88vh-122px)] flex-col gap-3 overflow-y-auto px-5 pb-[calc(18px+env(safe-area-inset-bottom,0px))]",children:[p&&!h&&t.jsx("div",{className:"rounded-2xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-4 py-3 text-[12px] text-amber-100",children:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(ys,{size:14,className:"mt-0.5 shrink-0 text-amber-300"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"mt-1 text-amber-200/90",children:p})]})]})}),h&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-3 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-text-secondary",children:"Live"}),t.jsx("div",{className:"mt-1 text-[18px] font-bold text-text-primary",children:h.runtimeCount})]}),t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-3 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"mt-1 text-[18px] font-bold text-text-primary",children:L.length})]}),t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-3 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-text-secondary",children:"Started"}),t.jsx("div",{className:"mt-1 text-[12px] font-semibold text-text-primary",children:ci(h.hostStartedAt)}),t.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:ii(h.hostStartedAt)})]})]}),U&&t.jsxs("div",{className:"rounded-2xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-4 py-3",children:[t.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-200",children:[t.jsx(ys,{size:13})," Latest warning"]}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:U.message})]}),t.jsxs("div",{className:"flex items-center justify-between gap-3 pt-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[t.jsx(ln,{size:14})," Live hosted runtimes"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[K>0&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:f==="session_host_prune_duplicate_sessions",onClick:()=>{v()},children:f==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${K}`}),t.jsxs("div",{className:"text-[11px] text-text-secondary",children:[b.length," dashboard session",b.length===1?"":"s"]})]})]}),t.jsx("div",{className:"text-[11px] text-text-secondary leading-relaxed",children:Ps("live")}),M.length===0?t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-4 text-[13px] text-text-secondary",children:"No live hosted CLI runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:M.map(S=>R(S,"live"))}),t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Recovery snapshots"}),t.jsx("div",{className:"mb-2 text-[11px] text-text-secondary leading-relaxed",children:Ps("recovery")}),L.length===0?t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-4 text-[13px] text-text-secondary",children:"No recovery snapshots need attention."}):t.jsx("div",{className:"space-y-2",children:L.map(S=>R(S,"recovery"))})]}),T.length>0&&t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Inactive records"}),t.jsx("div",{className:"mb-2 text-[11px] text-text-secondary leading-relaxed",children:Ps("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:T.map(S=>R(S,"inactive"))})]}),C.length>0&&t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Recent activity"}),t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary divide-y divide-border-subtle",children:C.map(S=>{const D=x.find(G=>G.sessionId===S.sessionId);return t.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-2.5",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-[12px] font-semibold text-text-primary",children:(D==null?void 0:D.displayName)||S.sessionId}),t.jsxs("div",{className:"mt-0.5 text-[11px] leading-relaxed text-text-secondary",children:[S.action,S.lifecycle?` · ${S.lifecycle}`:"",S.detail?` · ${S.detail}`:"",S.error?` · ${S.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${S.success===!1?"text-red-300":"text-text-secondary"}`,children:ii(S.timestamp)})]},`${S.sessionId}:${S.timestamp}:${S.action}`)})})]})]})]})]})})}function ll(e){return!e.hasLoadedInitialResults&&!e.isLoading}function tr({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 dl({busy:e,savedSessionsLoading:s,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?zc(n):null;return t.jsxs(tr,{title:"Saved history",description:Da(),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:Om()})]}),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 Hn(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 Or(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Dh({machines:e,conversations:s,ides:r,onClose:n,onBrowseDirectory:a,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:l,onListSavedSessions:u,sendDaemonCommand:p,onOpenConversation:m}){var At,Mt;const f=xr(),w=o.useMemo(()=>[...e].sort(Na),[e]),[k,A]=o.useState(((At=w[0])==null?void 0:At.id)||""),d=o.useMemo(()=>w.find(Y=>Y.id===k)||w[0],[k,w]),b=o.useMemo(()=>((d==null?void 0:d.workspaces)||[]).map(Y=>({id:Y.id,path:Y.path,label:Y.label})),[d]),y=(d==null?void 0:d.defaultWorkspaceId)||null,[h,N]=o.useState(""),[_,g]=o.useState(""),[I,j]=o.useState(Hn(w[0])),[v,x]=o.useState(""),[$,M]=o.useState(""),[L,T]=o.useState([]),[K,U]=o.useState(""),[C,R]=o.useState([]),[O,S]=o.useState(!1),[D,G]=o.useState(!1),[q,H]=o.useState(""),[re,ae]=o.useState(!1),[Ne,X]=o.useState(()=>vt()),[he,ke]=o.useState(!1),[ie,xe]=o.useState(null),[pe,V]=o.useState(!1),[ge,ne]=o.useState(""),[ce,Z]=o.useState(!1),[le,ee]=o.useState(""),[ye,be]=o.useState([]),[B,ve]=o.useState(!1),[Ce,Ae]=o.useState(""),[Q,Pe]=o.useState(!1),He=o.useRef(null),$e=o.useRef(0);o.useEffect(()=>{var Y;!k&&((Y=w[0])!=null&&Y.id)&&A(w[0].id)},[k,w]),o.useEffect(()=>{!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||f(d.id,{minFreshMs:3e4}).catch(()=>{})},[f,d]);const Be=o.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(Y=>Y.category==="cli"&&Y.installed!==!1),[d]),Ye=o.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(Y=>Y.category==="acp"&&Y.installed!==!1),[d]),Ve=o.useMemo(()=>((d==null?void 0:d.detectedIdes)||[]).map(Y=>({id:Y.type,label:Y.name||Y.type,meta:Y.running?"Detected locally":"Available to open"})),[d]),ut=o.useMemo(()=>I==="cli"?Be.map(Y=>({id:Y.type,label:Y.displayName||Y.type,meta:"CLI provider"})):I==="acp"?Ye.map(Y=>({id:Y.type,label:Y.displayName||Y.type,meta:"ACP provider"})):Ve,[Ye,I,Be,Ve]);o.useEffect(()=>{var Re;if(!d)return;if(He.current!==d.id){He.current=d.id,N(y||((Re=b[0])==null?void 0:Re.id)||"__home__"),g(""),j(Hn(d)),x(""),M(""),U(""),R([]),G(!1),H(""),X(vt()),ne("");return}N(P=>{var W;return P==="__custom__"||P==="__home__"||b.some(F=>F.id===P)?P:y||((W=b[0])==null?void 0:W.id)||"__home__"}),j(P=>P==="ide"&&Ve.length>0||P==="cli"&&Be.length>0||P==="acp"&&Ye.length>0?P:Hn(d))},[Ye.length,Be.length,y,Ve.length,d,b]),o.useEffect(()=>{var Y;I&&(ut.some(Re=>Re.id===v)||x(((Y=ut[0])==null?void 0:Y.id)||""))},[I,ut,v]);const at=o.useCallback(async(Y,Re)=>{const P=$e.current+1;return $e.current=P,S(!0),H(""),u(Y,Re).then(W=>{$e.current===P&&R(W)}).catch(W=>{$e.current===P&&(R([]),H(W instanceof Error?W.message:"Could not load saved sessions"))}).finally(()=>{$e.current===P&&(S(!1),G(!0))})},[u]),pt=o.useCallback((Y,Re)=>{T(al(Y,Re))},[]);o.useEffect(()=>{$e.current+=1,U(""),X(vt()),!d||!v||I==="ide"?T([]):pt(d.id,v),G(!1),R([]),H(""),S(!1)},[I,pt,at,d,v]),o.useEffect(()=>{if(!K)return;const Y=C.find(Re=>Re.providerSessionId===K);Y!=null&&Y.canResume||U("")},[C,K]);const ze=h==="__custom__"?_.trim():h==="__home__"?"":((Mt=b.find(Y=>Y.id===h))==null?void 0:Mt.path)||"",ft=o.useMemo(()=>d?r.filter(Y=>Y.id!==d.id&&Y.daemonId===d.id).map(Y=>Y.workspace):[],[r,d]),xt=o.useMemo(()=>((d==null?void 0:d.recentLaunches)||[]).map(Y=>Y.workspace),[d]),ot=o.useCallback(Y=>{const Re=String(Y.workspace||"").trim();if(!Re)return;const P=b.find(W=>Or(W.path)===Or(Re));if(P){N(P.id),g("");return}N("__custom__"),g(Re)},[b]),Te=o.useCallback(Y=>{const Re=String(Y.workspace||"").trim();if(!Re)return{workspaceId:null,workspacePath:null};const P=b.find(W=>Or(W.path)===Or(Re));return P?{workspaceId:P.id,workspacePath:null}:{workspaceId:null,workspacePath:Re}},[b]),Ge=o.useMemo(()=>C.find(Y=>Y.providerSessionId===K)||null,[C,K]),Oe=o.useMemo(()=>{var Re;if(I!=="cli"||!d||!v)return null;const Y=((Re=Be.find(P=>P.type===v))==null?void 0:Re.displayName)||v;return{routeId:d.id,daemonId:d.id,providerSessionId:K||void 0,transport:"pty",mode:"chat",agentName:Y,agentType:v,status:"idle",title:Y,messages:[],ideType:v,workspaceName:ze,displayPrimary:Y,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${d.id}:${v}`,machineName:_t(d,{fallbackId:d.id})}},[I,Be,ze,d,K,v]),Ue=o.useCallback(()=>{var Re;if(!d)return;N("__custom__"),Z(!0),Ae("");const Y=xn(d.platform,hn(_.trim(),ze,ft,xt,d.defaultWorkspacePath,(Re=b.find(P=>P.id===y))==null?void 0:Re.path,b.map(P=>P.path)));ve(!0),a(d.id,Y).then(P=>{ee(P.path),g(P.path),be(P.directories)}).catch(P=>{Ae(P instanceof Error?P.message:"Could not load folder")}).finally(()=>ve(!1))},[_,y,xt,ft,a,ze,d,b]),wt=o.useCallback(Y=>{d&&(ve(!0),Ae(""),a(d.id,Y).then(Re=>{ee(Re.path),g(Re.path),be(Re.directories)}).catch(Re=>{Ae(Re instanceof Error?Re.message:"Could not load folder")}).finally(()=>ve(!1)))},[a,d]),bt=o.useCallback(async()=>{if(!d||!ze)return;Pe(!0),ne("");const Y=await i(d.id,ze);if(Pe(!1),!Y.ok){ne(Y.error||"Could not save workspace");return}ne("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,ze,d]),yt=o.useCallback(async()=>{if(!d||!I||!v)return;V(!0),ne("");const Y=$.trim()?$.trim().split(/\s+/).filter(Boolean):[],Re=I==="ide"?await c(d.id,v,{workspacePath:ze||null}):await l(d.id,I,v,{workspaceId:h!=="__home__"&&h!=="__custom__"?h:null,workspacePath:h==="__custom__"&&ze||null,resumeSessionId:I==="cli"&&K?K:null,cliArgs:Y});if(V(!1),!Re.ok){ne(Re.error||"Could not start session");return}I!=="ide"&&$.trim()&&(ol(d.id,v,$),pt(d.id,v)),n()},[I,$,pt,n,c,l,ze,d,K,v,h]),jt=I?bc(I,I==="cli"&&!!K):"Start",Ot=I?gc(I,I==="cli"&&!!K):"Starting…";return d?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 or recover 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, resume saved history, or recover a hosted runtime."})]}),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:n,"aria-label":"Close new session dialog",children:t.jsx(It,{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(tr,{title:"Machine",children:t.jsx("select",{value:d.id,onChange:Y=>A(Y.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:pe,children:w.map(Y=>t.jsx("option",{value:Y.id,children:_t(Y,{fallbackId:Y.id})},Y.id))})}),I==="cli"&&t.jsx(tr,{title:"Hosted runtimes",description:"Review live runtimes, recovery snapshots, and recover or restart options without leaving this launch flow.",action:t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:pe||!d,onClick:()=>ke(!0),children:[t.jsx(qt,{size:14}),Km()]})}),t.jsxs(tr,{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:Ue,disabled:pe,children:"Browse…"}),children:[t.jsxs("select",{value:h,onChange:Y=>{const Re=Y.target.value;N(Re),Re==="__custom__"?Ue():ne("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:pe,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),b.map(Y=>t.jsxs("option",{value:Y.id,children:[Y.id===y?"⭐ ":"",pn(Y.path,Y.label)||Y.path]},Y.id)),t.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h==="__home__"?"Launch without a workspace.":ze||"Select a workspace folder."}),h==="__custom__"&&ze&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ue,disabled:pe,children:[t.jsx(Es,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:bt,disabled:pe||Q,children:Q?"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:Be.length>0},{id:"ide",label:"IDE",enabled:Ve.length>0},{id:"acp",label:"ACP",enabled:Ye.length>0}].map(Y=>t.jsx("button",{type:"button",className:`btn btn-sm ${I===Y.id?"btn-primary":"btn-secondary"}`,onClick:()=>j(Y.id),disabled:!Y.enabled||pe,children:Y.label},Y.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:I==="ide"?"Choose IDE":I==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[ut.map(Y=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${v===Y.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>x(Y.id),disabled:pe,children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Y.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Y.meta})]},Y.id)),ut.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."})]})]}),I!=="ide"&&t.jsxs(tr,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:$,onChange:Y=>M(Y.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:pe}),L.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:L.map(Y=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>M(Y),disabled:pe,title:Y,children:Y},Y))})]}),I==="cli"&&t.jsx(dl,{busy:pe,savedSessionsLoading:O,savedSessionsError:q,selectedSession:Ge,onRefresh:()=>{!d||!v||at(d.id,v)},onOpenHistory:()=>{!d||!v||(ae(!0),ll({hasLoadedInitialResults:D,isLoading:O})&&at(d.id,v))},onClearSelection:()=>U("")}),ge&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ge.includes("saved")||ge.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:ge})]}),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:n,disabled:pe,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:yt,disabled:pe||!I||!v||h==="__custom__"&&!ze,children:[t.jsx(va,{size:14}),pe?Ot:jt]})]})]})}),ce&&t.jsx(gn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:le,directories:ye,busy:B,error:Ce,onClose:()=>Z(!1),onNavigate:wt,onConfirm:Y=>{g(Y),ee(Y),N("__custom__"),Z(!1)}}),re&&Oe&&t.jsx(Ba,{activeConv:Oe,ides:[],isCreatingChat:!1,isRefreshingHistory:O,savedSessions:C,isSavedSessionsLoading:O,isResumingSavedSessionId:ie,savedHistoryFilters:Ne,onSavedHistoryFiltersChange:X,onClose:()=>ae(!1),onNewChat:()=>{U(""),ae(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!d||!v||at(d.id,v)},onResumeSavedSession:Y=>{if(!d||!v||ie||!Y.canResume)return;const Re=Te(Y);U(Y.providerSessionId),ot(Y),xe(Y.providerSessionId),ae(!1),V(!0),ne(""),l(d.id,"cli",v,{workspaceId:Re.workspaceId,workspacePath:Re.workspacePath,resumeSessionId:Y.providerSessionId}).then(P=>{if(!P.ok){ne(P.error||"Could not resume session");return}n()}).finally(()=>{V(!1),xe(P=>P===Y.providerSessionId?null:P)})}}),he&&d&&t.jsx(Ph,{machineCards:[{id:d.id,label:_t(d,{fallbackId:d.id}),subtitle:[d.platform||"machine",Gc(d)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:d.id,sendDaemonCommand:p,onOpenConversation:Y=>{ke(!1),n(),m(Y)},onClose:()=>ke(!1)})]}):null}function Eh(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 $h(e){return e instanceof Error?e.message:String(e||"")}function Bh(e){const s=$h(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Kh({showMobileChatMode:e,isMobile:s,activeConv:r,chatIdes:n,wsStatus:a,isConnected:i,onOpenHistory:c,onOpenRemote:l,onStopCli:u,activeCliViewMode:p,onSetActiveCliViewMode:m,mobileChatConversations:f,hiddenConversations:w,ides:k,actionLogs:A,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:h,initialDataLoaded:N,userName:_,requestedMobileTabKey:g,onRequestedMobileTabConsumed:I,requestedMachineId:j,onRequestedMachineConsumed:v,requestedMobileSection:x,onRequestedMobileSectionConsumed:$,containerRef:M,isSplitMode:L,numGroups:T,groupSizes:K,groupedConvs:U,clearedTabs:C,focusedGroup:R,setFocusedGroup:O,moveTabToGroup:S,splitTabRelative:D,closeGroup:G,handleResizeStart:q,groupActiveTabIds:H,setGroupActiveTabIds:re,groupTabOrders:ae,setGroupTabOrders:Ne,toggleHiddenTab:X,visibleConversations:he,requestedDesktopTabKey:ke,onRequestedDesktopTabConsumed:ie,onDesktopActiveTabChange:xe,onHideConversation:pe,onShowHiddenConversation:V,onShowAllHiddenConversations:ge,scrollToBottomRequest:ne,machineEntries:ce,onBrowseMachineDirectory:Z,onSaveMachineWorkspace:le,onLaunchMachineIde:ee,onLaunchMachineProvider:ye,onListMachineSavedSessions:be,notifications:B,notificationUnreadCount:ve,notificationStateBySessionId:Ce,liveSessionInboxState:Ae,onMarkNotificationRead:Q,onMarkNotificationUnread:Pe,onDeleteNotification:He,onMarkNotificationTargetRead:$e}){const Be=rt.useRef(null),[Ye,Ve]=rt.useState(!1),[ut,at]=rt.useState(!1),[pt,ze]=rt.useState(!1),[ft,xt]=rt.useState(!1),ot=rt.useCallback(se=>{var Me;ir.flushSync(()=>{V(se)}),(Me=Be.current)==null||Me.restoreHiddenTabToSavedLocation(se.tabKey)},[V]),Te=rt.useCallback(se=>{var Ee;const Me=f.find(tt=>lr(tt,se))||w.find(tt=>lr(tt,se));Me&&(w.some(tt=>tt.tabKey===Me.tabKey)&&ot(Me),xe(Me.tabKey),(Ee=Be.current)==null||Ee.activateConversationTab(Me.tabKey)),Q(se.id),(se.sessionId||se.providerSessionId||se.tabKey||se.routeId)&&$e({sessionId:se.sessionId,providerSessionId:se.providerSessionId,tabKey:se.tabKey,routeId:se.routeId}),Ve(!1)},[ot,w,f,xe,Q,$e]),[Ge,Oe]=rt.useState(!1),[Ue,wt]=rt.useState("quickstart"),[bt,yt]=rt.useState("workspace"),jt=!e&&!s,Ot=rt.useCallback(se=>{Ve(se),se&&at(!1)},[]),At=rt.useCallback(se=>{at(se),se&&Ve(!1)},[]),Mt=rt.useCallback(()=>{var Me;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Me=Be.current)==null||Me.resetAllPanelsToMain(),at(!1))},[]),Y=rt.useCallback(()=>{wt(he.length===0?"quickstart":"shortcuts"),yt("workspace"),ze(!0),Ve(!1),at(!1)},[he.length]),Re=rt.useCallback(async se=>{var J;if(!r)return;const Me=(J=r.modalButtons)==null?void 0:J[se];if(!Me)return;const Ee=mr(r);if(!Ee)return;const tt=Me.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),E=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(tt);try{await d(Ee,"resolve_action",{button:Me,action:E?"approve":"reject",buttonIndex:se,...Rs(r)})}catch(de){Bh(de)||console.error("[Shortcut approval] Failed:",de)}},[r,d]),{isMac:P,actionDefinitions:W,actionShortcuts:F,shortcutListening:z,shortcutListeningDraft:te,setShortcutListening:Se,setShortcutListeningDraft:_e,saveShortcuts:Ie}=hh({enabled:jt&&!pt,onTrigger:se=>{var Me,Ee,tt,E,J,de,me,Le,we,Je,kt,ht,Qt,ks,yr,vr;if(se==="openShortcutHelp"){Y();return}if(se==="hideCurrentTab"){r&&pe(r);return}if(se==="toggleHiddenTabs"){At(!ut);return}if(se==="openHistoryForActiveTab"){r&&!Xe(r)&&c(r);return}if(se==="openRemoteForActiveTab"){r&&!Ze(r)&&!Xe(r)&&l(r);return}if(se==="splitActiveTabRight"){(Me=Be.current)==null||Me.splitActiveTabRight();return}if(se==="splitActiveTabDown"){(Ee=Be.current)==null||Ee.splitActiveTabDown();return}if(se==="floatActiveTab"){(tt=Be.current)==null||tt.floatActiveTab();return}if(se==="popoutActiveTab"){(E=Be.current)==null||E.popoutActiveTab();return}if(se==="dockActiveTab"){(J=Be.current)==null||J.dockActiveTab();return}if(se==="focusLeftPane"){(de=Be.current)==null||de.focusLeftPane();return}if(se==="focusRightPane"){(me=Be.current)==null||me.focusRightPane();return}if(se==="focusUpPane"){(Le=Be.current)==null||Le.focusUpPane();return}if(se==="focusDownPane"){(we=Be.current)==null||we.focusDownPane();return}if(se==="moveActiveTabToLeftPane"){(Je=Be.current)==null||Je.moveActiveTabToLeftPane();return}if(se==="moveActiveTabToRightPane"){(kt=Be.current)==null||kt.moveActiveTabToRightPane();return}if(se==="moveActiveTabToUpPane"){(ht=Be.current)==null||ht.moveActiveTabToUpPane();return}if(se==="moveActiveTabToDownPane"){(Qt=Be.current)==null||Qt.moveActiveTabToDownPane();return}if(se==="triggerPrimaryApprovalAction"){Re(0);return}if(se==="triggerSecondaryApprovalAction"){Re(1);return}if(se==="triggerTertiaryApprovalAction"){Re(2);return}if(se==="setActiveTabShortcut"){(ks=Be.current)==null||ks.setShortcutForActiveTab();return}if(se==="selectPreviousGroupTab"){(yr=Be.current)==null||yr.activatePreviousTabInGroup();return}if(se==="selectNextGroupTab"){(vr=Be.current)==null||vr.activateNextTabInGroup();return}!r||!Ze(r)||Xe(r)||se==="toggleCliView"&&m(p==="chat"?"terminal":"chat")}}),Ke=rt.useCallback(()=>{ze(!1),Se(null),_e([])},[Se,_e]),De=rt.useMemo(()=>bt==="all"?W:W.filter(se=>Eh(se)===bt),[W,bt]),Qe=rt.useCallback(()=>{const se=Object.fromEntries(W.map(Me=>[Me.id,""]));Ie(se)},[W,Ie]),et=rt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const se=Object.fromEntries(W.map(Me=>[Me.id,Me.defaultShortcut]));Ie(se)},[W,Ie]);return rt.useEffect(()=>{const se=Me=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Me.metaKey&&Me.key.toLowerCase()==="w":Me.ctrlKey&&Me.key.toLowerCase()==="w")&&(Me.preventDefault(),r&&pe&&pe(r))};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[r,pe]),rt.useEffect(()=>{if(!pt||z)return;const se=Me=>{Me.key==="Escape"&&(Me.preventDefault(),Ke())};return window.addEventListener("keydown",se,!0),()=>window.removeEventListener("keydown",se,!0)},[Ke,pt,z]),rt.useEffect(()=>{if(!jt){Oe(!1);return}Oe(!0);const se=window.setTimeout(()=>{Oe(!1)},1e4);return()=>window.clearTimeout(se)},[jt]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(Pm,{activeConv:r,agentCount:n.length,wsStatus:a,isConnected:i,conversations:he,hiddenConversations:w,onOpenHistory:c,onHideConversation:pe,onShowConversation:ot,onShowAllHidden:ge,onResetPanelsToMain:Mt,notifications:B,notificationUnreadCount:ve,onOpenNotification:Te,onMarkNotificationRead:Q,onMarkNotificationUnread:Pe,onDeleteNotification:He,inboxOpen:Ye,onInboxOpenChange:Ot,hiddenOpen:ut,onHiddenOpenChange:At,onOpenNewSession:s?void 0:()=>xt(!0),actionShortcuts:F,onOpenRemote:()=>{!r||Ze(r)||Xe(r)||l(r)},onStopCli:u,activeCliViewMode:p,onSetCliViewMode:m}),e?t.jsx(rh,{conversations:f,hiddenConversations:w,ides:k,actionLogs:A,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:h,userName:_,requestedActiveTabKey:g,onRequestedActiveTabConsumed:I,requestedMachineId:j,onRequestedMachineConsumed:v,requestedMobileSection:x,onRequestedMobileSectionConsumed:$,onOpenHistory:c,onOpenRemote:l,onStopCli:u,wsStatus:a,isConnected:i,onShowHiddenConversation:ot,onShowAllHiddenConversations:ge,onOpenNewSession:()=>xt(!0),notificationStateBySessionId:Ce,liveSessionInboxState:Ae,onMarkNotificationTargetRead:$e}):s?t.jsx(uh,{containerRef:M,isSplitMode:L,numGroups:T,groupSizes:K,groupedConvs:U,clearedTabs:C,ides:k,actionLogs:A,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:h,hasRegisteredMachines:ce.length>0,userName:_,focusedGroup:R,setFocusedGroup:O,moveTabToGroup:S,splitTabRelative:D,closeGroup:G,handleResizeStart:q,groupActiveTabIds:H,setGroupActiveTabIds:re,groupTabOrders:ae,setGroupTabOrders:Ne,toggleHiddenTab:X,allowTabShortcuts:!1,notificationStateBySessionId:Ce,liveSessionInboxState:Ae}):t.jsx(Nh,{visibleConversations:he,clearedTabs:C,ides:k,actionLogs:A,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:h,hasRegisteredMachines:ce.length>0,initialDataLoaded:N,userName:_,toggleHiddenTab:X,actionShortcuts:F,registerActionHandlers:se=>{Be.current=se},notificationStateBySessionId:Ce,liveSessionInboxState:Ae,onActiveTabChange:xe,requestedActiveTabKey:ke,onRequestedActiveTabConsumed:ie,scrollToBottomRequest:ne}),ft&&t.jsx(Dh,{machines:ce,conversations:f,ides:k,onClose:()=>xt(!1),onBrowseDirectory:Z,onSaveWorkspace:le,onLaunchIde:ee,onLaunchProvider:ye,onListSavedSessions:be,sendDaemonCommand:d,onOpenConversation:se=>{xt(!1),V(se),xe(se.tabKey)}}),pt&&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:Ke,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:se=>se.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:Ke,"aria-label":"Close dashboard guide",children:t.jsx(It,{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(se=>t.jsx("button",{type:"button",className:`btn btn-sm ${Ue===se.id?"btn-primary":"btn-secondary"}`,onClick:()=>wt(se.id),children:se.label},se.id))}),Ue==="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 ",P?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Ue==="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."]})]})]})]}),Ue==="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(se=>t.jsx("button",{type:"button",className:`btn btn-sm ${bt===se.id?"btn-primary":"btn-secondary"}`,onClick:()=>yt(se.id),children:se.label},se.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Qe,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:et,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:De.map(se=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${z===se.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:se.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:se.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:se.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:z===se.id?te.length>0?`${te.join(" ")} ...`:"Listening...":F[se.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Se(se.id),_e([])},children:z===se.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Me={...F};Me[se.id]="",Ie(Me)},children:"Disable"})]})]})},se.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",P?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&t.jsxs("button",{type:"button",onClick:Y,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 ${Ge?"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:"?"}),Ge&&t.jsx("span",{children:"Guide"})]})]})}const Un=[{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 Wh({onClose:e}){const[s,r]=o.useState(0),n=Un[s],a=s===Un.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.target===i.currentTarget&&e()},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(It,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Un.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.jsxs("div",{className:"flex justify-between items-center mt-6",children:[t.jsx("button",{onClick:e,className:"btn btn-secondary border-none",children:"Skip"}),t.jsx("button",{onClick:()=>a?e():r(i=>i+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})]})]}),t.jsx("style",{children:`
57
+ @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
58
+ @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
59
+ `})]})}function Oh({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 Hh({ideData:e,allIdes:s,connectionStates:r,localUserMessages:n,ideName:a,preferredTabKey:i}){const[c,l]=o.useState(()=>i||"native"),u=o.useMemo(()=>vc(s),[s]),p=o.useMemo(()=>e?Ka(e,n,{machineNames:u,connectionStates:r,defaultConnectionState:"new"}):[],[e,n,u,r]),m=o.useMemo(()=>p.find(b=>b.streamSource==="native"),[p]),f=o.useMemo(()=>p.filter(b=>b.streamSource==="agent-stream"),[p]),w=o.useMemo(()=>e?Wt(p,e.id):null,[p,e]);o.useEffect(()=>{i&&l(i)},[i]),o.useEffect(()=>{if(i||!w)return;const b=w.streamSource==="native"?"native":w.tabKey;!b||c===b||c==="native"&&l(b)},[c,w,i]),o.useEffect(()=>{var b;c!=="native"&&(f.some(y=>y.tabKey===c)||l(((b=f[0])==null?void 0:b.tabKey)||"native"))},[c,f]),o.useEffect(()=>{c==="native"&&(m||f[0]&&l(f[0].tabKey))},[c,m,f]);const k=o.useMemo(()=>c==="native"&&m?m:f.find(b=>b.tabKey===c)||w||m||f[0],[c,m,w,f]),A=o.useMemo(()=>f.map(b=>({tabKey:b.tabKey,title:fc(b)||a,status:b.status})),[f,a]),d=o.useCallback(b=>{if(b)return p.find(y=>lr(y,{sessionId:b,routeId:b,tabKey:b,providerSessionId:b}))},[p]);return{activeChatTab:c,setActiveChatTab:l,activeConv:k,conversations:p,extensionTabs:A,hasExtensions:A.length>0,resolveConversationByTarget:d}}function Uh({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:a,localUserMessages:i,sendDaemonCommand:c,setLocalUserMessages:l,setActionLogs:u,isStandalone:p,userName:m,onOpenHistory:f,onConversationChange:w,onClose:k}){const[A,d]=o.useState("split"),[b,y]=o.useState(()=>ss(e)?"native":e.tabKey),h=o.useRef(null),N=o.useMemo(()=>s||r.find(S=>S.id===e.routeId),[e.routeId,s,r]),_=o.useMemo(()=>nt((N==null?void 0:N.type)||""),[N==null?void 0:N.type]),{conversations:g,extensionTabs:I,hasExtensions:j}=Hh({ideData:N,allIdes:r,connectionStates:n,localUserMessages:i,ideName:_||"IDE",preferredTabKey:ss(e)?void 0:e.tabKey}),v=o.useMemo(()=>N?Wt(g,N.id):null,[N,g]);o.useEffect(()=>{const S=h.current,D={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(h.current=D,!(S&&S.routeId===D.routeId&&S.tabKey===D.tabKey&&S.streamSource===D.streamSource)){if(ss(e)){y("native");return}y(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(b==="native"){if(g.some(S=>S.streamSource==="native"))return;(v==null?void 0:v.streamSource)==="agent-stream"&&y(v.tabKey);return}if(!g.some(S=>S.tabKey===b)){if((v==null?void 0:v.streamSource)==="agent-stream"){y(v.tabKey);return}y("native")}},[g,b,v]);const x=o.useMemo(()=>b==="native"?g.find(S=>S.streamSource==="native")||e:g.find(S=>S.tabKey===b)||e,[e,g,b]),$=Rc(x),M=o.useMemo(()=>$.status||$.modalMessage||$.modalButtons?{...x,...$.status?{status:$.status}:{},...$.modalMessage!==void 0?{modalMessage:$.modalMessage}:{},...$.modalButtons!==void 0?{modalButtons:$.modalButtons}:{}}:x,[x,$]),L=hr(M),T=fn({sendDaemonCommand:c,activeConv:M,setLocalUserMessages:l,setActionLogs:u,isStandalone:p}),{connScreenshot:K,screenshotUsage:U,handleRemoteAction:C}=Qc({doId:L,targetSessionId:Ji(M),connState:M.connectionState||"new",viewMode:A}),R=o.useMemo(()=>a.filter(S=>S.routeId===M.tabKey),[a,M.tabKey]);o.useEffect(()=>{w==null||w(M)},[M,w]),o.useEffect(()=>{const S=D=>{D.key==="Escape"&&k()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[k]);const O=o.useCallback(S=>{S.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:k,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:O,children:[t.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[t.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[t.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(Rt,{size:16})}),t.jsx("span",{className:"truncate",children:Aa(x)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:k,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(S=>{const D=A===S;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${D?"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:()=>d(S),title:S==="split"?"Split view":"Remote only",children:S==="split"?t.jsx(pd,{size:15}):t.jsx(Rt,{size:15})},S)})}),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(x),title:"Chat History",children:[t.jsx(ya,{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:k,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${A==="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:[A!=="remote"&&t.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${A==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[t.jsx(Oh,{hasExtensions:j,ideName:_||"IDE",activeChatTab:b,extensionTabs:I,onSelectTab:y}),t.jsx(Bi,{activeConv:M,onModalButton:T.handleModalButton}),t.jsx(aa,{activeConv:M,ideEntry:N,showMetaChips:!1,handleSendChat:T.handleSendChat,isSendingChat:T.isSendingChat,sendFeedbackMessage:T.sendFeedbackMessage,handleFocusAgent:T.handleFocusAgent,isFocusingAgent:T.isFocusingAgent,actionLogs:R,userName:m})]}),t.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${A==="split"?"order-1 md:order-2":""}`,children:t.jsx(Pi,{addLog:()=>{},connState:M.connectionState||"new",connScreenshot:K,screenshotUsage:U,transportType:M.transport,onAction:C})})]})]})})}function Fh({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=Tm(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 zh({historyModalOpen:e,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:a,savedHistorySessions:i,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:l,onCloseHistory:u,onNewHistoryChat:p,onSwitchHistorySession:m,onRefreshHistory:f,onResumeSavedHistorySession:w,remoteDialogConv:k,remoteDialogIdeEntry:A,connectionStates:d,actionLogs:b,localUserMessages:y,sendDaemonCommand:h,setLocalUserMessages:N,setActionLogs:_,isStandalone:g,userName:I,onOpenRemoteHistory:j,onRemoteConversationChange:v,onCloseRemoteDialog:x,cliStopDialogOpen:$,cliStopTargetConv:M,onCancelCliStop:L,onStopCliNow:T,onSaveCliAndStop:K,toasts:U,onDismissToast:C,onClickToast:R,showOnboarding:O,onCloseOnboarding:S}){var q;const[D,G]=rt.useState(()=>vt());return t.jsxs(t.Fragment,{children:[e&&s&&t.jsx(Ba,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:a,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:l,savedHistoryFilters:D,onSavedHistoryFiltersChange:G,onClose:u,onNewChat:p,onSwitchSession:m,onRefreshHistory:f,onResumeSavedSession:w}),k&&t.jsx(Uh,{activeConv:k,ideEntry:A,ides:r,connectionStates:d,actionLogs:b,localUserMessages:y,sendDaemonCommand:h,setLocalUserMessages:N,setActionLogs:_,isStandalone:g,userName:I,onOpenHistory:j,onConversationChange:v,onClose:x}),$&&M&&(Ze(M)||Xe(M))&&t.jsx(Fh,{activeConv:M,canSaveAndStop:Ze(M)&&!Xe(M)&&!!((q=M.resume)!=null&&q.supported),onCancel:L,onStopNow:T,onSaveAndStop:K}),t.jsx(yc,{toasts:U,onDismiss:C,onClickToast:R}),O&&t.jsx(Wh,{onClose:S})]})}function Vh({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(zs,{size:14})}),t.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[t.jsxs("span",{children:[r?"Daemon update required":"Update available",s?t.jsxs(t.Fragment,{children:[": ",t.jsxs("strong",{children:["v",s]})]}):null]}),e.map(c=>{const l=_t(c,{fallbackId:c.id}),u=n[c.id],p=c.version||c.daemonVersion||"unknown",m=c.versionUpdateRequired===!0;return t.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:m?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${m?"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",p]}),m&&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:m?"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:m?"var(--status-danger)":"var(--status-warning)",background:m?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${m?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:m?"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(It,{size:16})})]})}function Gh(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function qh(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function li(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 Xh(){var ao,oo,io,co,lo;const{sendCommand:e}=Pt(),s=xr(),r=xa(),n=Fs(),[a,i]=Hl(),c=a.get("activeTab"),l=((ao=r.state)==null?void 0:ao.openRemoteForTabKey)||null,u=((oo=r.state)==null?void 0:oo.openMachineId)||null,p=((io=r.state)==null?void 0:io.mobileSection)||null,m=lc(),f=m.ides||[],w=m.initialLoaded??!0,{updateRouteChats:k,setToasts:A}=m,[d,b]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),y=m.toasts||[],h=m.wsStatus||"connected",N=m.isConnected??!0,_=m.connectionStates||{},g=m.showReconnected||!1,{groupAssignments:I,setGroupAssignments:j,focusedGroup:v,setFocusedGroup:x,groupActiveTabIds:$,setGroupActiveTabIds:M,groupTabOrders:L,setGroupTabOrders:T,groupSizes:K,setGroupSizes:U,isMobile:C,hasHydratedStoredLayout:R,hydrateStoredLayout:O}=cf(),[S,D]=o.useState(!1),[G,q]=o.useState(!1),[H,re]=o.useState(null),[ae,Ne]=o.useState([]),[X,he]=o.useState(!1),[ke,ie]=o.useState(null),[xe,pe]=o.useState(()=>Ua());o.useEffect(()=>Ip(pe),[]);const V=o.useMemo(()=>Gh({isMobile:C,mobileViewMode:xe}),[C,xe]),[ge,ne]=o.useState([]),[ce,Z]=o.useState({}),[le,ee]=o.useState({}),[ye,be]=o.useState({}),[B,ve]=o.useState(null),[Ce,Ae]=o.useState(null),[Q,Pe]=o.useState(null),He=o.useRef(null);pr("Dashboard",{ideCount:f.length,toastCount:y.length,focusedGroup:v,groupCount:Object.keys(I).length,localMessageTabs:Object.keys(ce).length,actionLogCount:ge.length});const $e=f.find(oe=>oe.type==="adhdev-daemon"),Be=o.useMemo(()=>f.filter(oe=>oe.type==="adhdev-daemon").sort(Na),[f]),Ye=!!$e;o.useEffect(()=>{!$e||!(!$e.detectedIdes||!$e.availableProviders||!$e.recentLaunches||!$e.workspaces)||s($e.id,{minFreshMs:3e4}).catch(()=>{})},[$e,s]);const Ve=($e==null?void 0:$e.terminalBackend)||null,ut=$e?_t($e,{fallbackId:$e.id}):null,at=($e==null?void 0:$e.id)||null,pt=o.useMemo(()=>Ep(f,le),[f,le]),{hiddenTabs:ze,hideTab:ft,toggleTab:xt,showTab:ot,showAllTabs:Te}=Dp(),{chatIdes:Ge,conversations:Oe,visibleConversations:Ue,visibleTabKeys:wt,resolveConversationBySessionId:bt,resolveConversationByTarget:yt}=qp({ides:pt,connectionStates:_,localUserMessages:ce,clearedTabs:ye,hiddenTabs:ze}),jt=o.useMemo(()=>new Map(Oe.map(oe=>[oe.tabKey,Pr(oe)])),[Oe]),Ot=o.useCallback(oe=>{const fe=jt.get(oe)||Pr({tabKey:oe});ft(fe)},[jt,ft]),At=o.useCallback(oe=>{const fe=jt.get(oe)||Pr({tabKey:oe});xt(fe)},[jt,xt]),Mt=o.useCallback(oe=>{const fe=jt.get(oe)||Pr({tabKey:oe});ot(fe)},[jt,ot]);gm(Ue,V),o.useEffect(()=>{Object.keys(le).length!==0&&ee(oe=>$p(oe,f))},[f,le]);const Y=o.useMemo(()=>qd(f),[f]),{notifications:Re,unreadCount:P,notificationStateBySessionId:W,markRead:F,markUnread:z,markTargetRead:te,deleteNotification:Se}=Rf({conversations:Oe,liveSessionInboxState:Y}),_e=o.useCallback(oe=>{const fe=Re.find(ue=>ue.id===oe),je=Math.max(Date.now(),(fe==null?void 0:fe.updatedAt)||0);F(oe,je),fe!=null&&fe.sessionId&&e(fe.machineId||fe.routeId,"mark_session_seen",{sessionId:fe.sessionId,seenAt:je}).catch(()=>{})},[F,Re,e]),Ie=o.useCallback(oe=>{const fe=Re.find(je=>je.id===oe);z(oe),fe!=null&&fe.sessionId&&e(fe.machineId||fe.routeId,"mark_notification_unread",{sessionId:fe.sessionId,notificationId:fe.id}).catch(()=>{})},[z,Re,e]),Ke=o.useCallback(oe=>{const fe=Re.find(je=>je.id===oe);Se(oe),fe!=null&&fe.sessionId&&e(fe.machineId||fe.routeId,"delete_notification",{sessionId:fe.sessionId,notificationId:fe.id}).catch(()=>{})},[Se,Re,e]),De=o.useRef(null),{containerRef:Qe,normalizedGroupAssignments:et,numGroups:se,isSplitMode:Me,groupedConvs:Ee,moveTabToGroup:tt,closeGroup:E,handleResizeStart:J,splitTabRelative:de}=xf({groupAssignments:I,setGroupAssignments:j,setFocusedGroup:x,setGroupActiveTabIds:M,setGroupTabOrders:T,groupSizes:K,setGroupSizes:U,isMobile:C,visibleConversations:Ue,visibleTabKeys:wt}),me=o.useMemo(()=>{var fe,je;if(!C){if(B){const ue=Oe.find(Fe=>Fe.tabKey===B);if(ue)return ue}return Ue[0]}const oe=$[v];if(oe){const ue=Oe.find(Fe=>Fe.tabKey===oe);if(ue)return ue}return((fe=Ee[v])==null?void 0:fe[0])||((je=Ee[0])==null?void 0:je[0])},[B,C,$,v,Oe,Ee,Ue]);o.useEffect(()=>{if(C){De.current=null;return}if(!(me!=null&&me.sessionId)){De.current=null;return}const oe=Zr(me,Y),fe=Ei(me),je=[me.tabKey,fr(me)||"",me.lastMessageHash||"",String(me.lastMessageAt||0),oe.inboxBucket,oe.unread?"1":"0"].join(":");if(De.current===je)return;const ue=()=>{if(document.visibilityState!=="visible"||De.current===je)return;De.current=je;const Fe=Math.max(Date.now(),ds(me),oe.lastUpdated||0);te({...fe},Fe),e(me.daemonId||me.routeId,"mark_session_seen",{sessionId:me.sessionId,seenAt:Fe}).catch(()=>{})};if(document.visibilityState==="visible"){const Fe=setTimeout(ue,1500),dt=()=>{document.visibilityState!=="visible"&&clearTimeout(Fe)};return document.addEventListener("visibilitychange",dt),()=>{clearTimeout(Fe),document.removeEventListener("visibilitychange",dt)}}else{const Fe=()=>{document.visibilityState==="visible"&&(setTimeout(ue,800),document.removeEventListener("visibilitychange",Fe))};return document.addEventListener("visibilitychange",Fe),()=>{document.removeEventListener("visibilitychange",Fe)}}},[me,C,Y,te,e]);const{requestedDesktopTabKey:Le,requestedMobileTabKey:we,consumeRequestedActiveTab:Je}=Yp({isMobile:C,urlActiveTab:c,resolveConversationBySessionId:bt,setSearchParams:i}),{remoteDialogConv:kt,remoteDialogIdeEntry:ht,remoteDialogActiveConv:Qt,setRemoteDialogActiveConv:ks,openRemoteDialog:yr,closeRemoteDialog:vr}=uf({isMobile:C,location:r,navigate:n,requestedRemoteTabTarget:l,requestedDesktopTabKey:Le,conversations:Oe,ides:f,resolveConversationByTarget:yt}),lt=Qt||kt||me,Ht=!!lt&&Ze(lt)&&!Xe(lt),wr=o.useMemo(()=>{if(!lt||!Ht)return null;const oe=lt.daemonId||lt.routeId||"",fe=Bt(lt);return`${oe}:${fe}`},[lt,Ht]),ml=o.useMemo(()=>Ue,[Ue]),jr=C&&xe==="chat",pl=o.useMemo(()=>Oe.filter(oe=>Fa(ze,oe)),[Oe,ze]),kr=o.useCallback(oe=>{const fe=new URLSearchParams(a);fe.set("activeTab",oe),i(fe,{replace:!0})},[a,i]),fl=o.useCallback(async(oe,fe)=>bn(e,oe,fe),[e]),hl=o.useCallback(async(oe,fe)=>{if(!fe.trim())return{ok:!1,error:"Choose a workspace path first."};try{const je=await e(oe,"workspace_add",{path:fe.trim()});return je!=null&&je.success?{ok:!0}:{ok:!1,error:(je==null?void 0:je.error)||"Could not save workspace"}}catch(je){return{ok:!1,error:je instanceof Error?je.message:"Could not save workspace"}}},[e]),xl=o.useCallback(async(oe,fe,je)=>{var ue;try{const Fe={ideType:fe,enableCdp:!0};(ue=je==null?void 0:je.workspacePath)!=null&&ue.trim()&&(Fe.workspace=je.workspacePath.trim());const dt=await e(oe,"launch_ide",Fe);return!(dt!=null&&dt.success)&&(dt==null?void 0:dt.success)!==void 0?{ok:!1,error:(dt==null?void 0:dt.error)||"Could not launch IDE"}:(Pe({machineId:oe,kind:"ide",providerType:fe,workspacePath:(je==null?void 0:je.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(Fe){return{ok:!1,error:Fe instanceof Error?Fe.message:"Could not launch IDE"}}},[e]),bl=o.useCallback(async(oe,fe,je,ue)=>{var dt,Ft,Ss;const Fe=Date.now();try{const Tt={cliType:je};(dt=ue==null?void 0:ue.workspacePath)!=null&&dt.trim()?Tt.dir=ue.workspacePath.trim():ue!=null&&ue.workspaceId&&(Tt.workspaceId=ue.workspaceId),(Ft=ue==null?void 0:ue.resumeSessionId)!=null&&Ft.trim()&&(Tt.resumeSessionId=ue.resumeSessionId.trim()),Array.isArray(ue==null?void 0:ue.cliArgs)&&ue.cliArgs.length>0&&(Tt.cliArgs=ue.cliArgs),(Ss=ue==null?void 0:ue.initialModel)!=null&&Ss.trim()&&(Tt.initialModel=ue.initialModel.trim());const gt=await e(oe,"launch_cli",Tt),Dt=(gt==null?void 0:gt.result)||gt,Gs=(Dt==null?void 0:Dt.sessionId)||(Dt==null?void 0:Dt.id);return gt!=null&&gt.success&&Gs?(kr(Gs),{ok:!0}):gt!=null&&gt.success?(Pe({machineId:oe,kind:fe,providerType:je,workspacePath:(ue==null?void 0:ue.workspacePath)||null,resumeSessionId:(ue==null?void 0:ue.resumeSessionId)||null,startedAt:Fe}),{ok:!0}):{ok:!1,error:(gt==null?void 0:gt.error)||(Dt==null?void 0:Dt.error)||`Could not launch ${fe.toUpperCase()} session`}}catch(Tt){return Yh(Tt)?(Pe({machineId:oe,kind:fe,providerType:je,workspacePath:(ue==null?void 0:ue.workspacePath)||null,resumeSessionId:(ue==null?void 0:ue.resumeSessionId)||null,startedAt:Fe}),{ok:!0}):{ok:!1,error:Tt instanceof Error?Tt.message:`Could not launch ${fe.toUpperCase()} session`}}},[kr,e]),gl=o.useCallback(async(oe,fe)=>{if(!oe||!fe)return[];try{const je=await e(oe,"list_saved_sessions",{providerType:fe,kind:"cli",limit:30}),ue=(je==null?void 0:je.result)??je;return Array.isArray(ue==null?void 0:ue.sessions)?ue.sessions:[]}catch(je){return console.error("List saved sessions failed",je),[]}},[e]);o.useEffect(()=>{if(!Q)return;const oe=li(Q.workspacePath),fe=f.find(ue=>{var Tt,gt,Dt,Gs;if(!ue||ue.type==="adhdev-daemon"||qh(ue.daemonId||ue.id)!==Q.machineId||(dr(ue)?"cli":Ls(ue)?"acp":"ide")!==Q.kind||String(ue.agentType||ue.type||"")!==Q.providerType)return!1;if(Q.resumeSessionId)return String(ue.providerSessionId||"")===Q.resumeSessionId;if(oe){const wn=li(ue.workspace||ue.runtimeWorkspaceLabel);return wn?wn===oe:!1}return Number(ue.lastUpdated||ue._lastUpdate||ue.timestamp||((Gs=(Dt=(gt=(Tt=ue.activeChat)==null?void 0:Tt.messages)==null?void 0:gt.at)==null?void 0:Dt.call(gt,-1))==null?void 0:Gs.timestamp)||0)>=Q.startedAt-5e3});if(!fe)return;const je=tc({entrySessionId:fe.sessionId,entryInstanceId:fe.instanceId,entryRouteId:fe.id,conversations:Oe});je&&(Pe(null),kr(je))},[Oe,kr,f,Q]),o.useEffect(()=>{if(!Q)return;const oe=window.setTimeout(()=>{Pe(fe=>!fe||fe.startedAt!==Q.startedAt?fe:null)},45e3);return()=>window.clearTimeout(oe)},[Q]),Bp({visibleConversations:Ue,clearedTabs:ye,setClearedTabs:be,setActionLogs:ne}),Xp({ides:f,sendDaemonCommand:e,setToasts:A,setLocalUserMessages:Z,resolveConversationByTarget:yt});const{isRefreshingHistory:yl,handleRefreshHistory:vl}=Uo({sendDaemonCommand:e,activeConv:me,chats:(co=f.find(oe=>oe.id===(me==null?void 0:me.routeId)))==null?void 0:co.chats,updateRouteChats:k,setToasts:A,setLocalUserMessages:Z,setClearedTabs:be}),{isCreatingChat:wl,isRefreshingHistory:jl,handleSwitchSession:kl,handleNewChat:Sl,handleRefreshHistory:Nl}=Uo({sendDaemonCommand:e,activeConv:lt,chats:(lo=f.find(oe=>oe.id===(lt==null?void 0:lt.routeId)))==null?void 0:lo.chats,updateRouteChats:k,setToasts:A,setLocalUserMessages:Z,setClearedTabs:be}),vn=o.useCallback(async()=>{if(!(!lt||!Ht||X)){he(!0);try{const oe=lt.daemonId||lt.routeId,fe=Bt(lt),je=await e(oe,"list_saved_sessions",{agentType:fe,providerType:fe,kind:"cli",limit:50}),ue=(je==null?void 0:je.result)??je;Ne(Array.isArray(ue==null?void 0:ue.sessions)?ue.sessions:[])}catch(oe){console.error("Refresh saved sessions failed",oe),Ne([])}finally{he(!1)}}},[lt,X,Ht,e]);o.useEffect(()=>{if(!S){He.current=null;return}if(!Ht){He.current=null,Ne([]),he(!1);return}!wr||X||He.current!==wr&&(He.current=wr,vn())},[vn,S,X,Ht,wr]);const Cl=o.useCallback(async oe=>{if(!lt||!Ht||!oe.providerSessionId||!oe.workspace)return;const fe=lt.daemonId||lt.routeId,je=Bt(lt);try{ie(oe.providerSessionId);const ue=await e(fe,"launch_cli",{cliType:je,dir:oe.workspace,resumeSessionId:oe.providerSessionId,initialModel:Ui(oe.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Fe=(ue==null?void 0:ue.result)??ue,dt=typeof(Fe==null?void 0:Fe.sessionId)=="string"?Fe.sessionId:typeof(Fe==null?void 0:Fe.id)=="string"?Fe.id:"";dt&&i(Ft=>{const Ss=new URLSearchParams(Ft);return Ss.set("activeTab",dt),Ss},{replace:!0}),D(!1)}catch(ue){console.error("Resume saved session failed",ue)}finally{ie(null)}},[lt,Ht,e,i]);df({urlActiveTab:C&&!jr?c:null,conversations:Oe,resolveConversationBySessionId:bt,normalizedGroupAssignments:et,hasHydratedStoredLayout:C&&!jr?R:!0,hydrateStoredLayout:C&&!jr?O:()=>{},setGroupActiveTabIds:M,setFocusedGroup:x,setSearchParams:i,historyModalOpen:S,activeConv:me,isRefreshingHistory:yl,ides:f,handleRefreshHistory:vl});const to=o.useCallback(async(oe,fe)=>{const je=fe||H||me;if(!je||!Ze(je)&&!Xe(je))return;const ue=Bt(je),Fe=je.routeId||je.daemonId||"";try{await e(Fe,"stop_cli",{cliType:ue,targetSessionId:je.sessionId,mode:oe})}catch(dt){console.error("Stop CLI failed:",dt)}},[me,H,e]),Il=o.useCallback(async oe=>{const fe=oe||me;!fe||!Ze(fe)&&!Xe(fe)||(re(fe),q(!0))},[me]),Al=o.useMemo(()=>!me||!Ze(me)||Xe(me)?null:Ks(me),[me]),Ml=o.useCallback(async oe=>{if(!me||!Ze(me)||Xe(me))return;const fe=Ks(me);if(fe===oe)return;const je=me.sessionId;je&&ee(ue=>({...ue,[je]:oe}));try{await e(as(me)||me.routeId,"set_cli_view_mode",{targetSessionId:me.sessionId,cliType:Bt(me),mode:oe})}catch(ue){const Fe=Va(ue);je&&!Fe&&ee(dt=>{const Ft={...dt};return fe===Ec(f,je)?delete Ft[je]:Ft[je]=fe,Ft}),za(ue)?console.warn(Fe?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",ue instanceof Error?ue.message:String(ue)):console.error("Failed to switch CLI view mode:",ue)}},[me,f,e]),{versionMismatchDaemons:Tl,hasRequiredVersionDaemons:so,appVersion:Ll,versionBannerDismissed:_l,setVersionBannerDismissed:Rl,upgradingDaemons:Pl,handleBannerUpgrade:Dl}=bf({ides:f,sendDaemonCommand:e}),ro=o.useCallback(oe=>{ve(oe.tabKey),i(fe=>{const je=new URLSearchParams(fe),ue=Hu(oe);return ue?je.set("activeTab",ue):je.delete("activeTab"),je},{replace:!0})},[i]),no=o.useCallback(oe=>{Mt(oe.tabKey),ro(oe)},[ro,Mt]),El=o.useCallback(oe=>{Ot(oe.tabKey)},[Ot]);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(_m,{wsStatus:h,showReconnected:g}),t.jsx(Rm,{terminalBackend:Ve,isStandalone:Ye,machineLabel:ut,machineKey:at}),(!_l||so)&&t.jsx(Vh,{daemons:Tl,targetVersion:Ll,required:so,upgradingDaemons:Pl,onUpgrade:Dl,onDismiss:()=>Rl(!0)}),t.jsx(Kh,{showMobileChatMode:jr,isMobile:C,activeConv:me,chatIdes:Ge,wsStatus:h,isConnected:N,onOpenHistory:oe=>{oe&&ks(oe),D(!0)},onOpenRemote:yr,onStopCli:Il,activeCliViewMode:Al,onSetActiveCliViewMode:Ml,mobileChatConversations:ml,ides:f,actionLogs:ge,sendDaemonCommand:e,setLocalUserMessages:Z,setActionLogs:ne,isStandalone:Ye,initialDataLoaded:w,userName:m.userName,requestedMobileTabKey:we,onRequestedMobileTabConsumed:Je,requestedMachineId:u,onRequestedMachineConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},requestedMobileSection:p,onRequestedMobileSectionConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},containerRef:Qe,isSplitMode:Me,numGroups:se,groupSizes:K,groupedConvs:Ee,clearedTabs:ye,focusedGroup:v,setFocusedGroup:x,moveTabToGroup:tt,splitTabRelative:de,closeGroup:E,handleResizeStart:J,groupActiveTabIds:$,setGroupActiveTabIds:M,groupTabOrders:L,setGroupTabOrders:T,toggleHiddenTab:At,visibleConversations:Ue,hiddenConversations:pl,requestedDesktopTabKey:Le,onRequestedDesktopTabConsumed:Je,onDesktopActiveTabChange:ve,onHideConversation:El,onShowHiddenConversation:no,onShowAllHiddenConversations:Te,scrollToBottomRequest:Ce,machineEntries:Be,onBrowseMachineDirectory:fl,onSaveMachineWorkspace:hl,onLaunchMachineIde:xl,onLaunchMachineProvider:bl,onListMachineSavedSessions:gl,notifications:Re,notificationUnreadCount:P,notificationStateBySessionId:W,liveSessionInboxState:Y,onMarkNotificationRead:_e,onMarkNotificationUnread:Ie,onDeleteNotification:Ke,onMarkNotificationTargetRead:te}),t.jsx("style",{children:`
60
+ body { overflow: hidden; overscroll-behavior: none; }
61
+ `}),t.jsx(zh,{historyModalOpen:S,historyTargetConv:lt,ides:f,isHistoryCreatingChat:wl,isHistoryRefreshingHistory:Ht?!1:jl,savedHistorySessions:ae,isSavedHistoryLoading:X,isResumingSavedHistorySessionId:ke,onCloseHistory:()=>D(!1),onNewHistoryChat:Sl,onSwitchHistorySession:kl,onRefreshHistory:Ht?vn:Nl,onResumeSavedHistorySession:Cl,remoteDialogConv:kt,remoteDialogIdeEntry:ht,connectionStates:_,actionLogs:ge,localUserMessages:ce,sendDaemonCommand:e,setLocalUserMessages:Z,setActionLogs:ne,isStandalone:Ye,userName:m.userName,onOpenRemoteHistory:oe=>{oe&&ks(oe),D(!0)},onRemoteConversationChange:ks,onCloseRemoteDialog:vr,cliStopDialogOpen:G,cliStopTargetConv:H,onCancelCliStop:()=>{q(!1),re(null)},onStopCliNow:async()=>{q(!1),await to("hard",H),re(null)},onSaveCliAndStop:async()=>{q(!1),await to("save",H),re(null)},toasts:y,onDismissToast:oe=>A(fe=>fe.filter(je=>je.id!==oe)),onClickToast:oe=>{if(oe.targetKey){const fe=yt(oe.targetKey);fe&&(x(et.get(fe.tabKey)??0),no(fe),Ae({tabKey:fe.tabKey,nonce:Date.now()}))}},showOnboarding:d,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}b(!1)}})]})}function Qh({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,u]=o.useState(null),[p,m]=o.useState(null),[f,w]=o.useState(!1),[k,A]=o.useState(null),[d,b]=o.useState(!1),[y,h]=o.useState(""),N=o.useRef(null),_=o.useCallback(S=>{N.current=S},[]),g=o.useCallback((S,D,G=!1)=>{c(q=>[...q.slice(-100),{timestamp:Date.now(),level:S,message:D}]),setTimeout(()=>{var q;return(q=a.current)==null?void 0:q.scrollIntoView({behavior:"smooth"})},100),G&&it.showToast(D,S==="error"||S==="warn"?"warning":"success")},[a]),I=o.useCallback(S=>{const D=S instanceof Error?S.message:String(S||"");return D.includes("P2P command timeout")||D.includes("P2P not connected")||D.includes("P2P not available")},[]),j=o.useCallback(async(S,D)=>{var G;if(!e||l)return!1;u(S),g("info",`Launching ${nt(S)}${D!=null&&D.workspace?` in ${D.workspace}`:""}...`);try{const q={ideType:S,enableCdp:!0};(G=D==null?void 0:D.workspace)!=null&&G.trim()?q.workspace=D.workspace.trim():D!=null&&D.useDefaultWorkspace&&(q.useDefaultWorkspace=!0);const H=await r(e,"launch_ide",q);return g(H!=null&&H.success?"info":"error",H!=null&&H.success?`${nt(S)} launched`:`Failed: ${H==null?void 0:H.error}`,!0),!!(H!=null&&H.success)}catch(q){return g("error",`Launch error: ${q.message}`,!0),!1}finally{u(null)}},[e,l,g,r]),v=o.useCallback(async S=>{if(!e)return{success:!1};const{cliType:D,dir:G,workspaceId:q,useDefaultWorkspace:H,useHome:re,argsStr:ae,model:Ne,resumeSessionId:X}=S;if(!D)return g("warn","Select a CLI or ACP provider first",!0),{success:!1};const he=ae?ae.split(/\s+/).filter(Boolean):void 0,ke=(G==null?void 0:G.trim())||(q?"(saved id)":H?"(default workspace)":re?"(home)":"");g("info",`Launching ${D}${ke?` in ${ke}`:""}${Ne?` (model: ${Ne})`:""}...`),m(D);try{const ie={cliType:D,cliArgs:he,initialModel:Ne||void 0};G!=null&&G.trim()?ie.dir=G.trim():q?ie.workspaceId=q:H?ie.useDefaultWorkspace=!0:re&&(ie.useHome=!0),X&&(ie.resumeSessionId=X);const xe=await r(e,"launch_cli",ie),pe=(xe==null?void 0:xe.result)||xe;return xe!=null&&xe.success?(g("info",`${D} launched`,!0),(pe==null?void 0:pe.launchSource)==="home"?g("info","📂 Running in home directory (explicit choice)"):(pe==null?void 0:pe.launchSource)==="defaultWorkspace"&&g("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:pe==null?void 0:pe.sessionId}):(g("error",`Failed: ${(xe==null?void 0:xe.error)||(pe==null?void 0:pe.error)}`,!0),(xe==null?void 0:xe.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&A({cliType:D,argsStr:ae,model:Ne}),{success:!1,sessionId:pe==null?void 0:pe.sessionId})}catch(ie){return I(ie)?(g("warn",`${D} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(g("error",`Launch error: ${ie.message}`,!0),{success:!1})}finally{m(null)}},[e,g,I,r]),x=o.useCallback(async(S,D,G,q)=>e?S?D.trim()?v({cliType:S,dir:D,argsStr:G,model:q}):(A({cliType:S,argsStr:G,model:q}),{success:!1}):(g("warn","Select a provider",!0),{success:!1}):{success:!1},[e,g,v]),$=o.useCallback(async(S,D,G)=>{if(e&&window.confirm(`Stop ${S}?
62
+ This will terminate the process.`))try{const q=await r(e,"stop_cli",{cliType:S,dir:D,targetSessionId:G});q!=null&&q.success?g("info",`${S} stopped`,!0):g("error",`Stop failed: ${(q==null?void 0:q.error)||"Unknown error"}`,!0)}catch(q){g("error",`Stop failed: ${q.message}`,!0)}},[e,g,r]),M=o.useCallback(async S=>{try{await r(S.daemonId,"restart_ide",{ideType:S.type}),g("info",`${nt(S.type)} restart initiated`,!0)}catch(D){g("error",`Restart failed: ${D.message}`,!0)}},[g,r]),L=o.useCallback(async S=>{if(window.confirm(`Stop ${nt(S.type)}?
63
+ This will disconnect CDP and optionally kill the process.`))try{const D=await r(S.daemonId,"stop_ide",{ideType:S.type,killProcess:!0});D!=null&&D.success?g("info",`${nt(S.type)} stopped`,!0):g("error",`Stop failed: ${(D==null?void 0:D.error)||"Unknown error"}`,!0)}catch(D){g("error",`Stop failed: ${D.message}`,!0)}},[g,r]),T=o.useCallback(async()=>{if(e)try{const S=await r(e,"detect_ides",{});g("info",`Found ${((S==null?void 0:S.result)||[]).length} IDE(s)`,!0)}catch(S){g("error",`Detection failed: ${S.message}`,!0)}},[e,g,r]),K=o.useCallback(async S=>{if(!e||!S.trim())return!1;w(!0);try{const D=await r(e,"workspace_add",{path:S.trim()});return D!=null&&D.success?(g("info",`Workspace added: ${S.trim()}`),!0):(g("error",(D==null?void 0:D.error)||"workspace_add failed"),!1)}catch(D){return g("error",D.message),!1}finally{w(!1)}},[e,g,r]),U=o.useCallback(async S=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){w(!0);try{const D=await r(e,"workspace_remove",{id:S});D!=null&&D.success?g("info","Workspace removed",!0):g("error",(D==null?void 0:D.error)||"workspace_remove failed",!0)}catch(D){g("error",D.message,!0)}finally{w(!1)}}},[e,g,r]),C=o.useCallback(async S=>{var D;if(e){w(!0);try{const G=await r(e,"workspace_set_default",S===null?{clear:!0}:{id:S});if(G!=null&&G.success){g("info",S?"Default workspace updated":"Default workspace cleared",!0);const q=typeof G.defaultWorkspacePath=="string"?G.defaultWorkspacePath:"";q&&((D=N.current)==null||D.call(N,q))}else g("error",(G==null?void 0:G.error)||"workspace_set_default failed",!0)}catch(G){g("error",G.message,!0)}finally{w(!1)}}},[e,g,r]),R=o.useCallback(async S=>{var G;if(!e||!S.trim())return;const D=S.trim();w(!0);try{const q=await r(e,"workspace_set_default",{path:D});q!=null&&q.success?(g("info","Default workspace set from history"),(G=N.current)==null||G.call(N,D)):g("error",(q==null?void 0:q.error)||"Could not set default (path missing on disk?)")}catch(q){g("error",q.message)}finally{w(!1)}},[e,g,r]),O=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:y}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:y})}catch(S){g("warn",`Live nickname updated, but account sync failed: ${S.message}`)}g("info",`Nickname set to "${y||"(cleared)"}"`),b(!1)}catch(S){g("error",`Failed: ${S.message}`)}},[e,y,s,g,n,r]);return{logs:i,launchingIde:l,launchingAgentType:p,workspaceBusy:f,launchPick:k,setLaunchPick:A,editingNickname:d,setEditingNickname:b,nicknameInput:y,setNicknameInput:h,addLog:g,handleLaunchIde:j,runLaunchCliCore:v,handleLaunchCli:x,handleStopCli:$,handleRestartIde:M,handleStopIde:L,handleDetectIdes:T,handleWorkspaceAdd:K,handleWorkspaceRemove:U,handleWorkspaceSetDefault:C,handleWorkspaceResumePath:R,handleSaveNickname:O,setOnDefaultWorkspaceChanged:_}}function Jh({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var M;const{workspaceBusy:l,handleWorkspaceAdd:u,handleWorkspaceRemove:p,handleWorkspaceSetDefault:m}=i,[f,w]=o.useState(!1),[k,A]=o.useState(""),[d,b]=o.useState([]),[y,h]=o.useState(!1),[N,_]=o.useState(""),g=o.useCallback(async L=>{h(!0),_("");try{const T=await bn(c,e,L);A(T.path),b(T.directories)}catch(T){_(T instanceof Error?T.message:"Could not load folder")}finally{h(!1)}},[e,c]),I=o.useCallback(()=>{w(!0);const L=[...r.map(K=>K.workspace),...n.map(K=>K.workspace),...a.map(K=>K.workspace)],T=xn(s.platform,hn(L,s.defaultWorkspacePath,(s.workspaces||[]).map(K=>K.path)));g(T)},[a,n,r,g,s.defaultWorkspacePath,s.platform,s.workspaces]),j=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,v=s.availableMem??s.freeMem??s.totalMem,x=j&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-v)/s.totalMem*100))):0,$=((M=s.loadavg)==null?void 0:M[0])||0;return t.jsxs("div",{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[t.jsx(Ir,{icon:t.jsx(Ti,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?Jd(s.uptime):"Waiting…"}),t.jsx(Ir,{icon:t.jsx(Rt,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(Ir,{icon:t.jsx(ln,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(Ir,{icon:t.jsx(xd,{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(vo,{value:j?Math.min(Math.round($/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:j?`${$.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(vo,{value:x,max:100,label:"Memory",color:"#3b82f6",detail:j?`${Cn(s.totalMem-v)} / ${Cn(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Cn(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(Es,{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:L=>void m(L.target.value===""?null:L.target.value),children:[t.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(L=>t.jsx("option",{value:L.id,children:L.label||L.path},L.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(L=>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:[L.id===s.defaultWorkspaceId&&t.jsx("span",{className:"text-[10px]",children:"⭐"}),t.jsx("span",{className:"font-medium text-text-primary truncate",children:pn(L.path,L.label)})]}),t.jsx("div",{className:"font-mono truncate text-[10px]",title:L.path,children:L.path})]}),t.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void p(L.id),children:"Remove"})]},L.id))})]}),f&&t.jsx(gn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:k,directories:d,busy:y,error:N,confirmLabel:"Add workspace",onClose:()=>w(!1),onNavigate:L=>{g(L)},onConfirm:L=>{(async()=>{if(!L)return;await u(L)&&w(!1)})()}})]})}function Zh(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 ex(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 Fn(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 di(e){if(!e||typeof e!="object")return null;if(Fn(e))return e;const s=e,r=s.result;return Fn(r)?r:Fn(s.sourceConfig)?s.sourceConfig:null}function tx(e){const s=e.trim();return s||null}const ui=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],sx=[{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 rx({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[u,p]=o.useState([]),[m,f]=o.useState(""),[w,k]=o.useState([]),[A,d]=o.useState(""),b=o.useRef(null),y=o.useRef(null),h=v=>{p(x=>x.includes(v)?x.filter($=>$!==v):[...x,v])},N=()=>p([...ui]),_=()=>p([]);o.useEffect(()=>{var v;(v=b.current)==null||v.scrollIntoView({behavior:"smooth"})},[w]),o.useEffect(()=>()=>{y.current&&clearInterval(y.current)},[]);const g=o.useCallback(()=>{y.current&&clearInterval(y.current),y.current=setInterval(async()=>{try{const v=await r(e,"provider_auto_fix_status",{providerType:s.type});(v==null?void 0:v.running)===!1&&a==="running"&&(i("done"),k(x=>[...x,`
64
+ ✅ Auto-fix completed!`]),y.current&&clearInterval(y.current))}catch{}},3e3)},[e,s.type,r,a]),I=async()=>{if(u.length!==0){i("running"),k(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,m?`💬 Comment: ${m}`:"",""]),d("");try{const v=await r(e,"provider_auto_fix",{providerType:s.type,functions:u,agent:c,...m?{comment:m}:{}});v!=null&&v.success&&(v!=null&&v.started||v!=null&&v.running)?(k(x=>[...x,"✅ Agent started. Monitoring progress..."]),g()):(i("error"),d((v==null?void 0:v.error)||"Failed to start auto-fix"))}catch(v){i("error"),d((v==null?void 0:v.message)||"Connection failed")}}},j=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),k(v=>[...v,`
65
+ ⚠️ Auto-fix cancelled.`]),i("done"),y.current&&clearInterval(y.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:v=>v.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:sx.map(v=>t.jsxs("button",{onClick:()=>l(v.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===v.value?v.color+"66":"var(--border-subtle)",background:c===v.value?v.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===v.value?v.color:"var(--text-primary)"},children:v.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:v.desc})]},v.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:N,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:_,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:ui.map(v=>t.jsxs("button",{onClick:()=>h(v),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(v)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(v)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(v)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(v)?"☑ ":"☐ ",v]},v))})]}),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:m,onChange:v=>f(v.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:[w.map((v,x)=>t.jsx("div",{className:v.startsWith("✅")?"text-green-400":"",style:v.startsWith("❌")||v.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:v},x)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:b})]}),A&&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:A})]})]}),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:j,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"),k([]),d("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function nx({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var g;const i=s.filter(I=>I.category==="ide"),[c,l]=o.useState(((g=i[0])==null?void 0:g.type)||""),[u,p]=o.useState(""),[m,f]=o.useState(""),[w,k]=o.useState(!1),[A,d]=o.useState(""),[b,y]=o.useState(!1),h=I=>{const j=I.toLowerCase().replace(/[^a-z0-9-]/g,"");p(j),(!m||m===N(u))&&f(N(j))},N=I=>I.split("-").map(j=>j.charAt(0).toUpperCase()+j.slice(1)).join(" "),_=async()=>{if(!(!u||!m||!c)){k(!0),d("");try{const I=await r(e,"provider_clone",{type:u,name:m,category:"ide",location:"user",cloneFrom:c});I!=null&&I.success||I!=null&&I.created?(y(!0),a==null||a(u)):d((I==null?void 0:I.error)||"Failed to create provider")}catch(I){d((I==null?void 0:I.message)||"Connection failed")}k(!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:b?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=>h(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:m,onChange:I=>f(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"})]}),A&&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:A})]})}),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:b?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:_,disabled:!u||!m||w,className:"machine-btn",style:{background:u&&m?"rgba(34,197,94,0.12)":void 0,borderColor:u&&m?"rgba(34,197,94,0.3)":void 0,color:u&&m?"#86efac":void 0,opacity:!u||!m||w?.4:1},children:w?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function ax({machineId:e,providers:s,sendDaemonCommand:r}){var M;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[p,m]=o.useState("all"),[f,w]=o.useState(null),[k,A]=o.useState(!1),[d,b]=o.useState(null),[y,h]=o.useState("normal"),[N,_]=o.useState(""),[g,I]=o.useState(!1),j=o.useCallback(async()=>{if(e)try{const L=await r(e,"get_provider_source_config",{}),T=di(L);T&&(b(T),h(T.sourceMode),_(T.explicitProviderDir||""))}catch{}},[e,r]),v=o.useCallback(async()=>{if(e){c(!0);try{const L=await r(e,"get_provider_settings",{}),T=Zh(L);if(T){const K=ex(T,s);K.sort((U,C)=>U.category.localeCompare(C.category)||U.displayName.localeCompare(C.displayName)),a(K)}}catch{}c(!1)}},[e,s,r]);o.useEffect(()=>{n.length===0&&v(),d||j()},[]);const x=async(L,T,K)=>{u(`${L}.${T}`),a(U=>U.map(C=>C.type===L?{...C,values:{...C.values,[T]:K}}:C));try{const U=await r(e,"set_provider_setting",{providerType:L,key:T,value:K});U!=null&&U.success||v()}catch{v()}u(null)},$=async()=>{I(!0);try{const L=await r(e,"set_provider_source_config",{providerSourceMode:y,providerDir:tx(N)}),T=di(L);T?(b(T),h(T.sourceMode),_(T.explicitProviderDir||"")):await j(),await v()}catch{await j()}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(L=>t.jsx("button",{onClick:()=>m(L),className:`machine-btn text-[10px] px-2 py-0.5 ${p===L?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:L.toUpperCase()},L))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>A(!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:v,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Existing running sessions may need restart."})]}),t.jsx("button",{onClick:j,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),t.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),t.jsxs("select",{value:y,onChange:L=>h(L.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:N,onChange:L=>_(L.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void $(),disabled:g,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:g?"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:"})," ",(d==null?void 0:d.userDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(d==null?void 0:d.upstreamDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((M=d==null?void 0:d.providerRoots)==null?void 0:M.join(" → "))||"loading…"]})]})]}),p!=="all"&&n.filter(L=>L.category===p).length>1&&(()=>{const L=n.filter(C=>C.category===p),T=new Map;for(const C of L)for(const R of C.schema){if(R.type!=="boolean")continue;const O=T.get(R.key),S=!!(C.values[R.key]??R.default);O?(O.onCount+=S?1:0,O.total+=1):T.set(R.key,{label:R.label||R.key,onCount:S?1:0,total:1})}const K=[...T.entries()].filter(([,C])=>C.total===L.length);if(K.length===0)return null;const U=async(C,R)=>{for(const O of L)await x(O.type,C,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 ",p.toUpperCase()," providers (",L.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:K.map(([C,R])=>{const O=R.onCount===R.total,S=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(C,!0),disabled:O,className:`machine-btn text-[9px] px-1.5 py-px ${O?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void U(C,!1),disabled:S,className:`machine-btn text-[9px] px-1.5 py-px ${S?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},C)})})]})})(),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(L=>p==="all"||L.category===p).map(L=>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:L.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:L.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:L.category==="acp"?"rgba(139,92,246,0.08)":L.category==="cli"?"rgba(59,130,246,0.08)":L.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:L.category==="acp"?"#a78bfa":L.category==="cli"?"#60a5fa":L.category==="ide"?"#86efac":"var(--status-warning)"},children:L.category}),L.category==="ide"&&t.jsx("button",{onClick:()=>w(s.find(T=>T.type===L.type)||{type:L.type,name:L.displayName,displayName:L.displayName,icon:L.icon,category:L.category}),className:"ml-auto machine-btn text-[9px] px-2 py-0.5 bg-violet-500/[0.06] border-violet-500/20 text-violet-400 hover:bg-violet-500/[0.12]",children:"🔧 Auto-Fix"})]}),t.jsx("div",{className:"flex flex-col gap-2",children:L.schema.map(T=>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:[T.label||T.key,l===`${L.type}.${T.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),T.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:T.description})]}),t.jsx("div",{className:"shrink-0",children:T.type==="boolean"?t.jsx("button",{onClick:()=>x(L.type,T.key,!(L.values[T.key]??T.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:L.values[T.key]??T.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:L.values[T.key]??T.default?21:3}})}):T.type==="number"?t.jsx("input",{type:"number",value:Number(L.values[T.key]??T.default??0)||0,min:T.min,max:T.max,onChange:K=>{const U=parseInt(K.target.value)||0;T.min!==void 0&&U<T.min||T.max!==void 0&&U>T.max||x(L.type,T.key,U)},className:"machine-input w-20 text-center text-[11px]"}):T.type==="select"&&T.options?t.jsx("select",{value:String(L.values[T.key]??T.default??""),onChange:K=>x(L.type,T.key,K.target.value),className:"machine-input text-[11px]",children:T.options.map(K=>t.jsx("option",{value:K,children:K},K))}):t.jsx("input",{type:"text",value:String(L.values[T.key]??T.default??""),onBlur:K=>x(L.type,T.key,K.target.value),className:"machine-input w-[120px] text-[11px]"})})]},T.key))})]},L.type))}),f&&t.jsx(rx,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>w(null)}),k&&t.jsx(nx,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>A(!1),onCreated:()=>{A(!1),v()}})]})}const ox=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function ix({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function cx(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function mi(e){if(!e||Object.keys(e).length===0)return"";try{const s=JSON.stringify(e);return s.length>220?`${s.slice(0,220)}…`:s}catch{return"[unserializable payload]"}}function lx({machineId:e,sendDaemonCommand:s}){const[r,n]=o.useState([]),[a,i]=o.useState([]),[c,l]=o.useState([]),[u,p]=o.useState(0),[m,f]=o.useState(0),[w,k]=o.useState(!0),[A,d]=o.useState("debug"),[b,y]=o.useState("all"),h=o.useRef(null),N=o.useRef(!1),_=cx(a,b);return o.useEffect(()=>{if(!e||!w)return;const g=async()=>{try{const[j,v]=await Promise.all([s(e,"get_logs",{count:200,minLevel:A,since:u}),s(e,"get_debug_trace",ix({count:120,since:m,category:b}))]),x=(j==null?void 0:j.result)||j;if(j!=null&&j.success&&Array.isArray(x==null?void 0:x.logs)&&x.logs.length>0){n(L=>[...L,...x.logs.map(K=>({timestamp:K.ts,level:K.level,message:`[${K.category}] ${K.message}`}))].slice(-300));const M=Math.max(...x.logs.map(L=>L.ts));p(M)}const $=(v==null?void 0:v.result)||v;if(v!=null&&v.success&&Array.isArray($==null?void 0:$.trace)){i($.trace.slice(-120));const M=$.trace.reduce((L,T)=>Math.max(L,Number(T.ts||0)),m);M>m&&f(M)}}catch{}l(Ds.list({limit:120}))};g();const I=setInterval(g,3e3);return()=>clearInterval(I)},[e,w,u,m,A,b,s]),o.useEffect(()=>{if(w&&(r.length>0||a.length>0||c.length>0)){const g=N.current?"smooth":"instant";setTimeout(()=>{var I;(I=h.current)==null||I.scrollIntoView({behavior:g}),N.current=!0},50)}},[r.length,a.length,c.length,w]),o.useEffect(()=>{i([]),f(0)},[b]),t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-3",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:"Level"}),["debug","info","warn","error"].map(g=>t.jsx("button",{onClick:()=>{d(g),n([]),p(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${A===g?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:g.toUpperCase()},g))]}),t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsxs("span",{className:"text-[10px] text-text-muted",children:["logs=",r.length," trace=",_.length," web=",c.length]}),t.jsx("button",{onClick:()=>k(!w),className:`machine-btn ${w?"text-green-500 border-green-500/30":""}`,children:w?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>{n([]),i([]),l([]),p(0),f(0),Ds.clear()},className:"machine-btn",children:"Clear"})]})]}),t.jsxs("div",{className:"grid gap-3",children:[t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[180px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),r.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs..."}),r.map((g,I)=>t.jsxs("div",{className:"flex gap-2 py-px",style:{color:g.level==="error"?"#ef4444":g.level==="warn"?"var(--status-warning)":g.level==="debug"?"#64748b":"#94a3b8"},children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(g.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:g.level==="error"?"ERR":g.level==="warn"?"WRN":g.level==="debug"?"DBG":"INF"}),t.jsx("span",{children:g.message})]},`log-${I}`))]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[180px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsxs("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",b==="session_host"?" · session_host only":""]}),t.jsx("div",{className:"flex gap-1 items-center",children:ox.map(g=>t.jsx("button",{onClick:()=>y(g.value),className:`machine-btn text-[10px] px-2 py-0.5 ${b===g.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:g.label},g.value))})]}),_.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:b==="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."}),_.map(g=>t.jsxs("div",{className:"py-1 border-b border-white/5 last:border-b-0",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted",children:[t.jsx("span",{children:new Date(g.ts).toLocaleTimeString()}),t.jsx("span",{children:g.level.toUpperCase()}),t.jsxs("span",{children:[g.category,".",g.stage]}),g.interactionId&&t.jsxs("span",{children:["ix=",g.interactionId]})]}),t.jsx("div",{children:mi(g.payload)})]},g.id))]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[160px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),c.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No browser debug events captured yet."}),c.map(g=>t.jsxs("div",{className:"py-1 border-b border-white/5 last:border-b-0",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted",children:[t.jsx("span",{children:new Date(g.ts).toLocaleTimeString()}),t.jsx("span",{children:g.kind}),g.topic&&t.jsxs("span",{children:["topic=",g.topic]}),g.interactionId&&t.jsxs("span",{children:["ix=",g.interactionId]})]}),t.jsx("div",{children:mi(g.payload)})]},g.id))]})]}),t.jsx("div",{ref:h})]})}function zn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Vn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function pi(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 dx(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function ux(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 mx(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 px({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),p=_c(e,{enabled:!!e,includeSessions:!0,limit:12,intervalMs:8e3}),m=p.diagnostics,f=p.loading,w=p.applyDiagnostics,k=o.useMemo(()=>Mh({diagnostics:m,loading:f,refreshing:l,error:n}),[m,f,l,n]),A=o.useMemo(()=>new Map(s.map(M=>[M.sessionId||M.id,M])),[s]),d=o.useCallback(async()=>{if(e){u(!0);try{const M=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),L=zn(M);if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Could not load hosted runtime diagnostics");w(L.diagnostics||L.result||null),a("")}catch(M){const L=M instanceof Error?M.message:"Could not load hosted runtime diagnostics";a(L)}finally{u(!1)}}},[w,e,r]);o.useEffect(()=>{!e||m||f||l||d()},[m,f,e,d,l]);const b=o.useCallback(async(M,L)=>{const T=`${M}:${L.sessionId}`;if(!(M==="session_host_stop_session"&&!window.confirm(`Stop ${L.displayName}?
66
+ This will terminate the hosted runtime.`))){c(T);try{const K=await r(e,M,{sessionId:L.sessionId}),U=zn(K);if(!(U!=null&&U.success))throw new Error((U==null?void 0:U.error)||"Session host action failed");const C=M==="session_host_resume_session"?"resumed":M==="session_host_restart_session"?"restarted":"stopped";it.showToast(`Session host ${C}: ${L.displayName}`,"success"),await d()}catch(K){const U=K instanceof Error?K.message:"Session host action failed";it.showToast(U,"warning"),a(U)}finally{c(K=>K===T?null:K)}}},[e,d,r]),y=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
67
+ 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 L=await r(e,"session_host_prune_duplicate_sessions",{}),T=zn(L);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Duplicate prune failed");const K=T.result||{},U=Array.isArray(K.prunedSessionIds)?K.prunedSessionIds.length:0,C=typeof K.duplicateGroupCount=="number"?K.duplicateGroupCount:0;it.showToast(`Pruned ${U} duplicate runtime(s) across ${C} group(s)`,"success"),await d()}catch(L){const T=L instanceof Error?L.message:"Duplicate prune failed";it.showToast(T,"warning"),a(T)}finally{c(L=>L==="session_host_prune_duplicate_sessions"?null:L)}}},[e,d,r]),h=o.useMemo(()=>[...(m==null?void 0:m.sessions)||[]].sort((M,L)=>(L.lastActivityAt||0)-(M.lastActivityAt||0)),[m==null?void 0:m.sessions]),N=o.useMemo(()=>m!=null&&m.liveRuntimes||m!=null&&m.recoverySnapshots||m!=null&&m.inactiveRecords?{liveRuntimes:(m==null?void 0:m.liveRuntimes)||[],recoverySnapshots:(m==null?void 0:m.recoverySnapshots)||[],inactiveRecords:(m==null?void 0:m.inactiveRecords)||[]}:il(h),[m==null?void 0:m.inactiveRecords,m==null?void 0:m.liveRuntimes,m==null?void 0:m.recoverySnapshots,h]),_=N.liveRuntimes,g=N.recoverySnapshots,I=N.inactiveRecords,j=o.useMemo(()=>mx(_),[_]),v=o.useMemo(()=>[...(m==null?void 0:m.recentTransitions)||[]].slice(-6).reverse(),[m==null?void 0:m.recentTransitions]),x=o.useMemo(()=>[...(m==null?void 0:m.recentLogs)||[]].reverse().find(M=>M.level==="warn"||M.level==="error")||null,[m==null?void 0:m.recentLogs]),$=(M,L)=>{var G;const T=i===`session_host_resume_session:${M.sessionId}`,K=i===`session_host_restart_session:${M.sessionId}`,U=i===`session_host_stop_session:${M.sessionId}`,C=Za(M.meta),R=A.get(M.sessionId),O=M.attachedClients.length===1?"1 client":`${M.attachedClients.length} clients`,S=L==="recovery"?"Recover":"Resume",D=cl(L);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:M.displayName||(R==null?void 0:R.cliName)||M.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${ux(M.lifecycle)}`,children:M.lifecycle}),C&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:C})]}),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:M.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||M.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:M.runtimeKey}),M.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",M.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((G=M.writeOwner)==null?void 0:G.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:dx(M.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(ga,{size:11})," ",O]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",pi(M.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",D]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[L==="recovery"&&(M.lifecycle==="interrupted"||M.lifecycle==="failed"||M.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_resume_session",M)},children:T?`${S}ing…`:S}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_restart_session",M)},children:K?"Restarting…":"Restart"}),L==="live"&&(M.lifecycle==="running"||M.lifecycle==="starting"||M.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:()=>{b("session_host_stop_session",M)},children:U?"Stopping…":"Stop"})]})]})},M.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(qt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Wm()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{y()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${j})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${k.toneClass}`,children:k.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{d()},disabled:f||l,children:[t.jsx(zs,{size:13}),f||l?"Refreshing…":"Refresh"]})]})]}),n&&!m&&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(ys,{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})]})]})}),m&&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:m.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:g.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:m.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:pi(m.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Vn(m.hostStartedAt)})]})]}),x&&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(ys,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:x.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Vn(x.timestamp),x.sessionId?` · ${x.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(ln,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ps("live")}),_.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:_.map(M=>$(M,"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(qt,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ps("recovery")}),g.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:g.map(M=>$(M,"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:Ps("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:I.map(M=>$(M,"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"}),v.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:v.map(M=>{var T;const L=h.find(K=>K.sessionId===M.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:(L==null?void 0:L.displayName)||((T=A.get(M.sessionId))==null?void 0:T.cliName)||M.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[M.action,M.lifecycle?` · ${M.lifecycle}`:"",M.detail?` · ${M.detail}`:"",M.error?` · ${M.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${M.success===!1?"text-red-300":"text-text-secondary"}`,children:Vn(M.timestamp)})]},`${M.sessionId}:${M.timestamp}:${M.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:m.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function fx({machine:e,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick: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 Gn({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 qn({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 hx({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),m=nr(e,"0.8.82");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(Gn,{icon:t.jsx(Yt,{size:13}),children:"Current Chats"}),t.jsx(qn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(f=>{const w=sa(f);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(f),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:ct(f)}),w>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:un(w)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ws(f)})]},f.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Gn,{icon:t.jsx(Ti,{size:13}),children:"Recent Launches"}),t.jsx(qn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(f=>{const{metaText:w,updatedLabel:k}=Vc(f);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(f),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:f.label}),k&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:k})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:w})]},f.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Gn,{icon:t.jsx(ys,{size:13}),children:"Daemon Update"}),t.jsx(qn,{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:m?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:m?"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(zs,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function xx(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const bx={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 Hr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Yn({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:p}){const m=Fs(),{handleLaunchIde:f,handleStopCli:w,handleRestartIde:k,handleStopIde:A,handleDetectIdes:d,launchingIde:b,launchingAgentType:y,addLog:h}=c,[N,_]=o.useState(null),g=o.useCallback(E=>{E&&m(rs(E))},[m]),I=bx[e],j=e==="ide",v=e==="acp",x=o.useMemo(()=>n.filter(E=>E.category===e&&(e==="ide"||E.installed!==!1)),[e,n]),$=o.useMemo(()=>new Map(x.map(E=>[E.type,E.displayName||E.type])),[x]),[M,L]=o.useState(""),[T,K]=o.useState(""),[U,C]=o.useState([]),[R,O]=o.useState(""),[S,D]=o.useState(""),[G,q]=o.useState([]),[H,re]=o.useState(!1),[ae,Ne]=o.useState(!1),[X,he]=o.useState(""),[ke,ie]=o.useState(!1),[xe,pe]=o.useState(()=>vt()),[V,ge]=o.useState(null),[ne,ce]=o.useState(p?"__custom__":u||s.defaultWorkspaceId||""),[Z,le]=o.useState(p||""),[ee,ye]=o.useState([]),[be,B]=o.useState(!1),[ve,Ce]=o.useState(""),[Ae,Q]=o.useState([]),[Pe,He]=o.useState(!1),[$e,Be]=o.useState(""),Ye=o.useRef(null),[Ve,ut]=o.useState(null),at=o.useRef("__home__"),[pt,ze]=o.useState("__home__"),[ft,xt]=o.useState(!1),ot=o.useRef(0),Te=ee.filter(E=>!a.some(J=>J.type===E&&Nt(J.status)!=="stopped")),Ge=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!ne&&ce(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(p){ce("__custom__"),le(p);return}u&&(ce(u),le(""))},[u,p]),o.useEffect(()=>{j||M&&(x.some(E=>E.type===M)||(L(""),D("")))},[x,j,M]);const Oe=(()=>{if(ne==="__custom__")return Z.trim();if(!ne)return"";const E=(s.workspaces||[]).find(J=>J.id===ne);return(E==null?void 0:E.path)||""})(),Ue=o.useCallback(E=>{const J=Ge.current[E];J&&(clearTimeout(J),delete Ge.current[E]),ye(de=>de.includes(E)?de.filter(me=>me!==E):de)},[]),wt=o.useRef(new Set),bt=o.useCallback(async E=>{if(l){He(!0),Be("");try{const J=await bn(l,r,E);Ce(J.path),le(J.path),Q(J.directories)}catch(J){Be(J instanceof Error?J.message:"Could not load folder")}finally{He(!1)}}},[r,l]),yt=o.useCallback(()=>{if(!l)return;ce("__custom__"),B(!0);const E=a.map(de=>de.workspace),J=xn(s.platform,hn(Z.trim(),Oe,p,E,s.defaultWorkspacePath,(s.workspaces||[]).map(de=>de.path)));bt(J)},[Z,p,bt,s.defaultWorkspacePath,s.platform,s.workspaces,a,Oe,l]),jt=o.useCallback(E=>{const J=String(E.workspace||"").trim();if(!J)return;const de=(s.workspaces||[]).find(me=>Hr(me.path)===Hr(J));if(de){ce(de.id),le("");return}ce("__custom__"),le(J)},[s.workspaces]),Ot=o.useCallback(E=>{const J=String(E.workspace||"").trim();if(!J)return{workspaceId:null,workspacePath:"",useHome:!0};const de=(s.workspaces||[]).find(me=>Hr(me.path)===Hr(J));return de?{workspaceId:de.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:J,useHome:!1}},[s.workspaces]),At=o.useCallback(async E=>{if(!l||!E||e!=="cli"){q([]),re(!1),Ne(!1),he("");return}const J=ot.current+1;ot.current=J,re(!0),he("");try{const de=await l(r,"list_saved_sessions",{providerType:E,kind:"cli",limit:30});if(ot.current!==J)return;const me=(de==null?void 0:de.result)??de;q(Array.isArray(me==null?void 0:me.sessions)?me.sessions:[])}catch(de){if(ot.current!==J)return;q([]),he(de instanceof Error?de.message:"Could not load saved sessions")}finally{ot.current===J&&(re(!1),Ne(!0))}},[e,r,l]),Mt=o.useMemo(()=>{if(e!=="cli"||!M)return null;const E=$.get(M)||M;return{routeId:r,daemonId:r,providerSessionId:S||void 0,transport:"pty",mode:"chat",agentName:E,agentType:M,status:"idle",title:E,messages:[],ideType:M,workspaceName:Oe,displayPrimary:E,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${M}`}},[e,r,$,Oe,S,M]),Y=o.useCallback(E=>{if(e==="ide"||!E){C([]);return}C(al(r,E))},[e,r]);o.useEffect(()=>{ot.current+=1,D(""),Y(M),Ne(!1),q([]),he(""),re(!1)},[e,Y,At,M]);const Re=o.useMemo(()=>G.find(E=>E.providerSessionId===S)||null,[G,S]);o.useEffect(()=>{if(!S)return;const E=G.find(J=>J.providerSessionId===S);E!=null&&E.canResume||D("")},[G,S]);const P=o.useCallback((E,J)=>{Ye.current=J,at.current=E.selectedWorkspaceKey||"__home__",ze(E.selectedWorkspaceKey||"__home__"),ut(E)},[]),W=o.useCallback(()=>{Ye.current&&(xt(!0),Ye.current().finally(()=>{Ye.current=null,xt(!1),ut(null)}))},[]),F=o.useCallback(E=>{if(!E)return;ye(de=>de.includes(E)?de:[...de,E]);const J=Ge.current[E];J&&clearTimeout(J),Ge.current[E]=setTimeout(()=>{ye(de=>de.includes(E)?de.filter(me=>me!==E):de),delete Ge.current[E]},2e4)},[]);o.useEffect(()=>{for(const J of a)Nt(J.status)!=="stopped"&&(ee.includes(J.type)&&!wt.current.has(J.type)&&(wt.current.add(J.type),h("info",`${$.get(J.type)||J.type} launched`,!0)),Ue(J.type));const E=new Set(a.filter(J=>Nt(J.status)!=="stopped").map(J=>J.type));wt.current.forEach(J=>{!ee.includes(J)&&!E.has(J)&&wt.current.delete(J)})},[h,Ue,a,ee,$]),o.useEffect(()=>()=>{Object.values(Ge.current).forEach(clearTimeout),Ge.current={}},[]);const[z,te]=o.useState({}),[Se,_e]=o.useState(null);o.useEffect(()=>{if(!j||!r||!l)return;(async()=>{try{const J=await l(r,"get_ide_extensions",{}),de=(J==null?void 0:J.result)||J;de!=null&&de.success&&(de!=null&&de.ideExtensions)&&te(de.ideExtensions)}catch{}})()},[j,r,l]);const Ie=E=>j?nt(E.type):e==="cli"?E.cliName:E.acpName,Ke=j?s.detectedIdes||[]:[],De=o.useCallback(async E=>{const J=(E==null?void 0:E.type)||M,de=(E==null?void 0:E.workspacePath)??Oe;if(j){await f(J,de?{workspace:de}:void 0)&&F(J);return}const me=await c.runLaunchCliCore({cliType:J,dir:E!=null&&E.workspaceId?void 0:de||void 0,workspaceId:(E==null?void 0:E.workspaceId)||void 0,useHome:(E==null?void 0:E.useHome)||!(E!=null&&E.workspaceId)&&!de,argsStr:(E==null?void 0:E.argsStr)??(T||void 0),model:(E==null?void 0:E.model)??(v&&R||void 0),resumeSessionId:(E==null?void 0:E.resumeSessionId)||!v&&e==="cli"&&J===M&&S||void 0});if(me.success||me.pending){const Le=(E==null?void 0:E.argsStr)??T;!j&&(Le!=null&&Le.trim())&&(ol(r,J,Le),Y(J)),F(J),me.success&&me.sessionId&&g(me.sessionId)}},[c,f,v,j,T,R,Y,F,r,g,Oe,S,M]),Qe=bc(j?"ide":v?"acp":"cli",!j&&!v&&!!S),et=gc(j?"ide":v?"acp":"cli",!j&&!v&&!!S),se=()=>{var Le;const E=j?nt(M):$.get(M)||M,J=!j&&!v&&!!S,{options:de,selectedKey:me}=bs({machine:s,currentWorkspaceId:ne&&ne!=="__custom__"?ne:null,currentWorkspacePath:Oe});P({title:J?Ea(E):ps("start-fresh",E),description:J?$a():fs("start-fresh"),confirmLabel:Qe,busyLabel:et,workspaceOptions:de,selectedWorkspaceKey:me,details:[{label:"Mode",value:I.label},{label:"Provider",value:E},...!j&&e==="cli"&&S?[{label:"Resume",value:((Le=G.find(we=>we.providerSessionId===S))==null?void 0:Le.title)||S}]:[],...!j&&T.trim()?[{label:"Arguments",value:T.trim()}]:[],...v&&R.trim()?[{label:"Model",value:R.trim()}]:[]]},async()=>{const we=de.find(Je=>Je.key===at.current);we!=null&&we.workspaceId?(ce(we.workspaceId),le("")):we!=null&&we.workspacePath?(ce("__custom__"),le(we.workspacePath)):(ce(""),le("")),await De({workspaceId:(we==null?void 0:we.workspaceId)??null,workspacePath:(we==null?void 0:we.workspacePath)??"",useHome:!(we!=null&&we.workspaceId)&&!(we!=null&&we.workspacePath)})})},Me=E=>{j?A(E):w(E.type,E.workspace,E.id)},Ee=o.useCallback(async(E,J,de=!1)=>{if(E.mode===J){de&&E.sessionId&&g(E.sessionId);return}if(!l||!E.sessionId){de&&E.sessionId&&g(E.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:E.sessionId,cliType:E.type,mode:J}),de&&g(E.sessionId)}catch(me){const Le=Va(me);za(me)?console.warn(Le?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",me instanceof Error?me.message:String(me)):console.error("Failed to switch CLI view mode:",me)}},[r,g,l]),tt=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:ne,onChange:E=>{const J=E.target.value;if(ce(J),J==="__custom__"&&l){yt();return}J!=="__custom__"&&le("")},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(E=>t.jsxs("option",{value:E.id,children:[E.id===s.defaultWorkspaceId?"⭐ ":"",pn(E.path,E.label)]},E.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…"})]})}),ne==="__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:yt,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:Z,onChange:E=>le(E.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:ne==="__custom__"?Oe?t.jsx("span",{className:"font-mono truncate block",title:Oe,children:Oe}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Oe?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:ne===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:Oe,children:Oe})]}):"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:j?Ke.length>0?Ke.map(E=>{const J=a.find(Je=>(Je.type||"").toLowerCase()===(E.type||"").toLowerCase()&&Nt(Je.status)!=="stopped"),de=E.running||!!J,me=!!J&&J.cdpConnected,Le=ee.includes(E.type||E.id||""),we=M===(E.type||"");return t.jsxs("button",{onClick:()=>{if(me&&J){const Je=J.sessionId;Je?m(rs(Je),{state:{openRemoteForTabKey:Je}}):m("/dashboard",{state:{openRemoteForTabKey:J.id}});return}Le||L(Je=>Je===(E.type||"")?"":E.type||"")},disabled:!!b||Le,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${me?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":we?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:b&&b!==E.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(E.type)}),de&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${me?"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:E.name||nt(E.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${me?"text-green-400":Le?"text-orange-400":we?"text-accent-primary":"text-text-muted"}`,children:me?"Open Session":Le?"Starting...":we?"Configure":"Select"})]})]},E.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:d,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(ud,{size:14})," Scan System"]})]}):x.length>0?x.map(E=>{const J=M===E.type,de=ee.includes(E.type),Le=!!a.find(we=>we.type===E.type&&Nt(we.status)!=="stopped");return t.jsxs("button",{onClick:()=>L(we=>we===E.type?"":E.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${J?"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:E.icon}),Le&&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:E.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${de?"text-orange-400":J?"text-accent-primary":"text-text-muted"}`,children:de?"Starting...":J?"Configure":"Select"})]})]},E.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."})]})}),M&&(j?Ke.find(E=>E.type===M):x.find(E=>E.type===M))&&t.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:j?nt(M):$.get(M)||M})]}),tt,!j&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&e==="cli"&&t.jsx(dl,{busy:!!y||!!b||ee.includes(M),savedSessionsLoading:H,savedSessionsError:X,selectedSession:Re,onRefresh:()=>void At(M),onOpenHistory:()=>{M&&(ie(!0),ll({hasLoadedInitialResults:ae,isLoading:H})&&At(M))},onClearSelection:()=>D("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&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:E=>O(E.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:T,onChange:E=>K(E.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(E=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>K(E),title:E,children:E},E))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:se,disabled:!!y||!!b||ee.includes(M),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:y===M||b===M?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+ee.filter(E=>!a.some(J=>J.type===E&&Nt(J.status)!=="stopped")).length,")"]}),a.length===0&&Te.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:[Te.map(E=>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(E)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:j?nt(E):$.get(E)||E}),t.jsx("div",{className:"text-[11px] text-text-muted",children:y===E?"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:${E}`)),a.map(E=>{const J=j?E:null,de=!j&&!v?E:null,me=Nt(E.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(E.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ie(E),(J==null?void 0:J.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",J.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:E.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 Le;(Le=navigator.clipboard)==null||Le.writeText(`adhdev attach ${de.runtimeKey}`),_(de.runtimeKey||null),window.setTimeout(()=>{_(we=>we===de.runtimeKey?null:we)},1200)},children:N===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:xx(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 ${me==="stopped"?"bg-red-500/[0.08] text-red-500":me==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:me}),j&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Le=E.sessionId;if(Le){m(rs(Le),{state:{openRemoteForTabKey:Le}});return}m("/dashboard",{state:{openRemoteForTabKey:E.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:t.jsx(Rt,{size:13})}),t.jsx("button",{onClick:()=>{const Le=E.workspace||"",{options:we,selectedKey:Je}=bs({machine:s,currentWorkspacePath:Le});P({title:ps("restart-ide",nt(E.type)),description:fs("restart-ide"),confirmLabel:Hs("restart-ide"),busyLabel:Us("restart-ide"),workspaceOptions:we,selectedWorkspaceKey:Je,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:nt(E.type)}]},async()=>{const kt=we.find(Qt=>Qt.key===at.current),ht=(kt==null?void 0:kt.workspacePath)??"";if(ht&&ht!==Le){await De({type:E.type,workspacePath:ht});return}await k(E)})},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(zs,{size:14})})]}),v&&t.jsx("button",{onClick:()=>{const Le=E.sessionId;Le&&g(Le)},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:!E.sessionId,children:t.jsx(Yt,{size:14})}),de&&me!=="stopped"&&t.jsxs(t.Fragment,{children:[de.mode&&t.jsx(Ra,{mode:de.mode,onChange:Le=>void Ee(de,Le,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Le=E.sessionId;Le&&g(Le)},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:!E.sessionId,children:de.mode==="chat"?t.jsx(Yt,{size:14}):t.jsx(Rt,{size:13})})]}),me==="stopped"?t.jsx("button",{onClick:()=>{const Le=E.workspace||"",we=j?nt(E.type):Ie(E),{options:Je,selectedKey:kt}=bs({machine:s,currentWorkspacePath:Le});P({title:ps("restart-stopped",we),description:fs("restart-stopped"),confirmLabel:Hs("restart-stopped"),busyLabel:Us("restart-stopped"),workspaceOptions:Je,selectedWorkspaceKey:kt,details:[{label:"Mode",value:I.label},{label:"Provider",value:we}]},async()=>{const ht=Je.find(Qt=>Qt.key===at.current);await De({type:E.type,workspaceId:(ht==null?void 0:ht.workspaceId)??null,workspacePath:(ht==null?void 0:ht.workspacePath)??"",useHome:!(ht!=null&&ht.workspaceId)&&!(ht!=null&&ht.workspacePath)})})},disabled:ee.includes(E.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:ee.includes(E.type)?"⏳":t.jsx(va,{size:14})}):t.jsx("button",{onClick:()=>Me(E),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(It,{size:14})})]})]}),J&&J.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:J.aiAgents.map(Le=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Wi(Le.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Le.name," · ",Nt(Le.status)]},Le.id))}),J&&(z[J.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:(z[J.type]||[]).map(Le=>t.jsxs("button",{disabled:Se===`${J.type}.${Le.type}`,onClick:async()=>{const we=`${J.type}.${Le.type}`;_e(we);try{await l(r,"set_ide_extension",{ideType:J.type,extensionType:Le.type,enabled:!Le.enabled}),te(Je=>({...Je,[J.type]:(Je[J.type]||[]).map(kt=>kt.type===Le.type?{...kt,enabled:!kt.enabled}:kt)}))}catch(Je){console.error("Extension toggle failed:",Je)}finally{_e(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 ${Le.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 ${Le.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Le.name,t.jsx("span",{className:"text-[9px] font-normal",children:Le.enabled?"ON":"OFF"})]},Le.type))})]})]},E.id)})]}),be&&l&&t.jsx(gn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:ve,directories:Ae,busy:Pe,error:$e,confirmLabel:"Use this folder",onClose:()=>B(!1),onNavigate:E=>{bt(E)},onConfirm:E=>{le(E),ce("__custom__"),B(!1)}}),Ve&&t.jsx(Qa,{title:Ve.title,description:Ve.description,details:Ve.details,workspaceOptions:Ve.workspaceOptions,selectedWorkspaceKey:pt,onWorkspaceChange:E=>{at.current=E,ze(E)},confirmLabel:Ve.confirmLabel,busyLabel:Ve.busyLabel,busy:ft,onConfirm:W,onCancel:()=>{Ye.current=null,ut(null)}}),ke&&Mt&&t.jsx(Ba,{activeConv:Mt,ides:[],isCreatingChat:!1,isRefreshingHistory:H,savedSessions:G,isSavedSessionsLoading:H,isResumingSavedSessionId:V,savedHistoryFilters:xe,onSavedHistoryFiltersChange:pe,onClose:()=>ie(!1),onNewChat:()=>{D(""),ie(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{At(M)},onResumeSavedSession:E=>{if(!E.canResume||V)return;const J=Ot(E);D(E.providerSessionId),jt(E),ge(E.providerSessionId),ie(!1),De({type:E.providerType,workspaceId:J.workspaceId,workspacePath:J.workspacePath,useHome:J.useHome,resumeSessionId:E.providerSessionId}).finally(()=>{ge(de=>de===E.providerSessionId?null:de)})}})]})}const fi=[{id:"ide",label:"IDE",helper:"Open a graphical workspace and attach CDP"},{id:"cli",label:"CLI",helper:"Launch a terminal-first workspace on this machine"},{id:"acp",label:"ACP",helper:"Launch an ACP-backed workspace on this machine"}];function gx({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:p,initialWorkspacePath:m,sendDaemonCommand:f}){var d;const[w,k]=o.useState(u);o.useEffect(()=>{k(u)},[u]);const A=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:fi.map(b=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${w===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>k(b.id),children:[t.jsx("span",{children:b.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${w===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:A[b.id]})]},b.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(d=fi.find(b=>b.id===w))==null?void 0:d.helper})]}),w==="ide"&&t.jsx(Yn,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),w==="cli"&&t.jsx(Yn,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),w==="acp"&&t.jsx(Yn,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m})]})}function yx({onNicknameSynced:e}={}){var V,ge,ne,ce,Z,le,ee,ye,be;const{id:s}=Ul(),r=Fs(),n=xa(),{sendCommand:a}=Pt(),i=xr(),c=lc(),l=c.ides||[],u=c.initialLoaded??!0,p=l.find(B=>B.id===s&&B.type==="adhdev-daemon"),m=l.some(B=>B.type==="adhdev-daemon"),[f,w]=o.useState("workspace"),[k,A]=o.useState("ide"),d=o.useRef(null),[b,y]=o.useState(null),h=o.useRef("__home__"),[N,_]=o.useState("__home__"),[g,I]=o.useState(!1),j=o.useRef(null);o.useEffect(()=>{!s||!p||!(!p.workspaces||!p.availableProviders||!p.detectedIdes||!p.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,p,s]),Lp(s&&f==="overview"?[s]:[],{enabled:f==="overview",intervalMs:15e3});const v=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},x=Qh({machineId:s,registeredMachineId:(p==null?void 0:p.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:j});o.useEffect(()=>it.onToast(ve=>{c.setToasts(Ae=>{if(Ae.some(He=>He.message===ve.message&&ve.timestamp-He.timestamp<3e3))return Ae;const Pe={id:ve.id,message:ve.message,type:ve.type,timestamp:ve.timestamp,targetKey:ve.targetKey,actions:ve.actions};return[...Ae.slice(-4),Pe]});const Ce=ve.duration||5e3;setTimeout(()=>c.setToasts(Ae=>Ae.filter(Q=>Q.id!==ve.id)),Ce)}),[c]);const $=(p==null?void 0:p.availableProviders)||[],M={};for(const B of $)M[B.type]=B.icon;const L=B=>M[B]||"",T=p?{id:p.id,hostname:Oi(p,{fallbackId:p.id}),platform:((V=p.machine)==null?void 0:V.platform)||"unknown",arch:((ge=p.machine)==null?void 0:ge.arch)||"",cpus:((ne=p.machine)==null?void 0:ne.cpus)||0,totalMem:((ce=p.machine)==null?void 0:ce.totalMem)||0,freeMem:(Z=p.machine)==null?void 0:Z.freeMem,availableMem:(le=p.machine)==null?void 0:le.availableMem,loadavg:(ee=p.machine)==null?void 0:ee.loadavg,uptime:(ye=p.machine)==null?void 0:ye.uptime,release:((be=p.machine)==null?void 0:be.release)||"",cdpConnected:!!p.cdpConnected,machineNickname:p.machineNickname||null,p2p:p.p2p?{screenshotActive:!1,...p.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:p.detectedIdes||[],workspaces:p.workspaces||[],defaultWorkspaceId:p.defaultWorkspaceId??p.activeWorkspaceId??null,defaultWorkspacePath:p.defaultWorkspacePath??p.activeWorkspacePath??null}:null,K=l.filter(B=>B.daemonId===s&&B.type!=="adhdev-daemon").filter(B=>!dr(B)&&!Ls(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,version:B.version||"",instanceId:B.instanceId||"",status:B.status,workspace:B.workspace||null,terminals:B.terminals||0,aiAgents:au(B.aiAgents||(B.agents||[]).map(ve=>({id:ve.name,name:ve.name,status:ve.status,version:ve.version}))),activeChat:B.activeChat||null,chats:B.chats||[],childSessions:B.childSessions||[],cdpConnected:B.cdpConnected||!1,daemonId:s})),U=l.filter(B=>B.daemonId===s&&dr(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,cliName:B.cliName||B.type,status:B.status,workspace:B.workspace||"",activeChat:B.activeChat||null,providerSessionId:B.providerSessionId,mode:B.mode,runtimeKey:B.runtimeKey,runtimeDisplayName:B.runtimeDisplayName,runtimeWorkspaceLabel:B.runtimeWorkspaceLabel,runtimeWriteOwner:B.runtimeWriteOwner||null,runtimeAttachedClients:B.runtimeAttachedClients||[],daemonId:s})),C=l.filter(B=>B.daemonId===s&&Ls(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,acpName:B.cliName||B.type,status:B.status,workspace:B.workspace||"",activeChat:B.activeChat||null,providerSessionId:B.providerSessionId,daemonId:s})),R=p?_t(p,{fallbackId:s}):"",O="workspace",S=n.state,D=S==null?void 0:S.initialMachineTab,G=S==null?void 0:S.initialWorkspaceCategory,q=S==null?void 0:S.initialWorkspaceId,H=S==null?void 0:S.initialWorkspacePath,re=D==="ides"||D==="clis"||D==="acps"?"workspace":D||O,ae=D==="ides"?"ide":D==="clis"?"cli":D==="acps"?"acp":G,Ne=[...K.map(B=>{var ve,Ce,Ae,Q,Pe;return{id:`ide:${B.type}:${B.workspace||""}`,label:((ve=B.activeChat)==null?void 0:ve.title)||B.type,kind:"ide",providerType:B.type,subtitle:B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:((Pe=(Q=(Ae=(Ce=B.activeChat)==null?void 0:Ce.messages)==null?void 0:Ae.at)==null?void 0:Q.call(Ae,-1))==null?void 0:Pe.timestamp)||0}}),...U.map(B=>{var ve,Ce,Ae,Q,Pe;return{id:`cli:${B.type}:${B.workspace||""}`,label:((ve=B.activeChat)==null?void 0:ve.title)||B.cliName,kind:"cli",providerType:B.type,providerSessionId:B.providerSessionId,subtitle:B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:((Pe=(Q=(Ae=(Ce=B.activeChat)==null?void 0:Ce.messages)==null?void 0:Ae.at)==null?void 0:Q.call(Ae,-1))==null?void 0:Pe.timestamp)||0}}),...C.map(B=>{var ve,Ce,Ae,Q,Pe;return{id:`acp:${B.type}:${B.workspace||""}`,label:((ve=B.activeChat)==null?void 0:ve.title)||B.acpName,kind:"acp",providerType:B.type,providerSessionId:B.providerSessionId,subtitle:vs(B.summaryMetadata)||B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:((Pe=(Q=(Ae=(Ce=B.activeChat)==null?void 0:Ce.messages)==null?void 0:Ae.at)==null?void 0:Q.call(Ae,-1))==null?void 0:Pe.timestamp)||0}})].sort((B,ve)=>(ve.lastLaunchedAt||0)-(B.lastLaunchedAt||0)),X=((p==null?void 0:p.recentLaunches)||[]).length>0?((p==null?void 0:p.recentLaunches)||[]).map(B=>({id:B.id,label:B.title||B.providerName||B.providerType,kind:B.kind,providerType:B.providerType,providerSessionId:B.providerSessionId,subtitle:vs(B.summaryMetadata)||B.workspace||void 0,workspace:B.workspace,summaryMetadata:B.summaryMetadata,lastLaunchedAt:B.lastLaunchedAt})):Ne,he=o.useMemo(()=>{var ve;const B=((ve=c.connectionStates)==null?void 0:ve[s||""])||void 0;return l.filter(Ce=>Ce.daemonId===s&&Ce.type!=="adhdev-daemon").flatMap(Ce=>Ka(Ce,{},{connectionStates:s&&B?{[s]:B}:void 0,defaultConnectionState:B})).filter(Ce=>!(Ce.transport==="pty"&&Ce.mode==="terminal")).sort((Ce,Ae)=>sa(Ae)-sa(Ce))},[l,c.connectionStates,s]),ke=o.useCallback(B=>{const ve=Ma(B);ve&&r(rs(ve))},[r]),ie=o.useCallback(()=>{d.current&&(I(!0),d.current().finally(()=>{d.current=null,I(!1),y(null)}))},[]),xe=o.useCallback(B=>{if(!T)return;const{options:ve,selectedKey:Ce}=bs({machine:T,currentWorkspacePath:B.workspace}),Ae=async()=>{A(B.kind),w("workspace")};d.current=async()=>{const Q=ve.find($e=>$e.key===h.current),Pe=(Q==null?void 0:Q.workspacePath)??null,He=(Q==null?void 0:Q.workspaceId)??null;if(B.kind==="ide"&&B.providerType){await x.handleLaunchIde(B.providerType,Pe?{workspace:Pe}:void 0);return}if((B.kind==="cli"||B.kind==="acp")&&B.providerType){await x.runLaunchCliCore({cliType:B.providerType,dir:He?void 0:Pe||"",workspaceId:He||void 0,model:B.kind==="acp"&&Ui(B.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:B.providerSessionId});return}await Ae()},h.current=Ce,_(Ce),y({title:B.kind==="ide"?ps("restart-ide",B.label):B.providerSessionId?Ea(B.label):ps("start-fresh",B.label),description:B.kind==="ide"?fs("restart-ide"):B.providerSessionId?$a():fs("start-fresh"),confirmLabel:B.kind==="ide"?Hs("restart-ide"):B.providerSessionId?sn(!0):Hs("start-fresh"),busyLabel:B.kind==="ide"?Us("restart-ide"):B.providerSessionId?Pa(!0):Us("start-fresh"),workspaceOptions:ve,details:[{label:"Mode",value:B.kind.toUpperCase()},...B.providerType?[{label:"Provider",value:B.providerType}]:[]]})},[x,T]);if(o.useEffect(()=>{w(re)},[O,re,s]),o.useEffect(()=>{ae&&A(ae)},[ae,s]),!T)return u?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:v,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 pe=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Rt,{size:14})," Workspace"]}),count:K.length+U.length+C.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(qt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(cn,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(md,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(ld,{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:v,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:[x.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:x.nicknameInput,onChange:B=>x.setNicknameInput(B.target.value),onKeyDown:B=>{B.key==="Enter"&&x.handleSaveNickname(),B.key==="Escape"&&x.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:x.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:()=>x.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:()=>{x.setEditingNickname(!0),x.setNicknameInput(T.machineNickname||"")},title:"Click to set nickname",children:R}),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:[T.platform," · ",T.arch]}),t.jsxs("span",{children:[T.cpus," cores"]}),(p==null?void 0:p.version)&&t.jsxs("span",{children:["v",p.version]}),T.p2p.available&&t.jsxs("span",{children:["P2P ",T.p2p.state==="connected"?"connected":T.p2p.state]}),T.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:T.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:pe.map(B=>t.jsxs("button",{onClick:()=>w(B.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===B.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[B.label,B.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===B.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:B.count})]},B.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:[f==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(hx,{machineEntry:p,providers:$,recentLaunches:X,currentConversations:he,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:xe,onOpenConversation:ke}),t.jsx(gx,{machine:T,machineId:s,providers:$,ideSessions:K,cliSessions:U,acpSessions:C,actions:x,getIcon:L,initialCategory:k,initialWorkspaceId:q,initialWorkspacePath:H,sendDaemonCommand:a})]}),f==="providers"&&t.jsx(ax,{machineId:s,providers:$,sendDaemonCommand:a}),f==="overview"&&t.jsx(Jh,{machineId:s,machine:T,ideSessions:K,cliSessions:U,acpSessions:C,actions:x,sendDaemonCommand:a}),f==="session-host"&&t.jsx(px,{machineId:s,cliSessions:U,sendDaemonCommand:a}),f==="logs"&&t.jsx(lx,{machineId:s,sendDaemonCommand:a})]})})}),x.launchPick&&T&&t.jsx(fx,{machine:T,launchPick:x.launchPick,actions:x}),b&&t.jsx(Qa,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:N,onWorkspaceChange:B=>{h.current=B,_(B)},confirmLabel:b.confirmLabel,busyLabel:b.busyLabel,busy:g,onConfirm:ie,onCancel:()=>{d.current=null,y(null)}}),t.jsx(yc,{toasts:c.toasts||[],onDismiss:B=>c.setToasts(ve=>ve.filter(Ce=>Ce.id!==B)),onClickToast:B=>{B.targetKey&&r(rs(B.targetKey))}}),t.jsx("style",{children:`
68
+ @keyframes toast-in {
69
+ from { opacity: 0; transform: translateX(40px); }
70
+ to { opacity: 1; transform: translateX(0); }
71
+ }
72
+ `})]})}function eo(){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=eo();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 Zt(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 wx{constructor(){qe(this,"adapters",new Map);qe(this,"states",new Map);qe(this,"runtimeListeners",new Map);qe(this,"screenshotCallbacks",new Map);qe(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}onScreenshot(s,r){return this.screenshotCallbacks.set(s,r),()=>{this.screenshotCallbacks.delete(s)}}emitScreenshot(s,r){this.screenshotCallbacks.forEach(n=>n(s,r))}onStatus(s){return this.statusCallbacks.add(s),()=>{this.statusCallbacks.delete(s)}}emitStatus(s,r){this.statusCallbacks.forEach(n=>n(s,r))}emitRuntimeSnapshot(s,r,n=0,a=!1){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:a})}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;const n=await Zt(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`);if(!n.ok)return;const a=await n.json();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})}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(a=>a(r))}}const zt=new wx;function jx(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=eo();return r?`${s}?token=${encodeURIComponent(r)}`:s}const Ur=jx(),hi=3e3,kx=3e4;let Ut=null,Sx=0;const on=new Map;let cs=null,or=null;function xi(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function Zs(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function Nx(e){return e==="connected"?"connected":e}async function Xr(e,s,r){const n=Jm(e,r||{}),a=Ut;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++Sx}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{on.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);on.set(i,{resolve:p=>{clearTimeout(u),c(p)},reject:p=>{clearTimeout(u),l(p)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function pa(e,s){const r=Ut;if(!r||r.readyState!==WebSocket.OPEN||!s||s.type!=="subscribe"&&s.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class Cx{constructor(s){qe(this,"daemonId");qe(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Ut==null?void 0:Ut.readyState)===WebSocket.OPEN}get connectionState(){return(Ut==null?void 0:Ut.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Xr(this.daemonId,s,r)}async sendInput(s,r){return Xr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,cs&&(clearInterval(cs),cs=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Xr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());zt.emitScreenshot(this.daemonId,a)}}catch{}};r(),cs=setInterval(r,2e3)}stopScreenshots(s){cs&&(clearInterval(cs),cs=null)}}let $t=null;function Ix(e){return(!$t||$t.daemonId!==e)&&($t=new Cx(e)),$t}function Ax({children:e}){const s=o.useRef(Jr()),r=Jr();s.current=r;const{setUserName:n}=gs(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((d,b)=>{l(d),or==null||or(d,b)},[]),p=o.useRef(null),m=o.useRef(),f=o.useRef(hi),w=o.useRef(!0),k=o.useRef(!1),A=o.useRef("initial_connect");return o.useEffect(()=>{w.current=!0,k.current=!1;function d(){var h,N;if(!w.current||((h=p.current)==null?void 0:h.readyState)===WebSocket.OPEN||((N=p.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Ur}...`),Zs("connect_attempt",{url:Ur,reason:A.current,delayMs:f.current});let y;try{y=new WebSocket(Ur)}catch(_){console.error("[Standalone WS] Failed to create WebSocket:",_),b();return}p.current=y,y.onopen=()=>{if(!w.current){y.close();return}u("connected"),f.current=hi,Zs("open",{url:Ur,reason:A.current}),ns.resubscribeAll({sendData:pa}),console.log("[Standalone WS] Connected")},Ut=y,y.onmessage=_=>{var g,I;try{const j=JSON.parse(_.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const v=on.get(j.requestId);v&&(on.delete(j.requestId),j.type==="error"?v.reject(new Error(((g=j.data)==null?void 0:g.message)||"Command failed")):v.resolve(j.data));return}if(j.type==="session_output"){const v=j.sessionId||j.cliId||j.cliType;v&&zt.emitSessionOutput(v,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){zt.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated);return}if(j.type==="topic_update"){const v=j.update;v&&ns.publish(v);return}if(j.type==="status"||j.type==="initial_state"){const v=j.data;if(!v)return;const{injectEntries:x,markLoaded:$,getIdes:M}=s.current,L=v.instanceId||"standalone",T=M().find(C=>C.id===L),K=Ix(L);zt.register(L,K),zt.setState(L,"connected"),u("connected",L),zt.emitStatus(L,v);const U=tn(v,{daemonId:L,existingDaemon:T,existingEntries:M()});xi("ws_status",{type:j.type,daemonId:L,sessions:(v.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(v.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),xi("entries",{daemonId:L,entries:U.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),U.length>0&&x(U,{authoritativeDaemonIds:[L]}),$(),c.current!==L&&((I=i.current)==null||I.call(i),c.current=L,i.current=ns.subscribe({sendData:pa},L,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${L}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const R=s.current.getIdes(),O=R.find(D=>D.id===L),S=tn(C.status,{daemonId:L,existingDaemon:O,existingEntries:R,timestamp:C.timestamp});S.length>0&&s.current.injectEntries(S),C.userName&&a.current&&a.current(C.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},y.onclose=_=>{w.current&&($t==null||$t.stopScreenshots(),$t&&zt.setState($t.daemonId,"disconnected"),u("disconnected"),p.current=null,A.current=`close:${_.code}${_.wasClean?":clean":":unclean"}`,Zs("close",{code:_.code,reason:_.reason||"",wasClean:_.wasClean}),b())},y.onerror=_=>{k.current||!w.current||(A.current="error",Zs("error",{message:_ instanceof Event?"event":String(_),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",_))}}function b(){if(!w.current)return;clearTimeout(m.current);const y=f.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),Zs("schedule_reconnect",{reason:A.current,delayMs:y}),m.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,kx),d()},y)}return d(),()=>{var y;w.current=!1,k.current=!0,(y=i.current)==null||y.call(i),i.current=null,c.current=null,clearTimeout(m.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,Ut=null),$t&&($t.stopScreenshots(),zt.unregister($t.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function Mx({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(or=(c,l)=>{r(c),l&&a(l)},()=>{or=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=Nx(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(Zl,{connectionOverrides:i,children:t.jsx(Ax,{children:e})})}const Tx=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Ni,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(qt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(cn,{}),label:"Settings"}];function Lx({children:e}){const s=Fs(),r=xa(),[n,a]=o.useState(!1),[i,c]=o.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),l=m=>{s(m),a(!1)},u=()=>{c(m=>{const f=!m;try{localStorage.setItem("sidebar-collapsed",f?"1":"0")}catch{}return f})},p=m=>`nav-item${r.pathname.startsWith(m)?" active":""} cursor-pointer ${i?"justify-center py-2.5 px-0":""}`;return t.jsxs("div",{className:`app-layout${n?" mobile-menu-open":""}${i?" sidebar-collapsed":""}`,children:[t.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:()=>a(!0),children:[t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"})]}),n&&t.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:()=>a(!1),onKeyDown:m=>m.key==="Escape"&&a(!1)}),t.jsxs("aside",{className:`sidebar ${n?"sidebar-open":""}`,children:[t.jsxs("div",{className:"sidebar-header",children:[t.jsxs("div",{className:`sidebar-logo ${i?"justify-center gap-0":""}`,children:[t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&t.jsx("span",{children:"ADHDev"})]}),t.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:()=>a(!1),children:t.jsx(It,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:Tx.map(m=>t.jsxs("div",{className:p(m.path),id:`nav-${m.id}`,onClick:()=>l(m.path),title:i?m.label:void 0,children:[t.jsx("span",{className:"nav-icon",children:m.icon}),!i&&m.label]},m.id))}),t.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":""}`,id:"nav-docs",onClick:()=>window.open("https://docs.adhf.dev","_blank"),title:i?"Docs":void 0,children:[t.jsx("span",{className:"nav-icon",children:t.jsx(Ci,{})}),!i&&t.jsxs(t.Fragment,{children:["Docs",t.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]})]}),t.jsxs("div",{className:`nav-item cursor-pointer${r.pathname==="/about"?" active":""} ${i?"justify-center py-2.5 px-0":""}`,id:"nav-about",onClick:()=>s("/about"),title:i?"About":void 0,children:[t.jsx("span",{className:"nav-icon",children:t.jsx(Ii,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.82"]}),t.jsx(dp,{collapsed:i}),t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:u,title:i?"Expand sidebar":"Collapse sidebar",children:[t.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&t.jsx("span",{className:"text-xs",children:"Collapse"})]})]})]}),t.jsx("main",{className:"main-content relative",children:t.jsx("div",{className:"main-content-inner",children:e})})]})}const _x=[{icon:t.jsx(qt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Yt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(Ai,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Rt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(cr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(Ci,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Rx=[{icon:t.jsx(hd,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Ni,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(dn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(cd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(ga,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(dd,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Px=[{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 Dx(){return t.jsxs(Nc,{icon:t.jsx(Ii,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:t.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.8.82"]}),children:[t.jsx(Lt,{children:t.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[t.jsxs("div",{className:"max-w-2xl",children:[t.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),t.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),t.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),t.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),t.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),t.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),t.jsx(Lt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:_x.map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Lt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:t.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:jc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Sc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:kc.map(e=>`${e.icon} ${e.name}`)}].map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[t.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),t.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(s=>t.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:s},s))})]},e.label))})}),t.jsx(Lt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Rx.map(e=>t.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Lt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:t.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:t.jsxs("table",{className:"w-full text-[13px]",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"bg-bg-secondary",children:[t.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),t.jsx("tbody",{children:Px.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(Cc,{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(Nd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Ex(){const{ides:e}=gs(),s=e.find(O=>O.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Pt(),{userName:a}=gs(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[p,m]=o.useState(null),[f,w]=o.useState("127.0.0.1"),[k,A]=o.useState(""),[d,b]=o.useState(""),[y,h]=o.useState(""),[N,_]=o.useState(""),[g,I]=o.useState(""),[j,v]=o.useState(!1),x=async()=>{const S=await(await Zt("/auth/session")).json();u(S)},$=async()=>{const S=await(await Zt("/api/v1/standalone/preferences")).json();m(S),w(S.standaloneBindHost)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([x(),$()]).catch(O=>{_(O instanceof Error?O.message:String(O))})},[]);const M=O=>{const S=O.target.value.trim();s!=null&&s.id&&S!==a&&n(s.id,"set_user_name",{userName:S}).catch(console.error)},[L,T]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),K=O=>{T(O);try{localStorage.setItem("adhdev_sound",O?"1":"0")}catch{}},U=async()=>{_(""),I(""),v(!0);try{const O=await Zt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:f})}),S=await O.json();if(!O.ok)throw new Error((S==null?void 0:S.error)||"Failed to save standalone network preference");m(S),w(S.standaloneBindHost),I(S.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(O){_(O instanceof Error?O.message:String(O))}finally{v(!1)}},C=async()=>{if(_(""),I(""),d.trim().length<4){_("Password must be at least 4 characters.");return}if(d!==y){_("New password and confirmation do not match.");return}v(!0);try{const O=await Zt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,newPassword:d})}),S=await O.json();if(!O.ok)throw new Error((S==null?void 0:S.error)||"Failed to save password");u(S),await $(),A(""),b(""),h(""),I(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),ul()}catch(O){_(O instanceof Error?O.message:String(O))}finally{v(!1)}},R=async()=>{_(""),I(""),v(!0);try{const O=await Zt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,clear:!0})}),S=await O.json();if(!O.ok)throw new Error((S==null?void 0:S.error)||"Failed to clear password");u(S),await $(),A(""),b(""),h(""),I("Standalone password disabled.")}catch(O){_(O instanceof Error?O.message:String(O))}finally{v(!1)}};return t.jsxs(Nc,{icon:t.jsx(cn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(_r,{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(_r,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),t.jsx(Lt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:t.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[t.jsx("span",{className:"text-text-muted",children:"Version"}),t.jsxs("span",{className:"font-mono text-xs",children:["v","0.8.82"]}),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:(p==null?void 0:p.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:(p==null?void 0:p.standaloneBindHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Auth"}),t.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),t.jsx(Lt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:f==="127.0.0.1",onChange:()=>w("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:f==="0.0.0.0",onChange:()=>w("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:()=>{U()},disabled:j,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:j?"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 ",(p==null?void 0:p.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),t.jsx(Lt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),N&&t.jsx(_r,{variant:"error",children:N}),g&&t.jsx(_r,{variant:"success",children:g}),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:k,onChange:O=>A(O.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:d,onChange:O=>b(O.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:y,onChange:O=>h(O.target.value)})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{C()},disabled:j,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:j?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&t.jsx("button",{type:"button",onClick:()=>{R()},disabled:j,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),t.jsx(Lt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?t.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):t.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(O=>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 ${O.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:O.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:O.type})]},O.type))})}),t.jsx(Lt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(fp,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Lt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode and theme.",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(gp,{})]}),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(Cp,{})]}),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(Mp,{})]})]})}),t.jsx(Lt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(up,{}),t.jsx(ls,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Sd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:L,onChange:K})]})}),t.jsx(Lt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:t.jsx("div",{className:"flex flex-col gap-3",children:t.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[t.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[t.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[t.jsx(id,{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:O=>c(O.target.value),onBlur:M,onKeyDown:O=>{O.key==="Enter"&&O.currentTarget.blur()}})]})})})]})}lp();Sp();const $x=ji({baseUrl:"",getToken:eo});function Bx({children:e}){const[s,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[p,m]=o.useState(!1),f=async()=>{a(!0),u("");try{const A=await(await Zt("/auth/session")).json();r(A)}catch(k){u(k instanceof Error?k.message:String(k))}finally{a(!1)}};o.useEffect(()=>{f()},[]);const w=async k=>{k.preventDefault(),m(!0),u("");try{const A=await Zt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),d=await A.json();if(!A.ok)throw new Error((d==null?void 0:d.error)||"Login failed");r(d),c(""),ul()}catch(A){u(A instanceof Error?A.message:String(A))}finally{m(!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:w,children:[t.jsx("input",{type:"password",value:i,onChange:k=>c(k.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:p||!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:p?"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 bi(){const{ides:e,initialLoaded:s}=gs();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(Jn,{to:`/machines/${r.id}`,replace:!0}):t.jsx(Jn,{to:"/dashboard",replace:!0})}function Kx(){const e=o.useMemo(()=>({sendCommand:Xr,sendData:pa}),[]);return t.jsx(Fl,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(sd,{client:$x,children:t.jsx(Bx,{children:t.jsx(Mx,{children:t.jsx(nd,{value:e,children:t.jsx(Lx,{children:t.jsxs(zl,{children:[t.jsx(os,{path:"/dashboard",element:t.jsx(Xh,{})}),t.jsx(os,{path:"/machine",element:t.jsx(bi,{})}),t.jsx(os,{path:"/machines/:id",element:t.jsx(yx,{})}),t.jsx(os,{path:"/machines",element:t.jsx(bi,{})}),t.jsx(os,{path:"/about",element:t.jsx(Dx,{})}),t.jsx(os,{path:"/settings",element:t.jsx(Ex,{})}),t.jsx(os,{path:"*",element:t.jsx(Jn,{to:"/dashboard",replace:!0})})]})})})})})})})}Sm({connectionManager:zt});Vl(document.getElementById("root")).render(t.jsx(Kx,{}));