@adhdev/daemon-standalone 0.8.96 → 0.8.98

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.
@@ -1,79 +0,0 @@
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 yd=Object.defineProperty;var vd=(e,s,r)=>s in e?yd(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var Ye=(e,s,r)=>vd(e,typeof s!="symbol"?s+"":s,r);import{r as o,j as t,M as Ra,a as _a,b as Ui,c as zi,u as Vs,R as lt,d as fr,t as wd,e as jd,D as kd,f as ma,g as fa,h as Pa,i as Sd,k as Nd,B as Cd,l as Id,m as ls,N as pa,n as Ad}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 Md(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 Bs=Md();function Lo(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 Ro(e){return!!e&&typeof e=="object"&&"text"in e}function Da(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:Ro(i)?String(i.text||""):"").join(r):Ro(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function is(e){return Da(e,{normalizeWhitespace:!0})}function Td(e,s){return typeof e=="string"&&e.trim().length>0&&e!==s}function _o(e){const s=Number((e==null?void 0:e.receivedAt)??(e==null?void 0:e.timestamp)??0);return Number.isFinite(s)?s:0}function Ld(e,s){if(!Array.isArray(e)||!Array.isArray(s)||e.length===0||s.length===0||e.length>s.length)return!1;const r=e[e.length-1],n=s[s.length-1];if(!r||!n)return!1;const a=String(r.role||"").toLowerCase(),i=String(n.role||"").toLowerCase();if(!a||a!==i||r.id&&n.id&&String(r.id)!==String(n.id)||typeof r.index=="number"&&typeof n.index=="number"&&r.index!==n.index)return!1;const c=is(r.content),l=is(n.content);if(!c||!l||c===l||c.length>=l.length||!l.startsWith(c))return!1;const u=_o(r),p=_o(n);return!(u&&p&&Math.abs(u-p)>15e3)}function ha(e,s){if(!e)return s??null;if(!s)return e??null;const r=Array.isArray(e.messages)?e.messages:[],n=Array.isArray(s.messages)?s.messages:[],a=r.length>0?Ld(r,n)?n:r:n,i=e.activeModal||(e.status==="waiting_approval"?s.activeModal:null);return{...s,...e,messages:a,activeModal:i,inputContent:e.inputContent??s.inputContent}}function ar(e,s){const r=Td(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:ha(e.activeChat,s==null?void 0:s.activeChat),controlValues:e.controlValues??(s==null?void 0:s.controlValues),providerControls:e.providerControls??(s==null?void 0:s.providerControls),summaryMetadata:e.summaryMetadata??(s==null?void 0:s.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(s==null?void 0:s.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(s==null?void 0:s.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(s==null?void 0:s.lastMessagePreview),lastMessageRole:e.lastMessageRole??(s==null?void 0:s.lastMessageRole),lastMessageAt:e.lastMessageAt??(s==null?void 0:s.lastMessageAt),lastMessageHash:e.lastMessageHash??(s==null?void 0:s.lastMessageHash),unread:e.unread??(s==null?void 0:s.unread),lastSeenAt:e.lastSeenAt??(s==null?void 0:s.lastSeenAt),inboxBucket:e.inboxBucket??(s==null?void 0:s.inboxBucket),completionMarker:e.completionMarker??(s==null?void 0:s.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(s==null?void 0:s.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(s==null?void 0:s.surfaceHidden),resume:e.resume??(s==null?void 0:s.resume),runtimeKey:e.runtimeKey??(s==null?void 0:s.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(s==null?void 0:s.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(s==null?void 0:s.runtimeWorkspaceLabel)}}function Po(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?ar(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}),Gi=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Do(e){var r,n;let s=0;return e.activeChat!==void 0&&(s+=4),(r=e.childSessions)!=null&&r.length&&(s+=2),e.workspace&&(s+=1),e.machine&&(s+=1),(n=e.agents)!=null&&n.length&&(s+=1),s}function Dn(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 ln(e){return Array.isArray(e)?e.map(ln):!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,ln(r)]))}function Rd(e,s){try{return JSON.stringify(ln(e))===JSON.stringify(ln(s))}catch{return!1}}function Rr(e,s,r){return Rd(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function _d(e,s,r){var p,d,x,g,w,A,m;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return e.map(f=>({...f,_lastUpdate:n}));const i=new Map;for(const f of s)i.set(f.id,f);for(const f of e){const b=i.get(f.id);if(!b){i.set(f.id,{...f,_lastUpdate:n});continue}const h=Do(f),S=Do(b);if(h>S){const R=(p=f.chats)!=null&&p.length?f.chats:b.chats,j=Po(b.childSessions,f.childSessions),C=ha(f.activeChat,b.activeChat),k=Dn(b,f,{...b,...f,chats:R,childSessions:j,activeChat:C,_lastUpdate:n});i.set(f.id,Rr(b,k,n))}else if(h<S){const R={};if(f.status&&f.status!==b.status&&(R.status=f.status),f.cdpConnected!==void 0&&(R.cdpConnected=f.cdpConnected),(d=f.chats)!=null&&d.length&&!((x=b.chats)!=null&&x.length)&&(R.chats=f.chats),f.title!==void 0&&(R.title=f.title),f.workspace!==void 0&&(R.workspace=f.workspace),f.providerSessionId!==void 0&&(R.providerSessionId=f.providerSessionId),f.parentSessionId!==void 0&&(R.parentSessionId=f.parentSessionId),f.sessionKind!==void 0&&(R.sessionKind=f.sessionKind),f.sessionCapabilities!==void 0&&(R.sessionCapabilities=f.sessionCapabilities),f.controlValues!==void 0&&(R.controlValues=f.controlValues),f.providerControls!==void 0&&(R.providerControls=f.providerControls),f.summaryMetadata!==void 0&&(R.summaryMetadata=f.summaryMetadata),f.lastMessagePreview!==void 0&&(R.lastMessagePreview=f.lastMessagePreview),f.lastMessageRole!==void 0&&(R.lastMessageRole=f.lastMessageRole),f.lastMessageAt!==void 0&&(R.lastMessageAt=f.lastMessageAt),f.lastMessageHash!==void 0&&(R.lastMessageHash=f.lastMessageHash),f.lastUpdated!==void 0&&(R.lastUpdated=f.lastUpdated),f.unread!==void 0&&(R.unread=f.unread),f.lastSeenAt!==void 0&&(R.lastSeenAt=f.lastSeenAt),f.inboxBucket!==void 0&&(R.inboxBucket=f.inboxBucket),f.completionMarker!==void 0&&(R.completionMarker=f.completionMarker),f.seenCompletionMarker!==void 0&&(R.seenCompletionMarker=f.seenCompletionMarker),f.surfaceHidden!==void 0&&(R.surfaceHidden=f.surfaceHidden),f.runtimeKey!==void 0&&(R.runtimeKey=f.runtimeKey),f.runtimeDisplayName!==void 0&&(R.runtimeDisplayName=f.runtimeDisplayName),f.runtimeWorkspaceLabel!==void 0&&(R.runtimeWorkspaceLabel=f.runtimeWorkspaceLabel),f.runtimeWriteOwner!==void 0&&(R.runtimeWriteOwner=f.runtimeWriteOwner),f.runtimeAttachedClients!==void 0&&(R.runtimeAttachedClients=f.runtimeAttachedClients),f.machineNickname!==void 0&&f.machineNickname!==b.machineNickname&&(R.machineNickname=f.machineNickname),f.version!==void 0&&(R.version=f.version),f.serverVersion!==void 0&&(R.serverVersion=f.serverVersion),f.versionMismatch===!0&&(R.versionMismatch=!0),Object.keys(R).length>0){const j=Dn(b,f,{...b,...R,_lastUpdate:n});i.set(f.id,Rr(b,j,n))}else Rr(b,{...b,_lastUpdate:n},n)}else{const R=f.timestamp||n,j=b._lastUpdate||b.timestamp||0;if(R>=j){const C=(g=f.chats)!=null&&g.length?f.chats:b.chats,k=Po(b.childSessions,f.childSessions),v=ha(f.activeChat,b.activeChat),y=Dn(b,f,{...b,...f,chats:C,childSessions:k,activeChat:v,_lastUpdate:n});i.set(f.id,Rr(b,y,n))}else(w=f.chats)!=null&&w.length&&!((A=b.chats)!=null&&A.length)&&i.set(f.id,{...b,chats:f.chats})}}const c=new Set(e.map(f=>f.id)),l=new Set,u=new Set;for(const f of e){const b=f.daemonId||((m=f.id)==null?void 0:m.split(":")[0]);b&&l.add(b),b&&f.type!=="adhdev-daemon"&&u.add(b)}for(const[f,b]of i){const h=b.daemonId||f.split(":")[0];if(!l.has(h))continue;if(a.has(h)&&!c.has(f)){i.delete(f);continue}const S=n-(b._lastUpdate||b.timestamp||0);(b.transport==="pty"&&u.has(h)&&!c.has(f)&&S>1e4||b.transport==="acp"&&u.has(h)&&!c.has(f)&&S>1e4||b.transport==="cdp-page"&&u.has(h)&&!c.has(f)&&S>3e4)&&i.delete(f)}for(const[f,b]of i){const h=b.daemonId||f.split(":")[0];if(l.has(h)&&b.transport&&!u.has(h))continue;n-(b._lastUpdate||b.timestamp||0)>3e5&&b.status!=="online"&&i.delete(f)}return Array.from(i.values())}function Pd(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 Dd({children:e,connectionOverrides:s}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[u,p]=o.useState(void 0),d=o.useRef(r);o.useEffect(()=>{d.current=r},[r]);const x=o.useCallback((b,h)=>{n(S=>{let R=!1;const j=S.map(C=>C.id!==b||C.chats===h?C:(R=!0,{...C,chats:h}));return R?j:S})},[]),g=o.useCallback((b,h)=>{n(S=>{const R=S.length===0?b:_d(b,S,h),j=!Pd(S,R);return j&&Bs.record({kind:"dashboard.entries_applied",payload:{incoming:Lo(b),next:Lo(R)}}),j?R:S})},[]),w=o.useCallback(()=>i(!0),[]),A=o.useMemo(()=>({injectEntries:g,markLoaded:w,getIdes:()=>d.current}),[g,w]),m=s,f=o.useMemo(()=>({ides:r,updateRouteChats:x,initialLoaded:a,toasts:c,setToasts:l,wsStatus:(m==null?void 0:m.wsStatus)??"connected",isConnected:(m==null?void 0:m.isConnected)??!0,connectionStates:(m==null?void 0:m.connectionStates)??{},connectionTransports:(m==null?void 0:m.connectionTransports)??{},showReconnected:(m==null?void 0:m.showReconnected)??!1,retryConnection:m==null?void 0:m.retryConnection,isP2PActive:(m==null?void 0:m.isP2PActive)??!1,p2pStates:(m==null?void 0:m.p2pStates)??{},userRole:m==null?void 0:m.userRole,userName:u,setUserName:p}),[r,x,a,c,m==null?void 0:m.wsStatus,m==null?void 0:m.isConnected,m==null?void 0:m.connectionStates,m==null?void 0:m.connectionTransports,m==null?void 0:m.showReconnected,m==null?void 0:m.retryConnection,m==null?void 0:m.isP2PActive,m==null?void 0:m.p2pStates,m==null?void 0:m.userRole,u]);return t.jsx(Gi.Provider,{value:A,children:t.jsx(Vi.Provider,{value:f,children:e})})}function ks(){return o.useContext(Vi)}function pr(){return o.useContext(Gi)}function qi(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),d=l.startsWith("http")?new URL(p):new URL(p,typeof window<"u"?window.location.origin:"http://localhost");return u&&d.searchParams.set("token",u),!l.startsWith("http")&&!s?`${d.pathname}${d.search}${d.hash}`:d.toString()}async function c(l,u={}){const p={"Content-Type":"application/json",...u.headers||{}},d=r==null?void 0:r();d&&(p.Authorization=`Bearer ${d}`);const x=a(l),g=new AbortController,w=setTimeout(()=>g.abort(),15e3);try{const A=await fetch(x,{...u,headers:p,signal:g.signal});if(A.status===401)throw n==null||n(),new Error("Unauthorized");if(!A.ok){const m=await A.json().catch(()=>({error:A.statusText}));throw new Error(m.error||`API Error: ${A.status}`)}return A.json()}finally{clearTimeout(w)}}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=qi({baseUrl:"http://localhost:3847"}),$d=o.createContext(Ed);function Kd({client:e,children:s}){return t.jsx($d.Provider,{value:e,children:s})}const Bd={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Yi=o.createContext(Bd);function Od({value:e,children:s}){return t.jsx(Yi.Provider,{value:e,children:s})}function Lt(){return o.useContext(Yi)}function Wd(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 Hd(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Xi(e){return e?Wd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Hd(e.content)]):""}const He={size:18};function Ji({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function Ea({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polyline",{points:"15 18 9 12 15 6"})})}function Zt({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),t.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),t.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),t.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function $a({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"9",cy:"7",r:"4"}),t.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),t.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Fd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Ud({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function Qi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),t.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),t.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),t.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function zd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 gn({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"3"}),t.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Zi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),t.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Vd({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function es({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Pt({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Ka({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),t.jsx("polyline",{points:"14 2 14 8 20 8"}),t.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),t.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Gd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"11",cy:"11",r:"8"}),t.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function Os({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function Gs({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"23 4 23 10 17 10"}),t.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function Ss({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),t.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),t.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function hr({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M12 22v-5"}),t.jsx("path",{d:"M9 8V2"}),t.jsx("path",{d:"M15 8V2"}),t.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function ec({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),t.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function tc({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),t.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),t.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),t.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function sc({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function qd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),t.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),t.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function yn({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"4 17 10 11 4 5"}),t.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Yd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Ba({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Xd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function It({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Jd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),t.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),t.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),t.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function Qd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),t.jsx("path",{d:"M12 2v6"}),t.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Zd({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function eu({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),t.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function vn({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),t.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function tu({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"5"}),t.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),t.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),t.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),t.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),t.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),t.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),t.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),t.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function su({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function ru({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function nu({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),t.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function au({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function ou({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),t.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function iu({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),t.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),t.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function cu({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),t.jsx("path",{d:"M13 2h9v9"}),t.jsx("path",{d:"M22 2L13 11"})]})}function lu({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"9 14 4 9 9 4"}),t.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function du({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),t.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),t.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),t.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),t.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),t.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),t.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),t.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),t.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),t.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function uu({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),t.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function mu({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),t.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),t.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const En=new Map;function Eo(e,s){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(s||""):!0}function fu(e){if(!Array.isArray(e)||e.length===0)return"0:empty";const s=e[e.length-1];return`${e.length}:${Xi(s)}`}function $o(e,s){const r=Math.max(0,e.scrollHeight-e.clientHeight-s.fromBottom);e.scrollTop=Number.isFinite(r)?r:s.top}function rc(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function pu(e,s,r){return Number(e.receivedAt||r[_s(e,s)]||0)||0}function nc(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function hu(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function _r(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 $n(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 Ko(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):nc(e)?t.jsx(Ra,{remarkPlugins:[_a,Ui,zi],children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function Pr({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:Ko(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const a=$n(r);return a?t.jsx("img",{src:a,alt:_r(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=$n(r);return a?t.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=$n(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:_r(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||_r(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=_r(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}),Ko(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 _s(e,s){const r=e,n=Da(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 xu=o.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(Ra,{remarkPlugins:[_a],children:s.text}),t.jsx("span",{className:"action-time",children:rc(s.timestamp)})]})},(e,s)=>e.log===s.log),bu=o.memo(function({message:s,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var C,k,v;const u=(s.role||"").toLowerCase(),p=u==="user"||u==="human",d=s.kind||(u==="tool"?"tool":"standard"),x=hu(s.content)?s.content:null,g=!!(x!=null&&x.some(y=>y.type!=="text")),w=Da(s.content,{joiner:`
4
- `});if(d==="thought"){const y=typeof((C=s.meta)==null?void 0:C.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(Zd,{size:13}),t.jsx("span",{children:y})]}),t.jsx("div",{className:"chat-msg-body",children:w})]})}if(d==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),g&&x?t.jsx("div",{className:"tool-text w-full",children:t.jsx(Pr,{parts:x,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:w})]});if(d==="terminal"){const y=(k=s.meta)!=null&&k.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:y}),t.jsx("span",{children:$})]}),g&&x?t.jsx("div",{className:"chat-msg-body",children:t.jsx(Pr,{parts:x,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:w})]})}if(d==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:g&&x?t.jsx(Pr,{parts:x,renderAsPreformatted:!1}):w.slice(0,100)});const A=s.meta,f=(typeof(A==null?void 0:A.renderMode)=="string"?A.renderMode.trim():"")==="preformatted",b=w,h=!1,S=b,R=f,j=!R&&nc(S);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${p?"self-end":"self-start"}`,children:(b||g||p)&&t.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${b||g?"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:rc(r)})]}),(b||g)&&t.jsx("div",{className:"chat-markdown",children:g&&x?t.jsx(Pr,{parts:x,renderAsPreformatted:R}):R?t.jsx("pre",{className:"chat-preformatted",children:S}):j?t.jsx(Ra,{remarkPlugins:[_a,Ui,zi],children:S}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:S})}),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),gu=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:d,isLoadingMore:x,hasMoreHistory:g,hiddenLiveCount:w=0,loadError:A,scrollToBottomRequestNonce:m},f){const b=o.useRef(null),h=o.useRef(null),S=o.useRef(null),R=o.useRef(0),j=o.useRef(""),C=o.useRef(!1),k=o.useRef(null),v=o.useRef(!1),y=o.useRef(null),$=o.useRef(!1),[L,M]=o.useState(new Set),_=o.useRef(!1),W=o.useRef(!1),H=()=>{const Y=b.current;return Y?Y.scrollHeight-Y.scrollTop-Y.clientHeight<200:!0},N=o.useCallback((Y="auto")=>{const he=b.current;he&&he.scrollTo({top:he.scrollHeight,behavior:Y})},[]),P=o.useCallback(()=>{var ie;const Y=b.current,he=(ie=window.getSelection)==null?void 0:ie.call(window);if(!Y||!he||he.rangeCount===0||he.isCollapsed){$.current=!1;return}const O=he.anchorNode,X=he.focusNode;$.current=!!(O&&X&&Y.contains(O)&&Y.contains(X))},[]),G=fu(s),I=o.useCallback(()=>{const Y=b.current;!Y||!l||En.set(l,{top:Y.scrollTop,fromBottom:Math.max(0,Y.scrollHeight-Y.scrollTop-Y.clientHeight),messageFingerprint:G})},[l,G]),E=o.useCallback((Y="auto")=>{k.current!=null&&cancelAnimationFrame(k.current),k.current=requestAnimationFrame(()=>{k.current=null,N(Y)})},[N]);o.useEffect(()=>{const Y=!C.current,he=j.current!==l;if(j.current=l,Y||he){if(C.current=!0,_.current=!1,v.current=!0,!$.current){const X=l?En.get(l):null;X&&Eo(X,G)?requestAnimationFrame(()=>{const ie=b.current;ie&&($o(ie,X),W.current=!0)}):E("auto")}R.current=s.length;return}s.length>R.current?!_.current&&!$.current&&E("auto"):H()&&!_.current&&!$.current&&E("auto"),R.current=s.length},[G,l,c,s.length,E]),o.useEffect(()=>{m&&(_.current=!1,v.current=!0,W.current=!0,y.current!=null&&window.clearTimeout(y.current),y.current=window.setTimeout(()=>{v.current=!1,y.current=null},180),$.current||E("auto"))},[E,m]),o.useEffect(()=>()=>{I(),k.current!=null&&cancelAnimationFrame(k.current),y.current!=null&&window.clearTimeout(y.current)},[I]),o.useEffect(()=>{const Y=h.current;if(!Y)return;const he=()=>{y.current!=null&&window.clearTimeout(y.current),y.current=window.setTimeout(()=>{v.current=!1,y.current=null},180)},O=new ResizeObserver(()=>{v.current&&($.current||(E("auto"),he()))});return O.observe(Y),()=>{O.disconnect(),y.current!=null&&(window.clearTimeout(y.current),y.current=null)}},[E,l]),o.useImperativeHandle(f,()=>({scrollToBottom:(Y="smooth")=>{N(Y)}}),[N]),o.useEffect(()=>{const Y=b.current;if(!Y)return;let he;const O=()=>{clearTimeout(he),he=setTimeout(()=>{_.current=!H(),I()},50)};return Y.addEventListener("scroll",O,{passive:!0}),()=>{Y.removeEventListener("scroll",O),clearTimeout(he)}},[I]),o.useEffect(()=>(document.addEventListener("selectionchange",P),()=>document.removeEventListener("selectionchange",P)),[P]);const B=o.useRef(0),U=o.useRef(!1);o.useEffect(()=>{const Y=b.current;if(!Y||!U.current||B.current===0)return;const he=Y.scrollHeight-B.current;he>0&&(Y.scrollTop=he),I(),B.current=0,U.current=!1},[s.length,I]),o.useEffect(()=>{if(W.current||!l)return;const Y=En.get(l),he=b.current;if(!(!Y||!he)){if(!Eo(Y,G)){N("auto"),W.current=!0;return}$o(he,Y),W.current=!0}},[l,G,s.length,N]);const V=()=>{const Y=b.current;Y&&(B.current=Y.scrollHeight),U.current=!0,d==null||d()},ae=o.useMemo(()=>{const Y=s.map((ie,le)=>({type:"message",data:ie,index:le,ts:pu(ie,le,u)}));if(!r||r.length===0)return Y;const he=[...r].sort((ie,le)=>ie.timestamp-le.timestamp).map((ie,le)=>({type:"action",data:ie,index:le,ts:ie.timestamp})),O=[];let X=0;for(const ie of Y){for(;X<he.length&&ie.ts>0&&he[X].ts<ie.ts;)O.push(he[X++]);O.push(ie)}for(;X<he.length;)O.push(he[X++]);return O},[s,r,u]),we=w>0||!!g,be=w>0?`↑ Show ${Math.min(w,80)} earlier messages${w>80?` (${w} hidden)`:""}`:A?`↻ ${A}`:"↑ Load older messages";return t.jsx("div",{ref:b,"data-chat-scroll":!0,className:"chat-container",children:t.jsxs("div",{ref:h,className:"chat-container-content",children:[x&&t.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),we&&!x&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{onClick:V,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${A&&w===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:be})}),ae.length===0&&!we&&(p||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),ae.map(Y=>{if(Y.type==="action"){const ke=Y.data;return t.jsx(xu,{log:ke},`action-${Y.index}`)}const he=Y.data,O=Y.index,X=_s(he,O),ie=he.receivedAt||u[X],le=`${l}-${X}`,me=L.has(le);return t.jsx(bu,{message:he,receivedAt:ie,agentName:n,userName:a,isCliMode:i,isTextExpanded:me,onToggleTextExpanded:()=>M(ke=>{const de=new Set(ke);return me?de.delete(le):de.add(le),de})},`msg-${X}`)}),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:S})]})})}),yu=o.memo(gu,(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),vu="modulepreload",wu=function(e){return"/"+e},Bo={},ju=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=wu(u),u in Bo)return;Bo[u]=!0;const p=u.endsWith(".css"),d=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const x=document.createElement("link");if(x.rel=p?"stylesheet":vu,p||(x.as="script"),x.crossOrigin="",x.href=u,l&&x.setAttribute("nonce",l),document.head.appendChild(x),p)return new Promise((g,w)=>{x.addEventListener("load",g),x.addEventListener("error",()=>w(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return a.then(c=>{for(const l of c||[])l.status==="rejected"&&i(l.reason);return s().catch(i)})};let Oo=!1;const ac=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),d=o.useRef(!1),x=o.useRef(!1),g=()=>{const w=i.current;if(w){p.current&&(w.clear(),p.current=!1);for(const A of u.current)w.write(A);u.current=[],d.current&&(w.fit(),d.current=!1),x.current&&(w.bumpResize(),x.current=!1)}};return o.useImperativeHandle(a,()=>({write:w=>{i.current?i.current.write(w):u.current.push(w)},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:(w,A)=>{i.current&&typeof i.current.resize=="function"&&i.current.resize(w,A)},fit:()=>{i.current?i.current.fit():d.current=!0},bumpResize:()=>{i.current?i.current.bumpResize():x.current=!0}}),[]),o.useEffect(()=>{if(!c)return;const w=requestAnimationFrame(()=>{g()});return()=>cancelAnimationFrame(w)},[c]),o.useEffect(()=>{let w=!1;return ju(()=>import("./terminal-2SYILvaH.js"),__vite__mapDeps([0,1,2])).then(A=>{Oo||(Oo=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),w||l(()=>A.GhosttyTerminalView)}).catch(A=>{console.error("[CliTerminal] failed to load terminal renderer",A)}),()=>{w=!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"}})});ac.displayName="CliTerminal";function Dr({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 Wo({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 ku({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 d,x,g,w;u>p?(d=a.width,x=a.width/u,g=0,w=(a.height-x)/2):(x=a.height,d=a.height*u,g=(a.width-d)/2,w=0);const A=a.left-i.left+g+d*e.nx,m=a.top-i.top+w+x*e.ny,f=Math.max(8,Math.min(i.width-8,A)),b=Math.max(8,Math.min(i.height-8,m));return t.jsxs("div",{style:{position:"absolute",left:f-8,top:b-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 Su({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:u,isConnActive:p,zoom:d,isMobile:x,mobileFillZoom:g,onZoomOut:w,onZoomReset:A,onZoomIn:m,transportType:f,screenshotUsage:b,lastActionStatus:h}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:S=>S.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(S=>!S),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:S=>S.stopPropagation(),onChange:S=>l(S.target.value),onKeyDown:S=>{u(S)},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(S=>!S),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"})]}),d>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),f==="direct"&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),f==="relay"&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),b&&b.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:b.budgetExhausted?"#ef4444":"#c4b5fd",background:b.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:b.budgetExhausted?"TURN blocked":`TURN ${b.dailyUsedMinutes}/${b.dailyBudgetMinutes}m`}),h&&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:S=>S.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[t.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",d<=(x?g:1)+.01?x?"FILL":"FIT":`${Math.round(d*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:S=>{S.stopPropagation(),w()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),t.jsx("button",{onClick:S=>{S.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:x?"FILL":"FIT"}),t.jsx("button",{onClick:S=>{S.stopPropagation(),m()},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 Nu({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 Cu(){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 Ho(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 jr(e,s){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!Cu())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,Ho(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,Ho(s[c])]))}),r.current=s})}function Iu({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:u,setPanX:p,setPanY:d,setZoom:x,lastWheelTimeRef:g,onAction:w,setLastActionStatus:A,spawnRippleFromNormalized:m,clampPan:f,isMobile:b,mobileFillZoom:h}){const[S,R]=o.useState(null),j=o.useRef(null),C=o.useRef(null),k=o.useRef(null),v=o.useRef(!1),y=o.useRef(null),$=o.useRef(0),L=o.useRef(null),M=o.useRef(1),_=o.useRef({x:0,y:0}),W=o.useRef(!1),H=o.useRef(n),N=o.useRef(w),P=30,G=550,I=18,E=60,B=400,U=12,V=()=>{if(j.current)return;const be={nx:.5,ny:.5};j.current=be,R(be)};return o.useEffect(()=>{H.current=n,n==="mouse"&&V()},[n]),o.useEffect(()=>{N.current=w},[w]),o.useEffect(()=>{const be=e.current;if(!be)return;const Y=me=>{if(!r.current)return null;const ke=r.current.getBoundingClientRect();return!ke.width||!ke.height?null:{nx:Math.max(0,Math.min(1,(me.clientX-ke.left)/ke.width)),ny:Math.max(0,Math.min(1,(me.clientY-ke.top)/ke.height))}},he=(me,ke)=>{if(!r.current)return{dnx:0,dny:0};const de=r.current,oe=de.getBoundingClientRect(),se=de.naturalWidth||oe.width,ue=de.naturalHeight||oe.height,te=se/ue,Ne=oe.width/oe.height;let Se,Ae;return te>Ne?(Se=oe.width,Ae=oe.width/te):(Ae=oe.height,Se=oe.height*te),{dnx:me/Se,dny:ke/Ae}},O=(me,ke,de)=>{if(de<=1.05)return;const oe=-(me-.5)*100,se=-(ke-.5)*100,ue=f(oe,se,de);(Math.abs(ue.x-l.current)>.1||Math.abs(ue.y-u.current)>.1)&&(p(ue.x),d(ue.y),l.current=ue.x,u.current=ue.y)},X=me=>{const ke=s.current;if(ke&&me.target instanceof Node&&ke.contains(me.target))me.preventDefault();else return;if(me.touches.length===1){const de=me.touches[0];C.current={x:de.clientX,y:de.clientY,time:Date.now()},k.current={x:de.clientX,y:de.clientY},W.current||(v.current=!1),y.current=setTimeout(()=>{if(!v.current&&!W.current)if(v.current=!0,H.current==="mouse"){const oe=j.current||{nx:.5,ny:.5};A("Right Click"),m(oe.nx,oe.ny,"right"),N.current("input_click",{...oe,button:"right"}).catch(()=>{})}else{const oe=Y(de);oe&&(A("Right Click"),m(oe.nx,oe.ny,"right"),N.current("input_click",{...oe,button:"right"}).catch(()=>{}))}},500);return}if(me.touches.length===2){y.current&&clearTimeout(y.current),v.current=!0,W.current=!0;const de=me.touches[1].clientX-me.touches[0].clientX,oe=me.touches[1].clientY-me.touches[0].clientY;L.current=Math.sqrt(de*de+oe*oe),M.current=c.current,_.current={x:(me.touches[0].clientX+me.touches[1].clientX)/2,y:(me.touches[0].clientY+me.touches[1].clientY)/2}}},ie=me=>{const ke=s.current;if(ke&&me.target instanceof Node&&ke.contains(me.target)&&me.preventDefault(),me.touches.length===1&&k.current){const de=me.touches[0],oe=de.clientX-k.current.x,se=de.clientY-k.current.y;if(!v.current&&C.current){const ue=de.clientX-C.current.x,te=de.clientY-C.current.y;Math.sqrt(ue*ue+te*te)>8&&(v.current=!0,y.current&&clearTimeout(y.current))}if(v.current)if(H.current==="mouse"){const ue=he(oe,se),te=j.current||{nx:.5,ny:.5},Ne=Math.max(0,Math.min(1,te.nx+ue.dnx)),Se=Math.max(0,Math.min(1,te.ny+ue.dny));j.current={nx:Ne,ny:Se},R({nx:Ne,ny:Se}),A(`Cursor: ${Math.round(Ne*100)}%, ${Math.round(Se*100)}%`),O(Ne,Se,c.current);const Ae=Date.now();Ae-g.current>=30&&(g.current=Ae,N.current("input_mouseMoved",{nx:Ne,ny:Se}).catch(()=>{}))}else if(c.current>1){const ue=s.current;if(ue){const te=ue.clientWidth,Ne=ue.clientHeight,Se=l.current+oe/te*100,Ae=u.current+se/Ne*100,T=f(Se,Ae,c.current);p(T.x),d(T.y),l.current=T.x,u.current=T.y}}else{const ue=Y(de);if(ue){const te=Date.now();te-g.current>=40&&(g.current=te,A("Scroll"),N.current("input_wheel",{nx:ue.nx,ny:ue.ny,deltaX:Math.round(-oe*2.5),deltaY:Math.round(-se*2.5)}).catch(()=>{}))}}k.current={x:de.clientX,y:de.clientY};return}if(me.touches.length===2&&L.current!==null){const de=me.touches[1].clientX-me.touches[0].clientX,oe=me.touches[1].clientY-me.touches[0].clientY,ue=Math.sqrt(de*de+oe*oe)/L.current,te=(me.touches[0].clientX+me.touches[1].clientX)/2,Ne=(me.touches[0].clientY+me.touches[1].clientY)/2,Se=te-_.current.x,Ae=Ne-_.current.y,T=Math.abs(ue-1)>.03;if(H.current==="mouse"){if(T){const xe=Math.max(i,Math.min(5,M.current*ue));x(xe),c.current=xe}else if(Math.abs(Se)>2||Math.abs(Ae)>2){const xe=j.current||{nx:.5,ny:.5},ve=Date.now();ve-g.current>=30&&(g.current=ve,A("Scroll"),N.current("input_wheel",{nx:xe.nx,ny:xe.ny,deltaX:Math.round(-Se*3),deltaY:Math.round(-Ae*3)}).catch(()=>{}))}}else{const xe=Math.max(i,Math.min(5,M.current*ue));x(xe),c.current=xe;const ve=s.current;if(ve&&xe>1){const Q=ve.clientWidth,ye=ve.clientHeight,_e=l.current+Se/Q*100,We=u.current+Ae/ye*100,Pe=f(_e,We,xe);p(Pe.x),d(Pe.y),l.current=Pe.x,u.current=Pe.y}}_.current={x:te,y:Ne}}},le=me=>{var ke;if(y.current&&clearTimeout(y.current),L.current=null,me.touches.length===1&&W.current){const de=me.touches[0];C.current={x:de.clientX,y:de.clientY,time:Date.now()},k.current={x:de.clientX,y:de.clientY},v.current=!0;return}if(me.touches.length===0){if(W.current){W.current=!1,v.current=!1;return}if(me.changedTouches.length===1){const de=me.changedTouches[0],oe=Date.now(),se=oe-(((ke=C.current)==null?void 0:ke.time)||0),ue=C.current?de.clientX-C.current.x:0,te=C.current?de.clientY-C.current.y:0,Ne=Math.sqrt(ue*ue+te*te);if(H.current==="mouse"){if(se<P||se>G||Ne>I){v.current=!1;return}const Se=j.current||Y(de);Se&&(A(`Click: ${Math.round(Se.nx*100)}%, ${Math.round(Se.ny*100)}%`),m(Se.nx,Se.ny,"left"),N.current("input_click",{...Se}).catch(()=>{}))}else{if(v.current){v.current=!1;return}if(se<E||se>B||Ne>U){v.current=!1;return}const Se=Y(de);if(!Se)return;oe-$.current<300?(A("Double tap"),m(Se.nx,Se.ny,"double"),N.current("input_click",{...Se,clickCount:2}).catch(()=>{}),$.current=0):(A(`Tap: ${Math.round(Se.nx*100)}%, ${Math.round(Se.ny*100)}%`),m(Se.nx,Se.ny,"left"),N.current("input_click",{...Se}).catch(()=>{}),$.current=oe)}}v.current=!1}};return be.addEventListener("touchstart",X,{passive:!1}),be.addEventListener("touchmove",ie,{passive:!1}),be.addEventListener("touchend",le,{passive:!1}),()=>{be.removeEventListener("touchstart",X),be.removeEventListener("touchmove",ie),be.removeEventListener("touchend",le),y.current&&clearTimeout(y.current)}},[e,s,r,i,c,l,u,p,d,x,g,A,m,f]),{cursorPos:S,cursorPosRef:j,handleToggleInputMode:()=>{a(be=>{const Y=be==="touch"?"mouse":"touch";return Y==="mouse"&&V(),Y})},handleZoomReset:()=>{const be=b?h:1;x(be),c.current=be,p(0),d(0),l.current=0,u.current=0}}}function oc({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,d]=o.useState(null),[x,g]=o.useState(""),[,w]=o.useState(!1),[A,m]=o.useState([]),f=o.useRef(0),[b,h]=o.useState(!1),[S,R]=o.useState(!1),j=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[C,k]=o.useState(j?"mouse":"touch"),[v,y]=o.useState(1),$=o.useRef(!1),[L,M]=o.useState(1),[_,W]=o.useState(0),[H,N]=o.useState(0);jr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:C,zoom:L,panX:_,panY:H,isMenuOpen:b,isImeOpen:S});const P=o.useRef(0),G=o.useRef(L),I=o.useRef(_),E=o.useRef(H);o.useEffect(()=>{G.current=L},[L]),o.useEffect(()=>{I.current=_},[_]),o.useEffect(()=>{E.current=H},[H]),o.useEffect(()=>{var se;(se=c.current)==null||se.focus()},[]);const B=r==="connected",U=n,V=B?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ae=B?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!j||$.current||!U)return;const se=u.current,ue=l.current;if(!se||!ue)return;const te=()=>{const Ne=ue.clientWidth,Se=ue.clientHeight,Ae=se.naturalWidth,T=se.naturalHeight;if(!Ae||!T||!Ne||!Se)return;const xe=Math.min(Ne/Ae,Se/T),Q=Math.max(Ne/Ae,Se/T)/xe;Q>1.01&&(y(Q),M(Q),G.current=Q),$.current=!0};se.complete&&se.naturalWidth?te():se.addEventListener("load",te,{once:!0})},[U,j]);const we=.5;o.useEffect(()=>{L<=we&&(W(0),N(0))},[L,we]);const be=(se,ue,te)=>{if(te<=we)return{x:0,y:0};const Ne=(te-1)/(2*te)*100,Se=(te-1)/(2*te)*100;return{x:Math.max(-Ne,Math.min(Ne,se)),y:Math.max(-Se,Math.min(Se,ue))}},Y=(se,ue)=>{if(!u.current)return null;const te=u.current.getBoundingClientRect();return!te.width||!te.height?null:{nx:Math.max(0,Math.min(1,(se-te.left)/te.width)),ny:Math.max(0,Math.min(1,(ue-te.top)/te.height))}},he=(se,ue,te)=>{const Ne=l.current;if(!Ne)return;const Se=Ne.getBoundingClientRect(),Ae=++f.current;m(T=>[...T,{id:Ae,x:se-Se.left,y:ue-Se.top,type:te}]),setTimeout(()=>m(T=>T.filter(xe=>xe.id!==Ae)),600)},O=(se,ue,te)=>{const Ne=u.current,Se=l.current;if(!Ne||!Se)return;const Ae=Ne.getBoundingClientRect(),T=Se.getBoundingClientRect(),xe=Ne.naturalWidth||Ae.width,ve=Ne.naturalHeight||Ae.height,Q=xe/ve,ye=Ae.width/Ae.height;let _e,We,Pe,ze;Q>ye?(_e=Ae.width,We=Ae.width/Q,Pe=0,ze=(Ae.height-We)/2):(We=Ae.height,_e=Ae.height*Q,Pe=(Ae.width-_e)/2,ze=0);const Qe=Ae.left-T.left+Pe+_e*se,it=Ae.top-T.top+ze+We*ue,et=++f.current;m(ft=>[...ft,{id:et,x:Qe,y:it,type:te}]),setTimeout(()=>m(ft=>ft.filter(tt=>tt.id!==et)),600)},X=async se=>{var te;const ue=Y(se.clientX,se.clientY);if(ue){d(`Click: ${Math.round(ue.nx*100)}%, ${Math.round(ue.ny*100)}%`),he(se.clientX,se.clientY,"left"),(te=c.current)==null||te.focus();try{const Ne=await e("input_click",{nx:ue.nx,ny:ue.ny});Ne!=null&&Ne.success||s(`❌ Click failed: ${Ne==null?void 0:Ne.error}`)}catch(Ne){s(`❌ Click error: ${Ne.message||Ne}`)}}},ie=async(se,ue,te,Ne=0)=>{try{await e("input_key",{type:te?"char":"keyDown",key:se,code:ue,text:te?se:void 0,unmodifiedText:te?se:void 0,modifiers:Ne})}catch(Se){s(`❌ Key error: ${Se.message||Se}`)}},le=async se=>{if(se.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(se.key)&&se.preventDefault();let te=0;se.altKey&&(te|=1),se.ctrlKey&&(te|=2),se.metaKey&&(te|=4),se.shiftKey&&(te|=8),d(`Key: ${se.key}`),await ie(se.key,se.code,se.key.length===1,te)},me=async se=>{if(se.key==="Enter"){if(se.nativeEvent.isComposing)return;if(x){const ue=x;g(""),d(`IME Sent: ${ue}`);try{const te=await e("input_type",{text:ue});te!=null&&te.success||s(`❌ IME error: ${te==null?void 0:te.error}`)}catch(te){s(`❌ IME error: ${te.message}`)}}else d("Key: Enter"),await ie("Enter","Enter",!1)}};o.useEffect(()=>{const se=c.current;if(!se)return;const ue=te=>{var Ne;if((Ne=u.current)!=null&&Ne.contains(te.target)){te.preventDefault();const Se=Date.now();if(Se-P.current<40)return;P.current=Se;const Ae=Y(te.clientX,te.clientY);if(!Ae)return;d(`Scroll: ${Math.round(te.deltaY)}`),e("input_wheel",{nx:Ae.nx,ny:Ae.ny,deltaX:Math.round(te.deltaX),deltaY:Math.round(te.deltaY)}).catch(()=>{})}};return se.addEventListener("wheel",ue,{passive:!1}),()=>se.removeEventListener("wheel",ue)},[e]);const{cursorPos:ke,handleToggleInputMode:de,handleZoomReset:oe}=Iu({containerRef:c,viewportRef:l,imgRef:u,inputMode:C,setInputMode:k,minZoom:we,zoomRef:G,panXRef:I,panYRef:E,setPanX:W,setPanY:N,setZoom:M,lastWheelTimeRef:P,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:O,clampPan:be,isMobile:j,mobileFillZoom:v});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:le,onContextMenu:se=>se.preventDefault(),onFocus:()=>w(!0),onBlur:()=>w(!1),tabIndex:0,children:[t.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[U?t.jsx("img",{ref:u,src:U,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${L}) translate(${_}%, ${H}%)`,transformOrigin:"center center",cursor:C==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:X,onContextMenu:se=>se.preventDefault(),onDragStart:se=>se.preventDefault()}):t.jsx(Nu,{waitingLabel:V,waitingHint:ae,transportType:i}),C==="mouse"&&U&&t.jsx(ku,{cursorPos:ke,viewportRef:l,imgRef:u}),A.map(se=>{const te={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[se.type];return t.jsxs("div",{style:{position:"absolute",left:se.x,top:se.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${te}, 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(${te}, 0.9)`,boxShadow:`0 0 12px rgba(${te}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},se.id)})]}),t.jsx(Su,{inputMode:C,onToggleInputMode:de,isImeOpen:S,setIsImeOpen:R,isMenuOpen:b,setIsMenuOpen:h,imeText:x,setImeText:g,handleImeSubmit:me,isConnActive:B,zoom:L,isMobile:j,mobileFillZoom:v,onZoomOut:()=>M(se=>Math.max(.5,se-.25)),onZoomReset:oe,onZoomIn:()=>M(se=>Math.min(5,se+.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 Nt(e){return(typeof e=="string"?e.trim():"")||void 0}function Qt(e,s){const r=Nt(s);return r?`${e}:${r}`:void 0}function ss(e,s,r){const n=Qt(s,r),a=Nt(r);n&&e.push(n),a&&e.push(a)}function Ps(e){const s=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),s.push(n));return s}function ic(e){return Nt(e.providerSessionId)||Nt(e.sessionId)||Nt(e.tabKey)||Nt(e.routeId)}function Oa(e){return Ps([Nt(e.providerSessionId),Nt(e.sessionId)])}function rs(e){const s=[];return ss(s,"provider",e.providerSessionId),ss(s,"session",e.sessionId),ss(s,"tab",e.tabKey),ss(s,"route",e.routeId),Ps(s)}function Au(e){const s=[];return Nt(e.providerSessionId)?(ss(s,"provider",e.providerSessionId),Ps(s)):Nt(e.sessionId)?(ss(s,"session",e.sessionId),Ps(s)):Nt(e.tabKey)?(ss(s,"tab",e.tabKey),Ps(s)):Nt(e.routeId)?(ss(s,"route",e.routeId),Ps(s)):[]}function Wa(e){return Qt("provider",e.providerSessionId)||Qt("session",e.sessionId)||Qt("tab",e.tabKey)||Qt("route",e.routeId)||"unknown:"}function kr(e){return Oa(e)[0]}function cc(e){const s=Nt(e.providerSessionId),r=Nt(e.sessionId),n=Nt(e.tabKey),a=Nt(e.routeId),i=[Qt("provider",s),Qt("session",r),Qt("tab",n),Qt("route",a)].filter(u=>typeof u=="string"),c=rs({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),l=Wa({providerSessionId:s,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:s,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:ic({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),historySessionId:kr({providerSessionId:s,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function xr(e,s){const r=cc(e);return Au(s).some(n=>r.lookupKeys.includes(n))}function wn(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 lc=e=>wn(e);function Mu(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden,completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function qs(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 Tu(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...Mu(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 dn(e,s){if(e.sessionId){const r=s.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,completionMarker:"",seenCompletionMarker:""}}function jn(e,s,r){const n=dn(e,s),a=qs(e),i=rs(e).map(A=>{var m;return(m=r==null?void 0:r.notificationStateBySessionId)==null?void 0:m.get(A)}).find(A=>!!A),c=a.isReconnecting,l=a.isConnecting,u=a.isGenerating,p=a.isWaiting,d=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||p,x=n.inboxBucket==="working"||u,w=!!(n.inboxBucket==="task_complete"&&(i?i.unreadCount>0:n.unread)&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:w,requiresAction:d,isWorking:x,isReconnecting:c,isConnecting:l,isGenerating:u,isWaiting:p,inboxBucket:d?"needs_attention":x?"working":w?"task_complete":"idle"}}function Lu(e,s,r){return jn(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation,notificationStateBySessionId:r==null?void 0:r.notificationStateBySessionId}).unread}function dc({activeConv:e,onModalButton:s}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!qs(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(Ss,{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(),d=/^(run|approve|accept|yes|allow|always)/.test(p),x=/^(reject|deny|delete|remove|abort)/.test(p),g=r===l,w=r!==null;return t.jsx("button",{onClick:()=>i(l),disabled:w,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${d?"font-extrabold":x?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${w&&!g?"opacity-40":"opacity-100"} ${w?"cursor-not-allowed":"cursor-pointer"}`,style:d?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:x?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:g?"⏳ ...":c(l)},u)})})]})]})}const Ha="adhdev_controls_bar_visible",xa="adhdev:controlsbarvisibilitychange";function Kn(e){if(!e)return!1;try{return e.getItem(Ha)==="1"}catch{return!1}}function Fo(e,s){if(s)try{s.setItem(Ha,e?"1":"0")}catch{}}function Uo(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(xa,{detail:{visible:e}}))}function uc(){const[e,s]=o.useState(()=>typeof window>"u"?!1:Kn(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(Kn(window.localStorage))},i=c=>{c.key===Ha&&s(Kn(window.localStorage))};return window.addEventListener(xa,a),window.addEventListener("storage",i),()=>{window.removeEventListener(xa,a),window.removeEventListener("storage",i)}},[]);const r=o.useCallback(a=>{s(a),typeof window<"u"&&Fo(a,window.localStorage),Uo(a)},[]),n=o.useCallback(()=>{s(a=>{const i=!a;return typeof window<"u"&&Fo(i,window.localStorage),Uo(i),i})},[]);return{isVisible:e,setVisibility:r,toggleVisibility:n}}var Ru=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function _u(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function St(e,s){if(_u(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":Ru.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 mc(e){return St(e)==="generating"}function dt(e){return e?e.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" "):"IDE"}function Pu(e){if(e<60)return`${Math.round(e)}s`;const s=Math.floor(e/60);if(s<60)return`${s}m`;const r=Math.floor(s/60),n=s%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const a=Math.floor(r/24),i=r%24;return`${a}d ${i}h`}function Bn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function kn(e,s){const r=typeof s=="string"?s.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const a=n.replace(/[\\/]+$/,""),i=a.split(/[\\/]/).filter(Boolean);return i[i.length-1]||a}function Du(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const s=e.split("_"),r=s[s.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function Eu(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function $u(e){return Du(e.trim().replace(/\.local$/i,""))}function Ku(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function fc(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 $u(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function _t(e,s={}){return Ku(e)||fc(e,s)}function pc(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 hc(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 Ns(e,s){return pc(e).join(" · ")}function br(e){return e.transport==="pty"}function Ds(e){return e.transport==="acp"}function Bu(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:dt(e)}function zo(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=dt(r||"").trim().toLowerCase();return n===a||n===i||n===c}function Ou(e){return St(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Wu(e){if(!Array.isArray(e)||e.length<=1)return e;const s=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),i=s.get(a),c=St(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 Hu(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 Fu(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&&Hu(s.receivedAt)||0}function Uu(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ba(e){return Math.max(Uu(e),Fu(e.activeChat))}function zu(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 Fa(e,s){return zu(ba(e),ba(s),_t(e,{fallbackId:e.id}),_t(s,{fallbackId:s.id}),e.id,s.id)}const xc="adhdev_notification_prefs",Vo={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Vu(){try{const e=localStorage.getItem(xc);if(e){const s=JSON.parse(e);return{...Vo,...s}}}catch{}return{...Vo}}function Gu(e){try{localStorage.setItem(xc,JSON.stringify(e))}catch{}}let Jt=Vu(),Zr=[];function qu(){Zr.forEach(e=>e())}function Yu(e){Jt={...Jt,...e},Gu(Jt),qu()}function Xu(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Zr.push(r),()=>{Zr=Zr.filter(n=>n!==r)}},[]);const s=o.useCallback(r=>{Yu(r)},[]);return[{...Jt},s]}function ir(e){if(!Jt.globalEnabled)return!1;switch(e){case"disconnect":return Jt.disconnectAlert;case"completion":return Jt.completionAlert;case"approval":return Jt.approvalAlert;case"browser":return Jt.browserNotifications;default:return!0}}const Ju={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function bc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function gc(){return"Notification"in window&&Notification.permission==="granted"}let ds=null;async function Qu(){if(ds!==null)return ds;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return ds=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(ds=!!await e.pushManager.getSubscription(),ds):(ds=!1,!1)}catch{return ds=!1,!1}}function ga(e,s,r){if(gc())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 Zu(e,s={}){const r={...Ju,...s},n=o.useRef(new Map),a=o.useRef(0),i=o.useRef(null);o.useEffect(()=>{Qu().then(l=>{i.current=l})},[]);const c=o.useCallback((l,u,p)=>{const d=Date.now();d-a.current<r.throttleMs||(a.current=d,ga(l,u,p))},[r.throttleMs]);o.useEffect(()=>{var l;if(!(!r.enabled||!gc())&&ir("browser")&&i.current!==!0){if(document.hasFocus()){for(const u of e)n.current.set(u.id,St(u.status,{activeModal:u.activeModal}));return}for(const u of e){const p=n.current.get(u.id),d=St(u.status,{activeModal:u.activeModal}),x=u.name||u.id;if(r.onApproval&&ir("approval")&&d==="waiting_approval"&&p!=="waiting_approval"){const g=((l=u.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${x} — Approval needed`,g.slice(0,120),`approval-${u.id}`)}r.onComplete&&ir("completion")&&mc(p)&&d==="idle"&&c(`✅ ${x} — Task complete`,"Agent has finished generating",`complete-${u.id}`),r.onError&&d==="error"&&p!=="error"&&c(`⚠️ ${x} — Error`,"Agent encountered an error",`error-${u.id}`),n.current.set(u.id,d)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const em=/^(run|approve|accept|yes|allow|always)/,tm=/^(run|approve|accept|yes|allow|always|proceed|save)/,sm=/^(reject|deny|delete|remove|abort|cancel|no)/;function Ua(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function rm(e){const s=Ua(e).toLowerCase();return em.test(s)?"primary":sm.test(s)?"danger":"default"}function nm(e){return tm.test(Ua(e).toLowerCase())?"approve":"reject"}function am(e){return e.map((s,r)=>({label:Ua(s),variant:rm(s),action:nm(s),button:s,buttonIndex:r}))}function om(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 im(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function cm(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 lm{constructor(){Ye(this,"dedupMap",new Map);Ye(this,"DEDUP_WINDOW_MS",5e3);Ye(this,"DEDUP_MAX_SIZE",50);Ye(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ye(this,"toastCallbacks",[]);Ye(this,"systemMessageCallbacks",[]);Ye(this,"clearSystemMessageCallbacks",[]);Ye(this,"resolveActionFn",null);Ye(this,"viewRequestRespondFn",null);Ye(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,m;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 d=dt(p);const x=this.resolveOwningDaemon(s);if(x){const f=_t(x,{fallbackId:x.id});f&&(d=!p||p==="adhdev-daemon"?f:`${f}/${d}`)}let g="",w="info";if(s.event==="agent:generating_completed"){const f=s.duration?` (${s.duration}s)`:"";g=`✅ ${d} agent task completed${f}`,w="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(s.event!=="agent:generating_started")if(s.event==="agent:waiting_approval"){if(g=`⚡ ${d} approval needed`,w="warning",n&&!((A=s.modalButtons)!=null&&A.length)&&this.emitSystemMessage(n,{role:"system",timestamp:a,content:om(s.modalMessage,s.modalButtons),_localId:`sys_approval_${a}`}),(m=s.modalButtons)!=null&&m.length&&this.resolveActionFn){const f=this.resolveActionRouteTarget(s);if(!f)return;const b=this.resolveActionFn,h=am(s.modalButtons).map(j=>({label:j.label,variant:j.variant,onClick:()=>{b(f,"resolve_action",{action:j.action,button:j.button,buttonIndex:j.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),S=im(d,s.modalMessage,g),R=Date.now();this.emitToast({id:R,message:S,type:w,timestamp:R,targetKey:n||f,actions:h,duration:15e3}),g=""}}else if(s.event==="monitor:long_generating"){const f=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";g=`⚠️ ${d} agent is taking a long time${f}`,w="warning",ir("browser")&&!document.hasFocus()&&ga(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${f.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const f=s.requesterName||"A team member",b=s.requestId,h=s.orgId;if(g=`👁️ ${f} wants to view your session`,w="warning",b&&h&&this.viewRequestRespondFn){const S=Date.now(),R=cm(h,b,this.viewRequestRespondFn,(j,C)=>console.error(`[EventManager] ${j} view request failed:`,C));this.emitToast({id:S,message:g,type:w,timestamp:S,actions:R,duration:3e4}),g=""}ir("browser")&&!document.hasFocus()&&ga("👁️ View Request",`${f} wants to view your session`,`view-request-${b}`)}else s.event==="team:view_request_approved"?(g="✅ View request approved",w="success"):s.event==="team:view_request_rejected"&&(g=`❌ ${s.targetName||"Team member"} declined your view request`,w="warning");if(g){const f=Date.now();this.emitToast({id:f,message:g,type:w,timestamp:f,targetKey:n||s.daemonId,duration:5e3})}}}const at=new lm,Go=new Map;function Ws(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Es(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function dm(e){return!Ws(e)||!Ws(e.controlResult)||!Array.isArray(e.controlResult.options)?null:e.controlResult}function Er(e){return!Ws(e)||!Ws(e.controlResult)||typeof e.controlResult.ok!="boolean"?null:e.controlResult}function Qs(e){if(!(!Ws(e)||typeof e.error!="string"||!e.error.trim()))return e.error}function $r(e){return Ws(e)&&e.success===!1}function um(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";at.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";at.showToast(n.notification.body,a)}}}function mm(e,s){return e&&Es(e.currentValue)?e.currentValue:s}function fm(e,s){return Es(s)?Es(e)?typeof e=="string"&&e.trim()==="":!0:!1}function pm(e,s){var i,c;if((s.now??Date.now())<s.localOverrideUntil){const l=s.localValues[e];if(Es(l))return l}const n=(i=s.controlValues)==null?void 0:i[e];if(Es(n))return n;const a=(c=s.defaultValues)==null?void 0:c[e];return Es(a)?a:void 0}function en(e,s){return e.options||s[e.id]||[]}const hm={antigravity:new Set(["new_session"]),"claude-cli":new Set(["compact","new_session"]),"claude-code-vscode":new Set(["new_session"]),codex:new Set(["new_session"])};function xm(e,s,r){var n;return((n=hm[s])==null?void 0:n.has(r.id))===!0}function za(e,s){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!xm(s.hostIdeType,s.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function On(e,s){return{value:s}}function bm(e,s,r){var a;return r?((a=en(e,s).find(i=>i.value===r))==null?void 0:a.label)||r:""}const gm={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function ym({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=Lt(),u=`${e}:${s||n}`,p=gm[n]||"#94a3b8",[d,x]=o.useState({}),g=o.useRef({}),w=o.useRef(c);g.current=d,w.current=c;const A=o.useRef(0),m={};for(const P of i||[])P.defaultValue!==void 0&&(m[P.id]=P.defaultValue);const f={...m,...c||{},...Date.now()<A.current?d:{}};o.useEffect(()=>{c&&Date.now()>A.current&&x({})},[c]);const[b,h]=o.useState(Go.get(u)||{}),[S,R]=o.useState(null),[j,C]=o.useState(null),k=o.useCallback(async(P,G={})=>{const I={...G,...s&&{targetSessionId:s}};return await l(e,P,I)},[e,s,l]),v=o.useCallback(async(P,G={})=>{const I=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await k("invoke_provider_script",{...I,scriptName:P,...G})},[k,n,r,s]),y=o.useCallback((P,G,I)=>{const E=mm(I,G);x(B=>({...B,[P.id]:E})),um(I==null?void 0:I.effects)},[]),$=o.useCallback((P,G)=>{x(I=>{const E={...I};return G===void 0?delete E[P.id]:E[P.id]=G,E}),A.current=0},[]);if(!i||i.length===0)return null;const L=za(i,{hostIdeType:r,providerType:n});if(L.length===0)return null;const M=async P=>{if(S===P.id){R(null);return}if(en(P,b).length>0){R(P.id);return}if(P.dynamic&&P.listScript){C(P.id);try{const I=await v(P.listScript,{}),E=dm(I);if(!E){const V=Qs(I);V&&at.showToast(V,"warning");return}const B=E.options;h(V=>{const ae={...V,[P.id]:B};return Go.set(u,ae),ae});const U=pm(P.id,{localOverrideUntil:A.current,localValues:g.current,controlValues:w.current,defaultValues:m});if(fm(U,E.currentValue)){const V=E.currentValue;x(ae=>({...ae,[P.id]:V}))}R(P.id)}catch(I){const E=I instanceof Error?I.message:`Could not load ${P.label}`;at.showToast(E,"warning")}finally{C(null)}}},_=async(P,G)=>{R(null);const I=(c==null?void 0:c[P.id])??m[P.id];x(E=>({...E,[P.id]:G})),A.current=Date.now()+5e3;try{if(!P.setScript)return;const E=await v(P.setScript,On(P,G)),B=Er(E);if(B&&!B.ok||$r(E))throw new Error((B==null?void 0:B.error)||Qs(E)||`Could not update ${P.label}`);y(P,G,B)}catch(E){$(P,I);const B=E instanceof Error?E.message:`Could not update ${P.label}`;at.showToast(B,"warning")}},W=async P=>{const G=en(P,b).map(ae=>ae.value);if(G.length===0)return;const I=String(f[P.id]||""),B=(G.indexOf(I)+1)%G.length,U=G[B];if(typeof U!="string")return;const V=(c==null?void 0:c[P.id])??m[P.id];x(ae=>({...ae,[P.id]:U})),A.current=Date.now()+5e3;try{if(!P.setScript)return;const ae=await v(P.setScript,On(P,U)),we=Er(ae);if(we&&!we.ok||$r(ae))throw new Error((we==null?void 0:we.error)||Qs(ae)||`Could not update ${P.label}`);y(P,U,we)}catch(ae){$(P,V);const we=ae instanceof Error?ae.message:`Could not update ${P.label}`;at.showToast(we,"warning")}},H=async P=>{const I=!f[P.id],E=(c==null?void 0:c[P.id])??m[P.id];x(B=>({...B,[P.id]:I})),A.current=Date.now()+5e3;try{if(!P.setScript)return;const B=await v(P.setScript,On(P,I)),U=Er(B);if(U&&!U.ok||$r(B))throw new Error((U==null?void 0:U.error)||Qs(B)||`Could not update ${P.label}`);y(P,I,U)}catch(B){$(P,E);const U=B instanceof Error?B.message:`Could not update ${P.label}`;at.showToast(U,"warning")}},N=async P=>{if(!P.invokeScript)return;if(P.confirmMessage){const I=[P.confirmTitle,P.confirmMessage,P.confirmLabel].filter(B=>typeof B=="string"&&B.trim().length>0);if(!window.confirm(I.join(`
29
-
30
- `)))return}const G=(c==null?void 0:c[P.id])??m[P.id];try{const I=await v(P.invokeScript),E=Er(I);if(E&&!E.ok||$r(I))throw new Error((E==null?void 0:E.error)||Qs(I)||`Could not run ${P.label}`);E&&y(P,G??!0,E)}catch(I){$(P,G);const E=I instanceof Error?I.message:`Could not run ${P.label}`;at.showToast(E,"warning")}};return t.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${p}33`,background:`${p}12`,color:p},children:a}),L.map(P=>{const G=String(f[P.id]||""),I=bm(P,b,G),E=S===P.id,B=j===P.id,U=en(P,b),V="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium transition-colors whitespace-nowrap";switch(P.type){case"select":return t.jsxs("div",{className:"relative max-w-full",children:[t.jsxs("button",{type:"button",className:`${V} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:E?`${p}55`:"var(--border-default)",background:E?`${p}10`:"var(--surface-tertiary)",color:G?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void M(P),title:P.label,children:[P.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:P.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:B?"Loading…":I||P.label}),t.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),E&&U.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>R(null)}),t.jsxs("div",{className:"absolute bottom-full left-0 z-[60] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[t.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:P.label}),U.map(ae=>t.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-[12px] transition-colors",style:{background:ae.value===G?`${p}14`:"transparent",color:ae.value===G?"var(--text-primary)":"var(--text-secondary)",borderLeft:ae.value===G?`2px solid ${p}`:"2px solid transparent"},title:ae.description||ae.label,onMouseEnter:we=>{we.currentTarget.style.background=`${p}10`},onMouseLeave:we=>{we.currentTarget.style.background=ae.value===G?`${p}14`:"transparent"},onClick:()=>void _(P,ae.value),children:[t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ae.label}),ae.value===G&&t.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:p},children:"✓"})]},ae.value))]})]})]},P.id);case"cycle":return t.jsxs("button",{type:"button",className:`${V} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:G?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void W(P),title:`Click to cycle: ${U.map(ae=>ae.label).join(" → ")}`,children:[P.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:P.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:I||P.label}),t.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},P.id);case"toggle":return t.jsxs("button",{type:"button",className:`${V} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:G?`${p}44`:"var(--border-default)",background:G?`${p}14`:"var(--surface-tertiary)",color:G?p:"var(--text-muted)"},onClick:()=>void H(P),"aria-pressed":!!G,children:[P.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:P.icon}),P.label]},P.id);case"action":return t.jsxs("button",{type:"button",className:`${V} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void N(P),children:[P.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:P.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:P.resultDisplay==="inline"&&G?`${P.label}: ${G}`:P.label})]},P.id);case"display":return t.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:G?"var(--text-primary)":"var(--text-muted)"},children:[P.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:P.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:G?`${P.label}: ${G}`:P.label})]},P.id);default:return null}})]})})}function vm({isActive:e=!0,isCliTerminal:s=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:p}=uc(),d=za(l,{hostIdeType:a,providerType:i});return!e||s||d.length===0||!p?null:t.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:t.jsx(ym,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:d,controlValues:u})})}function wm({hasDraft:e,isBusy:s=!1}){return!e||s}const yc=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),[d,x]=o.useState(""),{isVisible:g,toggleVisibility:w}=uc();o.useEffect(()=>{x("")},[s]),o.useEffect(()=>{var m;l&&((m=p.current)==null||m.focus())},[s,l]);const A=async()=>{const m=d.trim();if(!m||a)return;await c(m)!==!1&&x("")};return t.jsxs("div",{className:"dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden transition-all duration-200 ease-out",style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[t.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[u&&t.jsx("button",{type:"button",onClick:w,"aria-label":g?"Hide controls":"Show controls","aria-pressed":g,title:g?"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:d,onChange:m=>x(m.target.value),onPaste:m=>{const f=m.clipboardData.getData("text");f&&x(b=>b+f),m.preventDefault()},onKeyDown:m=>{if(m.key==="Enter"){if(m.nativeEvent.isComposing){m.preventDefault();return}m.preventDefault(),A()}},onBlur:m=>{if(window.innerWidth<768){const f=m.relatedTarget;if((f==null?void 0:f.tagName)==="BUTTON")return;setTimeout(()=>{document.documentElement.scrollTop=0},300)}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:()=>{A()},disabled:wm({hasDraft:!!d.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${d.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:d.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:d.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),i&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),nt=e=>e.transport==="pty",Hs=(e,s)=>nt(e)?e.mode||"terminal":"chat",vc=(e,s)=>nt(e)&&Hs(e)==="terminal",Ze=e=>e.transport==="acp";function ns(e){return e.streamSource!=="agent-stream"}function cs(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function wc(e){return e.machineName||""}function Sr(e){return cs(e)}function Wt(e){return e.agentType||""}function un(e){return e.hostIdeType||""}function Va(e){return e.displayPrimary||e.agentName||"Agent"}function jc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function jm(e){return e.lastMessagePreview||e.displaySecondary||""}function kc(e){return[e.displaySecondary,wc(e)].filter(Boolean)}function Fs(e){return e.agentName||dt(Wt(e))}function km(e){var s,r;if(!ns(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return dt(un(e)||Wt(e))}function Sc(e){return ns(e)?e.sessionId:e.nativeSessionId}function qo(e){return ns(e)?"native":e.tabKey}function Sm(e){return e.sessionId}function Nm(e,s){if(s)return ns(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function Cm(e,s){const r=Wt(e),n=ns(e),a=nt(e)||Ze(e),i=n?a?Fs(e)||(s==null?void 0:s.cliName)||dt(un(e)||r):s!=null&&s.type?dt(s.type):dt(un(e)||r):Fs(e);return{isNativeConversation:n,isCli:nt(e),isAcp:Ze(e),isCliTerminal:vc(e),providerType:r,displayLabel:i,targetEntry:Nm(e,s)}}function Im(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function ps(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||Im(s==null?void 0:s.receivedAt)||0}function ya(e,s=0){return ps(e)||e.lastUpdated||s||0}function Nc(e){return ps(e)||e.lastUpdated||0}function Cc(e,s,r=Nc){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 va(e){var r;const s=St(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function Am(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!va(e)&&!e.title.trim()}function Mm(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(va(r))-Number(va(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:Cc(s,r)})[0]||null}function Ft(e,s){const r=e.filter(c=>c.routeId===s);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,a=r.filter(c=>c.streamSource==="agent-stream"),i=Mm(a);return n?i&&Am(n)?i:n:i||r[0]||null}function as(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ga(e){return kr(e)||e.tabKey||e.routeId||null}function Ic(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=Ft(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?Ga(a):null}function Ac({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Vs(),c=cs(e),l=wc(e),u=e.transport==="cdp-page"||e.transport==="cdp-webview",p=e.streamSource==="agent-stream"&&!!e.agentName,d=!p&&(e.transport==="pty"||e.transport==="acp"),x=Fs(e),g=km(e),w=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),A=o.useCallback(()=>{if(r){r();return}const m=Ga(e);m&&i(as(m))},[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:g,children:[t.jsx(Pt,{size:12}),t.jsx("span",{children:g})]}):t.jsxs("span",{className:"conversation-meta-chip",title:g,children:[t.jsx(Pt,{size:12}),t.jsx("span",{children:g})]})),p&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[t.jsx(hr,{size:12}),t.jsx("span",{children:x})]}),d&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[t.jsx(hr,{size:12}),t.jsx("span",{children:x})]}),l&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:w,title:l,children:[t.jsx(Zt,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(Zt,{size:12}),t.jsx("span",{children:l})]}))]})}function Wn(e,s){return`${e}:${s}`}function Tm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Kr(e,s){Tm()&&console.debug(`[subscription-manager] ${e}`,s)}class Lm{constructor(){Ye(this,"active",new Map)}subscribe(s,r,n,a){var p;const i=Wn(n.topic,n.key),c=this.active.get(i);let l=!0;if(c)c.handlers.add(a),c.lastUpdate&&a(c.lastUpdate);else{const d={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,d),Kr("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 g;const d=this.active.get(i);if(!d||(d.handlers.delete(a),d.handlers.size>0))return;this.active.delete(i);const x={type:"unsubscribe",topic:n.topic,key:n.key};Kr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(g=s.sendData)==null||g.call(s,r,x)};return u.initialSendAccepted=l,u}publish(s){const r=Wn(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,Bs.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),Bs.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=Wn(s,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(s){var r;Kr("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);Kr("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 os=new Lm;function Rm(e,s){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===s&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,mode:n.mode,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash,completionMarker:n.completionMarker,seenCompletionMarker:n.seenCompletionMarker});for(const i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const c=r.get(i.id)||{};r.set(i.id,{...c,...i})}}return r}function _m(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 mn(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:d}=_m(u),x=Rm(i,n),g=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,w=p.filter(f=>f.kind==="workspace"&&f.transport==="cdp-page"),A=p.filter(f=>f.kind==="agent"&&f.transport==="pty"),m=p.filter(f=>f.kind==="agent"&&f.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...g&&{machine:g,platform:g.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},cdpConnected:w.some(f=>!!f.cdpConnected)});for(const f of w){const b=x.get(f.id),h=ar(f,b),S=(d.get(f.id)||[]).map(R=>ar(R,x.get(R.id)));r.push({id:`${n}:ide:${f.id}`,sessionId:f.id,providerSessionId:f.providerSessionId??(b==null?void 0:b.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,status:h.cdpConnected?"online":"detected",daemonId:n,instanceId:f.id,workspace:h.workspace,terminals:0,childSessions:S,agents:S.map(R=>({id:R.id,name:R.providerName||R.providerType,type:R.providerType,status:R.status})),activeChat:h.activeChat,chats:[],cdpConnected:h.cdpConnected,...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l})}for(const f of A){const b=x.get(f.id),h=ar(f,b);r.push({id:`${n}:cli:${f.id}`,sessionId:f.id,providerSessionId:f.providerSessionId??(b==null?void 0:b.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:f.id,cliName:h.providerName||h.providerType,mode:h.mode||(b==null?void 0:b.mode)||"terminal",workspace:h.workspace||"",activeChat:h.activeChat,...h.resume!==void 0&&{resume:h.resume},...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l,_isCli:!0})}for(const f of m){const b=x.get(f.id),h=ar(f,b);r.push({id:`${n}:acp:${f.id}`,sessionId:f.id,providerSessionId:f.providerSessionId??(b==null?void 0:b.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:f.id,cliName:h.providerName||h.providerType,mode:"chat",workspace:h.workspace||"",activeChat:h.activeChat,...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const Pm=15e3,Dm=15e3,Em=6e4,$m=1200,Yo=12,Km=8e3,Bm=4e3,Hn=new Map,Fn=new Map,Br=new Set,cr=new Map;function Om(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 Xo(e,s){const r=cr.get(e);!r||r.size===0||(cr.delete(e),r.forEach(n=>n(s)))}function Wm(e,s){return new Promise(r=>{const n=cr.get(e)||new Set;cr.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&cr.delete(e),r(c)},i=setTimeout(()=>a(!1),s);n.add(a)})}function Nr(){const{sendCommand:e,sendData:s}=Lt(),{injectEntries:r,getIdes:n}=pr();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??Em,l=Fn.get(a)||0;if(!(i!=null&&i.force)&&Br.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=Hn.get(a);if(u)return u;const p=(async()=>{if(s&&!Br.has(a)){const m=os.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},f=>{const b=n(),h=b.find(R=>R.id===a),S=mn(f.status,{daemonId:a,existingDaemon:h,existingEntries:b,timestamp:f.timestamp});S.length>0&&r(S),Fn.set(a,Date.now()),Xo(a,!0)});if(m.initialSendAccepted?Br.add(a):Br.delete(a),!(i!=null&&i.force)&&m.initialSendAccepted&&await Wm(a,$m))return}const d=await e(a,"get_status_metadata"),x=Om(d);if(!x)return;const g=n(),w=g.find(m=>m.id===a),A=mn(x,{daemonId:a,existingDaemon:w,existingEntries:g,timestamp:x.timestamp||Date.now()});A.length>0&&r(A,{authoritativeDaemonIds:[a]}),Fn.set(a,Date.now()),Xo(a,!0)})().finally(()=>{Hn.delete(a)});return Hn.set(a,p),p},[n,r,e,s])}function qt(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function qa(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=is(e.content),i=is(s.content);if(!a||!i||!(a===i||gr(a,i)||gr(i,a)))return!1;const l=qt(e),u=qt(s);return l&&u?Math.abs(l-u)<=15e3:!!e._localId!=!!s._localId}function Jo(e){let s=0;return e!=null&&e._localId||(s+=4),e!=null&&e.id&&(s+=3),e!=null&&e._turnKey&&(s+=2),qt(e)&&(s+=1),s}function Cs(e){return is(e==null?void 0:e.content)}function gr(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 Hm(e,s){const r=Cs(e),n=Cs(s);return!r||!n||r===n?null:gr(r,n)?e:gr(n,r)?s:null}function Fm(e,s){const r=Hm(e,s);if(r)return r;const n=Jo(e),a=Jo(s);return a!==n?a>n?s:e:Cs(s).length>=Cs(e).length?s:e}function Um(e){return!!e&&!!(e.id||e._localId||e._turnKey)}function lr(e){if(!e)return[];const s=[],r=l=>{l&&s.push(l)};e.id&&r(`id:${String(e.id)}`),e._localId&&r(`local:${String(e._localId)}`),e._turnKey&&r(`turn:${String(e._turnKey)}`);const n=String(e.role||"").toLowerCase(),a=Cs(e),i=qt(e),c=i?Math.round(i/15e3):0;return n&&a&&(r(`content:${n}:${a}`),r(`preview:${n}:${a.slice(0,120)}:${c}`)),s}function hs(e,s=qa){const r=[],n=new Map,a=(c,l)=>{for(const u of lr(c)){const p=n.get(u);p?p.push(l):n.set(u,[l])}},i=(c,l)=>{for(const u of lr(c)){const p=n.get(u);if(!p)continue;const d=p.filter(x=>x!==l);d.length>0?n.set(u,d):n.delete(u)}};for(const c of e){const l=new Set;for(const d of lr(c)){const x=n.get(d);x&&x.forEach(g=>l.add(g))}const u=l.size>0?Array.from(l).sort((d,x)=>d-x).find(d=>s(r[d],c)):Um(c)?-1:r.findIndex(d=>s(d,c));if(u!==void 0&&u>=0){const d=Fm(r[u],c);d!==r[u]&&(i(r[u],u),r.splice(u,1,d),a(d,u));continue}const p=r.length;r.push(c),a(c,p)}return r}function zm(e,s){const r=Array.isArray(e)?e:[],n=Array.isArray(s)?s:[];return r.length===0?n:n.length===0?r:hs([...r,...n])}function Qo(e){return[...e].sort((s,r)=>{const n=qt(s),a=qt(r);return n&&a&&n!==a?n-a:0})}function Zo(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=>qa(i,n));return a>=0?(r.splice(a,1),!1):!0})}function Vm(e,s,r=qa){const n=new Map,a=i=>{for(const c of lr(i)){const l=n.get(c);l?l.push(i):n.set(c,[i])}};return s.forEach(a),e.filter(i=>{const c=Cs(i),l=String((i==null?void 0:i.role)||"").toLowerCase(),u=qt(i),p=new Set;for(const x of lr(i)){const g=n.get(x);g&&g.forEach(w=>p.add(w))}return!(p.size>0?Array.from(p):s).some(x=>{if(r(i,x))return!0;const g=String((x==null?void 0:x.role)||"").toLowerCase();if(!c||!l||l!==g)return!1;const w=Cs(x);if(!gr(w,c)&&w!==c)return!1;const A=qt(x);return u&&A?Math.abs(u-A)<=15e3:!0})})}function $s(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:nt(e)||Ze(e)?{agentType:Wt(e)}:e.streamSource==="agent-stream"?{agentType:Wt(e)}:s}function yr(e){return e?Sr(e):""}function Zs(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Ya(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 Gm(e){const s=e instanceof Error?e.message:String(e||""),r=s.toLowerCase();return r.includes("still processing the previous prompt")?"Wait for the current reply to finish before sending another message.":r.includes("awaiting confirmation")?"Resolve the pending approval prompt before sending another message.":r.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":r.includes("not running")?"Runtime is not available right now.":s||"Unable to send message right now."}const qm=60,Ym=1e3;function Mc(e={}){return e.isCliLike?Ym:qm}function Xm(e={}){return Mc(e)}const Cr=60,Jm=1e3,Xa=12e4,Qm=new Set(["generating","waiting_approval","starting","streaming","working"]),ei=new Map;function Tc(e,s){return`${e}::${s}`}function wa(e=Cr){return{liveMessages:[],cursor:Rc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Lc(e){return Xi(e)}function Rc(e,s=Cr){return{knownMessageCount:e.length,lastMessageSignature:Lc(e[e.length-1]),tailLimit:s}}function Or(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 Zm(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return hs([...e,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return hs([...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 hs([...e.slice(0,a),...r])}return r}default:return r}}class ef{constructor(s){Ye(this,"manager");Ye(this,"sendData");Ye(this,"daemonId");Ye(this,"sessionId");Ye(this,"historySessionId");Ye(this,"subscriptionKey");Ye(this,"snapshot");Ye(this,"transportSubscription",null);Ye(this,"listeners",new Set);Ye(this,"retainCount",0);Ye(this,"loadHistoryPromise",null);Ye(this,"pendingDisconnectTimer",null);Ye(this,"pendingSubscribeRetryTimer",null);this.manager=s.manager||os,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.snapshot=wa(Math.max(0,s.tailLimit??Cr))}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=hs([...r,...this.snapshot.liveMessages]);if(n.length<r.length)return;const a=Rc(n,this.snapshot.cursor.tailLimit);Or(this.snapshot.liveMessages)===Or(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a},this.emit())}subscribe(s){return this.listeners.add(s),s(this.snapshot),()=>{this.listeners.delete(s)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(s){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await s(),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},knownMessageCount:this.snapshot.cursor.knownMessageCount,lastMessageSignature:this.snapshot.cursor.lastMessageSignature,...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}clearPendingSubscribeRetry(){this.pendingSubscribeRetryTimer&&(clearTimeout(this.pendingSubscribeRetryTimer),this.pendingSubscribeRetryTimer=null)}scheduleSubscribeRetry(){this.pendingSubscribeRetryTimer||!this.sendData||!this.daemonId||!this.sessionId||this.retainCount===0||(this.pendingSubscribeRetryTimer=setTimeout(()=>{if(this.pendingSubscribeRetryTimer=null,!this.sendData||!this.daemonId||!this.sessionId||this.retainCount===0)return;this.sendData(this.daemonId,this.buildSubscribeRequest())||this.scheduleSubscribeRetry()},Jm))}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),s=>{this.handleUpdate(s)}),this.transportSubscription.initialSendAccepted||this.scheduleSubscribeRetry())}disconnect(){var s;this.clearPendingSubscribeRetry(),(s=this.transportSubscription)==null||s.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(s=>s(this.snapshot))}handleUpdate(s){this.clearPendingSubscribeRetry();const r=Zm(this.snapshot.liveMessages,s),n={knownMessageCount:r.length,lastMessageSignature:typeof s.lastMessageSignature=="string"?s.lastMessageSignature:Lc(r[r.length-1]),tailLimit:this.snapshot.cursor.tailLimit};Or(this.snapshot.liveMessages)===Or(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 _c(e){const s=Tc(e.daemonId,e.sessionId),r=ei.get(s);if(r)return r.updateOptions(e),r;const n=new ef(e);return ei.set(s,n),n}function tf(e,s){return{...e,loadHistoryPage:s}}function sf(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function rf(e,s={}){const r=String(e.status||"").trim().toLowerCase();if(Qm.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??Xa)),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 nf(e=Xa){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function af(e,s={}){const r=new Set,n=[];for(const a of e){if(!rf(a,s))continue;const i=Sr(a),c=a.sessionId||"";if(!i||!c)continue;const l=Tc(i,c);if(r.has(l))continue;r.add(l);const u=kr(a);n.push({daemonId:i,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(sf),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function of(e,s){const{sendData:r,sendCommand:n}=Lt(),a=(s==null?void 0:s.enabled)!==!1,i=Sr(e),c=e.sessionId||"",l=kr(e)||c,u=`daemon:${i}:session:${c}`,p=Math.max(0,(s==null?void 0:s.tailLimit)??Cr),d=o.useMemo(()=>!a||!i||!c?null:_c({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:p}),[i,a,l,r,c,u,p]),[x,g]=o.useState(()=>(d==null?void 0:d.getSnapshot())||wa(p));o.useEffect(()=>{if(!d){g(wa(p));return}d.retain(),g(d.getSnapshot());const A=d.subscribe(m=>{g(m)});return()=>{A(),d.release()}},[d,p]),o.useEffect(()=>{d&&(d.hydrateLiveMessages(e.messages),g(d.getSnapshot()))},[e.messages,d]);const w=o.useCallback(async()=>{!d||!i||!c||await d.loadHistoryPage(async()=>{const A=e.agentType,m=await n(i,"chat_history",{agentType:A,offset:d.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),f=m&&typeof m=="object"&&"result"in m?m.result||{}:m||{};return{messages:Array.isArray(f.messages)?f.messages:[],hasMore:f.hasMore===!0}})},[e.agentType,d,i,l,n,c]);return o.useMemo(()=>tf(x,w),[w,x])}function cf(e,s){const{sendData:r}=Lt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,(s==null?void 0:s.tailLimit)??Cr),i=Math.max(0,Number((s==null?void 0:s.recentActivityMs)??Xa)),c=nf(i),[l,u]=o.useState(0);o.useEffect(()=>{if(!n||e.length===0)return;const d=setInterval(()=>{u(x=>x+1)},c);return()=>{clearInterval(d)}},[e.length,n,c]);const p=o.useMemo(()=>af(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||p.descriptors.length===0)return;const d=p.descriptors.map(x=>_c({...x,sendData:r,tailLimit:a}));return d.forEach(x=>x.retain()),()=>{d.forEach(x=>x.release())}},[p.signature,n,r,a])}function lf(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function df(e){return lf(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const uf=60;function ja({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:p=!1,scrollToBottomRequestNonce:d,isInputActive:x=!0}){var we,be,Y,he,O;const g=o.useRef(new Map),w=Nr();jr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const A=lt.useMemo(()=>qs(e),[e.status,e.connectionState]),m=o.useMemo(()=>Cm(e,s),[e,s]),f=o.useMemo(()=>{var X;return za((X=m.targetEntry)==null?void 0:X.providerControls,{hostIdeType:e.hostIdeType,providerType:m.providerType})},[e.hostIdeType,m.providerType,(we=m.targetEntry)==null?void 0:we.providerControls]),b=Mc({isCliLike:m.isCli||m.isAcp}),h=Xm({isCliLike:m.isCli||m.isAcp}),S=of(e,{enabled:!!e.sessionId,tailLimit:h}),[R,j]=o.useState(b),C=e.tabKey,k=S.historyMessages,v=S.hasMoreHistory,y=S.historyError,$=zm(S.liveMessages,e.messages);o.useEffect(()=>{j(b)},[b,C]);const L=Math.max(0,$.length-R),M=Va(e),_=Sr(e),W=df(e),H=Ya(e),N=a||H,P=!!H,[G,I]=o.useState(!1);o.useEffect(()=>{const X=m.targetEntry;_&&(!X||X.providerControls===void 0||X.controlValues===void 0)&&w(_,{minFreshMs:3e4}).catch(()=>{})},[_,m.isAcp,(be=m.targetEntry)==null?void 0:be.providerControls,(Y=m.targetEntry)==null?void 0:Y.controlValues,w]);const E=o.useCallback(async()=>{if(!G){if($.length>R){j(X=>Math.min($.length,X+uf));return}I(!0);try{await S.loadHistoryPage()}finally{I(!1)}}},[S,G,$.length,R]),{allMessages:B,receivedAtMap:U}=o.useMemo(()=>{const X=L>0?$.slice(-R):$;if(k.length===0){const ke=Qo(hs(X)),de={};return ke.forEach((oe,se)=>{const ue=`${e.tabKey}:${_s(oe,se)}`;let te=qt(oe)||g.current.get(ue)||0;te||(te=Date.now(),g.current.set(ue,te)),de[_s(oe,se)]=te}),{allMessages:ke,receivedAtMap:de}}const ie=Vm(k,X),le=Qo(hs([...ie,...X])),me={};return le.forEach((ke,de)=>{const oe=`${e.tabKey}:${_s(ke,de)}`;let se=qt(ke)||g.current.get(oe)||0;se||(se=Date.now(),g.current.set(oe,se)),me[_s(ke,de)]=se}),{allMessages:le,receivedAtMap:me}},[e.tabKey,L,k,$,R]),V=o.useMemo(()=>l.filter(X=>X.routeId===e.tabKey).sort((X,ie)=>X.timestamp-ie.timestamp),[l,e.tabKey]),ae=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")&&I(!1),e.status==="not_monitored"&&W)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(hr,{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(Os,{size:14})," Open ",M," 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"&&W)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(ec,{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(Os,{size:14})," Open ",M," 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"&&!G)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,W,i,c,G,$.length,M,A.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[p&&t.jsx(Ac,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(yu,{messages:B,actionLogs:V,agentName:Fs(e)||M||"Agent",userName:u,isCliMode:m.isCli||m.isAcp,isWorking:A.isGenerating,contextKey:e.tabKey,receivedAtMap:U,onLoadMore:E,isLoadingMore:G,hasMoreHistory:v,hiddenLiveCount:L,loadError:y??void 0,emptyState:ae,scrollToBottomRequestNonce:d}),t.jsx(vm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:m.providerType,displayLabel:m.displayLabel,controls:(he=m.targetEntry)==null?void 0:he.providerControls,controlValues:(O=m.targetEntry)==null?void 0:O.controlValues,isActive:x,isCliTerminal:m.isCliTerminal}),!m.isCliTerminal&&t.jsx(yc,{contextKey:e.tabKey,panelLabel:M,isSending:n,isBusy:P,statusMessage:N,onSend:r,isActive:x,showControlsToggle:f.length>0})]})}let Pc=ks;function Dc(){return Pc()}class mf{constructor(){Ye(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 Ec=new mf;class ff{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 rt=new ff;function pf(e){e.dashboardWS&&(Ec=e.dashboardWS),e.connectionManager&&(rt=e.connectionManager),e.useDaemonsHook&&(Pc=e.useDaemonsHook)}const $c=.6,Kc=1.15;function ti(e,s,r){return Math.min(r,Math.max(s,e))}function hf(e,s,r={}){const n=typeof r.minScale=="number"?r.minScale:$c,a=typeof r.maxScale=="number"?r.maxScale:Kc;if(!Number.isFinite(e)||e<=0||!Number.isFinite(s)||s<=0)return 1;if(e<=480){const l=s/760;return Number(ti(l,n,.82).toFixed(2))}const i=e/960,c=s/720;return Number(ti(Math.min(i,c),n,a).toFixed(2))}function mt(e){return Va(e)}function Is(e){return kc(e).join(" · ")}function Bc(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=is(s==null?void 0:s.content);return r||(e.title?e.title:Is(e)||"No messages yet")}function Oc(e,s){const{isReconnecting:r,isConnecting:n}=qs(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function xf(e,s){const r=["Chat",...kc(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function xs(e){return Oc(e)||Is(e)}function bf(e){return`${mt(e)} · ${Bc(e)}`}function gf(e){const s=un(e),r=s?dt(s):Fs(e);return`${mt(e)} — ${r||"Agent"}`}function yf(e){return Fs(e)||"CLI"}function Wc(e){return jc(e)}function Hc(e){return e?`Remote · ${mt(e)||e.workspaceName||"Session"}`:"Remote"}function vf({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var E;ks();const{sendData:u}=Lt(),[p,d]=o.useState(!1),[x,g]=o.useState(1),[w,A]=o.useState({width:0,height:0}),m=o.useRef(null),f=o.useRef(!1),b=o.useRef(0),h=o.useRef(!1),S=o.useRef(""),R=o.useRef(null),j=o.useRef(!1),C=o.useRef(null),k=e.tabKey,v=e.sessionId||"",y=e.daemonId||((E=e.routeId)==null?void 0:E.split(":")[0])||e.routeId||"",$=Ya(e),L=p?i||$:"Runtime terminal unavailable",M=$c,_=Kc,W=()=>hf(w.width,w.height,{minScale:M,maxScale:_}),H=()=>{var B,U;b.current=0,h.current=!1,S.current="",R.current=null,j.current=!1,C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),d(!1),(U=(B=r.current)==null?void 0:B.reset)==null||U.call(B)},N=()=>{var B,U;b.current=0,h.current=!1,S.current="",R.current=null,j.current=!1,C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),d(!0),(U=(B=r.current)==null?void 0:B.reset)==null||U.call(B)},P=()=>{var U;if(C.current=null,!c)return;const B=S.current;B&&(S.current="",(U=r.current)==null||U.write(B))},G=B=>{B&&(S.current+=B,c&&C.current===null&&(C.current=requestAnimationFrame(P)))},I=(B,U=0,V,ae)=>{var we,be,Y,he,O;U>0&&b.current>=U||U===0&&h.current||(b.current=U,d(!0),typeof V=="number"&&typeof ae=="number"&&V>0&&ae>0&&((be=(we=r.current)==null?void 0:we.resize)==null||be.call(we,V,ae)),(he=(Y=r.current)==null?void 0:Y.reset)==null||he.call(Y),B&&((O=r.current)==null||O.write(B)))};return o.useEffect(()=>{H()},[v]),o.useEffect(()=>{var U;if(!v)return;const B=((U=rt.onRuntimeEvent)==null?void 0:U.call(rt,v,V=>{if(!(!V||V.sessionId!==v)){if(V.type==="runtime_snapshot"){if(!c){R.current={text:V.text||"",seq:V.seq||0,cols:V.cols,rows:V.rows};return}I(V.text||"",V.seq||0,V.cols,V.rows);return}if(V.type==="session_output"){h.current=!0,typeof V.seq=="number"&&(b.current=Math.max(b.current,V.seq)),p||d(!0),typeof V.data=="string"&&G(V.data);return}if(V.type==="session_cleared"){if(!c){j.current=!0,S.current="",R.current=null;return}N()}}}))||(()=>{});return()=>{B()}},[y,v,r,c,p]),o.useEffect(()=>{var U,V,ae;if(!v)return;y&&((U=rt.getState)==null?void 0:U.call(rt,y))==="connected"&&(d(!0),(V=rt.requestRuntimeSnapshot)==null||V.call(rt,y,v).catch(()=>{}));const B=(ae=rt.onStateChange)==null?void 0:ae.call(rt,(we,be)=>{var Y;we!==y||be!=="connected"||(d(!0),(Y=rt.requestRuntimeSnapshot)==null||Y.call(rt,y,v).catch(()=>{}))});return()=>{B==null||B()}},[y,v,r]),o.useEffect(()=>{s&&H()},[s,k,r]),o.useEffect(()=>{const B=m.current;if(!B||typeof ResizeObserver>"u")return;const U=new ResizeObserver(V=>{const ae=V[0];if(!ae)return;const{width:we,height:be}=ae.contentRect;A(Y=>{const he=Math.round(we),O=Math.round(be);return Y.width===he&&Y.height===O?Y:{width:he,height:O}})});return U.observe(B),()=>U.disconnect()},[]),o.useEffect(()=>{(()=>{f.current||g(W())})()},[w.height,w.width]),o.useEffect(()=>{var U,V;if(!c)return;j.current&&(j.current=!1,N());const B=R.current;B&&(R.current=null,I(B.text,B.seq,B.cols,B.rows)),y&&v&&((U=rt.getState)==null?void 0:U.call(rt,y))==="connected"&&((V=rt.requestRuntimeSnapshot)==null||V.call(rt,y,v).catch(()=>{})),S.current&&C.current===null&&(C.current=requestAnimationFrame(P)),requestAnimationFrame(()=>{var ae;(ae=r.current)==null||ae.bumpResize()})},[y,c,v]),o.useEffect(()=>()=>{C.current!==null&&(cancelAnimationFrame(C.current),C.current=null)},[]),o.useEffect(()=>{const B=U=>{var ae;const V=U.detail;V!=null&&V.sessionId&&V.sessionId!==v||p&&((ae=r.current)==null||ae.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",B),()=>{window.removeEventListener("adhdev:fit-cli-terminal",B)}},[p,v,r]),t.jsxs(t.Fragment,{children:[t.jsxs("div",{ref:m,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:()=>{f.current=!0,g(B=>Math.max(M,Number((B-.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:()=>{f.current=!0,g(B=>Math.min(_,Number((B+.1).toFixed(2))))},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{className:"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:t.jsx("div",{style:{width:`${100/x}%`,height:`${100/x}%`,transform:`scale(${x})`,transformOrigin:"top left"},children:t.jsx(ac,{ref:r,readOnly:!p||!c,sizingMode:"measured",onInput:B=>{p&&(u==null||u(y,{type:"pty_input",sessionId:v,targetSessionId:v,data:B}))}})})}),!p&&t.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:"Runtime terminal unavailable"})]}),t.jsx(yc,{contextKey:e.tabKey,panelLabel:mt(e),isSending:a,isBusy:!p||!!$,statusMessage:L,onSend:async B=>!p||$?!1:n(B),isActive:l&&c,showControlsToggle:!1})]})}function wf({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 jf({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 Ja({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(yn,{size:n}):t.jsx(es,{size:n})})}function kf({wsStatus:e,isConnected:s,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),i=a.filter(l=>l==="connected").length,c=a.filter(l=>l==="connecting"||l==="new"||l==="checking").length;return r>0&&c>0&&i===0?{tone:"limited",title:"Connected to dashboard",subtitle:"Connecting to machine..."}:s?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function si({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function ri({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=wn(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 Sf({activeConv:e,wsStatus:s,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:u,onHideConversation:p,hiddenConversations:d=[],onShowConversation:x,onShowAllHidden:g,onResetPanelsToMain:w,inboxOpen:A,onInboxOpenChange:m,hiddenOpen:f,onHiddenOpenChange:b,onOpenNewSession:h,actionShortcuts:S,notifications:R,notificationUnreadCount:j,onOpenNotification:C,onMarkNotificationRead:k,onMarkNotificationUnread:v,onDeleteNotification:y}){const{ides:$,p2pStates:L={}}=ks(),M=!!e&&nt(e)&&!Ze(e),_=!!e&&Ze(e),W=l||(e?vc(e)?"terminal":"chat":null),[H,N]=o.useState(!1),P=o.useRef(null),G=o.useRef(null),I=$.filter(O=>O.type==="adhdev-daemon"),E=kf({wsStatus:s,isConnected:r,daemonCount:I.length,p2pStates:L}),B=E.subtitle,U=E.tone==="connected"?"#22c55e":E.tone==="limited"?"#eab308":"#ef4444",V=E.tone==="connected"?"0 0 4px #22c55e80":E.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",ae=o.useMemo(()=>R.filter(O=>!O.readAt),[R]),we=o.useMemo(()=>R.filter(O=>!!O.readAt),[R]),be=o.useMemo(()=>ae.slice(0,9),[ae]),Y=j;o.useEffect(()=>{if(!A)return;const O=X=>{var ie;(ie=P.current)!=null&&ie.contains(X.target)||m(!1)};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[A,m]),o.useEffect(()=>{if(!f)return;const O=X=>{var ie;(ie=G.current)!=null&&ie.contains(X.target)||b(!1)};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[f,b]),o.useEffect(()=>{if(!f&&!A)return;const O=X=>{if(!X.altKey)return;const ie=X.code.match(/^Digit([1-9])$/);if(!ie)return;const le=Number(ie[1])-1,me=f?d[le]:void 0,ke=A?be[le]:void 0;if(!(!me&&!ke)){if(X.preventDefault(),X.stopPropagation(),me){x==null||x(me),b(!1);return}ke&&(C(ke),m(!1))}};return window.addEventListener("keydown",O,!0),()=>window.removeEventListener("keydown",O,!0)},[d,f,A,be,b,m,C,x]);const he=O=>{if(!O)return;const X=n.find(ie=>ie.tabKey===O);X&&(p==null||p(X))};return t.jsxs("div",{className:"dashboard-header",children:[t.jsx("div",{className:"flex items-center gap-3",children:t.jsx("div",{className:"header-title-block",children:t.jsxs("div",{className:"header-title-row",children:[t.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[t.jsx(es,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?mt(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:U,boxShadow:V}})})]}),t.jsxs("div",{className:"header-subtitle flex items-center",children:[t.jsx("span",{title:E.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:U,boxShadow:V}}),B&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",B]}),h&&t.jsx("button",{type:"button",onClick:h,className:"btn btn-secondary btn-sm ml-2",title:"Start or recover a session","aria-label":"Start or recover a session",children:t.jsx(Xd,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(M||_||!Ze(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:Is(e)||mt(e),children:mt(e)}),(M||_)&&c&&t.jsxs(t.Fragment,{children:[M&&u&&W&&t.jsx(Ja,{mode:W,onChange:u,compact:!0}),t.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:_?"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})})]}),!Ze(e)&&t.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(Ka,{size:14})}),!M&&!Ze(e)&&t.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(Pt,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:P,children:[t.jsxs("div",{className:`dashboard-header-hidden${H?" is-drop-target":""}`,ref:G,onDragEnter:O=>{O.dataTransfer.types.includes("text/tab-key")&&(O.preventDefault(),N(!0))},onDragOver:O=>{O.dataTransfer.types.includes("text/tab-key")&&(O.preventDefault(),O.dataTransfer.dropEffect="move",N(!0))},onDragLeave:O=>{O.currentTarget.contains(O.relatedTarget)||N(!1)},onDrop:O=>{const X=O.dataTransfer.getData("text/tab-key");O.preventDefault(),N(!1),he(X)},children:[t.jsxs("button",{type:"button",onClick:()=>b(!f),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${S!=null&&S.toggleHiddenTabs?` (${S.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(tc,{size:16}),d.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:d.length})]}),f&&t.jsxs("div",{className:"dashboard-header-hidden-popover",children:[t.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),t.jsx(si,{value:S==null?void 0:S.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[w&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:w,children:"Reset panels"}),d.length>0&&g&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{g(),b(!1)},children:"Restore all"})]})]}),e&&p&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>p(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(si,{value:S==null?void 0:S.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:mt(e)})]}),d.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(O=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{x==null||x(O),b(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:mt(O)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(O)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(O)+1]}):null,Is(O)]})]},O.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>m(!A),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(vn,{size:16}),Y>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:Y})]}),A&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[ae.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),ae.map(O=>t.jsx(ri,{notification:O,shortcutIndex:be.indexOf(O)>=0?be.indexOf(O)+1:void 0,onOpen:()=>C(O),onMarkRead:()=>k(O.id),onMarkUnread:()=>v(O.id),onDelete:()=>y(O.id)},O.id))]}),we.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),we.map(O=>t.jsx(ri,{notification:O,onOpen:()=>C(O),onMarkRead:()=>k(O.id),onMarkUnread:()=>v(O.id),onDelete:()=>y(O.id)},O.id))]}),R.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function wt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Nf(e,s){return String(e||"")!==String(s||"")}function Cf(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&&!pc(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
32
- `).includes(a)))}function If(e,s="recent"){const r=e.slice();return r.sort((n,a)=>{if(s==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(s==="messages"){const i=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(i!==0)return i}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function Fc(e,s={}){return If(Cf(e,s),s.sortMode||"recent")}function fn(e){return e?"Resume saved history":"Start fresh"}function Qa(e){return e?"Resuming saved history…":"Starting fresh…"}function Af(){return"Start fresh"}function Uc(e,s=!1){return e==="cli"?fn(s):e==="ide"?"Start IDE":"Start ACP session"}function zc(e,s=!1){return e==="cli"?Qa(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Mf(){return"Recover hosted runtime"}function Tf(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Lf(){return"Open saved history"}function Rf(){return"Saved History"}function Za(){return"Use saved history when you want continuity in the same provider conversation."}function _f(){return"No saved history found yet."}function Pf(){return"Refresh saved history"}function Df(){return"Refreshing saved history…"}function bs(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function gs(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 Us(e){return e==="start-fresh"?"Start fresh":"Restart"}function zs(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function eo(e){return`Resume saved history with ${e}?`}function to(){return"Review or change the target workspace before resuming saved history."}function Ef(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 so({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:p,onNewChat:d,onSwitchSession:x,onRefreshHistory:g,onResumeSavedSession:w}){var v;const A=s.find(y=>y.id===e.routeId),m=(A==null?void 0:A.chats)||[],f=(v=A==null?void 0:A.activeChat)==null?void 0:v.id,b=nt(e)&&!Ze(e),[h,S]=o.useState(()=>wt()),R=l||h,j=y=>{if(u){u(y);return}S(y)},C=o.useMemo(()=>Fc(a,{textQuery:R.textQuery,workspaceQuery:R.workspaceQuery,modelQuery:R.modelQuery,resumableOnly:R.resumableOnly,sortMode:R.sortMode}),[R.modelQuery,R.resumableOnly,R.sortMode,R.textQuery,R.workspaceQuery,a]),k=t.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[t.jsx("div",{onClick: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:b?Rf():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:gf(e)}),b&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Za()})]}),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:[!b&&t.jsx("button",{onClick:d,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),b?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:R.textQuery,onChange:y=>j({...R,textQuery:y.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:R.workspaceQuery,onChange:y=>j({...R,workspaceQuery:y.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:R.modelQuery,onChange:y=>j({...R,modelQuery:y.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:R.sortMode,onChange:y=>j({...R,sortMode:y.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:R.resumableOnly,onChange:y=>j({...R,resumableOnly:y.target.checked})}),"Resume-ready only"]})]}),C.map(y=>{const $=e.providerSessionId===y.providerSessionId,L=$||!y.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{L||!w||w(y)},disabled:L,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"} ${L?"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:y.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:y.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Ef(y.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:y.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:[y.workspace||"Workspace unknown",Ns(y.summaryMetadata)?` · ${Ns(y.summaryMetadata)}`:"",y.messageCount>0?` · ${y.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:$?"ACTIVE":y.canResume?c===y.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},y.id)})]}):m.map(y=>t.jsxs("div",{onClick:()=>{x(e.routeId,y.id),p()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${f===y.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[t.jsx("div",{className:`font-bold text-sm mb-1 ${f===y.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:y.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:[y.id.substring(0,12),"..."]}),f===y.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},y.id)),(b&&!i&&C.length===0||!b&&m.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(eu,{size:32})}),t.jsx("div",{className:"text-[13px]",children:b?a.length>0?"No saved history matches these filters.":_f():"No recent chat sessions found."})]}),b&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:Df()})})]}),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:g,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(Gs,{size:13})," ",b?Pf():"Refresh History"]})})})]})]});return typeof document>"u"?k:fr.createPortal(k,document.body)}const ni={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 Vc({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=ni[n.type]||ni.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 $f=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Kf(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function Bf(e){return e.sessionId||e.instanceId||e.agentType}function Un(e,s){return e||s}function ai(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 Gc(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=_t(r,{fallbackId:r.id}));return s}function qc(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 ro(e,s,r={}){return Of(e,s,qc(e,r))}function Of(e,s,r={}){var x,g,w,A,m,f;const n=[],a=r.machineName,i=r.connectionState,c=Kf(e),l=Bu(e.type,{agentName:e.cliName}),u=nt(e)||Ze(e)?l:dt(e.type),p=Array.isArray(e.childSessions)?e.childSessions.map(b=>{var h,S;return{sessionId:b.id,instanceId:b.id,providerSessionId:b.providerSessionId,transport:b.transport,sessionCapabilities:b.capabilities,agentType:b.providerType,agentName:b.providerName||dt(b.providerType),status:b.status,title:b.title,lastMessagePreview:b.lastMessagePreview,lastMessageRole:b.lastMessageRole,lastMessageAt:b.lastMessageAt,lastMessageHash:b.lastMessageHash,messages:((h=b.activeChat)==null?void 0:h.messages)||[],activeModal:((S=b.activeChat)==null?void 0:S.activeModal)||void 0,unread:b.unread,lastSeenAt:b.lastSeenAt,lastUpdated:b.lastUpdated,inboxBucket:b.inboxBucket,surfaceHidden:b.surfaceHidden}}):[],d=$f(e);if(d){const b=e.sessionId||e.instanceId,h=l,S=(x=e.activeChat)==null?void 0:x.activeModal,R=S&&Array.isArray(S.buttons)&&S.buttons.length>0,j=St((g=e.activeChat)==null?void 0:g.status,{activeModal:(w=e.activeChat)==null?void 0:w.activeModal})||St((m=(A=e.agents)==null?void 0:A[0])==null?void 0:m.status)||"idle",C=e.activeChat||{title:"",messages:[]};let k=C.title&&String(C.title).trim()?String(C.title).trim():"";const v=(f=e.activeChat)==null?void 0:f.id,y=e.chats;if(v&&Array.isArray(y)&&y.length>0){const H=y.find(N=>N.id===v||N.id&&String(N.id)===String(v));H!=null&&H.title&&String(H.title).trim()&&(k=String(H.title).trim())}const $=(nt(e)||Ze(e),e.type),L=(nt(e)||Ze(e))&&zo(k,h,$)?"":k,M=C.messages||[],_=ai(s,[e.id,b]),W=Zo(M,_);n.push({routeId:e.id,sessionId:b,providerSessionId:e.providerSessionId,nativeSessionId:b,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:nt(e)?e.mode||"terminal":"chat",agentName:h,agentType:$,status:j,title:L,messages:[...M,...W],resume:e.resume,hostIdeType:!nt(e)&&!Ze(e)?e.type:void 0,workspaceName:c,displayPrimary:L||c||(nt(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:R?S.buttons:void 0,modalMessage:R?S.message:void 0,streamSource:"native",tabKey:Un(b,e.id),machineName:a,connectionState:i})}if(d&&(nt(e)||Ze(e)))return n;for(const b of p){const h=b.activeModal&&Array.isArray(b.activeModal.buttons)&&b.activeModal.buttons.length>0,S=Ou(b),R=Bf(b),j=`${e.id}:${R}`,C=b.title&&String(b.title).trim()||"",k=zo(C,b.agentName,b.agentType)?"":C,v=b.messages||[],y=ai(s,[j,b.sessionId,b.instanceId]),$=Zo(v,y);(b.transport==="cdp-webview"||b.sessionId||b.providerSessionId||v.length>0||$.length>0||h||k||!["idle","panel_hidden","disconnected","not_monitored"].includes(S))&&n.push({routeId:e.id,sessionId:b.sessionId||b.instanceId,providerSessionId:b.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:b.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:b.sessionCapabilities,mode:"chat",agentName:b.agentName,agentType:b.agentType,status:S,title:k,messages:[...v,...$],hostIdeType:e.type,workspaceName:c,displayPrimary:k||c||b.agentName||u,displaySecondary:`${u} · ${b.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:b.lastMessagePreview,lastMessageRole:b.lastMessageRole,lastMessageAt:b.lastMessageAt,lastMessageHash:b.lastMessageHash,lastUpdated:b.lastUpdated||e.lastUpdated,modalButtons:h?b.activeModal.buttons:void 0,modalMessage:h?b.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Un(b.sessionId||b.instanceId,j),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:Un(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function Wf(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 Hf(e,s){const r=Wf(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Yc=[{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:"🏄"}],Xc=[{id:"aider-cli",name:"Aider",icon:"🛠️"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"gemini-cli",name:"Gemini CLI",icon:"✨"},{id:"github-copilot-cli",name:"GitHub Copilot CLI",icon:"🤖"},{id:"goose-cli",name:"Goose",icon:"🪿"},{id:"opencode-cli",name:"OpenCode CLI",icon:"🧩"}],Jc=[{id:"cline",name:"Cline",icon:"🧠"},{id:"codex",name:"Codex",icon:"📦"},{id:"roo-code",name:"Roo Code",icon:"🦘"},{id:"claude-code-vscode",name:"Claude Code (VS Code)",icon:"🟠"}],Ff=Yc,Uf=Xc,zf=Jc;function As(...e){return wd(jd(e))}function Vf({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:As("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 Qc({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(Vf,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:As("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Rt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:As("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 Zc({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:As("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 Gf={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"},qf={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Wr({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:As("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Gf[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:qf[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 Yf={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"},Xf={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Jf({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:As("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Yf[e],r),children:[t.jsx("span",{className:As("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Xf[e])}),n]})}const ka="adhdev:themechange";function Qf(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Ls(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Rs(e){return e==="system"?Qf():e}function el(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function tn(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(ka,{detail:{preference:e,theme:s}}))}function Zf(){const e=Ls(),s=Rs(e);el(s),tn(e,s)}function no(){const[e,s]=o.useState(Ls),[r,n]=o.useState(()=>Rs(Ls()));o.useEffect(()=>{el(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),tn("system",p)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const p=u.detail||{},d=p.preference,x=p.theme;s(d==="dark"||d==="light"||d==="system"?d:Ls()),n(x==="dark"||x==="light"?x:Rs(Ls()))},l=u=>{if(u.key!=="theme")return;const p=Ls(),d=Rs(p);s(p),n(d)};return window.addEventListener(ka,c),window.addEventListener("storage",l),()=>{window.removeEventListener(ka,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=Rs(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}tn(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=Rs(l);n(u);try{localStorage.setItem("theme",l)}catch{}return tn(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const oi={dark:"Dark",light:"Light",system:"System"};function ep({collapsed:e}){const{preference:s,cycleTheme:r}=no(),n=s==="dark"?t.jsx(su,{size:16}):s==="light"?t.jsx(tu,{size:16}):t.jsx(ru,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${oi[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:oi[s]})]})}function ms({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 tp({onPrefChange:e}){const[s,r]=Xu(),[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(ms,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(vn,{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(ms,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Pt,{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:()=>{bc().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(ms,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(nu,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:c=>i("completionAlert",c)}),t.jsx(ms,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(au,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:c=>i("approvalAlert",c)}),t.jsx(ms,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(hr,{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 pn(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function sp(e,s){const r=pn(e),n=pn(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 tl(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function dr(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||sp(r,s)>=0)return!1;const n=pn(r),a=pn(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function rp(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function zn(e,s){return e instanceof Error?e.message:s}function np({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(Zc,{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(op,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function ii({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 fr.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 ap(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Ff,...Uf,...zf].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 op({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var W,H;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[p,d]=o.useState(null),[x,g]=o.useState("idle"),[w,A]=o.useState(""),m=e.version||null,f=((W=e.machine)==null?void 0:W.platform)||((H=e.system)==null?void 0:H.platform)||"",b=_t(e,{fallbackId:e.id}),h=f==="win32"?"🪟":f==="darwin"?"🍎":"🐧",S=s.filter(N=>N.daemonId===e.id&&N.transport==="cdp-page"),R=s.filter(N=>N.daemonId===e.id&&N.transport==="pty"),j=s.filter(N=>N.daemonId===e.id&&N.transport==="acp"),C=e.p2p,k=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const N=rp(await r(e.id,"daemon_upgrade",{}));N.alreadyLatest?(c("done"),u(`Already on v${N.version||"latest"}.`)):N.upgraded||N.success?(c("done"),u(`Upgrade to v${N.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(N.error||"Upgrade failed"))}catch(N){c("error"),u(zn(N,"Connection lost during upgrade"))}}},v=async()=>{if(d(null),!!n){g("loading");try{await n(e.id),g("done"),A("Machine disconnected.")}catch(N){g("error"),A(zn(N,"Failed to disconnect"))}}},y=async()=>{if(d(null),!!a){g("loading");try{await a(e.id),g("done"),A("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(N){g("error"),A(zn(N,"Failed to revoke token"))}}},$="0.8.96",L=tl(e,$),M=dr(e,$),_=S.length+R.length+j.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:b}),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),"…"]}),m&&t.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${L?"":"bg-bg-secondary"}`,style:L?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",m,!L&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&L&&t.jsx("button",{onClick:k,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${$}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${M?"↑ Update now":`↑ Update${` to v${$}`}`}`}),n&&t.jsx("button",{onClick:()=>d("disconnect"),disabled:x==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&t.jsx("button",{onClick:()=>d("revoke"),disabled:x==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(Jf,{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:[C&&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 ${C.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${C.state==="connecting"||C.state==="new"?"animate-pulse":""}`,style:C.state==="connecting"||C.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",C.state==="connected"?"connected":C.state==="connecting"||C.state==="new"?"connecting...":C.state||"off"]}),C.peers!==void 0&&C.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",C.peers," peer",C.peers!==1?"s":"",")"]})]}),C&&_>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),_>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[S.map(N=>{const P=ap(N.type),G=N.cdpConnected;return t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:P.icon}),t.jsx("span",{children:P.name}),G!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${G?"bg-green-400":"animate-pulse"}`,style:G?void 0:{background:"var(--status-warning)"},title:G?"CDP connected":"CDP connecting..."})]},N.id)}),R.map(N=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"⌨️"}),t.jsx("span",{children:N.cliName||"CLI"})]},N.id)),j.map(N=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"🔗"}),t.jsx("span",{children:N.cliName||"ACP"})]},N.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||w)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||x==="error"?"text-red-400":i==="done"||x==="done"?"text-green-400":"text-text-muted"}`,children:w||l})]}),p==="disconnect"&&t.jsx(ii,{title:"🔌 Disconnect Machine",message:`Disconnect "${b}" 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:()=>d(null)}),p==="revoke"&&t.jsx(ii,{title:"⚠️ Remove Machine",message:`Remove "${b}" 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:y,onCancel:()=>d(null)})]})}const ip=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function cp(){const{preference:e,setPreference:s}=no();return t.jsx("div",{className:"flex gap-2",children:ip.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 lp(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 dp(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Vn(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function ci(e){const{r:s,g:r,b:n}=dp(e);return .2126*Vn(s)+.7152*Vn(r)+.0722*Vn(n)}function li(e,s){const r=ci(e),n=ci(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function sl(e){const s=lp(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return li(s,r)>=li(s,n)?r:n}const Sa={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},Na={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},up=[{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"}}}],rl="adhdev-chat-theme",nl="adhdev-chat-theme-custom";function sn(){if(typeof window>"u")return"ember";try{return localStorage.getItem(rl)||"ember"}catch{return"ember"}}function Ht(e){try{const s=localStorage.getItem(nl);if(s){const r=JSON.parse(s);return{...e==="dark"?Sa:Na,...r[e]}}}catch{}return e==="dark"?Sa:Na}function Hr(e,s){try{localStorage.setItem(nl,JSON.stringify({dark:e,light:s}))}catch{}}function Kt(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 hn(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 mp={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function ur(e,s){var a;const r=(a=mp[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",hn(r,24)),n.style.setProperty("--accent-on-primary",sl(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${hn(r,18)})`),n.style.setProperty("--border-accent",Kt(r,.35)),n.style.setProperty("--nav-active-bg",Kt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Kt(r,.06)}`)}function ys(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Kt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Kt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Kt(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",Kt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Kt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",hn(e.accentColor,30)),s.style.setProperty("--accent-on-primary",sl(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${hn(e.accentColor,40)})`),s.style.setProperty("--border-accent",Kt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Kt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Kt(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 ${Kt(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 ao(){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 fp(e){try{localStorage.setItem(rl,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=vs()?"dark":"light";ys(Ht(s))}else ao(),ur(e,vs()?"dark":"light")}function pp(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=sn();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=vs()?"dark":"light";ys(Ht(s))}else ao(),ur(e,vs()?"dark":"light")}function vs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function kt({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 er({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 hp({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>Ht(r));o.useEffect(()=>{a(Ht(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const p={...u,[c]:l},x=Ht(r==="dark"?"light":"dark");return r==="dark"?Hr(p,x):Hr(x,p),ys(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(er,{title:"App Background",children:[t.jsx(kt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(kt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(kt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs(er,{title:"App Text",children:[t.jsx(kt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(kt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(kt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs(er,{title:"Borders & Accent",children:[t.jsx(kt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(kt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(kt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs(er,{title:"Chat Bubbles",children:[t.jsx(kt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(kt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(kt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(kt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs(er,{title:"Chat Layout",children:[t.jsx(kt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(kt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(kt,{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?Sa:Na,u=Ht(e?"light":"dark");e?Hr(c,u):Hr(u,c),a(c),ys(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 xp(){const[e,s]=o.useState(sn),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Ht("dark"));o.useEffect(()=>{n(vs());const u=new MutationObserver(()=>{const x=vs();n(x);const g=sn();g==="custom"?ys(Ht(x?"dark":"light")):ur(g,x?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const x=vs();n(x);const g=sn();g==="custom"?ys(Ht(x?"dark":"light")):ur(g,x?"dark":"light")};return p.addEventListener("change",d),()=>{u.disconnect(),p.removeEventListener("change",d)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ys(Ht(r?"dark":"light")):(ao(),ur(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Ht(r?"dark":"light"))},[r]);const c=u=>{s(u),fp(u)},l=[...up,{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,d=r?u.preview.dark:u.preview.light,x=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:d.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"Hello! How can I help?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.userBubble,color:x},children:"Fix the bug please"}),t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[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(hp,{dark:r,onColorsChange:u=>i(u)})]})}const oo="adhdev_mobileDashboardMode_v1",Ca="adhdev:mobile-dashboard-mode-change";function io(){try{return localStorage.getItem(oo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function bp(e){if(typeof window>"u")return()=>{};const s=a=>{e(a??io())},r=a=>{const i=a.detail;s(i)},n=a=>{a.key&&a.key!==oo||s()};return window.addEventListener(Ca,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Ca,r),window.removeEventListener("storage",n)}}function gp(e){try{localStorage.setItem(oo,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ca,{detail:e}))}function yp(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(io()==="chat")},[]),t.jsx(ms,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(es,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{s(r),gp(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Gn=new Map,di=new Map;function vp(e){if(!e||typeof e!="object")return null;const s=e,r=s.machine;return!r||typeof r!="object"?null:{machine:r,timestamp:typeof s.timestamp=="number"?s.timestamp:void 0}}function wp(e,s,r,n){return{...e||{},id:s,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n,platform:r.platform,machine:r}}function al(){const{sendCommand:e}=Lt(),{injectEntries:s,getIdes:r}=pr();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??Dm,c=di.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=Gn.get(n);if(l)return l;const u=(async()=>{const p=await e(n,"get_machine_runtime_stats"),d=vp(p);if(!d)return;const x=r().find(w=>w.id===n),g=wp(x,n,d.machine,d.timestamp||Date.now());s([g]),di.set(n,Date.now())})().finally(()=>{Gn.delete(n)});return Gn.set(n,u),u},[r,s,e])}function jp(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 kp(e,s){const{sendData:r}=Lt(),{injectEntries:n,getIdes:a}=pr(),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=>os.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:s==null?void 0:s.intervalMs}},d=>{const x=a().find(w=>w.id===u),g=jp(x,u,d);n([g])}));return()=>{l.forEach(u=>u())}},[i,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}function ol(e,s){const{sendData:r}=Lt(),[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=os.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)},Bm):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 Sp(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function il(e){const{sendData:s}=Lt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=Sp(e);if(!a||!e.sessionId||!s){n({});return}const i=os.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}),Bs.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return i.initialSendAccepted||n({}),()=>{i()}},[e.daemonId,e.routeId,e.sessionId,s]),r}const cl="adhdev_hiddenTabs";function Np(){try{const e=localStorage.getItem(cl);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function Ms(e){try{localStorage.setItem(cl,JSON.stringify([...e]))}catch{}}function Fr(e){return Wa(e)}function co(e,s){return rs(s).some(r=>e.has(r))}function Cp(){const[e,s]=o.useState(Np),r=o.useCallback(p=>{s(d=>{const x=new Set(d);return x.has(p)?x.delete(p):x.add(p),Ms(x),x})},[]),n=o.useCallback(p=>{s(d=>{if(d.has(p))return d;const x=new Set(d);return x.add(p),Ms(x),x})},[]),a=o.useCallback(p=>{s(d=>{if(!d.has(p))return d;const x=new Set(d);return x.delete(p),Ms(x),x})},[]),i=o.useCallback(()=>{s(p=>{if(p.size===0)return p;const d=new Set;return Ms(d),d})},[]),c=o.useCallback((p,d)=>{s(x=>{const g=new Set(x);for(const w of d)g.add(w);return Ms(g),g})},[]),l=o.useCallback((p,d)=>{s(x=>{const g=new Set(x);for(const w of d)g.delete(w);return Ms(g),g})},[]),u=o.useCallback(p=>co(e,p),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function ll(e){return e instanceof Error?e.message:String(e||"")}function lo(e){const s=ll(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 uo(e){const s=ll(e);return s.includes("P2P command timeout")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function ui(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 Ip(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=ui(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>ui(u,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function dl(e,s){if(!s)return null;for(const r of e){if(r.sessionId===s&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===s&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function Ap(e,s){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,i]of Object.entries(e))dl(s,a)===i&&(delete n[a],r=!0);return r?n:e}function Mp({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{bc()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:Wc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Zu(a),o.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),p={};for(const[d,x]of Object.entries(l))u-x<5e3&&(p[d]=x);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 Tp(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 qn(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 Lp(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 mi(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?Lp(is(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 Rp(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||""),mi(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),mi(r.activeChat)].join(":"))].join("|")}function _p(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 Pp(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 Dp(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 Ep(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const i of rs({routeId:n.routeId}))r.set(i,a);for(const i of rs({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of rs({tabKey:n.tabKey}))r.set(i,n)}return r}function $p(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function Kp(e){const s=$p(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=is(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Bp({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:a}){const i=o.useMemo(()=>Tp(e),[e]),c=o.useMemo(()=>Gc(e),[e]),l=o.useRef([]),u=o.useRef([]),p=o.useRef([]),d=o.useRef(new Map),x=o.useRef(new Map),g=o.useMemo(()=>{const j=new Map,C=[];for(const $ of i){const{connectionState:L="new",machineName:M}=qc($,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),_=Pp($,r),W=Rp($),H=d.current.get($.id);if(H&&H.ide===$&&H.sourceSignature===W&&H.connectionState===L&&H.machineName===M&&Dp(H.localRefs,_)){j.set($.id,H),C.push(...H.conversations);continue}const N=ro($,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),P={ide:$,sourceSignature:W,connectionState:L,machineName:M,localRefs:_,conversations:N};j.set($.id,P),C.push(...N)}d.current=j;const k=new Map,v=$=>{const L=Kp($),M=x.current.get($.tabKey);if(M&&M.signature===L)return k.set($.tabKey,M),M.timestamp;const _={signature:L,timestamp:Nc($)||(M==null?void 0:M.timestamp)||0};return k.set($.tabKey,_),_.timestamp},y=[...C].sort(($,L)=>Cc($,L,v));return x.current=k,y},[i,r,s,c]),w=o.useMemo(()=>{const j=_p(g,n);return qn(l.current,j)?l.current:(l.current=j,j)},[g,n]),A=o.useMemo(()=>{const j=new Map,C=Array.from(new Set(w.map(k=>k.routeId)));for(const k of C){const v=Ft(w,k);v&&j.set(k,v)}return j},[w]),m=o.useMemo(()=>{const j=new Map;for(const C of w){const k=A.get(C.routeId),v=C.streamSource==="native"&&k?k:C;for(const y of rs({providerSessionId:C.providerSessionId,sessionId:C.sessionId}))j.set(y,v)}return j},[w,A]),f=o.useMemo(()=>Ep(w,A),[w,A]),b=o.useCallback(j=>{if(j)return m.get(j)},[m]),h=o.useCallback(j=>{if(j)return f.get(j)},[f]),S=o.useMemo(()=>{const j=w.filter(C=>!co(a,C));return qn(u.current,j)?u.current:(u.current=j,j)},[w,a]),R=o.useMemo(()=>{const j=S.map(C=>C.tabKey);return qn(p.current,j)?p.current:(p.current=j,j)},[S]);return{chatIdes:i,conversations:w,visibleConversations:S,visibleTabKeys:R,resolveConversationBySessionId:b,resolveConversationByTarget:h}}function Op({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 Wp({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:a}){o.useEffect(()=>{at.setIdes(e)},[e]),o.useEffect(()=>{at.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),o.useEffect(()=>{const i=at.onToast(u=>{r(d=>d.some(g=>g.message===u.message&&u.timestamp-g.timestamp<3e3)?d:[...d.slice(-4),{id:u.id,message:u.message,type:u.type,timestamp:u.timestamp,targetKey:u.targetKey,actions:u.actions}]);const p=u.duration||5e3;setTimeout(()=>r(d=>d.filter(x=>x.id!==u.id)),p)}),c=at.onSystemMessage((u,p)=>{var w,A;const d=a(u),x=(w=p._localId)==null?void 0:w.startsWith("sys_approval_"),g=!!(d&&(d.status==="waiting_approval"||(A=d.modalButtons)!=null&&A.length||d.modalMessage));x&&g||n(m=>({...m,[u]:[...m[u]||[],p]}))}),l=at.onClearSystemMessage((u,p)=>{n(d=>{var x;return(x=d[u])!=null&&x.length?{...d,[u]:d[u].filter(g=>{var w;return!(g.role==="system"&&((w=g._localId)!=null&&w.startsWith(p)))})}:d})});return()=>{i(),c(),l()}},[r,n]),o.useEffect(()=>{const i=Ec.on("status_event",c=>{at.handleRawEvent(c,"ws")});return()=>{i()}},[]),o.useEffect(()=>{var c;const i=l=>{var f;const u=l.data;if((u==null?void 0:u.type)!=="notification_action"||typeof u.action!="string"||!u.action.startsWith("approval_")||!(u.daemonId||u.targetSessionId||u.targetKey))return;const p=u.targetSessionId||u.targetKey||u.daemonId,d=a(p),x=(d==null?void 0:d.routeId)||u.daemonId;if(!x)return;const g=Number(u.buttonIndex),w=u.button||((f=d==null?void 0:d.modalButtons)==null?void 0:f[g])||"Approve",A=String(w).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),m=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(A);s(x,"resolve_action",{action:m?"approve":"reject",button:w,...Number.isFinite(g)&&{buttonIndex:g},...(d==null?void 0:d.sessionId)&&{targetSessionId:d.sessionId},...u.targetSessionId&&{targetSessionId:u.targetSessionId}}).catch(b=>console.error("[SW Action] approval failed:",b))};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 Hp="adhdev_dashboardLayout_v1",Fp="adhdev_dashboardDockview_v1",Up="adhdev_dashboardDockviewHiddenRestore_v1",tr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function mo(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function ul(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function ml(e){return`${Hp}:${e}`}function zp(e){const s=ml(e);return mo(s,null)}function Vp(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=ml(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function fl(e){return`${Fp}:${e}`}function Gp(e){const s=fl(e);return mo(s,null)}function qp(e,s){try{const r=fl(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function pl(e){return`${Up}:${e}`}function Yp(e){const s=pl(e);return mo(s,{})}function Xp(e,s){try{const r=pl(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Jp(){return{groupAssignments:[...tr.groupAssignments],focusedGroup:tr.focusedGroup,groupActiveTabIds:{...tr.groupActiveTabIds},groupTabOrders:{...tr.groupTabOrders},groupSizes:[...tr.groupSizes]}}function Qp(){const[e]=o.useState(()=>ul(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,d]=o.useState([]),[x,g]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[w,A]=o.useState(!1),m=o.useCallback(()=>{if(w)return;const f=zp(e)??Jp();r(new Map(f.groupAssignments)),a(f.focusedGroup),c(f.groupActiveTabIds),u(f.groupTabOrders),d(f.groupSizes),A(!0)},[w,e]);return o.useEffect(()=>{w&&Vp(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:p})},[w,e,s,n,i,l,p]),o.useEffect(()=>{const f=window.matchMedia("(max-width: 767px)"),b=h=>g(h.matches);return f.addEventListener("change",b),()=>f.removeEventListener("change",b)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:a,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:u,groupSizes:p,setGroupSizes:d,isMobile:x,hasHydratedStoredLayout:w,hydrateStoredLayout:m}}function Zp(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=Oa(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function eh({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:l,setSearchParams:u,historyModalOpen:p,activeConv:d,isRefreshingHistory:x,ides:g,handleRefreshHistory:w}){const A=o.useRef(!1),m=o.useRef(!1),f=o.useRef(null),b=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 S=n.get(h.tabKey)??0;c(R=>({...R,[S]:h.tabKey})),l(S),A.current=!0,m.current=!0,f.current!=null&&(window.clearTimeout(f.current),f.current=null),u(R=>{const j=new URLSearchParams(R);return j.delete("activeTab"),j},{replace:!0})},[e,s,r,n,a,i,c,l,u]),o.useEffect(()=>{if(!(m.current||a)&&s.length!==0){if(!e){i(),m.current=!0;return}if(A.current){m.current=!0;return}if(f.current==null)return f.current=window.setTimeout(()=>{f.current=null,!(m.current||a)&&(i(),m.current=!0)},1500),()=>{f.current!=null&&(window.clearTimeout(f.current),f.current=null)}}},[e,s.length,a,i]),o.useEffect(()=>{if(!p){b.current=!1;return}if(!d||b.current||x)return;const h=g.find(S=>S.id===d.routeId);h&&(!h.chats||h.chats.length===0||Zp(h.chats,d))&&(b.current=!0,w())},[p,d,x,g,w]),o.useEffect(()=>{if(!d)return;let h=null,S=0,R=-1,j=0;const C=()=>{h=null;const k=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(y=>y.offsetParent!==null);if(k.length===0){S<18&&(S+=1,h=requestAnimationFrame(C));return}let v=0;for(const y of k)y.scrollTop=y.scrollHeight,v+=y.scrollHeight;v===R?j+=1:(j=0,R=v),S+=1,!(j>=2||S>=18)&&(h=requestAnimationFrame(C))};return h=requestAnimationFrame(C),()=>{h!=null&&cancelAnimationFrame(h)}},[d==null?void 0:d.tabKey])}function th({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,p]=o.useState(null),[d,x]=o.useState(null),g=o.useMemo(()=>{if(e||!n)return null;const b=l(n);return b&&!nt(b)&&!Ze(b)?b:null},[e,n,l]),w=o.useMemo(()=>{const b=u==null?void 0:u.routeId;if(!b)return null;const h=u!=null&&u.tabKey?i.find(S=>S.tabKey===u.tabKey):a?i.find(S=>S.tabKey===a):null;return(h==null?void 0:h.routeId)===b?h:Ft(i,b)},[i,u,a]),A=o.useMemo(()=>{if(w)return c.find(b=>b.id===w.routeId)},[c,w]);o.useEffect(()=>{g&&(p({routeId:g.routeId,tabKey:qo(g)}),x(g),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,g]);const m=o.useCallback(b=>{b&&(p({routeId:b.routeId,tabKey:qo(b)}),x(b))},[]),f=o.useCallback(()=>{p(null),x(null)},[]);return{remoteDialogConv:w,remoteDialogIdeEntry:A,remoteDialogActiveConv:d,setRemoteDialogActiveConv:x,openRemoteDialog:m,closeRemoteDialog:f}}function Yn(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=Oa(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function fi({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setLocalUserMessages:i,setClearedTabs:c}){const[l,u]=o.useState(!1),[p,d]=o.useState(!1),x=o.useCallback(async m=>{try{await e("standalone","launch_ide",{ideType:m,enableCdp:!0})}catch(f){console.error("Launch failed",f)}},[e]),g=o.useCallback(async(m,f)=>{try{const b=m||(s==null?void 0:s.daemonId)||"",h=await e(b,"switch_chat",{id:f,sessionId:f,...$s(s)}),S=h==null?void 0:h.result;if((h==null?void 0:h.success)===!0||S==="switched"||S==="switched-by-title")return;S===!1||S==="not_found"?Zs(a,"⚠️ Session tab not found — try refreshing history"):typeof S=="string"&&S.startsWith("error:")?Zs(a,`⚠️ Switch error: ${S}`):Zs(a,"⚠️ Session switch failed")}catch(b){console.error("Switch failed",b),Zs(a,`❌ Switch failed: ${b.message||"connection error"}`)}},[s,e,a]),w=o.useCallback(async()=>{if(!(!s||l)){u(!0);try{const m=yr(s);await e(m,"new_chat",{...$s(s)}),c(f=>({...f,[s.tabKey]:Date.now()})),i(f=>({...f,[s.tabKey]:[]}))}catch(m){console.error("New chat failed",m)}finally{u(!1)}}},[s,l,e,c,i]),A=o.useCallback(async()=>{var m,f;if(!(!s||p)){d(!0);try{const b=yr(s),h=async()=>e(b,"list_chats",{forceExpand:!0,...$s(s)});let S=await h(),R=(S==null?void 0:S.chats)||((m=S==null?void 0:S.result)==null?void 0:m.chats);Yn(R,s)&&(await new Promise(j=>setTimeout(j,450)),S=await h(),R=(S==null?void 0:S.chats)||((f=S==null?void 0:S.result)==null?void 0:f.chats)),S!=null&&S.success&&Array.isArray(R)&&(n(s.routeId,R),Yn(R,s)&&!Yn(r,s)&&Zs(a,"⚠️ History dialog did not fully open — try once more"))}catch(b){console.error("Refresh history failed",b)}finally{d(!1)}}},[s,r,p,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:p,handleLaunchIde:x,handleSwitchSession:g,handleNewChat:w,handleRefreshHistory:A}}function sh(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 rh(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function pi(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 Ur(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 hi(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 nh(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 ah(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 xi(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 bi(e){return Array(e).fill(100/e)}function oh({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:a,groupSizes:i,setGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:p}){const d=o.useRef(null),x=o.useMemo(()=>Ur(e,p),[e,p]),g=x.assignments,w=o.useMemo(()=>l?1:x.groupCount,[x.groupCount,l]),A=w>1,m=o.useCallback((j,C)=>{s(k=>{const v=new Map(Ur(k,p).assignments);return C===0?v.delete(j):v.set(j,C),v}),n(k=>({...k,[C]:j})),r(C)},[s,p,n,r]),f=o.useCallback(j=>{s(C=>{const k=Ur(C,p).assignments,v=new Map;for(const[y,$]of k)$!==j&&($>j?v.set(y,$-1):v.set(y,$));return v}),c(C=>{if(C.length<=1)return[];const k=[...C];k.splice(j,1);const v=k.reduce((y,$)=>y+$,0);return v>0?k.map(y=>y/v*100):[]}),r(0)},[s,p,c,r]),b=o.useCallback((j,C)=>{C.preventDefault();const k=d.current;if(!k)return;const v=C.clientX,y=k.offsetWidth,$=i.length===w?[...i]:bi(w),L=_=>{const H=(_.clientX-v)/y*100,N=[...$];N[j]=Math.max(15,$[j]+H),N[j+1]=Math.max(15,$[j+1]-H),c(N)},M=()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",M),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",L),document.addEventListener("mouseup",M)},[i,w,c]),h=o.useCallback((j,C,k)=>{if(w>=4)return;const v=k==="left"?C:C+1;s(y=>{const $=Ur(y,p).assignments,L=new Map;for(const M of u){const _=$.get(M.tabKey)??0,W=_>=v?_+1:_;W>0&&L.set(M.tabKey,W)}return v>0&&L.set(j,v),L}),c(y=>{const $=y.length===w?[...y]:bi(w),L=$[C]??100/w,M=Math.max(15,L/2),_=Math.max(15,L/2),W=[...$];W[C]=M,W.splice(v,0,_);const H=W.reduce((N,P)=>N+P,0);return W.map(N=>N/H*100)}),n(y=>{const $=xi(y,v);return $[v]=j,$}),a(y=>{const $=xi(y,v);return $[v]=[j],$}),r(v)},[w,s,p,u,c,n,a,r]);o.useEffect(()=>{sh(e,g)||s(g)},[e,g,s]),o.useEffect(()=>{const{mapping:j,usedGroups:C}=x;n(k=>{const v=hi(k,j);return pi(k,v)?k:v}),a(k=>{const v=hi(k,j);return pi(k,v)?k:v}),r(k=>{const v=l?0:nh(k,C,j);return k===v?k:v}),c(k=>{const v=l?[]:ah(k,C,x.groupCount);return rh(k,v)?k:v})},[x,l,n,a,r,c]);const S=o.useMemo(()=>{const j=Array.from({length:w},()=>[]);for(const C of u){const k=g.get(C.tabKey)??0,v=Math.min(k,w-1);j[v].push(C)}return j},[u,g,w]),R=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:d,normalizedGroupAssignments:g,numGroups:w,isSplitMode:A,groupedConvs:S,moveTabToGroup:m,closeGroup:f,handleResizeStart:b,splitTabRelative:h,clearAllSplits:R}}function ih({ides:e,sendDaemonCommand:s}){const r="0.8.96",n=o.useMemo(()=>e.filter(d=>d.type!=="adhdev-daemon"?!1:tl(d,r)).sort((d,x)=>Number(dr(x,r))-Number(dr(d,r))),[r,e]),a=o.useMemo(()=>n.some(d=>dr(d,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),p=o.useCallback(async d=>{var x,g;u(w=>({...w,[d]:"upgrading"}));try{const w=await s(d,"daemon_upgrade",{});(x=w==null?void 0:w.result)!=null&&x.upgraded||(g=w==null?void 0:w.result)!=null&&g.success?u(A=>({...A,[d]:"done"})):u(A=>({...A,[d]:"error"}))}catch{u(w=>({...w,[d]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:p}}const Ia="adhdev_dashboard_notifications_v2",Aa="adhdev_dashboard_notifications_v1",Ir=80;function rn(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function fo(e){return{...e,createdAt:rn(e.createdAt),updatedAt:rn(e.updatedAt,e.createdAt),lastEventAt:rn(e.lastEventAt,e.updatedAt||e.createdAt)}}function ch(e){const s=Wa(e);return s==="unknown:"?e.id:s}function gi(e){return[e.type,ic(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function lh(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=gi({type:"task_complete",sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,lastMessageHash:l.lastMessageHash,lastMessageAt:l.lastMessageAt,lastUpdated:(u==null?void 0:u.lastUpdated)||l.lastUpdated}),d=!!((c=n==null?void 0:n.get(p))!=null&&c.forceUnread),x=jn(l,s,{notificationStateBySessionId:r}),g=x.inboxBucket==="needs_attention"?"needs_attention":x.inboxBucket==="task_complete"&&x.unread||(u==null?void 0:u.inboxBucket)==="task_complete"&&d?"task_complete":null;if(!g)continue;const w=rn(l.lastMessageAt||(u==null?void 0:u.lastUpdated)||l.lastUpdated,a),A=g==="task_complete"?p:gi({type:g,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(fo({id:A,dedupKey:A,type:g,routeId:l.routeId,machineId:l.daemonId||l.routeId,sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,title:jc(l),preview:jm(l),createdAt:w,updatedAt:w,lastEventAt:w}))}return i.sort((l,u)=>u.updatedAt-l.updatedAt)}function dh(e,s=Ir){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=ch(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 uh(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 mh(e){return new Map(e.map(s=>[s.id,s]))}function hl(e,s,r=Ir){const n=new Map;for(const i of s)n.set(i.id,i);const a=e.map(i=>{const c=fo(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 dh(a,r)}function fh(e,s,r=Ir){const n=new Set(hl(s,[],r).map(a=>a.id));return e.filter(a=>n.has(a.id)).slice(0,Math.max(0,r))}function ph(e,s,r=Date.now()){const n=e.filter(a=>a.id!==s);return n.push({id:s,readAt:r}),n}function hh(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,forceUnread:!0}),r}function xh(e,s,r,n=Date.now()){const a=e.filter(i=>{const c=s.find(l=>l.id===i.id);return!c||!xr(c,r)});for(const i of s)xr(i,r)&&a.push({id:i.id,readAt:n});return a}function bh(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,deletedAt:Date.now()}),r}function gh(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function yh(e){const s=new Map;for(const r of e){if(r.deletedAt)continue;const n=rs(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 vh(){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(Ia),r=s?JSON.parse(s):[];if(Array.isArray(r))return r.map(e).filter(n=>!!n)}catch{}try{const s=window.localStorage.getItem(Aa),r=s?JSON.parse(s):[];return Array.isArray(r)?uh(r.map(n=>fo(n)).filter(n=>!n.deletedAt)):[]}catch{return[]}}function wh(e){if(!(typeof window>"u"))try{const s=e.filter(r=>typeof r.readAt=="number"||typeof r.deletedAt=="number"||r.forceUnread===!0).slice(0,Ir);if(s.length===0){window.localStorage.removeItem(Ia),window.localStorage.removeItem(Aa);return}window.localStorage.setItem(Ia,JSON.stringify(s)),window.localStorage.removeItem(Aa)}catch{}}function jh(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 kh(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=Ir}=e,[a,i]=o.useState(()=>vh()),c=o.useMemo(()=>mh(a),[a]),l=o.useMemo(()=>lh(s,r,void 0,c),[s,r,c]),u=o.useMemo(()=>hl(l,a,n),[l,a,n]),p=o.useMemo(()=>yh(u),[u]);o.useEffect(()=>{i(m=>{const f=fh(m,l,n);return jh(m,f)?m:f})},[l,n]),o.useEffect(()=>{wh(a)},[a]);const d=o.useMemo(()=>gh(u),[u]),x=o.useCallback((m,f)=>{i(b=>ph(b,m,f))},[]),g=o.useCallback(m=>{i(f=>hh(f,m))},[]),w=o.useCallback((m,f)=>{i(b=>xh(b,u,m,f))},[u]),A=o.useCallback(m=>{i(f=>bh(f,m))},[]);return{notifications:u,unreadCount:d,notificationStateBySessionId:p,markRead:x,markUnread:g,markTargetRead:w,deleteNotification:A}}function xl(){return"select_session"}function Sh(){return"open_panel"}function Nh({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function Ch(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function yi(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function vi(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function po(e){return e instanceof Error?e.message:String(e||"")}function wi(e){const s=po(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function ji(e,s){const r=po(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function Sn({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:a}){const[i,c]=o.useState(!1),[l,u]=o.useState(!1),[p,d]=o.useState(null),x=o.useRef(!1),g=o.useRef(null);o.useEffect(()=>{d(null)},[s==null?void 0:s.tabKey]);const w=o.useCallback(async b=>{if(!s)return!1;const h=b.trim(),S=Ya(s);if(Nh({hasMessage:!!h,blockedMessage:S,sendInFlight:x.current}))return S&&d(S),!1;const R=Date.now(),j={tabKey:s.tabKey,message:h,timestamp:R};if(Ch(g.current,j))return d(null),!0;x.current=!0,u(!0),d(null),g.current=j;const C=`${R}-${Math.random().toString(36).slice(2,8)}`,k={role:"user",content:h,timestamp:R,_localId:C},v=!0;r(y=>({...y,[j.tabKey]:[...y[j.tabKey]||[],k]}));try{const y=yr(s);if(!y)return g.current=yi(g.current,j),v&&r(M=>({...M,[j.tabKey]:(M[j.tabKey]||[]).filter(_=>_._localId!==C)})),d("Unable to send message right now."),!1;const $=await e(y,"send_chat",{message:h,...$s(s)}),L=vi($);if(v&&(L!=null&&L.deduplicated))return r(M=>({...M,[j.tabKey]:(M[j.tabKey]||[]).filter(_=>_._localId!==C)})),d(null),!0;if((L==null?void 0:L.sent)===!1)throw new Error((L==null?void 0:L.error)||"Send failed");if((L==null?void 0:L.success)===!1)throw new Error((L==null?void 0:L.error)||"Send failed");return setTimeout(()=>{const M=Date.now()-6e4;r(_=>{const W=_[j.tabKey];if(!W)return _;const H=W.filter(N=>N.timestamp>M);return H.length===W.length?_:{..._,[j.tabKey]:H}})},6e4),d(null),!0}catch(y){const $=po(y);return $.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",$):console.warn("Send blocked/failed",y),g.current=yi(g.current,j),r(L=>({...L,[j.tabKey]:(L[j.tabKey]||[]).filter(M=>M._localId!==C)})),d(Gm(y)),!1}finally{x.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(b){console.error("Relaunch failed",b)}},[s,e]),m=o.useCallback(async b=>{if(s)try{const S=(s.modalButtons||[]).indexOf(b),R=b.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),j=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(R),C=yr(s);if(!C)return;const k=await e(C,"resolve_action",{button:b,action:j?"approve":"reject",...S>=0&&{buttonIndex:S},...$s(s)}),v=vi(k);v.success||n(y=>[...y,{routeId:s.tabKey,text:ji(b,v==null?void 0:v.error),timestamp:Date.now()}])}catch(h){wi(h)||console.error("[ModalButton] Error:",h),n(S=>[...S,{routeId:s.tabKey,text:wi(h)?ji(b,h):`❌ **${b}** error`,timestamp:Date.now()}])}},[s,e,n]),f=o.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,Sh(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(b){console.error("Focus agent failed",b)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,sendFeedbackMessage:p,isFocusingAgent:i,handleSendChat:w,handleRelaunch:A,handleModalButton:m,handleFocusAgent:f}}const ho=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:d=null,handleFocusAgent:x,isFocusingAgent:g,actionLogs:w,userName:A,scrollToBottomRequestNonce:m,isInputActive:f=!0}){const b=il(s),h=b.status||b.modalMessage||b.modalButtons?{...s,...b.status?{status:b.status}:{},...b.modalMessage!==void 0?{modalMessage:b.modalMessage}:{},...b.modalButtons!==void 0?{modalButtons:b.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(dc,{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(Ss,{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(vf,{activeConv:h,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:d,isVisible:n,isInputActive:f})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(ja,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:d,handleFocusAgent:x,isFocusingAgent:g,actionLogs:w,userName:A,scrollToBottomRequestNonce:m,isInputActive:f})})]}):t.jsx(ja,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:d,handleFocusAgent:x,isFocusingAgent:g,actionLogs:w,userName:A,scrollToBottomRequestNonce:m,isInputActive:f})]})},(e,s)=>e.activeConv===s.activeConv&&e.isCliTerminal===s.isCliTerminal&&e.ideEntry===s.ideEntry&&e.terminalRef===s.terminalRef&&e.handleModalButton===s.handleModalButton&&e.handleRelaunch===s.handleRelaunch&&e.handleSendChat===s.handleSendChat&&e.isSendingChat===s.isSendingChat&&e.sendFeedbackMessage===s.sendFeedbackMessage&&e.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive);function Ih({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:p,onOpenNativeConversation:d,onOpenMachine:x,onOpenHistory:g,onOpenRemote:w,onHideConversation:A,onStopCli:m,cliViewMode:f,onSetCliViewMode:b,handleSendChat:h,handleFocusAgent:S,handleModalButton:R,handleRelaunch:j}){const C=o.useRef(null),k=nt(e)&&!s,v=k&&f==="terminal",y=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 ${y} 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(Ea,{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:mt(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(Ac,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>x(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[k&&f&&t.jsx(Ja,{mode:f,onChange:b,compact:!0}),k&&m&&t.jsx("button",{onClick:()=>{m(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:()=>g(e),type:"button",children:t.jsx(Ka,{size:14})}),!s&&!k&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:t.jsx(Pt,{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(ho,{activeConv:e,clearToken:0,isCliTerminal:v,ideEntry:n,terminalRef:C,handleModalButton:R,handleRelaunch:j,handleSendChat:h,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:S,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const Xn={unix:{cmd:"curl -fsSL https://adhf.dev/install | sh",shell:"Terminal",prompt:"$ "},powershell:{cmd:"irm https://adhf.dev/install.ps1 | iex",shell:"PowerShell",prompt:"PS> "},cmd:{cmd:"curl -fsSL https://adhf.dev/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd",shell:"CMD",prompt:"> "}};function Ah(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function bl(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(Ah())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Xn[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:Xn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:Xn[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 gl({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Pt},{key:"chats",label:"Chats",icon:es}];return t.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:t.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label: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 zr({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 Ts({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 sr({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 Vr({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}=qs(e.conversation),d=mt(e.conversation),x=Is(e.conversation),g=Oc(e.conversation,{requiresAction:s==="needs_attention"}),w=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",m=c?"text-text-secondary":"text-text-primary",f=c?"text-text-muted":"text-text-secondary",b=c?"text-text-secondary opacity-80":"text-text-muted",h=c?"text-text-muted opacity-80":"text-text-muted",S="text-[color:var(--status-warning)]";return t.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${w}`,onClick:()=>n(e.conversation),type:"button",children:[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(d)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${m}`,children:d}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${h}`,children:lc(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${f}`,children:[x,u?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${S} 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…"})]}):g==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:S,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${b}`,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 ki({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 Mh({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:p,onShowAllHidden:d,onOpenNewSession:x,onOpenMachine:g,onOpenSettings:w,onSectionChange:A,wsStatus:m="connected",isStandalone:f=!1}){const b=m==="disconnected"||m==="reconnecting"||m==="offline"||m==="auth_failed",h=c.length>0,S=s.length>0||r.length>0||n.length>0||a.length>0,R=e==="machines"?"Machines":"Chats",j=f?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",C=f?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return t.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[t.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${j}`,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:R}),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(vn,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:w,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:t.jsx(gn,{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] ${C}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:b?t.jsx(sr,{icon:t.jsx(ki,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:m==="offline"?"Your device appears to be offline. Waiting for network…":m==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?t.jsx(sr,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:f?"Waiting for your daemon":"Connect your machines",subtitle:f?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!f&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(bl,{})})}):t.jsx(Ts,{children:c.map((k,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:()=>g(k.id),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(k.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:k.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:k.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[k.unread," new"]}):k.total>0?`${k.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:k.subtitle}),k.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[k.total," chat",k.total!==1?"s":"",k.unread>0?` · ${k.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},k.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(zr,{title:"Needs attention",className:"mb-0"}),t.jsx(Ts,{children:s.map((k,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Vr,{item:k,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(zr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(Ts,{children:r.map((k,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Vr,{item:k,type:"task_complete",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(zr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(Ts,{children:n.map((k,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Vr,{item:k,type:"working",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&t.jsx(zr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(Ts,{children:a.map((k,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Vr,{item:k,type:"earlier",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))}):S?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):b?t.jsx(sr,{icon:t.jsx(ki,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):h?t.jsx(sr,{icon:t.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:t.jsx(es,{size:20})}),title:"No conversations yet",subtitle:"Your machines are available. Open a machine, wait for P2P to connect, then launch your first IDE, CLI, or ACP session."}):t.jsx(sr,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[t.jsx("span",{children:"Hidden"}),t.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:d,children:"Restore all"})]}),t.jsx(Ts,{className:"bg-bg-secondary/25",children:i.map((k,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(k),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:l(mt(k))}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:mt(k)}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:Is(k)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},k.tabKey))})]})]}),e==="chats"&&x&&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:x,"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(gl,{section:e,onSectionChange:A})]})}function Th(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 yl(e){const s=[e.workspace||"Workspace unknown"],r=Ns(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=Th(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Nn(...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 Lh(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 Cn(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=Lh(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 Rh(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 _h(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function In(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=_h(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,d)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${d}`:p==="/"||p==="\\"?`${c}${d}`:`${p.replace(/[\\/]+$/,"")}${c}${d}`,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,d)=>p.name.localeCompare(d.name)):[];return{path:i,directories:u}}function An({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:p}){const[d,x]=o.useState(r);o.useEffect(()=>{x(r)},[r]);const g=Rh(r),w=d.trim();return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:t.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:l,"aria-label":"Close folder browser",children:t.jsx(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:()=>{!g||a||u(g)},disabled:!g||a,children:[t.jsx(Ea,{size:15}),"Parent"]}),t.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"text",value:d,onChange:A=>x(A.target.value),onKeyDown:A=>{A.key!=="Enter"||!w||a||(A.preventDefault(),u(w))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!w||a||u(w)},disabled:!w||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(Os,{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(w||r),disabled:!w&&!r||a,children:c})]})]})})}function xo({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:p,argsValue:d,onArgsChange:x,showModelInput:g,modelValue:w,onModelChange:A,historyProviderNode:m,onConfirm:f,onCancel:b}){const h=n==null?void 0:n.find(S=>S.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:b,"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:S=>i(S.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(S=>t.jsx("option",{value:S.key,children:S.label},S.key))}),(h==null?void 0:h.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h.description})]}),m,r.map(S=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:S.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:S.value})]},`${S.label}:${S.value}`)),g&&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:w||"",onChange:S=>A(S.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&&x&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),t.jsx("input",{type:"text",value:d||"",onChange:S=>x(S.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:b,disabled:u,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:f,disabled:u,children:[t.jsx(Ba,{size:14}),u?l:c]})]})]})})}function Si(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ws(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?"⭐ ":""}${Si(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:Si(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 Ph(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Dh(e){return[Ph(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Eh(e){return e.lastLaunchedAt?wn(e.lastLaunchedAt):""}function vl(e){return{metaText:Dh(e),updatedLabel:Eh(e)}}function Jn(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function $h({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var tt,Ct,pt,st;const c=Nr(),[l,u]=o.useState(!1),p=(((tt=e.detectedIdes)==null?void 0:tt.length)||0)>0,d=o.useMemo(()=>(e.workspaces||[]).map(Re=>({id:Re.id,path:Re.path,label:Re.label})),[e]),x=e.defaultWorkspaceId||null,[g,w]=o.useState(x||((Ct=d[0])==null?void 0:Ct.id)||""),[A,m]=o.useState(""),[f,b]=o.useState(""),[h,S]=o.useState([]),[R,j]=o.useState(!1),[C,k]=o.useState(""),[v,y]=o.useState(!1),[$,L]=o.useState(Jn(p,s.length,r.length)),M=o.useRef(null),[_,W]=o.useState(null),H=o.useRef("__home__"),[N,P]=o.useState("__home__"),[G,I]=o.useState(""),[E,B]=o.useState(""),[U,V]=o.useState(""),[ae,we]=o.useState([]),[be,Y]=o.useState(()=>wt().textQuery),[he,O]=o.useState(()=>wt().workspaceQuery),[X,ie]=o.useState(()=>wt().modelQuery),[le,me]=o.useState(()=>wt().resumableOnly),[ke,de]=o.useState(()=>wt().sortMode),[oe,se]=o.useState(!1),[ue,te]=o.useState(!1),Ne=o.useRef(null),Se=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const Ae=g==="__custom__"?A.trim():((pt=d.find(Re=>Re.id===g))==null?void 0:pt.path)||"",T=g==="__custom__"&&!!Ae&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),xe=g!=="__custom__"&&((st=d.find(Re=>Re.id===g))==null?void 0:st.path)||"",ve=o.useMemo(()=>(e.recentLaunches||[]).map(Re=>Re.workspace),[e]),Q=o.useCallback(async Re=>{j(!0),k("");try{const Ge=await a(Re);b(Ge.path),m(Ge.path),S(Ge.directories)}catch(Ge){k(Ge instanceof Error?Ge.message:"Could not load folder")}finally{j(!1)}},[a]),ye=o.useCallback(()=>{var Ge;w("__custom__"),y(!0);const Re=Cn(e.platform,Nn(A.trim(),xe,ve,e.defaultWorkspacePath,(Ge=d.find(Be=>Be.id===x))==null?void 0:Ge.path,d.map(Be=>Be.path)));Q(Re)},[A,x,Q,ve,xe,e.platform,d]),_e=o.useCallback(Re=>{if(Re!=null&&Re.workspaceId){w(Re.workspaceId),m("");return}if(Re!=null&&Re.workspacePath){w("__custom__"),m(Re.workspacePath);return}w(""),m("")},[]),We=o.useCallback(Re=>{if(w(Re),Re==="__custom__"){ye();return}m("")},[ye]),Pe=o.useCallback(Re=>{w("__custom__"),m(Re)},[]),ze=o.useCallback((Re,Ge)=>{M.current=Ge,H.current=Re.selectedWorkspaceKey||"__home__",P(Re.selectedWorkspaceKey||"__home__"),I(Re.initialArgs||""),B(Re.initialModel||""),V(""),we([]);const Be=Re.providerType?`${e.id}:${Re.providerType}`:null;if(Nf(Se.current,Be)){const qe=wt();Y(qe.textQuery),O(qe.workspaceQuery),ie(qe.modelQuery),me(qe.resumableOnly),de(qe.sortMode)}Se.current=Be,W(Re),Re.providerType&&i&&(se(!0),i(Re.providerType).then(qe=>we(qe||[])).catch(qe=>console.warn("Failed to load saved sessions",qe)).finally(()=>se(!1)))},[i,e.id]),Qe=o.useMemo(()=>Fc(ae,{textQuery:be,workspaceQuery:he,modelQuery:X,resumableOnly:le,sortMode:ke}),[X,le,ae,ke,be,he]);o.useEffect(()=>{U&&(Qe.some(Re=>Re.providerSessionId===U)||V(""))},[Qe,U]);const it=o.useCallback(()=>{M.current&&(te(!0),M.current().finally(()=>{M.current=null,te(!1),W(null)}))},[]),et=o.useCallback(()=>{M.current=null,W(null)},[]),ft=o.useCallback(Re=>{H.current=Re,P(Re)},[]);return o.useEffect(()=>{var Re;Ne.current!==e.id&&(Ne.current=e.id,w(x||((Re=d[0])==null?void 0:Re.id)||"__custom__"),m(""),b(""),S([]),k(""),y(!1),Y(wt().textQuery),O(wt().workspaceQuery),ie(wt().modelQuery),me(wt().resumableOnly),de(wt().sortMode),Se.current=null,L(Jn(p,s.length,r.length)))},[r.length,s.length,x,p,e.id,d]),o.useEffect(()=>{var Re;g!=="__custom__"&&(g&&d.some(Ge=>Ge.id===g)||w(x||((Re=d[0])==null?void 0:Re.id)||"__custom__"))},[x,g,d]),o.useEffect(()=>{$==="ide"&&p||$==="cli"&&s.length>0||$==="acp"&&r.length>0||L(Jn(p,s.length,r.length))},[$,r.length,s.length,p]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:d,defaultWorkspaceId:x,workspaceChoice:g,customWorkspacePath:A,browseCurrentPath:f,browseDirectories:h,browseBusy:R,browseError:C,browseDialogOpen:v,activeLauncherKind:$,launchConfirm:_,launchConfirmWorkspaceKeyRef:H,launchConfirmWorkspaceKey:N,launchConfirmArgs:G,launchConfirmModel:E,launchConfirmResumeId:U,launchConfirmSavedSessions:ae,launchConfirmTextFilter:be,launchConfirmWorkspaceFilter:he,launchConfirmModelFilter:X,launchConfirmResumableOnly:le,launchConfirmSortMode:ke,filteredLaunchConfirmSavedSessions:Qe,launchConfirmSessionsLoading:oe,launchConfirmBusy:ue,resolvedWorkspacePath:Ae,canCreateMissingWorkspace:T,openBrowseDialog:ye,loadBrowsePath:Q,handleWorkspaceChoiceChange:We,chooseCustomWorkspacePath:Pe,setCustomWorkspacePath:m,setBrowseDialogOpen:y,setActiveLauncherKind:L,openLaunchConfirm:ze,handleConfirmLaunch:it,closeLaunchConfirm:et,setWorkspaceSelectionFromOption:_e,setLaunchConfirmWorkspaceKeyAndSync:ft,setLaunchConfirmArgs:I,setLaunchConfirmModel:B,setLaunchConfirmResumeId:V,setLaunchConfirmTextFilter:Y,setLaunchConfirmWorkspaceFilter:O,setLaunchConfirmModelFilter:ie,setLaunchConfirmResumableOnly:me,setLaunchConfirmSortMode:de}}function Kh({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:p,showBottomNav:d,onBack:x,onSectionChange:g,onOpenConversation:w,onOpenRecent:A,onOpenMachineDetails:m,onMachineUpgrade:f,onLaunchDetectedIde:b,onAddWorkspace:h,onBrowseDirectory:S,onLaunchWorkspaceProvider:R,onListSavedSessions:j}){const C=N=>N==="ide"?"IDE":N==="cli"?"CLI":"ACP",k=r.slice(0,4),v=s.slice(0,3),y=$h({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:S,onListSavedSessions:j}),$=o.useMemo(()=>k.map(N=>{const{metaText:P,updatedLabel:G}=vl(N);return{key:`recent-launch:${N.id}`,primary:N.label,secondary:P,updatedLabel:G,onClick:()=>{const{options:I,selectedKey:E}=ws({machine:{workspaces:y.workspaceRows,defaultWorkspaceId:y.defaultWorkspaceId},currentWorkspacePath:N.workspace});y.openLaunchConfirm({title:N.kind==="ide"?bs("restart-ide",N.label):N.providerSessionId?eo(N.label):bs("start-fresh",N.label),description:N.kind==="ide"?gs("restart-ide"):N.providerSessionId?to():gs("start-fresh"),confirmLabel:N.kind==="ide"?Us("restart-ide"):N.providerSessionId?fn(!0):Us("start-fresh"),busyLabel:N.kind==="ide"?zs("restart-ide"):N.providerSessionId?Qa(!0):zs("start-fresh"),workspaceOptions:I,selectedWorkspaceKey:E,details:[{label:"Mode",value:C(N.kind)},...N.providerType?[{label:"Provider",value:N.providerType}]:[]]},async()=>{const B=I.find(U=>U.key===y.launchConfirmWorkspaceKeyRef.current);y.setWorkspaceSelectionFromOption(B),await A({...N,workspace:(B==null?void 0:B.workspacePath)??null})})}}}),[y,A,k]),L=o.useMemo(()=>v.map(N=>({key:`recent-chat:${N.conversation.tabKey}`,primary:mt(N.conversation),secondary:xf(N.conversation,{timestampLabel:N.timestamp?lc(N.timestamp):null}),unread:N.unread,onClick:()=>w(N.conversation)})),[w,v]),M=y.showAllRecent?$:$.slice(0,4),_=$.length>0,W=L.length>0,H=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 ${H} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:x,type:"button","aria-label":"Back",children:t.jsx(Ea,{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:[W&&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:L.map(N=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${N.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:N.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:N.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))})]}),_&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:M.map(N=>t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:N.onClick,children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:N.primary}),N.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:N.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))}),$.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:()=>y.setShowAllRecent(N=>!N),children:y.showAllRecent?"Show fewer":`Show ${$.length-4} more`})})]}),(y.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:y.workspaceChoice,onChange:N=>y.handleWorkspaceChoiceChange(N.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:y.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[y.workspaceRows.map(N=>t.jsxs("option",{value:N.id,children:[N.id===y.defaultWorkspaceId?"⭐ ":"",kn(N.path,N.label)||N.path]},N.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),y.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(Os,{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:y.resolvedWorkspacePath||y.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:y.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:()=>{y.resolvedWorkspacePath&&h(y.resolvedWorkspacePath)},disabled:!y.resolvedWorkspacePath||y.browseBusy,children:"Save as workspace"})]})]}),y.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:y.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[y.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${y.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:()=>y.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${y.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:()=>y.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${y.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:()=>y.setActiveLauncherKind("acp"),children:"ACP"})]}),y.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:y.activeLauncherKind==="ide"?"Choose an IDE":y.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:y.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(N=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:P,selectedKey:G}=ws({machine:{workspaces:y.workspaceRows,defaultWorkspaceId:y.defaultWorkspaceId},currentWorkspaceId:y.workspaceChoice!=="__custom__"?y.workspaceChoice:null,currentWorkspacePath:y.resolvedWorkspacePath});y.openLaunchConfirm({title:`Launch ${N.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:P,selectedWorkspaceKey:G,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:N.name}]},async()=>{const I=P.find(E=>E.key===y.launchConfirmWorkspaceKeyRef.current);y.setWorkspaceSelectionFromOption(I),b(N.type,{workspacePath:(I==null?void 0:I.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:N.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:y.resolvedWorkspacePath||"Use selected workspace"})]},N.type)):(y.activeLauncherKind==="cli"?n:a).map(N=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const P=y.activeLauncherKind==="cli"?"cli":"acp",{options:G,selectedKey:I}=ws({machine:{workspaces:y.workspaceRows,defaultWorkspaceId:y.defaultWorkspaceId},currentWorkspaceId:y.workspaceChoice!=="__custom__"?y.workspaceChoice:null,currentWorkspacePath:y.resolvedWorkspacePath});y.openLaunchConfirm({title:`Launch ${N.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${P.toUpperCase()}`,workspaceOptions:G,selectedWorkspaceKey:I,details:[{label:"Mode",value:P.toUpperCase()},{label:"Provider",value:N.displayName}],showArgsInput:!0,showModelInput:P==="acp",initialArgs:"",initialModel:"",providerType:N.type},async()=>{const E=G.find(B=>B.key===y.launchConfirmWorkspaceKeyRef.current);y.setWorkspaceSelectionFromOption(E),R(P,N.type,{workspaceId:(E==null?void 0:E.workspaceId)??null,workspacePath:(E==null?void 0:E.workspacePath)??null,args:y.launchConfirmArgs,model:y.launchConfirmModel,resumeSessionId:y.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[N.icon?`${N.icon} `:"",N.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:y.resolvedWorkspacePath||"Use selected workspace"})]},N.type))})]}),l.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,y.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(y.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:f,children:[t.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:m,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"})]})]})]})]}),y.browseDialogOpen&&t.jsx(An,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:y.browseCurrentPath,directories:y.browseDirectories,busy:y.browseBusy,error:y.browseError,confirmLabel:"Use this folder",onClose:()=>y.setBrowseDialogOpen(!1),onNavigate:N=>{y.loadBrowsePath(N)},onConfirm:N=>{y.chooseCustomWorkspacePath(N),y.setBrowseDialogOpen(!1)}}),y.launchConfirm&&t.jsx(xo,{title:y.launchConfirm.title,description:y.launchConfirm.description,details:y.launchConfirm.details,workspaceOptions:y.launchConfirm.workspaceOptions,selectedWorkspaceKey:y.launchConfirmWorkspaceKey,onWorkspaceChange:y.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:y.launchConfirm.providerType?fn(!!y.launchConfirmResumeId):y.launchConfirm.confirmLabel,busyLabel:y.launchConfirm.providerType?void 0:y.launchConfirm.busyLabel,busy:y.launchConfirmBusy,showArgsInput:y.launchConfirm.showArgsInput,argsValue:y.launchConfirmArgs,onArgsChange:y.setLaunchConfirmArgs,showModelInput:y.launchConfirm.showModelInput,modelValue:y.launchConfirmModel,onModelChange:y.setLaunchConfirmModel,historyProviderNode:y.launchConfirm.providerType&&(y.launchConfirmSessionsLoading||y.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"}),y.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:Za()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:y.launchConfirmTextFilter,onChange:N=>y.setLaunchConfirmTextFilter(N.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:y.launchConfirmWorkspaceFilter,onChange:N=>y.setLaunchConfirmWorkspaceFilter(N.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:y.launchConfirmModelFilter,onChange:N=>y.setLaunchConfirmModelFilter(N.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading}),t.jsxs("select",{value:y.launchConfirmSortMode,onChange:N=>y.setLaunchConfirmSortMode(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:y.launchConfirmBusy||y.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:y.launchConfirmResumableOnly,onChange:N=>y.setLaunchConfirmResumableOnly(N.target.checked),disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:y.launchConfirmResumeId,onChange:N=>y.setLaunchConfirmResumeId(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:Af()}),y.filteredLaunchConfirmSavedSessions.map(N=>t.jsxs("option",{value:N.providerSessionId,disabled:!N.canResume,children:[N.title||N.providerSessionId," ",N.canResume?"":"(workspace missing)"]},N.providerSessionId))]}),!y.launchConfirmSessionsLoading&&y.launchConfirmSavedSessions.length>0&&y.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),y.launchConfirmResumeId&&(()=>{const N=y.filteredLaunchConfirmSavedSessions.find(G=>G.providerSessionId===y.launchConfirmResumeId);if(!N)return null;const P=yl(N);return t.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[t.jsx("div",{className:"font-semibold text-text-primary truncate",children:P.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:P.providerSessionId}),t.jsx("div",{className:"mt-1",children:P.metaLine}),P.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:P.updatedLabel}),P.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:P.preview})]})})()]}),onConfirm:y.handleConfirmLaunch,onCancel:y.closeLaunchConfirm}),d&&t.jsx(gl,{section:p,onSectionChange:g})]})}function wl(e){var r;const s=((r=e.p2p)==null?void 0:r.state)||"";return s==="connected"?"Connected":s==="connecting"||s==="new"||s==="checking"?"Connecting":"Offline"}function Bh(e,s){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:Ns(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,d;const a=br(n)?"cli":Ds(n)?"acp":"ide",i=Ns(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(br(n)?n.cliName||n.type:Ds(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ds(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((d=(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:d.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Oh(e,s){const r=new Map;for(const n of s){const a=cs(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((x,g)=>g.timestamp-x.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=ba(n),u=a.filter(x=>x.unread||x.requiresAction).length,p=wl(n),d=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:_t(n,{fallbackId:n.id}),subtitle:d.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?bf(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 Gr(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 Wh({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:x,requestedMobileSection:g,onRequestedMobileSectionConsumed:w,setSelectedTabKey:A,setScreen:m,setSelectedMachineId:f,setSection:b,setMachineBackTarget:h,resetMachineAction:S,markNotificationTargetRead:R}){const j=o.useRef(null),C=o.useCallback(k=>{if(!(k!=null&&k.sessionId))return;const v=dn(k,c),y=Math.max(Date.now(),ps(k),v.lastUpdated||0);Gr("mark_read:start",{tabKey:k.tabKey,sessionId:k.sessionId,displayPrimary:mt(k),inboxBucket:v.inboxBucket,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,activityAt:ps(k),readAt:y}),R({sessionId:k.sessionId,providerSessionId:k.providerSessionId,tabKey:k.tabKey,routeId:k.routeId},y),l(cs(k)||k.routeId,"mark_session_seen",{sessionId:k.sessionId,seenAt:y}).then($=>{Gr("mark_read:result",{tabKey:k.tabKey,sessionId:k.sessionId,result:$})}).catch($=>{Gr("mark_read:error",{tabKey:k.tabKey,sessionId:k.sessionId,error:$ instanceof Error?$.message:String($)})})},[c,l]);return o.useEffect(()=>{var v;if(!n){m("inbox"),A(((v=e[0])==null?void 0:v.tabKey)||null),j.current=null;return}if(i!=="chat"){j.current=null;return}const k=`${n.tabKey}:${n.sessionId||""}`;j.current!==k&&(j.current=k,C(n))},[e,C,i,n,m,A]),o.useEffect(()=>{if(!u)return;const k=e.find(v=>v.tabKey===u);k&&(A(k.tabKey),m("chat"),p==null||p())},[e,p,u,m,A]),o.useEffect(()=>{if(!d)return;const k=s.find(v=>v.id===d);k&&(f(k.id),S(),b("machines"),h("inbox"),m("machine"),x==null||x())},[s,x,d,S,h,m,b,f]),o.useEffect(()=>{g&&(b(g),m("inbox"),w==null||w())},[w,g,m,b]),o.useEffect(()=>{const k=r.filter(v=>v.inboxBucket==="task_complete"||v.unread);k.length!==0&&Gr("inbox_state",{screen:i,selectedTabKey:a,items:k.map(v=>{const y=dn(v.conversation,c);return{liveState:y,tabKey:v.conversation.tabKey,sessionId:v.conversation.sessionId,displayPrimary:mt(v.conversation),serverBucket:y.inboxBucket,computedBucket:v.inboxBucket,serverUnread:y.unread,computedUnread:v.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,activityAt:ps(v.conversation)}})})},[r,c,i,a]),{markConversationRead:C}}function Hh(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Ni(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Fh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Uh({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,p]=o.useState(null),d=o.useCallback(()=>{i("idle"),l(""),p(null)},[]),x=o.useCallback(async(h,S,R)=>{var j;try{i("loading"),l(`Launching ${S}…`);const C={ideType:S,enableCdp:!0};(j=R==null?void 0:R.workspacePath)!=null&&j.trim()&&(C.workspace=R.workspacePath.trim()),await e(h,"launch_ide",C),i("done"),l(`${S} launch requested`)}catch(C){i("error"),l(C instanceof Error?C.message:"Launch IDE failed"),console.error("Launch IDE failed",C)}},[e]),g=o.useCallback(async(h,S,R)=>{if(S.trim())try{i("loading"),l(R!=null&&R.createIfMissing?"Creating folder…":"Saving workspace…");const j=await e(h,"workspace_add",{path:S.trim(),createIfMissing:(R==null?void 0:R.createIfMissing)===!0});if(j!=null&&j.success){i("done"),l(R!=null&&R.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((j==null?void 0:j.error)||"Could not save workspace")}catch(j){i("error"),l(j instanceof Error?j.message:"Could not save workspace")}},[e]),w=o.useCallback(async h=>{var S,R,j,C,k,v;try{i("loading"),l("Starting daemon upgrade…");const y=await e(h,"daemon_upgrade",{});if((S=y==null?void 0:y.result)!=null&&S.alreadyLatest){i("done"),l(`Already on v${((R=y==null?void 0:y.result)==null?void 0:R.version)||"latest"}.`);return}if((j=y==null?void 0:y.result)!=null&&j.upgraded||(C=y==null?void 0:y.result)!=null&&C.success){i("done"),l(`Upgrade to v${((k=y==null?void 0:y.result)==null?void 0:k.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((v=y==null?void 0:y.result)==null?void 0:v.error)||"Upgrade failed")}catch(y){i("error"),l(y instanceof Error?y.message:"Upgrade failed")}},[e]),A=o.useCallback(async(h,S,R,j)=>{var v,y,$;const C=Date.now(),k={machineId:h,kind:S,providerType:R,workspaceId:(j==null?void 0:j.workspaceId)||null,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:C};try{i("loading"),l(`Launching ${R}…`),p(k);const L={cliType:R};(v=j==null?void 0:j.workspacePath)!=null&&v.trim()?L.dir=j.workspacePath.trim():j!=null&&j.workspaceId&&(L.workspaceId=j.workspaceId),j!=null&&j.resumeSessionId&&(L.resumeSessionId=j.resumeSessionId),(y=j==null?void 0:j.args)!=null&&y.trim()&&(L.cliArgs=j.args.trim().split(/\s+/).filter(Boolean)),($=j==null?void 0:j.model)!=null&&$.trim()&&(L.initialModel=j.model.trim());const M=await e(h,"launch_cli",L),_=(M==null?void 0:M.result)||M,W=(_==null?void 0:_.sessionId)||(_==null?void 0:_.id);if(M!=null&&M.success&&W){p(null),i("done"),l(`${R} launched`),s(as(W));return}if(M!=null&&M.success){i("loading"),l(`${R} launch requested — waiting for session…`);return}p(null),i("error"),l((M==null?void 0:M.error)||(_==null?void 0:_.error)||`Could not launch ${S.toUpperCase()} workspace`)}catch(L){if(Fh(L)){i("loading"),l(`${R} launch requested — waiting for session…`);return}p(null),i("error"),l(L instanceof Error?L.message:`Could not launch ${S.toUpperCase()} workspace`)}},[s,e]),m=o.useCallback(async(h,S)=>{try{const R=await e(h,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),j=(R==null?void 0:R.result)??R;return Array.isArray(j==null?void 0:j.sessions)?j.sessions:[]}catch(R){return console.error("Failed to list saved sessions on mobile:",R),[]}},[e]),f=o.useCallback(async(h,S)=>In(e,h,S),[e]);o.useEffect(()=>{if(!u)return;const h=Ni(u.workspacePath),S=r.find(j=>{var L,M,_,W;if(!j||j.type==="adhdev-daemon"||Hh(j.daemonId||j.id)!==u.machineId||(j.transport==="acp"?"acp":j.transport==="pty"?"cli":null)!==u.kind||String(j.agentType||j.type||"")!==u.providerType)return!1;const y=String(j.providerSessionId||"");if(u.resumeSessionId&&y)return y===u.resumeSessionId;if(h){const H=Ni(j.workspace||j.runtimeWorkspaceLabel);return H?H===h:!1}return Number(j.lastUpdated||j._lastUpdate||j.timestamp||((W=(_=(M=(L=j.activeChat)==null?void 0:L.messages)==null?void 0:M.at)==null?void 0:_.call(M,-1))==null?void 0:W.timestamp)||0)>=u.startedAt-5e3});if(!S)return;const R=Ic({entrySessionId:S.sessionId,entryInstanceId:S.instanceId,entryRouteId:S.id,conversations:n});R&&(p(null),i("done"),l(`${u.providerType} launched`),s(as(R)))},[n,r,s,u]),o.useEffect(()=>{if(!u)return;const h=window.setTimeout(()=>{p(S=>!S||S.startedAt!==u.startedAt?S:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[u]);const b=o.useCallback(async(h,S)=>{if(S.kind==="ide"&&S.providerType){await x(h,S.providerType,{workspacePath:S.workspace||null});return}(S.kind==="cli"||S.kind==="acp")&&S.providerType&&await A(h,S.kind,S.providerType,{workspacePath:S.workspace||null,resumeSessionId:S.providerSessionId||null})},[x,A]);return{machineAction:{state:a,message:c},resetMachineAction:d,handleLaunchDetectedIde:x,handleAddWorkspace:g,handleMachineUpgrade:w,handleLaunchWorkspaceProvider:A,handleListSavedSessions:m,handleBrowseDirectory:f,handleOpenRecent:b}}function zh({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:p}){const d=o.useCallback(b=>{i(b.tabKey),c("chat"),n(b)},[n,c,i]),x=o.useCallback(b=>{const h=e.find(S=>S.routeId===b.routeId&&S.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),g=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),w=o.useCallback((b,h="inbox")=>{l(b),a(),u("machines"),p(h),c("machine")},[a,p,c,u,l]),A=o.useCallback(b=>{const h=cs(b);h&&w(h,"chat")},[w]),m=o.useCallback(()=>{a(),c(r)},[r,a,c]),f=o.useCallback(b=>{u(b),c("inbox")},[c,u]);return{openConversation:d,openNativeConversation:x,backFromConversation:g,openMachine:w,openConversationMachine:A,backFromMachine:m,changeMachineSection:f}}function Vh(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function qr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Gh({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,userName:u,requestedActiveTabKey:p,onRequestedActiveTabConsumed:d,requestedMachineId:x,onRequestedMachineConsumed:g,requestedMobileSection:w,onRequestedMobileSectionConsumed:A,onOpenHistory:m,onOpenRemote:f,onStopCli:b,wsStatus:h,isConnected:S,onShowHiddenConversation:R,onShowAllHiddenConversations:j,onHideConversation:C,onOpenNewSession:k,notificationStateBySessionId:v,liveSessionInboxState:y,onMarkNotificationTargetRead:$}){const[L,M]=o.useState(()=>{var Q;return((Q=e[0])==null?void 0:Q.tabKey)||null}),[_,W]=o.useState(()=>e[0]?"chat":"inbox"),[H,N]=o.useState("chats"),[P,G]=o.useState(null),[I,E]=o.useState("inbox"),B=Vs(),U="0.8.96",V=o.useMemo(()=>e.find(Q=>Q.tabKey===L)||e[0]||null,[e,L]),ae=o.useMemo(()=>V?r.find(Q=>Q.id===V.routeId):void 0,[r,V]),we=o.useMemo(()=>!V||Ze(V)||!nt(V)?null:Hs(V),[V]),be=o.useMemo(()=>r.filter(Q=>Q.type==="adhdev-daemon").sort(Fa),[r]),Y=o.useMemo(()=>be.find(Q=>Q.id===P)||null,[be,P]),he=Sn({sendDaemonCommand:a,activeConv:V||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),O=Uh({sendDaemonCommand:a,navigate:B,ides:r,conversations:e}),X=o.useMemo(()=>e.map(Q=>{const ye=_==="chat"&&(V==null?void 0:V.tabKey)===Q.tabKey,_e=jn(Q,y,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ye,notificationStateBySessionId:v}),We=ps(Q),Pe=Bc(Q);return{conversation:Q,timestamp:We,preview:Pe,unread:_e.unread,requiresAction:_e.requiresAction,isWorking:_e.isWorking,inboxBucket:_e.inboxBucket}}),[e,y,v,_,V]),{markConversationRead:ie}=Wh({conversations:e,machineEntries:be,items:X,selectedConversation:V,selectedTabKey:L,screen:_,liveSessionInboxState:y,sendDaemonCommand:a,requestedActiveTabKey:p,onRequestedActiveTabConsumed:d,requestedMachineId:x,onRequestedMachineConsumed:g,requestedMobileSection:w,onRequestedMobileSectionConsumed:A,setSelectedTabKey:M,setScreen:W,setSelectedMachineId:G,setSection:N,setMachineBackTarget:E,resetMachineAction:O.resetMachineAction,markNotificationTargetRead:$}),le=zh({conversations:e,selectedConversation:V,machineBackTarget:I,markConversationRead:ie,resetMachineAction:O.resetMachineAction,setSelectedTabKey:M,setScreen:W,setSelectedMachineId:G,setSection:N,setMachineBackTarget:E}),me=o.useMemo(()=>qr(X.filter(Q=>Q.requiresAction)),[X]),ke=o.useMemo(()=>qr(X.filter(Q=>Q.unread&&!Q.requiresAction)),[X]),de=o.useMemo(()=>qr(X.filter(Q=>!Q.unread&&!Q.requiresAction&&Q.isWorking)),[X]),oe=o.useMemo(()=>qr(X.filter(Q=>!Q.unread&&!Q.requiresAction&&!Q.isWorking)),[X]),se=o.useMemo(()=>Y?X.filter(Q=>cs(Q.conversation)===Y.id):[],[X,Y]),ue=o.useMemo(()=>Bh(Y,r),[r,Y]),te=(Y==null?void 0:Y.version)||null,Ne=!!Y&&!!te&&!0&&te!==U,Se=o.useMemo(()=>(Y==null?void 0:Y.availableProviders)||[],[Y]),Ae=o.useMemo(()=>Se.filter(Q=>Q.category==="cli"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[Se]),T=o.useMemo(()=>Se.filter(Q=>Q.category==="acp"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[Se]),xe=o.useMemo(()=>Oh(be,X),[X,be]),ve=o.useCallback(async Q=>{Y&&await O.handleOpenRecent(Y.id,Q)},[O,Y]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:_==="chat"&&V?t.jsx(Ih,{selectedConversation:V,isAcp:Ze(V),isStandalone:l,selectedIdeEntry:ae,actionLogs:n,userName:u,isSendingChat:he.isSendingChat,sendFeedbackMessage:he.sendFeedbackMessage,isFocusingAgent:he.isFocusingAgent,handleModalButton:he.handleModalButton,handleRelaunch:he.handleRelaunch,onBack:le.backFromConversation,onOpenNativeConversation:le.openNativeConversation,onOpenMachine:le.openConversationMachine,onHideConversation:C,onOpenHistory:m,onOpenRemote:f,onStopCli:b,cliViewMode:we,onSetCliViewMode:async Q=>{if(V&&we!==Q)try{await a(cs(V)||V.routeId,"set_cli_view_mode",{targetSessionId:V.sessionId,cliType:Wt(V),mode:Q})}catch(ye){const _e=uo(ye);lo(ye)?console.warn(_e?"CLI view mode result was lost after send; keeping optimistic mobile mode override:":"Skipped CLI view mode switch:",ye instanceof Error?ye.message:String(ye)):console.error("Failed to switch CLI view mode:",ye)}},handleSendChat:he.handleSendChat,handleFocusAgent:he.handleFocusAgent}):_==="machine"&&Y?t.jsx(Kh,{selectedMachineEntry:Y,selectedMachineConversations:se,selectedMachineRecentLaunches:ue,cliProviders:Ae,acpProviders:T,selectedMachineNeedsUpgrade:Ne,appVersion:U,machineAction:O.machineAction,isStandalone:l,section:H,showBottomNav:I==="inbox",onBack:le.backFromMachine,onSectionChange:le.changeMachineSection,onOpenConversation:le.openConversation,onOpenRecent:ve,onOpenMachineDetails:()=>B(`/machines/${Y.id}`),onMachineUpgrade:()=>O.handleMachineUpgrade(Y.id),onLaunchDetectedIde:(Q,ye)=>O.handleLaunchDetectedIde(Y.id,Q,ye),onAddWorkspace:(Q,ye)=>O.handleAddWorkspace(Y.id,Q,ye),onBrowseDirectory:Q=>O.handleBrowseDirectory(Y.id,Q),onLaunchWorkspaceProvider:(Q,ye,_e)=>O.handleLaunchWorkspaceProvider(Y.id,Q,ye,_e),onListSavedSessions:Q=>O.handleListSavedSessions(Y.id,Q)}):t.jsx(Mh,{section:H,attentionItems:me,unreadItems:ke,workingItems:de,completedItems:oe,hiddenConversations:s,machineCards:xe,getAvatarText:Vh,onOpenConversation:le.openConversation,onShowConversation:R,onShowAllHidden:j,onOpenNewSession:k,onOpenMachine:le.openMachine,onOpenSettings:()=>B("/settings"),onSectionChange:N,wsStatus:h,isConnected:S,isStandalone:l})})}function Qn(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function qh({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[p,d]=o.useState(null),x=o.useCallback(()=>{c.current=0,u(!1),d(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",x),window.addEventListener("drop",x),()=>{window.removeEventListener("dragend",x),window.removeEventListener("drop",x)}),[x]);const g=o.useCallback(f=>{f.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),w=o.useCallback(f=>{if(!f.dataTransfer.types.includes("text/tab-key"))return;if(f.preventDefault(),!Qn(s,r)){d("merge");return}const b=f.currentTarget.getBoundingClientRect(),h=f.clientX-b.left,S=b.width/3;h<S?d("split-left"):h>S*2?d("split-right"):d("merge")},[s,r]),A=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),d(null))},[]),m=o.useCallback(f=>{c.current=0,u(!1);const b=f.dataTransfer.getData("text/tab-key"),h=b?e.some(R=>R.tabKey===b):!1,S=p;if(d(null),i(),!!b){if(f.preventDefault(),S==="split-left"&&Qn(s,r)){r==null||r(b,"split-left");return}if(S==="split-right"&&Qn(s,r)){r==null||r(b,"split-right");return}if(h){a(b);return}n==null||n(b)}},[e,p,s,r,n,a,i]);return{dragOver:l,dropAction:p,resetDragState:x,handleDragEnter:g,handleDragOver:w,handleDragLeave:A,handleDrop:m}}function Yh(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 Xh({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(s??null),[l,u]=o.useState(r??[]),[p,d]=o.useState(null),x=o.useRef(null),g=o.useRef(null),w=o.useRef(n),A=o.useRef(a);o.useEffect(()=>{w.current=n},[n]),o.useEffect(()=>{A.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{u(k=>{const v=Yh(k,e);return v.length===k.length&&v.every((y,$)=>y===k[$])?k:v})},[e]);const m=o.useMemo(()=>{const k=p??l;if(k.length===0)return e;const v=new Map(k.map((y,$)=>[y,$]));return[...e].sort((y,$)=>{const L=v.get(y.tabKey)??999,M=v.get($.tabKey)??999;return L-M})},[e,p,l]);o.useEffect(()=>{var v,y;if(m.length===0){i!==null&&(c(null),(v=w.current)==null||v.call(w,null));return}if(i&&m.some($=>$.tabKey===i))return;const k=m[0].tabKey;k!==i&&(c(k),(y=w.current)==null||y.call(w,k))},[m,i]);const f=o.useMemo(()=>m.find(k=>k.tabKey===i),[m,i]),b=o.useCallback(k=>{var v;c(k),(v=w.current)==null||v.call(w,k)},[]),h=o.useCallback((k,v,y)=>{u($=>{var W;const L=$.filter(H=>H!==k),M=L.indexOf(v);if(M<0)return $;const _=y==="left"?M:M+1;return L.splice(_,0,k),(W=A.current)==null||W.call(A,L),L}),d(null)},[]),S=o.useCallback((k,v,y)=>{const L=(l.length>0?l:e.map(W=>W.tabKey)).filter(W=>W!==k),M=L.indexOf(v);if(M<0)return;const _=y==="left"?M:M+1;L.splice(_,0,k),x.current=L,d(L)},[l,e]),R=o.useCallback(()=>{var v;const k=x.current;k&&(u(k),(v=A.current)==null||v.call(A,k))},[]),j=o.useCallback(()=>{x.current=null,d(null)},[]),C=o.useCallback(k=>{u(v=>{var $;const y=v.filter(L=>L!==k);return y.push(k),($=A.current)==null||$.call(A,y),y})},[]);return{activeTabId:i,activeConv:f,sortedConversations:m,previewOrderRef:x,draggingTabRef:g,selectTab:b,handleTabReorder:h,updatePreviewOrder:S,commitPreviewOrder:R,clearPreviewOrder:j,moveTabToEnd:C,setDraggingTabKey:k=>{g.current=k}}}function Jh({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 bo({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(bl,{}),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 jl="adhdev-tab-shortcuts";function kl(){try{return JSON.parse(localStorage.getItem(jl)||"{}")}catch{return{}}}function Sl({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>kl()),[l,u]=o.useState(null),p=o.useCallback(x=>{const g=[];return x.metaKey&&g.push(a?"⌘":"Meta"),x.ctrlKey&&g.push("Ctrl"),x.altKey&&g.push(a?"⌥":"Alt"),x.shiftKey&&g.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(x.key)?null:(g.push(x.key.length===1?x.key.toUpperCase():x.key),g.join("+"))},[a]),d=o.useCallback(x=>{c(x);try{localStorage.setItem(jl,JSON.stringify(x))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const x=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){u(null);return}const w=p(g);if(!w)return;const A={...i};for(const[m,f]of Object.entries(A))f===w&&delete A[m];A[l]=w,d(A),u(null)};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[e,l,i,d,p]),o.useEffect(()=>{if(!e)return;const x=g=>{if(!(!g.ctrlKey&&!g.metaKey&&!g.altKey)){for(const[w,A]of Object.entries(i))if(s.includes(w)&&p(g)===A){g.preventDefault(),r(),n(w);return}}};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[e,i,s,r,n,p]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:d}}const Qh=o.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:p,onConversationActivated:d,onPreviewReorder:x,onReorderTab:g,onCommitPreviewOrder:w,onClearPreviewOrder:A,onDragStateReset:m,onDragTabKeyChange:f,onReceiveTab:b,onOpenContextMenu:h,longPressTimer:S,isGroupActive:R}){const j=qs(s),C=j.isGenerating?"agent-tab-generating":j.isWaiting?"agent-tab-waiting":"",k=j.isReconnecting,v=o.useCallback(P=>{l.current=s.tabKey,f(s.tabKey),P.dataTransfer.setData("text/tab-key",s.tabKey),P.dataTransfer.effectAllowed="move"},[s.tabKey,l,f]),y=o.useCallback(()=>{l.current=null,f(null),w(),A(),m()},[l,f,w,A,m]),$=o.useCallback(P=>{const G=l.current;if(!(!G||G===s.tabKey)&&P.dataTransfer.types.includes("text/tab-key")){P.preventDefault(),P.stopPropagation();const I=P.currentTarget.getBoundingClientRect(),E=P.clientX<I.left+I.width/2?"left":"right";x(G,s.tabKey,E)}},[s.tabKey,l,x]),L=o.useCallback(P=>{P.preventDefault(),P.stopPropagation();const G=P.dataTransfer.getData("text/tab-key");if(G&&G!==s.tabKey){const I=P.currentTarget.getBoundingClientRect(),E=P.clientX<I.left+I.width/2?"left":"right";c.includes(G)?g(G,s.tabKey,E):b&&b(G)}A()},[s.tabKey,c,g,b,A]),M=o.useCallback(P=>{P.stopPropagation(),u(),p(s.tabKey),d(s)},[s,d,u,p]),_=o.useCallback(P=>{P.preventDefault(),h(P.clientX,P.clientY,s.tabKey)},[s.tabKey,h]),W=o.useCallback(P=>{const G=P.touches[0];S.current=setTimeout(()=>{h(G.clientX,G.clientY,s.tabKey)},600)},[s.tabKey,S,h]),H=o.useCallback(()=>{S.current&&clearTimeout(S.current)},[S]),N=["adhdev-dockview-tab",C,r&&"is-active",R&&"is-group-active",k&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:N,draggable:!0,onDragStart:v,onDragEnd:y,onDragOver:$,onDrop:L,onClick:M,onContextMenu:_,onTouchStart:W,onTouchEnd:H,onTouchMove:H,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:j.isGenerating?t.jsx("div",{className:"tab-spinner"}):j.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):k?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):j.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:mt(s),children:mt(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:k?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:xs(s)}):j.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[xs(s),t.jsx("span",{className:"connecting-dots"})]}):xs(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 Zh({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:d,onClearPreviewOrder:x,onDragStateReset:g,onDragTabKeyChange:w,onReceiveTab:A,onHideTab:m,isGroupActive:f,allowTabShortcuts:b=!0}){const[h,S]=o.useState(null),R=o.useRef(null),j=o.useRef(null),C=o.useMemo(()=>e.map(_=>_.tabKey),[e]);jr("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:k,tabShortcuts:v,shortcutListening:y,setShortcutListening:$,saveShortcuts:L}=Sl({enabled:b,sortedTabKeys:e.map(_=>_.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const _=W=>{const H=document.querySelector("[data-pane-context-menu]");H&&H.contains(W.target)||S(null)};return window.addEventListener("mousedown",_,!0),()=>window.removeEventListener("mousedown",_,!0)},[h]),o.useEffect(()=>{const _=j.current;if(!_)return;const W=H=>{Math.abs(H.deltaY)<=Math.abs(H.deltaX)||(H.preventDefault(),_.scrollLeft+=H.deltaY)};return _.addEventListener("wheel",W,{passive:!1}),()=>_.removeEventListener("wheel",W)},[]);const M=o.useCallback((_,W,H)=>{S({x:_,y:W,tabKey:H})},[]);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:j,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(_=>t.jsx(Qh,{conv:_,isActive:s===_.tabKey,isDraggedTab:a.current===_.tabKey,isTaskCompleteUnread:n.has(_.tabKey),shortcut:b?v[_.tabKey]:void 0,conversationKeys:C,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:d,onClearPreviewOrder:x,onDragStateReset:g,onDragTabKeyChange:w,onReceiveTab:A,onOpenContextMenu:M,longPressTimer:R,isGroupActive:f},_.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:[b&&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:_=>{_.stopPropagation(),$(h.tabKey),S(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 _={...v};delete _[h.tabKey],L(_),S(null)},children:"✕ Remove shortcut"})]}),m&&t.jsxs(t.Fragment,{children:[b&&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:()=>{m(h.tabKey),S(null)},children:"🚫 Hide from Dashboard"})]})]}),b&&y&&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:_=>_.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",k?"⌘+1":"Ctrl+1",", ",k?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function ex({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,userName:p,groupIndex:d,onFocus:x,isSplitMode:g,numGroups:w,onMoveTab:A,onReceiveTab:m,style:f,onActiveTabChange:b,initialActiveTabId:h,initialTabOrder:S,onTabOrderChange:R,onHideTab:j,isFocused:C,allowTabShortcuts:k=!0,notificationStateBySessionId:v,liveSessionInboxState:y}){const{sendCommand:$}=Lt(),L=o.useRef(null),{activeTabId:M,activeConv:_,sortedConversations:W,draggingTabRef:H,selectTab:N,handleTabReorder:P,updatePreviewOrder:G,commitPreviewOrder:I,clearPreviewOrder:E,moveTabToEnd:B,setDraggingTabKey:U}=Xh({conversations:e,initialActiveTabId:h,initialTabOrder:S,onActiveTabChange:b,onTabOrderChange:R}),V=Sn({sendDaemonCommand:a,activeConv:_,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:ae,dropAction:we,resetDragState:be,handleDragEnter:Y,handleDragOver:he,handleDragLeave:O,handleDrop:X}=qh({conversations:e,numGroups:w,onMoveTab:A,onReceiveTab:m,onOwnTabDrop:B,onClearPreviewOrder:E}),ie=_&&!Ze(_)&&Hs(_)==="terminal",le=o.useMemo(()=>_?s.find(oe=>oe.id===_.routeId):void 0,[s,_]),me=o.useMemo(()=>_?n.filter(oe=>oe.routeId===_.tabKey):[],[n,_]),ke=o.useMemo(()=>new Set(W.filter(oe=>Lu(oe,y,{isOpenConversation:oe.tabKey===M,notificationStateBySessionId:v})).map(oe=>oe.tabKey)),[M,y,W]);jr("PaneGroup",{groupIndex:d,conversationCount:e.length,activeTabId:M,dragOver:ae});const de=o.useCallback(oe=>{oe.streamSource==="agent-stream"&&oe.agentType&&$(oe.routeId,xl(),{agentType:oe.agentType,...oe.sessionId&&{targetSessionId:oe.sessionId}}).catch(()=>{})},[$]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:x,style:{...f,outline:ae?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(Zh,{conversations:W,activeTabId:M,groupIndex:d,numGroups:w,unreadTabKeys:ke,draggingTabRef:H,onFocus:x,onSelectTab:N,onConversationActivated:de,onPreviewReorder:G,onReorderTab:P,onCommitPreviewOrder:I,onClearPreviewOrder:E,onDragStateReset:be,onDragTabKeyChange:U,onMoveTab:A,onReceiveTab:m,onHideTab:j,isGroupActive:C??!1,allowTabShortcuts:k}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:Y,onDragOver:he,onDragLeave:O,onDrop:X,children:[ae&&t.jsx(Jh,{dropAction:we,canSplit:!!(w<4&&A)}),_?t.jsx(ho,{activeConv:_,clearToken:r[_.tabKey]||0,isCliTerminal:!!ie,ideEntry:le,terminalRef:L,handleModalButton:V.handleModalButton,handleRelaunch:V.handleRelaunch,handleSendChat:V.handleSendChat,isSendingChat:V.isSendingChat,sendFeedbackMessage:V.sendFeedbackMessage,handleFocusAgent:V.handleFocusAgent,isFocusingAgent:V.isFocusingAgent,actionLogs:me,userName:p,isInputActive:!g||!!C}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(bo,{conversationsCount:e.length,isSplitMode:g,isStandalone:l,hasRegisteredMachines:u})})]})]})}function tx({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:d,isStandalone:x,hasRegisteredMachines:g,userName:w,focusedGroup:A,setFocusedGroup:m,moveTabToGroup:f,splitTabRelative:b,closeGroup:h,handleResizeStart:S,groupActiveTabIds:R,setGroupActiveTabIds:j,groupTabOrders:C,setGroupTabOrders:k,toggleHiddenTab:v,allowTabShortcuts:y=!0,notificationStateBySessionId:$,liveSessionInboxState:L}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map((M,_)=>{const W=s&&n.length===r?`${n[_]}%`:void 0;return t.jsxs(lt.Fragment,{children:[s&&_>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:H=>S(_-1,H),onDoubleClick:()=>h(_),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(ex,{style:s?{flexBasis:W??`${100/r}%`,flexGrow:W?0:1,flexShrink:W?0:1}:void 0,conversations:M,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:d,isStandalone:x,hasRegisteredMachines:g,userName:w,groupIndex:_,isFocused:s&&A===_,onFocus:()=>m(_),isSplitMode:s,numGroups:r,onMoveTab:(H,N)=>{N==="left"&&_>0?f(H,_-1):N==="right"&&_<r-1?f(H,_+1):N==="split-left"&&r<4?b(H,_,"left"):N==="split-right"&&r<4&&b(H,_,"right")},onReceiveTab:H=>f(H,_),onActiveTabChange:H=>j(N=>(N[_]??null)===(H??null)?N:{...N,[_]:H}),initialActiveTabId:R[_],initialTabOrder:C[_],onTabOrderChange:H=>k(N=>{const P=N[_]||[];return P.length===H.length&&P.every((G,I)=>G===H[I])?N:{...N,[_]:H}}),onHideTab:v,allowTabShortcuts:y,notificationStateBySessionId:$,liveSessionInboxState:L})]},_)})})}function Nl({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?rt.onScreenshot("ide-page",(d,x)=>{if(d!==e)return;const g=new FileReader;g.onload=()=>i(g.result),g.readAsDataURL(x)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var d;return e?((d=rt.onStatus)==null?void 0:d.call(rt,(x,g)=>{x===e&&g!=null&&g.screenshotUsage&&l(g.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const p=e?rt.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,d)=>{const x=e?rt.get(e):null;return!x||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):x.sendInput(p,d,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const Cl="adhdev-dashboard-action-shortcuts",sx=1200,rx={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function nx(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function ct(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 Il(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:ct("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:ct("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:ct("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:ct("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:ct("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:ct("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:ct("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:ct("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:ct("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:ct("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:ct("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:ct("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:ct("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:ct("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:ct("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:ct("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:ct("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:ct("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:ct("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:ct("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:ct("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:ct("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:ct("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:ct("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:ct("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 xn(e){const s=Object.fromEntries(Il(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Cl)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(rx))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function Al(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function ax({enabled:e=!0,onTrigger:s}){const r=nx(),[n,a]=o.useState(()=>xn(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),p=o.useRef({parts:[],timer:null}),d=o.useCallback(m=>{const f=[];return m.metaKey&&f.push(r?"⌘":"Meta"),m.ctrlKey&&f.push("Ctrl"),m.altKey&&f.push(r?"⌥":"Alt"),m.shiftKey&&m.key.length!==1&&f.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(f.push(Al(m.key)),f.join("+"))},[r]),x=o.useCallback(m=>{a(m);try{localStorage.setItem(Cl,JSON.stringify(m))}catch{}},[]);o.useEffect(()=>{const m=xn(r),f=Object.entries(n),b=Object.entries(m);f.length===b.length&&f.every(([h,S])=>m[h]===S)||x(m)},[n,r,x]);const g=o.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),w=o.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},sx))},[]);o.useEffect(()=>{if(!i)return;const m=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){c(null),u([]);return}const b=d(f);if(!b)return;const S=!(f.metaKey||f.ctrlKey||f.altKey)&&/^[A-Z0-9]$/.test(b);if(l.length===0&&S){u([b]);return}const j=[...l,b].slice(0,2).join(" "),C={...n};for(const[k,v]of Object.entries(C))v===j&&delete C[k];C[i]=j,x(C),c(null),u([])};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[n,d,x,i,l]),o.useEffect(()=>{if(!e||i)return;const m=f=>{if(f.defaultPrevented)return;const b=d(f);if(!b)return;const h=f.metaKey||f.ctrlKey||f.altKey;if(Ma(f.target)&&!h)return;const S=p.current.parts,R=h?[b]:[...S.slice(-1),b].slice(-2),j=R.join(" "),C=R[R.length-1],k=Object.entries(n).filter(([,M])=>!!M),v=k.find(([,M])=>M===j);if(v){f.preventDefault(),g(),s(v[0]);return}if(k.some(([,M])=>M.startsWith(`${j} `))){f.preventDefault(),p.current.parts=R,w();return}const $=k.find(([,M])=>M===C);if($){f.preventDefault(),g(),s($[0]);return}if(k.some(([,M])=>M.startsWith(`${C} `))){f.preventDefault(),p.current.parts=[C],w();return}g()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[n,w,e,d,s,g,i]),o.useEffect(()=>()=>g(),[g]);const A=o.useMemo(()=>Il(r),[r]);return{isMac:r,actionDefinitions:A,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:x}}function ox({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 Ml(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function Ci({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!Ml(n):!0}function ix({previousVisibleConversationCount:e,visibleConversationCount:s,ides:r}){return s>0||e<=0?!1:Ml(r)}const Tl=o.createContext(null);function Mn(){const e=o.useContext(Tl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function nn(e){return mt(e)||e.tabKey}function cx(e){return`remote:${e}`}function Ot(e){return e.startsWith("remote:")}function Ii(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Zn(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 Yr(e,s){e.classList.remove(ma.className,fa.className),e.classList.add(s==="light"?ma.className:fa.className)}function Ai(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 lx(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 dx(e,s,r){var c;const n=[s];let a;for(const l of n){let u;for(const p of l){const d=e.addPanel({id:p.tabKey,component:"conversation",title:nn(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=d.id)}a=u??a}return r??((c=s[0])==null?void 0:c.tabKey)??null}function Mi(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Ot(n.id)||r.has(n.id)||e.removePanel(n);for(const n of s){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==nn(n)&&a.api.setTitle(nn(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:nn(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 Ti(e,s,r){var u,p;const n=r?cx(r):null;for(const d of[...e.panels])Ot(d.id)&&(!n||d.id!==n)&&e.removePanel(d);if(!r||!n)return;const a=Ft(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(d=>!Ot(d.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 ux({params:e,api:s}){var x;const r=Mn(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=Sn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const g=[s.onDidActiveChange(w=>i(w.isActive)),s.onDidActiveGroupChange(w=>{if(!s.isActive&&!w.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const w of g)w.dispose()}},[s]);const u=o.useMemo(()=>c?r.ides.find(g=>g.id===c.routeId):void 0,[r.ides,c]),p=o.useMemo(()=>c?r.actionLogs.filter(g=>g.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(bo,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const d=!Ze(c)&&Hs(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(ho,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:d,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:p,userName:r.userName,scrollToBottomRequestNonce:((x=r.scrollToBottomRequest)==null?void 0:x.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a})})}function mx({params:e}){var u;const s=Mn(),r=o.useMemo(()=>Ft([...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}=Nl({doId:a,targetSessionId:r?Sc(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(oc,{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 fx(){const e=Mn();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(bo,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function px(e){var w,A;lx(e);const s=Mn(),r=o.useCallback(m=>{"button"in m&&m.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const m=Ft([...s.conversationsByTabKey.values()],e.params.routeId),f=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,b=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${f?" is-active":""}${b?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(m==null?void 0:m.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:m!=null&&m.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:m.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=jn(n,s.liveSessionInboxState,{isOpenConversation:a,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,u=c.isConnecting,p=c.isGenerating,d=c.isWaiting,x=c.unread,g=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:mt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:m=>{var f;m.preventDefault(),r(m),s.openTabContextMenu({x:m.clientX,y:m.clientY,tabKey:n.tabKey,sourceDocument:((f=m.target)==null?void 0:f.ownerDocument)??document})},children:[x&&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"}):d?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):u?t.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:mt(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:xs(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:xs(n)}):t.jsx("span",{children:xs(n)})})]}),g&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:g,children:g})]})}function hx({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,initialDataLoaded:p,userName:d,toggleHiddenTab:x,actionShortcuts:g,registerActionHandlers:w,onActiveTabChange:A,onRequestScrollToBottom:m,requestedActiveTabKey:f,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:h,scrollToBottomRequest:S,notificationStateBySessionId:R,liveSessionInboxState:j}){var De,$e,ot;const{theme:C}=no(),{sendCommand:k}=Lt(),v=o.useRef(null),y=o.useRef(null),$=o.useRef(!1),L=o.useRef(!1),M=o.useRef(!1),_=o.useRef(null),W=o.useRef([]),[H,N]=o.useState(null),[P,G]=o.useState(!1),[I,E]=o.useState(!1),[B,U]=o.useState(0),V=o.useRef(null),ae=o.useMemo(()=>ul(typeof window<"u"?window.innerWidth:1280),[]),we=o.useRef(typeof window>"u"?{}:Yp(ae)),be=o.useMemo(()=>new Map(e.map(K=>[K.tabKey,K])),[e]),Y=o.useMemo(()=>{const K=v.current;return K?K.groups.some(F=>{try{const z=F.model.location.type;return z!=="floating"&&z!=="popout"?!1:F.panels.some(q=>be.has(q.id))}catch{return!1}}):!1},[be,B,e]),he=o.useCallback(()=>{var K;(K=v.current)==null||K.focus()},[]),O=o.useCallback((K,F)=>{m==null||m(K,F)},[m]),X=o.useCallback(K=>{const F=document,z=K.document;for(const Ie of F.querySelectorAll('link[rel="stylesheet"]')){const Oe=z.createElement("link");Oe.rel="stylesheet",Oe.href=Ie.href,Ie.crossOrigin&&(Oe.crossOrigin=Ie.crossOrigin),z.head.appendChild(Oe)}for(const Ie of F.querySelectorAll("style")){const Oe=z.createElement("style");Oe.textContent=Ie.textContent,z.head.appendChild(Oe)}const q=[];for(const Ie of F.styleSheets)try{for(const Oe of Ie.cssRules)Oe instanceof CSSStyleRule&&(Oe.selectorText===":root"||Oe.selectorText==="html")&&q.push(Oe.cssText)}catch{}if(q.length>0){const Ie=z.createElement("style");Ie.textContent=q.join(`
44
- `),z.head.appendChild(Ie)}const re=F.documentElement.getAttribute("data-theme");re&&z.documentElement.setAttribute("data-theme",re),z.documentElement.style.colorScheme=re==="light"?"light":"dark",z.body.className=F.body.className;const Ce=F.documentElement.getAttribute("style");Ce&&z.documentElement.setAttribute("style",Ce);const Te=z.getElementById("dv-popout-window");Te instanceof HTMLElement&&(Te.classList.add("adhdev-dockview"),Yr(Te,C))},[C]),ie=o.useCallback(()=>{var F;const K=v.current;if(K)for(const z of K.groups)try{const q=(F=z.element)==null?void 0:F.ownerDocument;if(!q||q===document)continue;const re=q.getElementById("dv-popout-window");re instanceof HTMLElement&&(re.classList.add("adhdev-dockview"),Yr(re,C));const Ce=document.documentElement.getAttribute("data-theme");Ce&&q.documentElement.setAttribute("data-theme",Ce),q.documentElement.style.colorScheme=Ce==="light"?"light":"dark",q.body.className=document.body.className;const Te=document.documentElement.getAttribute("style");Te?q.documentElement.setAttribute("style",Te):q.documentElement.removeAttribute("style")}catch{}},[C]),le=o.useCallback(()=>{var F;const K=v.current;if(K)for(const z of K.groups)try{const q=(F=z.element)==null?void 0:F.ownerDocument;if(!q||q===document)continue;const re=q.getElementById("dv-popout-window");if(!(re instanceof HTMLElement))continue;re.classList.add("adhdev-dockview"),Yr(re,C),re.classList.toggle("is-showing-dockview-overlay",I),re.classList.toggle("is-dragging-dockview",P)}catch{}},[P,I,C]),me=o.useCallback(K=>{const F=v.current;if(!F)return;const z=F.getPanel(K);z&&F.addPopoutGroup(z,{popoutUrl:"/popout.html",onDidOpen:({window:q})=>{X(q),Ae();const re=be.get(K);q.document.title=re?`${mt(re)} — ADHDev`:"ADHDev — Popout"}})},[be,X]),ke=o.useCallback(K=>{const F=v.current,z=F==null?void 0:F.getPanel(K);if(!F||!z)return;const q=F.groups.filter(re=>{var Ce;try{return((Ce=re.element)==null?void 0:Ce.ownerDocument)===document}catch{return!0}});q.length>0?z.api.moveTo({group:q[0],position:"center"}):z.api.moveTo({position:"center"}),z.api.setActive()},[]),de=o.useCallback(K=>{var q;const F=v.current;if(!F)return!1;const z=F.getPanel(K);if(!z)return!1;try{return((q=z.group.element)==null?void 0:q.ownerDocument)!==document}catch{return!1}},[]),oe=o.useCallback(K=>{de(K)&&ke(K),x(K)},[de,ke,x]),se=o.useCallback(K=>{const F=v.current,z=F==null?void 0:F.getPanel(K);!F||!z||F.addFloatingGroup(z,{width:600,height:500})},[]),ue=o.useCallback(K=>{var z;const F=(z=v.current)==null?void 0:z.getPanel(K);if(!F)return!1;try{return F.group.model.location.type==="floating"}catch{return!1}},[]),te=o.useCallback(()=>{var F,z;const K=(z=(F=v.current)==null?void 0:F.activePanel)==null?void 0:z.id;return!K||Ot(K)?null:be.has(K)?K:null},[be]),Ne=o.useCallback(K=>{const F=v.current,z=F==null?void 0:F.getPanel(K);if(!F||!z)return;const q=F.groups.filter(re=>{try{return re.model.location.type==="grid"}catch{return!0}});q.length>0?z.api.moveTo({group:q[0],position:"center"}):z.api.moveTo({position:"center"}),z.api.setActive()},[]),Se=o.useCallback(()=>{var Ce;const K=v.current;if(!K)return;const z=K.groups.filter(Te=>{var Ie;try{return((Ie=Te.element)==null?void 0:Ie.ownerDocument)===document&&Te.model.location.type==="grid"}catch{return!1}})[0]||null,q=[...K.panels];for(const Te of q){const Ie=(Ce=Te.group.element)==null?void 0:Ce.ownerDocument,Oe=Te.group.model.location.type;Ie===document&&Oe==="grid"||(z&&z.id!==Te.group.id?Te.api.moveTo({group:z,position:"center"}):Te.api.moveTo({position:"center"}))}const re=K.activePanel;re&&(re.group.model.openPanel(re),re.api.setActive()),Zn(document)},[]),Ae=o.useCallback(()=>{var F,z;const K=v.current;if(K)for(const q of K.groups){const re=(F=q.element)==null?void 0:F.ownerDocument;if(!re||re===document)continue;const Ce=re.getElementById("dv-popout-window");if(!(Ce instanceof HTMLElement))continue;let Te=null,Ie=re.title||"ADHDev",Oe="Popout workspace";const Ue=q.activePanel;if(Ue)if(Te=Ue.id,Ot(Ue.id)){const Fe=((z=Ue.params)==null?void 0:z.routeId)||Ue.id.slice(7),D=Ft([...be.values()],Fe);Ie=Hc(D),Oe=D!=null&&D.machineName?`Remote view · ${D.machineName}`:"Remote view"}else{const Fe=be.get(Ue.id);Ie=Fe?mt(Fe):Ue.title||Ue.id,Oe=Fe?xs(Fe):"Dockview panel"}re.title=`${Ie} — ADHDev`;let J=re.getElementById("adhdev-popout-header");J instanceof HTMLElement||(J=re.createElement("div"),J.id="adhdev-popout-header",re.body.appendChild(J)),J.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(";")),J.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;">${Ii(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;">${Ii(Oe)}</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
- `,Ce.style.top="52px",Ce.style.height="calc(100% - 52px)";const Me=J.querySelector("[data-adhdev-popout-focus]");Me&&(Me.onclick=()=>{window.focus()});const Ve=J.querySelector("[data-adhdev-popout-dock]");Ve&&(Ve.disabled=!Te,Ve.style.opacity=Te?"1":"0.5",Ve.style.cursor=Te?"pointer":"default",Ve.onclick=()=>{var Fe;Te&&ke(Te),(Fe=re.defaultView)==null||Fe.focus()})}},[be,ke]),T=o.useCallback(K=>{var q;const F=v.current,z=F==null?void 0:F.getPanel(K);if(!(!F||!z)){z.group.model.openPanel(z),z.api.setActive(),O(K,"dockview-shortcut");try{const re=z.group.model.location;re.type==="popout"?re.getWindow().focus():Zn((q=z.group.element)==null?void 0:q.ownerDocument)}catch{}}},[O]),xe=o.useCallback(K=>{const F=v.current,z=F==null?void 0:F.activePanel,q=(F==null?void 0:F.activeGroup)||(z==null?void 0:z.group);if(!F||!z||!q)return;const re=q.panels||[];if(re.length<=1)return;const Ce=re.findIndex(Oe=>Oe.id===z.id);if(Ce<0)return;const Te=(Ce+K+re.length)%re.length,Ie=re[Te];Ie&&(Ie.group.model.openPanel(Ie),Ie.api.setActive(),Ot(Ie.id)||O(Ie.id,"dockview-shortcut"))},[O]),ve=o.useCallback(K=>{var Ve;const F=v.current,z=(F==null?void 0:F.activeGroup)||((Ve=F==null?void 0:F.activePanel)==null?void 0:Ve.group);if(!F||!z)return;const q=F.groups||[],re=q.find(Fe=>Fe.id===z.id);if(!re)return;const Ce=re.element.getBoundingClientRect(),Te=Ce.left+Ce.width/2,Ie=Ce.top+Ce.height/2,Oe=(Fe,D,ee,ce)=>Math.max(0,Math.min(D,ce)-Math.max(Fe,ee)),Ue=Fe=>{const D=Fe.element.getBoundingClientRect(),ee=D.left+D.width/2,ce=D.top+D.height/2;let Ke=0,Le=0,Ee=0,Xe=!1;if(K==="left"?(Xe=ee<Te,Ke=Math.max(0,Ce.left-D.right),Le=Math.abs(ce-Ie),Ee=Oe(Ce.top,Ce.bottom,D.top,D.bottom)):K==="right"?(Xe=ee>Te,Ke=Math.max(0,D.left-Ce.right),Le=Math.abs(ce-Ie),Ee=Oe(Ce.top,Ce.bottom,D.top,D.bottom)):K==="above"?(Xe=ce<Ie,Ke=Math.max(0,Ce.top-D.bottom),Le=Math.abs(ee-Te),Ee=Oe(Ce.left,Ce.right,D.left,D.right)):(Xe=ce>Ie,Ke=Math.max(0,D.top-Ce.bottom),Le=Math.abs(ee-Te),Ee=Oe(Ce.left,Ce.right,D.left,D.right)),!Xe)return Number.POSITIVE_INFINITY;const je=Ee>0?0:120;return Ke*3+Le+je};let J=null,Me=Number.POSITIVE_INFINITY;for(const Fe of q){if(Fe.id===re.id)continue;const D=Ue(Fe);Number.isFinite(D)&&(D>=Me||(Me=D,J=Fe))}return J||void 0},[]),Q=o.useCallback(K=>{var q;const F=ve(K);if(!F)return;const z=F.activePanel||F.panels[0];z&&(F.model.openPanel(z),z.api.setActive(),Ot(z.id)||O(z.id,"dockview-focus"),Zn((q=F.element)==null?void 0:q.ownerDocument))},[ve,O]),ye=o.useCallback((K,F)=>{const z=v.current,q=z==null?void 0:z.activePanel,re=(z==null?void 0:z.activeGroup)||(q==null?void 0:q.group);if(!z||!q||!re)return;let Ce=ve(K);!Ce&&(F!=null&&F.createGroupIfMissing)&&(Ce=z.addGroup({referenceGroup:re,direction:K})),Ce&&(q.api.moveTo({group:Ce,position:"center"}),q.group.model.openPanel(q),q.api.setActive(),Ot(q.id)||O(q.id,F!=null&&F.createGroupIfMissing?"dockview-split":"dockview-move"))},[ve,O]),{isMac:_e,tabShortcuts:We,shortcutListening:Pe,setShortcutListening:ze,saveShortcuts:Qe}=Sl({sortedTabKeys:e.map(K=>K.tabKey),onFocus:he,onSelectTab:T}),it=o.useCallback(()=>{var z;const K=v.current;if(!K)return;const F=K.activePanel;if(F){if(Ot(F.id)){const q=((z=F.params)==null?void 0:z.routeId)||F.id.slice(7),re=Ft(e,q);re!=null&&re.tabKey&&ze(re.tabKey);return}be.has(F.id)&&ze(F.id)}},[be,T,ze,e]),et=o.useCallback(K=>{const F=[];return K.metaKey&&F.push(_e?"⌘":"Meta"),K.ctrlKey&&F.push("Ctrl"),K.altKey&&F.push(_e?"⌥":"Alt"),K.shiftKey&&K.key.length!==1&&F.push(_e?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(K.key)?null:(F.push(Al(K.key)),F.join("+"))},[_e]),ft=o.useCallback(K=>{var F,z;switch(K){case"splitActiveTabRight":ye("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":ye("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const q=te();q&&se(q);return}case"popoutActiveTab":{const q=te();q&&me(q);return}case"dockActiveTab":{const q=te();if(!q)return;de(q)?ke(q):ue(q)&&Ne(q);return}case"focusLeftPane":Q("left");return;case"focusRightPane":Q("right");return;case"focusUpPane":Q("above");return;case"focusDownPane":Q("below");return;case"moveActiveTabToLeftPane":ye("left");return;case"moveActiveTabToRightPane":ye("right");return;case"moveActiveTabToUpPane":ye("above");return;case"moveActiveTabToDownPane":ye("below");return;case"selectPreviousGroupTab":xe(-1);return;case"selectNextGroupTab":xe(1);return;case"setActiveTabShortcut":it();return;case"hideCurrentTab":{const q=(z=(F=v.current)==null?void 0:F.activePanel)==null?void 0:z.id;q&&!Ot(q)&&oe(q);return}default:return}},[xe,Ne,Q,se,te,oe,ue,de,ke,ye,me,it]);o.useEffect(()=>{if(!H)return;const K=H.sourceDocument,F=K.defaultView??window,z=q=>{const re=K.querySelector("[data-dockview-tab-context-menu]");re&&re.contains(q.target)||N(null)};return F.addEventListener("mousedown",z,!0),F!==window&&window.addEventListener("mousedown",()=>N(null),!0),()=>{F.removeEventListener("mousedown",z,!0),F!==window&&window.removeEventListener("mousedown",()=>N(null),!0)}},[H]);const tt=o.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:be,hasDetachedConversationPanels:Y,ides:r,isStandalone:l,hasRegisteredMachines:u,liveSessionInboxState:j,notificationStateBySessionId:R,sendDaemonCommand:a,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:oe,userName:d,scrollToBottomRequest:S,tabShortcuts:We,openTabContextMenu:({x:K,y:F,tabKey:z,sourceDocument:q})=>N({x:K,y:F,tabKey:z,sourceDocument:q??document}),popoutTab:me,moveTabBackToMain:ke,isTabInPopout:de,floatTab:se,isTabFloating:ue}),[n,s,be,Y,r,l,u,j,R,a,c,i,oe,d,S,We,me,ke,de,se,ue]),Ct=H?ox({isTabInPopout:de(H.tabKey),isTabFloating:ue(H.tabKey),tabShortcut:We[H.tabKey],actionShortcuts:g}):[],pt=o.useCallback(K=>{var q;const F=v.current;if((((q=F==null?void 0:F.activePanel)==null?void 0:q.id)??null)===K.id){K.group.model.openPanel(K);return}K.group.model.openPanel(K),K.api.setActive()},[]),st=o.useCallback((K,F="requested-tab")=>{if(!K)return!1;const z=v.current;if(!z)return!1;const q=z.getPanel(K);return q?(pt(q),O(K,F),h==null||h(),!0):!1},[pt,h,O]),Re=o.useCallback(()=>{if(M.current)return!1;const K=st(_.current,"stored-layout-restore");return K&&(M.current=!0),K},[st]),Ge=o.useCallback(()=>{var F;const K=v.current;K&&qp(ae,{activeTabId:((F=K.activePanel)==null?void 0:F.id)??null,layout:K.toJSON()})},[ae]),Be=o.useCallback(()=>{Xp(ae,we.current)},[ae]),qe=o.useCallback(K=>{var q,re,Ce,Te;const F=v.current;if(!F)return{kind:"grid"};const z=F.toJSON();for(const Ie of z.floatingGroups||[])if((re=(q=Ie.data)==null?void 0:q.views)!=null&&re.includes(K)&&Ie.position)return{kind:"floating",position:Ie.position};for(const Ie of z.popoutGroups||[])if((Te=(Ce=Ie.data)==null?void 0:Ce.views)!=null&&Te.includes(K))return{kind:"popout",position:Ie.position,popoutUrl:Ie.url};return{kind:"grid"}},[]),At=o.useCallback(K=>{const F=v.current;if(!F)return;const z=F.getPanel(K),q=we.current[K];if(!z||!q||q.kind==="grid")return;if(z.group.model.location.type===q.kind){delete we.current[K],Be();return}if(q.kind==="floating"){F.addFloatingGroup(z,{x:q.position.left??24,y:q.position.top??24,width:q.position.width,height:q.position.height}),delete we.current[K],Be();return}delete we.current[K],Be()},[Be]);o.useEffect(()=>(w==null||w({setShortcutForActiveTab:it,restoreHiddenTabToSavedLocation:At,activateConversationTab:T,resetAllPanelsToMain:Se,activatePreviousTabInGroup:()=>xe(-1),activateNextTabInGroup:()=>xe(1),floatActiveTab:()=>{const K=te();K&&se(K)},popoutActiveTab:()=>{const K=te();K&&me(K)},dockActiveTab:()=>{const K=te();K&&(de(K)?ke(K):ue(K)&&Ne(K))},splitActiveTabRight:()=>ye("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>ye("below",{createGroupIfMissing:!0}),focusLeftPane:()=>Q("left"),focusRightPane:()=>Q("right"),focusUpPane:()=>Q("above"),focusDownPane:()=>Q("below"),moveActiveTabToLeftPane:()=>ye("left"),moveActiveTabToRightPane:()=>ye("right"),moveActiveTabToUpPane:()=>ye("above"),moveActiveTabToDownPane:()=>ye("below")}),()=>w==null?void 0:w(null)),[xe,Ne,se,Q,te,ue,de,ye,ke,me,w,Se,At,T,it]);const bt=o.useCallback(()=>{const K=y.current;if(!K)return;const F=K.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const z of F)z.setAttribute("data-adhdev-force-hidden","true")},[]),jt=o.useCallback(()=>{const K=y.current;if(!K)return;const F=K.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const z of F)z.removeAttribute("data-adhdev-force-hidden")},[]),gt=o.useCallback(()=>{const K=y.current;if(!K)return;const F=K.querySelectorAll(".dv-drop-target-container");for(const re of F)re.remove();const z=K.querySelectorAll(".dv-drop-target-dropzone");for(const re of z)re.remove();const q=K.querySelectorAll(".dv-drop-target");for(const re of q)re.classList.remove("dv-drop-target")},[]),Mt=o.useCallback(()=>{G(!1),E(!1),jt(),bt(),gt(),!(typeof window>"u")&&(V.current!=null&&window.clearTimeout(V.current),window.requestAnimationFrame(()=>{bt(),gt()}),V.current=window.setTimeout(()=>{bt(),gt(),V.current=null},80))},[jt,bt,gt]),Tt=o.useCallback(K=>{var z;v.current=K.api;const F=Gp(ae);if(_.current=(F==null?void 0:F.activeTabId)??null,F!=null&&F.layout&&K.api.fromJSON(F.layout,{reuseExistingPanels:!1}),L.current=Ci({hasStoredLayout:!!(F!=null&&F.layout),initialDataLoaded:p,visibleConversationCount:e.length,ides:r}),L.current||(Mi(K.api,e),Ti(K.api,e,b)),K.api.totalPanels===0&&e.length>0){const q=dx(K.api,e,f);if(q){const re=K.api.getPanel(q);re&&pt(re)}}else!L.current&&!st(f)&&Re();$.current=!0,K.api.onDidActivePanelChange(q=>{var Ce;if(_.current=(q==null?void 0:q.id)??null,M.current=!0,Ae(),q&&Ot(q.id)){const Te=((Ce=q.params)==null?void 0:Ce.routeId)||q.id.slice(7),Ie=Ft(e,Te);A((Ie==null?void 0:Ie.tabKey)??null),Ge();return}if(A((q==null?void 0:q.id)??null),Ge(),!q)return;const re=be.get(q.id);(re==null?void 0:re.streamSource)==="agent-stream"&&re.agentType&&k(re.routeId,xl(),{agentType:re.agentType,...re.sessionId&&{targetSessionId:re.sessionId}}).catch(()=>{})}),K.api.onDidLayoutChange(()=>{Ge(),Ae(),U(q=>q+1)}),K.api.onWillDragPanel(()=>{G(!0),E(!1),bt()}),K.api.onWillDragGroup(()=>{G(!0),E(!1),bt()}),K.api.onWillShowOverlay(()=>{jt(),E(!0)}),K.api.onDidMovePanel(Mt),K.api.onDidDrop(Mt),K.api.onDidAddGroup(q=>{requestAnimationFrame(()=>{var re,Ce;try{const Te=(re=q.element)==null?void 0:re.ownerDocument;if(!Te||Te===document)return;(Ce=Te.getElementById("dv-popout-window"))==null||Ce.classList.add("adhdev-dockview");const Ie=document.documentElement.getAttribute("data-theme");Ie&&Te.documentElement.setAttribute("data-theme",Ie),Te.body.className=document.body.className;const Oe=document.documentElement.getAttribute("style");Oe&&Te.documentElement.setAttribute("style",Oe)}catch{}Ae(),U(Te=>Te+1)})}),A(((z=K.api.activePanel)==null?void 0:z.id)??null)},[pt,st,Mt,jt,be,r,p,ae,bt,A,Ge,f,b,k,Ae,e]);o.useLayoutEffect(()=>{const K=v.current;if(!K||!$.current||L.current&&Ci({hasStoredLayout:!0,initialDataLoaded:p,visibleConversationCount:e.length,ides:r}))return;L.current&&(L.current=!1);const F=W.current,z=new Set(F),q=e.map(J=>J.tabKey),re=new Set(q),Ce=ix({previousVisibleConversationCount:F.length,visibleConversationCount:e.length,ides:r});let Te=!1;for(const J of F)re.has(J)||Ce||(we.current[J]=qe(J),Te=!0);Te&&Be(),Ce||(Mi(K,e),Ti(K,e,b));const Ie=q.filter(J=>!z.has(J));let Oe=!1;for(const J of Ie){const Me=K.getPanel(J),Ve=we.current[J];if(!Me||!Ve||Ve.kind==="grid")continue;if(Me.group.model.location.type===Ve.kind){delete we.current[J],Oe=!0;continue}if(Ve.kind==="floating"){K.addFloatingGroup(Me,{x:Ve.position.left??24,y:Ve.position.top??24,width:Ve.position.width,height:Ve.position.height}),delete we.current[J],Oe=!0;continue}}if(Oe&&Be(),W.current=q,f&&st(f))return;!K.activePanel&&K.panels[0]&&pt(K.panels[0]),!!(K.activePanel&&K.getPanel(K.activePanel.id))||Re()},[pt,st,Re,r,p,Be,qe,f,b,e]),o.useEffect(()=>{$.current&&st(f)},[st,f]),o.useEffect(()=>{if(!P||typeof window>"u")return;const K=()=>Mt();return window.addEventListener("pointerup",K),window.addEventListener("mouseup",K),window.addEventListener("dragend",K),()=>{window.removeEventListener("pointerup",K),window.removeEventListener("mouseup",K),window.removeEventListener("dragend",K)}},[Mt,P]),o.useEffect(()=>()=>{typeof window>"u"||V.current!=null&&window.clearTimeout(V.current)},[]),o.useEffect(()=>{const K=z=>{const q=z.target;if(!q)return;const re=q.querySelector("[data-tab-key]")||q.closest("[data-tab-key]");if(re){const Ce=re.getAttribute("data-tab-key");if(Ce&&z.dataTransfer){const Te=q.closest(".dv-tab")||re.closest(".dv-tab")||re;z.dataTransfer.effectAllowed="move",z.dataTransfer.setData("text/tab-key",Ce),Te instanceof HTMLElement&&z.dataTransfer.setDragImage(Te,Math.max(12,Math.round(Te.clientWidth/2)),Math.max(10,Math.round(Te.clientHeight/2)))}}};window.addEventListener("dragstart",K);const F=Ai(v.current);for(const z of F)z.addEventListener("dragstart",K);return()=>{window.removeEventListener("dragstart",K);for(const z of F)z.removeEventListener("dragstart",K)}},[B]),o.useEffect(()=>{var F;const K=(F=y.current)==null?void 0:F.querySelector(".adhdev-dockview");K instanceof HTMLElement&&Yr(K,C),ie(),Ae(),le()},[Ae,le,ie,C]),o.useEffect(()=>{Ae(),le()},[Ae,le]),o.useEffect(()=>{const K=F=>{if(F.defaultPrevented||Pe)return;const z=et(F);if(!z)return;const q=F.metaKey||F.ctrlKey||F.altKey;Ma(F.target)&&!q||xn(_e).setActiveTabShortcut!==z||(F.preventDefault(),F.stopPropagation(),it())};return window.addEventListener("keydown",K,!0),()=>window.removeEventListener("keydown",K,!0)},[et,_e,Pe,it]),o.useEffect(()=>{const K=y.current;if(!K)return;const F=z=>{var Ie,Oe;if(!z.isTrusted)return;const q=(Oe=(Ie=z.target)==null?void 0:Ie.closest)==null?void 0:Oe.call(Ie,".dv-scrollable");if(!q)return;z.preventDefault(),z.stopPropagation();const re=Math.abs(z.deltaX),Ce=Math.abs(z.deltaY),Te=re>Ce?z.deltaX:z.deltaY;q.dispatchEvent(new WheelEvent("wheel",{deltaY:Te,deltaMode:z.deltaMode,bubbles:!1,cancelable:!0}))};return K.addEventListener("wheel",F,{passive:!1,capture:!0}),()=>K.removeEventListener("wheel",F,{capture:!0})},[]),o.useEffect(()=>{const K=Ai(v.current);if(K.length===0)return;const F=K.map(z=>{let q=[],re=null;const Ce=()=>{re!=null&&z.clearTimeout(re),re=null,q=[]},Te=()=>{re!=null&&z.clearTimeout(re),re=z.setTimeout(()=>{re=null,q=[]},1200)},Ie=Ue=>{if(!Ue.ctrlKey&&!Ue.metaKey&&!Ue.altKey)return;const J=et(Ue);if(!J)return;const Me=kl();for(const[Ve,Fe]of Object.entries(Me))if(e.some(D=>D.tabKey===Ve)&&Fe===J){Ue.preventDefault(),T(Ve);return}},Oe=Ue=>{if(Ue.defaultPrevented||Pe)return;const J=et(Ue);if(!J)return;const Me=Ue.metaKey||Ue.ctrlKey||Ue.altKey;if(Ma(Ue.target)&&!Me)return;const Ve=xn(_e),Fe=Object.entries(Ve).filter(([je,ut])=>!!ut&&(je==="splitActiveTabRight"||je==="splitActiveTabDown"||je==="floatActiveTab"||je==="popoutActiveTab"||je==="dockActiveTab"||je==="focusLeftPane"||je==="focusRightPane"||je==="focusUpPane"||je==="focusDownPane"||je==="moveActiveTabToLeftPane"||je==="moveActiveTabToRightPane"||je==="moveActiveTabToUpPane"||je==="moveActiveTabToDownPane"||je==="selectPreviousGroupTab"||je==="selectNextGroupTab"||je==="setActiveTabShortcut"||je==="hideCurrentTab")),D=Me?[J]:[...q.slice(-1),J].slice(-2),ee=D.join(" "),ce=D[D.length-1],Ke=Fe.find(([,je])=>je===ee);if(Ke){Ue.preventDefault(),Ce(),ft(Ke[0]);return}if(Fe.some(([,je])=>je.startsWith(`${ee} `))){Ue.preventDefault(),q=D,Te();return}const Ee=Fe.find(([,je])=>je===ce);if(Ee){Ue.preventDefault(),Ce(),ft(Ee[0]);return}if(Fe.some(([,je])=>je.startsWith(`${ce} `))){Ue.preventDefault(),q=[ce],Te();return}Ce()};return z.addEventListener("keydown",Ie),z.addEventListener("keydown",Oe),()=>{Ce(),z.removeEventListener("keydown",Ie),z.removeEventListener("keydown",Oe)}});return()=>{for(const z of F)z()}},[et,_e,B,T,Pe,ft,e]);const Dt=C==="light"?ma:fa,Z=((ot=($e=(De=v.current)==null?void 0:De.activePanel)==null?void 0:$e.group.element)==null?void 0:ot.ownerDocument)??document;return t.jsxs(Tl.Provider,{value:tt,children:[t.jsx("div",{ref:y,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(kd,{className:`h-full min-h-0 min-w-0 adhdev-dockview${P?" is-dragging-dockview":""}${I?" is-showing-dockview-overlay":""}`,components:{conversation:ux,remote:mx},defaultTabComponent:px,watermarkComponent:fx,onReady:Tt,singleTabMode:"default",tabAnimation:"smooth",theme:Dt,popoutUrl:"/popout.html"})}),H&&fr.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:H.x,top:H.y},children:Ct.map(K=>{if(K.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},K.id);let F=t.jsx(du,{size:13,className:"shrink-0 opacity-70"}),z=()=>{};switch(K.id){case"dockInWindow":case"dockBackToGrid":F=t.jsx(mu,{size:13,className:"shrink-0 opacity-70"}),z=()=>{Ne(H.tabKey),N(null)};break;case"moveBackToMain":F=t.jsx(lu,{size:13,className:"shrink-0 opacity-70"}),z=()=>{ke(H.tabKey),N(null)};break;case"floatAsPanel":F=t.jsx(uu,{size:13,className:"shrink-0 opacity-70"}),z=()=>{se(H.tabKey),N(null)};break;case"openInNewWindow":F=t.jsx(cu,{size:13,className:"shrink-0 opacity-70"}),z=()=>{me(H.tabKey),N(null)};break;case"setShortcut":z=q=>{q.stopPropagation(),ze(H.tabKey),N(null)};break;case"removeShortcut":F=t.jsx(It,{size:13,className:"shrink-0 opacity-70"}),z=()=>{const q={...We};delete q[H.tabKey],Qe(q),N(null)};break;case"hideTab":F=t.jsx(tc,{size:13,className:"shrink-0 opacity-70"}),z=()=>{oe(H.tabKey),N(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 ${K.tone==="muted"?"text-text-muted":""}`,onClick:z,children:[F,t.jsx("span",{className:"flex-1 min-w-0",children:K.label}),K.shortcut?t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:K.shortcut}):null]},K.id)})}),H.sourceDocument.body),Pe&&fr.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:()=>ze(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:K=>K.stopPropagation(),children:[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. ",_e?"⌘+1":"Ctrl+1",", ",_e?"⌥+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"})]})}),Z.body)]})}const Ll="adhdev-recent-launch-args-v1",xx=8;function bx(e){return String(e||"").trim().replace(/\s+/g," ")}function Rl(e,s){return`${e.trim()}::${s.trim()}`}function _l(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Ll)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function gx(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Ll,JSON.stringify(e))}catch{}}function Pl(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=_l().byKey[Rl(r,n)])==null?void 0:i.items)||[]}function Dl(e,s,r){var d;const n=String(e||"").trim(),a=String(s||"").trim(),i=bx(r);if(!n||!a||!i)return;const c=_l(),l=Rl(n,a),u=((d=c.byKey[l])==null?void 0:d.items)||[],p=[i,...u.filter(x=>x!==i)].slice(0,xx);c.byKey[l]={items:p},gx(c)}function yx(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 go(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 El(e){var a;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=go((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 $l(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Ks(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 ea(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function vx(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Li(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function Ri(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 wx(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function jx(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 kx(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 Sx({machineCards:e,conversations:s,ides:r,initialMachineId:n,sendDaemonCommand:a,onOpenConversation:i,onClose:c}){var G;const[l,u]=o.useState(n||((G=e[0])==null?void 0:G.id)||null),[p,d]=o.useState(""),[x,g]=o.useState(null),[w,A]=o.useState(!1);o.useEffect(()=>{var I;u(n||((I=e[0])==null?void 0:I.id)||null)},[n,e]);const m=o.useMemo(()=>e.find(I=>I.id===l)||e[0]||null,[l,e]),f=o.useMemo(()=>r.filter(I=>{if(I.type==="adhdev-daemon"||I.transport!=="pty")return!1;const E=vx(I.daemonId||I.id);return!!(m!=null&&m.id)&&E===m.id}),[m==null?void 0:m.id,r]),b=ol(m==null?void 0:m.id,{enabled:!!(m!=null&&m.id),includeSessions:!0,limit:6,intervalMs:1e4}),h=b.diagnostics,S=b.loading,R=b.applyDiagnostics,j=o.useMemo(()=>{const I=new Map;for(const E of f){const B=s.find(U=>U.sessionId===E.sessionId||U.routeId===E.id);E.sessionId&&B&&I.set(E.sessionId,B)}return I},[f,s]),C=o.useCallback(async()=>{if(m!=null&&m.id){A(!0);try{const I=await a(m.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),E=ea(I);if(!(E!=null&&E.success))throw new Error((E==null?void 0:E.error)||"Could not load hosted runtime diagnostics");R(E.diagnostics||E.result||null),d("")}catch(I){const E=I instanceof Error?I.message:"Could not load hosted runtime diagnostics";d(E)}finally{A(!1)}}},[m==null?void 0:m.id,R,a]);o.useEffect(()=>{!(m!=null&&m.id)||h||S||w||C()},[m==null?void 0:m.id,h,S,C,w]);const k=o.useCallback(async(I,E)=>{if(!(m!=null&&m.id)||I==="session_host_stop_session"&&!window.confirm(`Stop ${E.displayName}?
55
- This will terminate the hosted runtime.`))return;const B=`${I}:${E.sessionId}`;g(B);try{const U=await a(m.id,I,{sessionId:E.sessionId}),V=ea(U);if(!(V!=null&&V.success))throw new Error((V==null?void 0:V.error)||"Session host action failed");const ae=I==="session_host_resume_session"?"resumed":I==="session_host_restart_session"?"restarted":"stopped";at.showToast(`Session host ${ae}: ${E.displayName}`,"success"),await C()}catch(U){const V=U instanceof Error?U.message:"Session host action failed";d(V),at.showToast(V,"warning")}finally{g(U=>U===B?null:U)}},[m==null?void 0:m.id,C,a]),v=o.useCallback(async()=>{if(!(!(m!=null&&m.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.`))){g("session_host_prune_duplicate_sessions");try{const E=await a(m.id,"session_host_prune_duplicate_sessions",{}),B=ea(E);if(!(B!=null&&B.success))throw new Error((B==null?void 0:B.error)||"Duplicate prune failed");const U=B.result||{},V=Array.isArray(U.prunedSessionIds)?U.prunedSessionIds.length:0,ae=typeof U.duplicateGroupCount=="number"?U.duplicateGroupCount:0;at.showToast(`Pruned ${V} duplicate runtime(s) across ${ae} group(s)`,"success"),await C()}catch(E){const B=E instanceof Error?E.message:"Duplicate prune failed";d(B),at.showToast(B,"warning")}finally{g(E=>E==="session_host_prune_duplicate_sessions"?null:E)}}},[m==null?void 0:m.id,C,a]),y=o.useMemo(()=>[...(h==null?void 0:h.sessions)||[]].sort((I,E)=>(E.lastActivityAt||0)-(I.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)||[]}:El(y),[h==null?void 0:h.inactiveRecords,h==null?void 0:h.liveRuntimes,h==null?void 0:h.recoverySnapshots,y]),L=$.liveRuntimes,M=$.recoverySnapshots,_=$.inactiveRecords,W=o.useMemo(()=>kx(L),[L]),H=o.useMemo(()=>[...(h==null?void 0:h.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[h==null?void 0:h.recentLogs]),N=o.useMemo(()=>[...(h==null?void 0:h.recentTransitions)||[]].slice(-3).reverse(),[h==null?void 0:h.recentTransitions]),P=(I,E)=>{var X,ie;const B=j.get(I.sessionId),U=f.find(le=>le.sessionId===I.sessionId),V=x===`session_host_resume_session:${I.sessionId}`,ae=x===`session_host_restart_session:${I.sessionId}`,we=x===`session_host_stop_session:${I.sessionId}`,be=go(I.meta),Y=typeof((X=I.meta)==null?void 0:X.runtimeRecoveryError)=="string"?String(I.meta.runtimeRecoveryError):"",he=E==="recovery"?"Recover":"Resume",O=$l(E);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:I.displayName||(U==null?void 0:U.runtimeDisplayName)||(U==null?void 0:U.cliName)||I.providerType}),t.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${jx(I.lifecycle)}`,children:I.lifecycle}),be&&t.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:be})]}),t.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:I.workspaceLabel||(U==null?void 0:U.runtimeWorkspaceLabel)||I.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:I.runtimeKey}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:((ie=I.writeOwner)==null?void 0:ie.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:wx(I.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($a,{size:11})," ",I.attachedClients.length]})]}),t.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",Ri(I.lastActivityAt),I.osPid?` · pid ${I.osPid}`:"",` · Next: ${O}`]}),Y&&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:Y})]})}),t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[B&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i(B),c()},children:"Open chat"}),E==="recovery"&&(I.lifecycle==="interrupted"||I.lifecycle==="failed"||I.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!x,onClick:()=>{k("session_host_resume_session",I)},children:V?`${he}ing…`:he}),t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!x,onClick:()=>{k("session_host_restart_session",I)},children:ae?"Restarting…":"Restart"}),E==="live"&&(I.lifecycle==="running"||I.lifecycle==="starting"||I.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:!!x,onClick:()=>{k("session_host_stop_session",I)},children:we?"Stopping…":"Stop"})]})]},I.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:I=>I.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(Zt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"mt-1 text-[18px] font-black tracking-tight text-text-primary",children:(m==null?void 0:m.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:()=>{C()},disabled:S||w,"aria-label":"Refresh hosted runtime recovery",children:t.jsx(Gs,{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(I=>t.jsx("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[12px] font-semibold transition-colors ${I.id===(m==null?void 0:m.id)?"border-accent-primary/40 bg-accent-primary/12 text-accent-primary":"border-border-subtle bg-bg-secondary text-text-secondary"}`,onClick:()=>u(I.id),children:I.label},I.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(Ss,{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:M.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:Ri(h.hostStartedAt)}),t.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:Li(h.hostStartedAt)})]})]}),H&&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(Ss,{size:13})," Latest warning"]}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:H.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(yn,{size:14})," Live hosted runtimes"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[W>0&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:x==="session_host_prune_duplicate_sessions",onClick:()=>{v()},children:x==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${W}`}),t.jsxs("div",{className:"text-[11px] text-text-secondary",children:[f.length," dashboard session",f.length===1?"":"s"]})]})]}),t.jsx("div",{className:"text-[11px] text-text-secondary leading-relaxed",children:Ks("live")}),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 live hosted CLI runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:L.map(I=>P(I,"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:Ks("recovery")}),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 recovery snapshots need attention."}):t.jsx("div",{className:"space-y-2",children:M.map(I=>P(I,"recovery"))})]}),_.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:Ks("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:_.map(I=>P(I,"inactive"))})]}),N.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:N.map(I=>{const E=y.find(B=>B.sessionId===I.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:(E==null?void 0:E.displayName)||I.sessionId}),t.jsxs("div",{className:"mt-0.5 text-[11px] leading-relaxed text-text-secondary",children:[I.action,I.lifecycle?` · ${I.lifecycle}`:"",I.detail?` · ${I.detail}`:"",I.error?` · ${I.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${I.success===!1?"text-red-300":"text-text-secondary"}`,children:Li(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]})]})]})]})})}function Kl(e){return!e.hasLoadedInitialResults&&!e.isLoading}function or({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 Bl({busy:e,savedSessionsLoading:s,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?yl(n):null;return t.jsxs(or,{title:"Saved history",description:Za(),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:Lf()})]}),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 ta(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 Xr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Nx({machines:e,conversations:s,ides:r,onClose:n,onBrowseDirectory:a,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:l,onListSavedSessions:u,sendDaemonCommand:p,onOpenConversation:d}){var Tt,Dt;const x=Nr(),g=o.useMemo(()=>[...e].sort(Fa),[e]),[w,A]=o.useState(((Tt=g[0])==null?void 0:Tt.id)||""),m=o.useMemo(()=>g.find(Z=>Z.id===w)||g[0],[w,g]),f=o.useMemo(()=>((m==null?void 0:m.workspaces)||[]).map(Z=>({id:Z.id,path:Z.path,label:Z.label})),[m]),b=(m==null?void 0:m.defaultWorkspaceId)||null,[h,S]=o.useState(""),[R,j]=o.useState(""),[C,k]=o.useState(ta(g[0])),[v,y]=o.useState(""),[$,L]=o.useState(""),[M,_]=o.useState([]),[W,H]=o.useState(""),[N,P]=o.useState([]),[G,I]=o.useState(!1),[E,B]=o.useState(!1),[U,V]=o.useState(""),[ae,we]=o.useState(!1),[be,Y]=o.useState(()=>wt()),[he,O]=o.useState(!1),[X,ie]=o.useState(null),[le,me]=o.useState(!1),[ke,de]=o.useState(""),[oe,se]=o.useState(!1),[ue,te]=o.useState(""),[Ne,Se]=o.useState([]),[Ae,T]=o.useState(!1),[xe,ve]=o.useState(""),[Q,ye]=o.useState(!1),_e=o.useRef(null),We=o.useRef(0);o.useEffect(()=>{var Z;!w&&((Z=g[0])!=null&&Z.id)&&A(g[0].id)},[w,g]),o.useEffect(()=>{!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||x(m.id,{minFreshMs:3e4}).catch(()=>{})},[x,m]);const Pe=o.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(Z=>Z.category==="cli"&&Z.installed!==!1),[m]),ze=o.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(Z=>Z.category==="acp"&&Z.installed!==!1),[m]),Qe=o.useMemo(()=>((m==null?void 0:m.detectedIdes)||[]).map(Z=>({id:Z.type,label:Z.name||Z.type,meta:Z.running?"Detected locally":"Available to open"})),[m]),it=o.useMemo(()=>C==="cli"?Pe.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"CLI provider"})):C==="acp"?ze.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"ACP provider"})):Qe,[ze,C,Pe,Qe]);o.useEffect(()=>{var De;if(!m)return;if(_e.current!==m.id){_e.current=m.id,S(b||((De=f[0])==null?void 0:De.id)||"__home__"),j(""),k(ta(m)),y(""),L(""),H(""),P([]),B(!1),V(""),Y(wt()),de("");return}S($e=>{var ot;return $e==="__custom__"||$e==="__home__"||f.some(K=>K.id===$e)?$e:b||((ot=f[0])==null?void 0:ot.id)||"__home__"}),k($e=>$e==="ide"&&Qe.length>0||$e==="cli"&&Pe.length>0||$e==="acp"&&ze.length>0?$e:ta(m))},[ze.length,Pe.length,b,Qe.length,m,f]),o.useEffect(()=>{var Z;C&&(it.some(De=>De.id===v)||y(((Z=it[0])==null?void 0:Z.id)||""))},[C,it,v]);const et=o.useCallback(async(Z,De)=>{const $e=We.current+1;return We.current=$e,I(!0),V(""),u(Z,De).then(ot=>{We.current===$e&&P(ot)}).catch(ot=>{We.current===$e&&(P([]),V(ot instanceof Error?ot.message:"Could not load saved sessions"))}).finally(()=>{We.current===$e&&(I(!1),B(!0))})},[u]),ft=o.useCallback((Z,De)=>{_(Pl(Z,De))},[]);o.useEffect(()=>{We.current+=1,H(""),Y(wt()),!m||!v||C==="ide"?_([]):ft(m.id,v),B(!1),P([]),V(""),I(!1)},[C,ft,et,m,v]),o.useEffect(()=>{if(!W)return;const Z=N.find(De=>De.providerSessionId===W);Z!=null&&Z.canResume||H("")},[N,W]);const tt=h==="__custom__"?R.trim():h==="__home__"?"":((Dt=f.find(Z=>Z.id===h))==null?void 0:Dt.path)||"",Ct=o.useMemo(()=>m?r.filter(Z=>Z.id!==m.id&&Z.daemonId===m.id).map(Z=>Z.workspace):[],[r,m]),pt=o.useMemo(()=>((m==null?void 0:m.recentLaunches)||[]).map(Z=>Z.workspace),[m]),st=o.useCallback(Z=>{const De=String(Z.workspace||"").trim();if(!De)return;const $e=f.find(ot=>Xr(ot.path)===Xr(De));if($e){S($e.id),j("");return}S("__custom__"),j(De)},[f]),Re=o.useCallback(Z=>{const De=String(Z.workspace||"").trim();if(!De)return{workspaceId:null,workspacePath:null};const $e=f.find(ot=>Xr(ot.path)===Xr(De));return $e?{workspaceId:$e.id,workspacePath:null}:{workspaceId:null,workspacePath:De}},[f]),Ge=o.useMemo(()=>N.find(Z=>Z.providerSessionId===W)||null,[N,W]),Be=o.useMemo(()=>{var De;if(C!=="cli"||!m||!v)return null;const Z=((De=Pe.find($e=>$e.type===v))==null?void 0:De.displayName)||v;return{routeId:m.id,daemonId:m.id,providerSessionId:W||void 0,transport:"pty",mode:"chat",agentName:Z,agentType:v,status:"idle",title:Z,messages:[],ideType:v,workspaceName:tt,displayPrimary:Z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${m.id}:${v}`,machineName:_t(m,{fallbackId:m.id})}},[C,Pe,tt,m,W,v]),qe=o.useCallback(()=>{var De;if(!m)return;S("__custom__"),se(!0),ve("");const Z=Cn(m.platform,Nn(R.trim(),tt,Ct,pt,m.defaultWorkspacePath,(De=f.find($e=>$e.id===b))==null?void 0:De.path,f.map($e=>$e.path)));T(!0),a(m.id,Z).then($e=>{te($e.path),j($e.path),Se($e.directories)}).catch($e=>{ve($e instanceof Error?$e.message:"Could not load folder")}).finally(()=>T(!1))},[R,b,pt,Ct,a,tt,m,f]),At=o.useCallback(Z=>{m&&(T(!0),ve(""),a(m.id,Z).then(De=>{te(De.path),j(De.path),Se(De.directories)}).catch(De=>{ve(De instanceof Error?De.message:"Could not load folder")}).finally(()=>T(!1)))},[a,m]),bt=o.useCallback(async()=>{if(!m||!tt)return;ye(!0),de("");const Z=await i(m.id,tt);if(ye(!1),!Z.ok){de(Z.error||"Could not save workspace");return}de("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,tt,m]),jt=o.useCallback(async()=>{if(!m||!C||!v)return;me(!0),de("");const Z=$.trim()?$.trim().split(/\s+/).filter(Boolean):[],De=C==="ide"?await c(m.id,v,{workspacePath:tt||null}):await l(m.id,C,v,{workspaceId:h!=="__home__"&&h!=="__custom__"?h:null,workspacePath:h==="__custom__"&&tt||null,resumeSessionId:C==="cli"&&W?W:null,cliArgs:Z});if(me(!1),!De.ok){de(De.error||"Could not start session");return}C!=="ide"&&$.trim()&&(Dl(m.id,v,$),ft(m.id,v)),n()},[C,$,ft,n,c,l,tt,m,W,v,h]),gt=C?Uc(C,C==="cli"&&!!W):"Start",Mt=C?zc(C,C==="cli"&&!!W):"Starting…";return m?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:t.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start 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(or,{title:"Machine",children:t.jsx("select",{value:m.id,onChange:Z=>A(Z.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:le,children:g.map(Z=>t.jsx("option",{value:Z.id,children:_t(Z,{fallbackId:Z.id})},Z.id))})}),C==="cli"&&t.jsx(or,{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:le||!m,onClick:()=>O(!0),children:[t.jsx(Zt,{size:14}),Mf()]})}),t.jsxs(or,{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:qe,disabled:le,children:"Browse…"}),children:[t.jsxs("select",{value:h,onChange:Z=>{const De=Z.target.value;S(De),De==="__custom__"?qe():de("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:le,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),f.map(Z=>t.jsxs("option",{value:Z.id,children:[Z.id===b?"⭐ ":"",kn(Z.path,Z.label)||Z.path]},Z.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.":tt||"Select a workspace folder."}),h==="__custom__"&&tt&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:qe,disabled:le,children:[t.jsx(Os,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:bt,disabled:le||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:Pe.length>0},{id:"ide",label:"IDE",enabled:Qe.length>0},{id:"acp",label:"ACP",enabled:ze.length>0}].map(Z=>t.jsx("button",{type:"button",className:`btn btn-sm ${C===Z.id?"btn-primary":"btn-secondary"}`,onClick:()=>k(Z.id),disabled:!Z.enabled||le,children:Z.label},Z.id))})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:C==="ide"?"Choose IDE":C==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[it.map(Z=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${v===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>y(Z.id),disabled:le,children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Z.meta})]},Z.id)),it.length===0&&t.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),C!=="ide"&&t.jsxs(or,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:$,onChange:Z=>L(Z.target.value),placeholder:"Optional flags...",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:le}),M.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:M.map(Z=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>L(Z),disabled:le,title:Z,children:Z},Z))})]}),C==="cli"&&t.jsx(Bl,{busy:le,savedSessionsLoading:G,savedSessionsError:U,selectedSession:Ge,onRefresh:()=>{!m||!v||et(m.id,v)},onOpenHistory:()=>{!m||!v||(we(!0),Kl({hasLoadedInitialResults:E,isLoading:G})&&et(m.id,v))},onClearSelection:()=>H("")}),ke&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ke.includes("saved")||ke.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:ke})]}),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:le,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:jt,disabled:le||!C||!v||h==="__custom__"&&!tt,children:[t.jsx(Ba,{size:14}),le?Mt:gt]})]})]})}),oe&&t.jsx(An,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:ue,directories:Ne,busy:Ae,error:xe,onClose:()=>se(!1),onNavigate:At,onConfirm:Z=>{j(Z),te(Z),S("__custom__"),se(!1)}}),ae&&Be&&t.jsx(so,{activeConv:Be,ides:[],isCreatingChat:!1,isRefreshingHistory:G,savedSessions:N,isSavedSessionsLoading:G,isResumingSavedSessionId:X,savedHistoryFilters:be,onSavedHistoryFiltersChange:Y,onClose:()=>we(!1),onNewChat:()=>{H(""),we(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!m||!v||et(m.id,v)},onResumeSavedSession:Z=>{if(!m||!v||X||!Z.canResume)return;const De=Re(Z);H(Z.providerSessionId),st(Z),ie(Z.providerSessionId),we(!1),me(!0),de(""),l(m.id,"cli",v,{workspaceId:De.workspaceId,workspacePath:De.workspacePath,resumeSessionId:Z.providerSessionId}).then($e=>{if(!$e.ok){de($e.error||"Could not resume session");return}n()}).finally(()=>{me(!1),ie($e=>$e===Z.providerSessionId?null:$e)})}}),he&&m&&t.jsx(Sx,{machineCards:[{id:m.id,label:_t(m,{fallbackId:m.id}),subtitle:[m.platform||"machine",wl(m)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:m.id,sendDaemonCommand:p,onOpenConversation:Z=>{O(!1),n(),d(Z)},onClose:()=>O(!1)})]}):null}function Cx(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 Ix(e){return e instanceof Error?e.message:String(e||"")}function Ax(e){const s=Ix(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Mx({showMobileChatMode:e,isMobile:s,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetActiveCliViewMode:p,mobileChatConversations:d,hiddenConversations:x,ides:g,actionLogs:w,sendDaemonCommand:A,setLocalUserMessages:m,setActionLogs:f,isStandalone:b,initialDataLoaded:h,userName:S,requestedMobileTabKey:R,onRequestedMobileTabConsumed:j,requestedMachineId:C,onRequestedMachineConsumed:k,requestedMobileSection:v,onRequestedMobileSectionConsumed:y,containerRef:$,isSplitMode:L,numGroups:M,groupSizes:_,groupedConvs:W,clearedTabs:H,focusedGroup:N,setFocusedGroup:P,moveTabToGroup:G,splitTabRelative:I,closeGroup:E,handleResizeStart:B,groupActiveTabIds:U,setGroupActiveTabIds:V,groupTabOrders:ae,setGroupTabOrders:we,toggleHiddenTab:be,visibleConversations:Y,requestedDesktopTabKey:he,onRequestedDesktopTabConsumed:O,onDesktopActiveTabChange:X,onRequestScrollToBottom:ie,onHideConversation:le,onShowHiddenConversation:me,onShowAllHiddenConversations:ke,scrollToBottomRequest:de,machineEntries:oe,onBrowseMachineDirectory:se,onSaveMachineWorkspace:ue,onLaunchMachineIde:te,onLaunchMachineProvider:Ne,onListMachineSavedSessions:Se,notifications:Ae,notificationUnreadCount:T,notificationStateBySessionId:xe,liveSessionInboxState:ve,onMarkNotificationRead:Q,onMarkNotificationUnread:ye,onDeleteNotification:_e,onMarkNotificationTargetRead:We}){const Pe=lt.useRef(null),[ze,Qe]=lt.useState(!1),[it,et]=lt.useState(!1),[ft,tt]=lt.useState(!1),[Ct,pt]=lt.useState(!1),st=lt.useCallback(J=>{var Me;fr.flushSync(()=>{me(J)}),(Me=Pe.current)==null||Me.restoreHiddenTabToSavedLocation(J.tabKey)},[me]),Re=lt.useCallback(J=>{var Ve;const Me=d.find(Fe=>xr(Fe,J))||x.find(Fe=>xr(Fe,J));Me&&(x.some(Fe=>Fe.tabKey===Me.tabKey)&&st(Me),X(Me.tabKey),(Ve=Pe.current)==null||Ve.activateConversationTab(Me.tabKey),ie(Me.tabKey,"notification-open")),Q(J.id),(J.sessionId||J.providerSessionId||J.tabKey||J.routeId)&&We({sessionId:J.sessionId,providerSessionId:J.providerSessionId,tabKey:J.tabKey,routeId:J.routeId}),Qe(!1)},[st,x,d,X,Q,We,ie]),[Ge,Be]=lt.useState(!1),[qe,At]=lt.useState("quickstart"),[bt,jt]=lt.useState("workspace"),gt=!e&&!s,Mt=lt.useCallback(J=>{Qe(J),J&&et(!1)},[]),Tt=lt.useCallback(J=>{et(J),J&&Qe(!1)},[]),Dt=lt.useCallback(()=>{var Me;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Me=Pe.current)==null||Me.resetAllPanelsToMain(),et(!1))},[]),Z=lt.useCallback(()=>{At(Y.length===0?"quickstart":"shortcuts"),jt("workspace"),tt(!0),Qe(!1),et(!1)},[Y.length]),De=lt.useCallback(async J=>{var ee;if(!r)return;const Me=(ee=r.modalButtons)==null?void 0:ee[J];if(!Me)return;const Ve=yr(r);if(!Ve)return;const Fe=Me.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),D=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Fe);try{await A(Ve,"resolve_action",{button:Me,action:D?"approve":"reject",buttonIndex:J,...$s(r)})}catch(ce){Ax(ce)||console.error("[Shortcut approval] Failed:",ce)}},[r,A]),{isMac:$e,actionDefinitions:ot,actionShortcuts:K,shortcutListening:F,shortcutListeningDraft:z,setShortcutListening:q,setShortcutListeningDraft:re,saveShortcuts:Ce}=ax({enabled:gt&&!ft,onTrigger:J=>{var Me,Ve,Fe,D,ee,ce,Ke,Le,Ee,Xe,je,ut,ts,Ys,Xs,Ar;if(J==="openShortcutHelp"){Z();return}if(J==="hideCurrentTab"){r&&le(r);return}if(J==="toggleHiddenTabs"){Tt(!it);return}if(J==="openHistoryForActiveTab"){r&&!Ze(r)&&i(r);return}if(J==="openRemoteForActiveTab"){r&&!nt(r)&&!Ze(r)&&c(r);return}if(J==="splitActiveTabRight"){(Me=Pe.current)==null||Me.splitActiveTabRight();return}if(J==="splitActiveTabDown"){(Ve=Pe.current)==null||Ve.splitActiveTabDown();return}if(J==="floatActiveTab"){(Fe=Pe.current)==null||Fe.floatActiveTab();return}if(J==="popoutActiveTab"){(D=Pe.current)==null||D.popoutActiveTab();return}if(J==="dockActiveTab"){(ee=Pe.current)==null||ee.dockActiveTab();return}if(J==="focusLeftPane"){(ce=Pe.current)==null||ce.focusLeftPane();return}if(J==="focusRightPane"){(Ke=Pe.current)==null||Ke.focusRightPane();return}if(J==="focusUpPane"){(Le=Pe.current)==null||Le.focusUpPane();return}if(J==="focusDownPane"){(Ee=Pe.current)==null||Ee.focusDownPane();return}if(J==="moveActiveTabToLeftPane"){(Xe=Pe.current)==null||Xe.moveActiveTabToLeftPane();return}if(J==="moveActiveTabToRightPane"){(je=Pe.current)==null||je.moveActiveTabToRightPane();return}if(J==="moveActiveTabToUpPane"){(ut=Pe.current)==null||ut.moveActiveTabToUpPane();return}if(J==="moveActiveTabToDownPane"){(ts=Pe.current)==null||ts.moveActiveTabToDownPane();return}if(J==="triggerPrimaryApprovalAction"){De(0);return}if(J==="triggerSecondaryApprovalAction"){De(1);return}if(J==="triggerTertiaryApprovalAction"){De(2);return}if(J==="setActiveTabShortcut"){(Ys=Pe.current)==null||Ys.setShortcutForActiveTab();return}if(J==="selectPreviousGroupTab"){(Xs=Pe.current)==null||Xs.activatePreviousTabInGroup();return}if(J==="selectNextGroupTab"){(Ar=Pe.current)==null||Ar.activateNextTabInGroup();return}!r||!nt(r)||Ze(r)||J==="toggleCliView"&&p(u==="chat"?"terminal":"chat")}}),Te=lt.useCallback(()=>{tt(!1),q(null),re([])},[q,re]),Ie=lt.useMemo(()=>bt==="all"?ot:ot.filter(J=>Cx(J)===bt),[ot,bt]),Oe=lt.useCallback(()=>{const J=Object.fromEntries(ot.map(Me=>[Me.id,""]));Ce(J)},[ot,Ce]),Ue=lt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const J=Object.fromEntries(ot.map(Me=>[Me.id,Me.defaultShortcut]));Ce(J)},[ot,Ce]);return lt.useEffect(()=>{const J=Me=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Me.metaKey&&Me.key.toLowerCase()==="w":Me.ctrlKey&&Me.key.toLowerCase()==="w")&&(Me.preventDefault(),r&&le&&le(r))};return window.addEventListener("keydown",J),()=>window.removeEventListener("keydown",J)},[r,le]),lt.useEffect(()=>{if(!ft||F)return;const J=Me=>{Me.key==="Escape"&&(Me.preventDefault(),Te())};return window.addEventListener("keydown",J,!0),()=>window.removeEventListener("keydown",J,!0)},[Te,ft,F]),lt.useEffect(()=>{if(!gt){Be(!1);return}Be(!0);const J=window.setTimeout(()=>{Be(!1)},1e4);return()=>window.clearTimeout(J)},[gt]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(Sf,{activeConv:r,wsStatus:n,isConnected:a,conversations:Y,hiddenConversations:x,onOpenHistory:i,onHideConversation:le,onShowConversation:st,onShowAllHidden:ke,onResetPanelsToMain:Dt,notifications:Ae,notificationUnreadCount:T,onOpenNotification:Re,onMarkNotificationRead:Q,onMarkNotificationUnread:ye,onDeleteNotification:_e,inboxOpen:ze,onInboxOpenChange:Mt,hiddenOpen:it,onHiddenOpenChange:Tt,onOpenNewSession:s?void 0:()=>pt(!0),actionShortcuts:K,onOpenRemote:()=>{!r||nt(r)||Ze(r)||c(r)},onStopCli:l,activeCliViewMode:u,onSetCliViewMode:p}),e?t.jsx(Gh,{conversations:d,hiddenConversations:x,ides:g,actionLogs:w,sendDaemonCommand:A,setLocalUserMessages:m,setActionLogs:f,isStandalone:b,userName:S,requestedActiveTabKey:R,onRequestedActiveTabConsumed:j,requestedMachineId:C,onRequestedMachineConsumed:k,requestedMobileSection:v,onRequestedMobileSectionConsumed:y,onOpenHistory:i,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowHiddenConversation:st,onShowAllHiddenConversations:ke,onOpenNewSession:()=>pt(!0),notificationStateBySessionId:xe,liveSessionInboxState:ve,onMarkNotificationTargetRead:We}):s?t.jsx(tx,{containerRef:$,isSplitMode:L,numGroups:M,groupSizes:_,groupedConvs:W,clearedTabs:H,ides:g,actionLogs:w,sendDaemonCommand:A,setLocalUserMessages:m,setActionLogs:f,isStandalone:b,hasRegisteredMachines:oe.length>0,userName:S,focusedGroup:N,setFocusedGroup:P,moveTabToGroup:G,splitTabRelative:I,closeGroup:E,handleResizeStart:B,groupActiveTabIds:U,setGroupActiveTabIds:V,groupTabOrders:ae,setGroupTabOrders:we,toggleHiddenTab:be,allowTabShortcuts:!1,notificationStateBySessionId:xe,liveSessionInboxState:ve}):t.jsx(hx,{visibleConversations:Y,clearedTabs:H,ides:g,actionLogs:w,sendDaemonCommand:A,setLocalUserMessages:m,setActionLogs:f,isStandalone:b,hasRegisteredMachines:oe.length>0,initialDataLoaded:h,userName:S,toggleHiddenTab:be,actionShortcuts:K,registerActionHandlers:J=>{Pe.current=J},notificationStateBySessionId:xe,liveSessionInboxState:ve,onActiveTabChange:X,requestedActiveTabKey:he,onRequestedActiveTabConsumed:O,onRequestScrollToBottom:ie,scrollToBottomRequest:de}),Ct&&t.jsx(Nx,{machines:oe,conversations:d,ides:g,onClose:()=>pt(!1),onBrowseDirectory:se,onSaveWorkspace:ue,onLaunchIde:te,onLaunchProvider:Ne,onListSavedSessions:Se,sendDaemonCommand:A,onOpenConversation:J=>{pt(!1),me(J),X(J.tabKey),ie(J.tabKey,"conversation-open")}}),ft&&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:Te,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:J=>J.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:Te,"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(J=>t.jsx("button",{type:"button",className:`btn btn-sm ${qe===J.id?"btn-primary":"btn-secondary"}`,onClick:()=>At(J.id),children:J.label},J.id))}),qe==="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 ",$e?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),qe==="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."]})]})]})]}),qe==="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(J=>t.jsx("button",{type:"button",className:`btn btn-sm ${bt===J.id?"btn-primary":"btn-secondary"}`,onClick:()=>jt(J.id),children:J.label},J.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Oe,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:Ue,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:Ie.map(J=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${F===J.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:J.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:J.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:J.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:F===J.id?z.length>0?`${z.join(" ")} ...`:"Listening...":K[J.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{q(J.id),re([])},children:F===J.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Me={...K};Me[J.id]="",Ce(Me)},children:"Disable"})]})]})},J.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",$e?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&t.jsxs("button",{type:"button",onClick:Z,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 sa=[{icon:"🦦",title:"Welcome to ADHDev",desc:"Monitor and control your AI coding agents from anywhere — web, mobile, or CLI.",visual:"🎉"},{icon:"💬",title:"Real-time chat",desc:"See what your AI agent is doing in real-time. Send messages, approve or reject actions — all from your browser or phone.",visual:"📱"},{icon:"🖥️",title:"Remote desktop",desc:"View and control your IDE screen via P2P connection. Click, type, scroll — just like being there.",visual:"🖱️"},{icon:"🚀",title:"Get started",desc:"Install the daemon and link it to your dashboard. It connects automatically.",code:"npm install -g @adhdev/daemon-standalone && adhdev-standalone"}];function Tx({onClose:e}){const[s,r]=o.useState(0),n=sa[s],a=s===sa.length-1;return t.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:i=>{i.stopPropagation()},children:[t.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[t.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:t.jsx(It,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:sa.map((i,c)=>t.jsx("div",{style:{width:c===s?24:8,height:8,borderRadius:4,background:c===s?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),t.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),t.jsxs("div",{style:{textAlign:"center"},children:[t.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[t.jsx("span",{children:n.icon})," ",n.title]}),t.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&t.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[t.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),t.jsx("div",{className:"flex justify-end items-center mt-6",children:t.jsx("button",{onClick:()=>a?e():r(i=>i+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),t.jsx("style",{children:`
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 Lx({hasExtensions:e,ideName:s,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?t.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[t.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${r==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a("native"),children:s}),n.map(i=>{const c=r===i.tabKey,l=i.status==="waiting_approval",u=i.status==="generating";return t.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${c?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(i.tabKey),children:[t.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":u?"var(--accent-primary)":"var(--text-muted)",boxShadow:u?"0 0 6px var(--accent-primary)":"none"}}),i.title,l&&t.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},i.tabKey)})]}):null}function Rx({ideData:e,allIdes:s,connectionStates:r,localUserMessages:n,ideName:a,preferredTabKey:i}){const[c,l]=o.useState(()=>i||"native"),u=o.useMemo(()=>Gc(s),[s]),p=o.useMemo(()=>e?ro(e,n,{machineNames:u,connectionStates:r,defaultConnectionState:"new"}):[],[e,n,u,r]),d=o.useMemo(()=>p.find(f=>f.streamSource==="native"),[p]),x=o.useMemo(()=>p.filter(f=>f.streamSource==="agent-stream"),[p]),g=o.useMemo(()=>e?Ft(p,e.id):null,[p,e]);o.useEffect(()=>{i&&l(i)},[i]),o.useEffect(()=>{if(i||!g)return;const f=g.streamSource==="native"?"native":g.tabKey;!f||c===f||c==="native"&&l(f)},[c,g,i]),o.useEffect(()=>{var f;c!=="native"&&(x.some(b=>b.tabKey===c)||l(((f=x[0])==null?void 0:f.tabKey)||"native"))},[c,x]),o.useEffect(()=>{c==="native"&&(d||x[0]&&l(x[0].tabKey))},[c,d,x]);const w=o.useMemo(()=>c==="native"&&d?d:x.find(f=>f.tabKey===c)||g||d||x[0],[c,d,g,x]),A=o.useMemo(()=>x.map(f=>({tabKey:f.tabKey,title:Wc(f)||a,status:f.status})),[x,a]),m=o.useCallback(f=>{if(f)return p.find(b=>xr(b,{sessionId:f,routeId:f,tabKey:f,providerSessionId:f}))},[p]);return{activeChatTab:c,setActiveChatTab:l,activeConv:w,conversations:p,extensionTabs:A,hasExtensions:A.length>0,resolveConversationByTarget:m}}function _x({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:a,localUserMessages:i,sendDaemonCommand:c,setLocalUserMessages:l,setActionLogs:u,isStandalone:p,userName:d,onOpenHistory:x,onConversationChange:g,onClose:w}){const[A,m]=o.useState("split"),[f,b]=o.useState(()=>ns(e)?"native":e.tabKey),h=o.useRef(null),S=o.useMemo(()=>s||r.find(I=>I.id===e.routeId),[e.routeId,s,r]),R=o.useMemo(()=>dt((S==null?void 0:S.type)||""),[S==null?void 0:S.type]),{conversations:j,extensionTabs:C,hasExtensions:k}=Rx({ideData:S,allIdes:r,connectionStates:n,localUserMessages:i,ideName:R||"IDE",preferredTabKey:ns(e)?void 0:e.tabKey}),v=o.useMemo(()=>S?Ft(j,S.id):null,[S,j]);o.useEffect(()=>{const I=h.current,E={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(h.current=E,!(I&&I.routeId===E.routeId&&I.tabKey===E.tabKey&&I.streamSource===E.streamSource)){if(ns(e)){b("native");return}b(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(f==="native"){if(j.some(I=>I.streamSource==="native"))return;(v==null?void 0:v.streamSource)==="agent-stream"&&b(v.tabKey);return}if(!j.some(I=>I.tabKey===f)){if((v==null?void 0:v.streamSource)==="agent-stream"){b(v.tabKey);return}b("native")}},[j,f,v]);const y=o.useMemo(()=>f==="native"?j.find(I=>I.streamSource==="native")||e:j.find(I=>I.tabKey===f)||e,[e,j,f]),$=il(y),L=o.useMemo(()=>$.status||$.modalMessage||$.modalButtons?{...y,...$.status?{status:$.status}:{},...$.modalMessage!==void 0?{modalMessage:$.modalMessage}:{},...$.modalButtons!==void 0?{modalButtons:$.modalButtons}:{}}:y,[y,$]),M=Sr(L),_=Sn({sendDaemonCommand:c,activeConv:L,setLocalUserMessages:l,setActionLogs:u,isStandalone:p}),{connScreenshot:W,screenshotUsage:H,handleRemoteAction:N}=Nl({doId:M,targetSessionId:Sc(L),connState:L.connectionState||"new",viewMode:A}),P=o.useMemo(()=>a.filter(I=>I.routeId===L.tabKey),[a,L.tabKey]);o.useEffect(()=>{g==null||g(L)},[L,g]),o.useEffect(()=>{const I=E=>{E.key==="Escape"&&w()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[w]);const G=o.useCallback(I=>{I.stopPropagation()},[]);return t.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:w,children:t.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:G,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(Pt,{size:16})}),t.jsx("span",{className:"truncate",children:Va(y)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:w,children:"Close"})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[t.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(I=>{const E=A===I;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${E?"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:()=>m(I),title:I==="split"?"Split view":"Remote only",children:I==="split"?t.jsx(Yd,{size:15}):t.jsx(Pt,{size:15})},I)})}),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:()=>x(y),title:"Chat History",children:[t.jsx(Ka,{size:14,className:"md:mr-1.5"}),t.jsx("span",{className:"hidden md:inline",children:"History"})]}),t.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:w,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${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(Lx,{hasExtensions:k,ideName:R||"IDE",activeChatTab:f,extensionTabs:C,onSelectTab:b}),t.jsx(dc,{activeConv:L,onModalButton:_.handleModalButton}),t.jsx(ja,{activeConv:L,ideEntry:S,showMetaChips:!1,handleSendChat:_.handleSendChat,isSendingChat:_.isSendingChat,sendFeedbackMessage:_.sendFeedbackMessage,handleFocusAgent:_.handleFocusAgent,isFocusingAgent:_.isFocusingAgent,actionLogs:P,userName:d})]}),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(oc,{addLog:()=>{},connState:L.connectionState||"new",connScreenshot:W,screenshotUsage:H,transportType:L.transport,onAction:N})})]})]})})}function Px({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=yf(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 Dx({historyModalOpen:e,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:a,savedHistorySessions:i,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:l,onCloseHistory:u,onNewHistoryChat:p,onSwitchHistorySession:d,onRefreshHistory:x,onResumeSavedHistorySession:g,remoteDialogConv:w,remoteDialogIdeEntry:A,connectionStates:m,actionLogs:f,localUserMessages:b,sendDaemonCommand:h,setLocalUserMessages:S,setActionLogs:R,isStandalone:j,userName:C,onOpenRemoteHistory:k,onRemoteConversationChange:v,onCloseRemoteDialog:y,cliStopDialogOpen:$,cliStopTargetConv:L,onCancelCliStop:M,onStopCliNow:_,onSaveCliAndStop:W,toasts:H,onDismissToast:N,onClickToast:P,showOnboarding:G,onCloseOnboarding:I}){var U;const[E,B]=lt.useState(()=>wt());return t.jsxs(t.Fragment,{children:[e&&s&&t.jsx(so,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:a,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:l,savedHistoryFilters:E,onSavedHistoryFiltersChange:B,onClose:u,onNewChat:p,onSwitchSession:d,onRefreshHistory:x,onResumeSavedSession:g}),w&&t.jsx(_x,{activeConv:w,ideEntry:A,ides:r,connectionStates:m,actionLogs:f,localUserMessages:b,sendDaemonCommand:h,setLocalUserMessages:S,setActionLogs:R,isStandalone:j,userName:C,onOpenHistory:k,onConversationChange:v,onClose:y}),$&&L&&(nt(L)||Ze(L))&&t.jsx(Px,{activeConv:L,canSaveAndStop:nt(L)&&!Ze(L)&&!!((U=L.resume)!=null&&U.supported),onCancel:M,onStopNow:_,onSaveAndStop:W}),t.jsx(Vc,{toasts:H,onDismiss:N,onClickToast:P}),G&&t.jsx(Tx,{onClose:I})]})}function Ex({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(Gs,{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",d=c.versionUpdateRequired===!0;return t.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[t.jsx("span",{className:"font-medium text-text-primary",children:l}),t.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",p]}),d&&t.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),u==="upgrading"?t.jsx("span",{className:"text-[10px] animate-pulse",style:{color:d?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):u==="done"?t.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):u==="error"?t.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(c.id),children:"retry"}):t.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:d?"var(--status-danger)":"var(--status-warning)",background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:d?"Update now":"Upgrade"})]},c.id)})]}),!r&&t.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:t.jsx(It,{size:16})})]})}function $x(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function Kx(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":return!0;case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function Bx(e,s,r=Date.now()){return!e||!Kx(s)?null:{tabKey:e,nonce:r}}function Ox(e){const s=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?s===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:r===e.autoReadKey?r:null}:r===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:r}:{shouldSchedule:!0,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!r,nextPendingKey:null}}function Wx(e){const s=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,i=[e.tabKey,e.historySessionId||"",s,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&s&&s!==r),autoReadKey:i,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Hx(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function _i(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Fx(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Ux(){var Co,Io,Ao,Mo,To;const{sendCommand:e}=Lt(),s=Nr(),r=al(),n=Pa(),a=Vs(),[i,c]=Sd(),l=i.get("activeTab"),u=((Co=n.state)==null?void 0:Co.openRemoteForTabKey)||null,p=((Io=n.state)==null?void 0:Io.openMachineId)||null,d=((Ao=n.state)==null?void 0:Ao.mobileSection)||null,x=Dc(),g=x.ides||[],w=x.initialLoaded??!0,{updateRouteChats:A,setToasts:m}=x,[f,b]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),h=x.toasts||[],S=x.wsStatus||"connected",R=x.isConnected??!0,j=x.connectionStates||{},C=x.showReconnected||!1,{groupAssignments:k,setGroupAssignments:v,focusedGroup:y,setFocusedGroup:$,groupActiveTabIds:L,setGroupActiveTabIds:M,groupTabOrders:_,setGroupTabOrders:W,groupSizes:H,setGroupSizes:N,isMobile:P,hasHydratedStoredLayout:G,hydrateStoredLayout:I}=Qp(),[E,B]=o.useState(!1),[U,V]=o.useState(!1),[ae,we]=o.useState(null),[be,Y]=o.useState([]),[he,O]=o.useState(!1),[X,ie]=o.useState(null),[le,me]=o.useState(()=>io());o.useEffect(()=>bp(me),[]);const ke=o.useMemo(()=>$x({isMobile:P,mobileViewMode:le}),[P,le]),[de,oe]=o.useState([]),[se,ue]=o.useState({}),[te,Ne]=o.useState({}),[Se,Ae]=o.useState({}),[T,xe]=o.useState(null),[ve,Q]=o.useState(null),[ye,_e]=o.useState(null),We=o.useRef(null);jr("Dashboard",{ideCount:g.length,toastCount:h.length,focusedGroup:y,groupCount:Object.keys(k).length,localMessageTabs:Object.keys(se).length,actionLogCount:de.length});const Pe=o.useMemo(()=>g.filter(ne=>ne.type==="adhdev-daemon").sort(Fa),[g]),ze=Pe[0],Qe=!!ze;o.useEffect(()=>{for(const ne of Pe){(!ne.detectedIdes||!ne.availableProviders||!ne.recentLaunches||!ne.workspaces)&&s(ne.id,{minFreshMs:3e4}).catch(()=>{});const ge=ne.machine;(typeof(ge==null?void 0:ge.cpus)!="number"||typeof(ge==null?void 0:ge.totalMem)!="number"||typeof(ge==null?void 0:ge.arch)!="string"||typeof(ge==null?void 0:ge.release)!="string")&&r(ne.id,{minFreshMs:3e4}).catch(()=>{})}},[s,r,Pe]);const it=(ze==null?void 0:ze.terminalBackend)||null,et=ze?_t(ze,{fallbackId:ze.id}):null,ft=(ze==null?void 0:ze.id)||null,tt=o.useMemo(()=>Ip(g,te),[g,te]),{hiddenTabs:Ct,hideTab:pt,toggleTab:st,showTab:Re,showAllTabs:Ge}=Cp(),{conversations:Be,visibleConversations:qe,visibleTabKeys:At,resolveConversationBySessionId:bt,resolveConversationByTarget:jt}=Bp({ides:tt,connectionStates:j,localUserMessages:se,clearedTabs:Se,hiddenTabs:Ct}),gt=o.useMemo(()=>new Map(Be.map(ne=>[ne.tabKey,Fr(ne)])),[Be]),Mt=o.useCallback(ne=>{const pe=gt.get(ne)||Fr({tabKey:ne});pt(pe)},[gt,pt]),Tt=o.useCallback(ne=>{const pe=gt.get(ne)||Fr({tabKey:ne});st(pe)},[gt,st]),Dt=o.useCallback(ne=>{const pe=gt.get(ne)||Fr({tabKey:ne});Re(pe)},[gt,Re]);cf(qe,ke),o.useEffect(()=>{Object.keys(te).length!==0&&Ne(ne=>Ap(ne,g))},[g,te]);const Z=o.useMemo(()=>Tu(g),[g]),{notifications:De,unreadCount:$e,notificationStateBySessionId:ot,markRead:K,markUnread:F,markTargetRead:z,deleteNotification:q}=kh({conversations:Be,liveSessionInboxState:Z}),re=o.useCallback(ne=>{const pe=De.find(fe=>fe.id===ne),ge=Math.max(Date.now(),(pe==null?void 0:pe.updatedAt)||0);K(ne,ge),pe!=null&&pe.sessionId&&e(pe.machineId||pe.routeId,"mark_session_seen",{sessionId:pe.sessionId,seenAt:ge}).catch(()=>{})},[K,De,e]),Ce=o.useCallback(ne=>{const pe=De.find(ge=>ge.id===ne);F(ne),pe!=null&&pe.sessionId&&e(pe.machineId||pe.routeId,"mark_notification_unread",{sessionId:pe.sessionId,notificationId:pe.id}).catch(()=>{})},[F,De,e]),Te=o.useCallback(ne=>{const pe=De.find(ge=>ge.id===ne);q(ne),pe!=null&&pe.sessionId&&e(pe.machineId||pe.routeId,"delete_notification",{sessionId:pe.sessionId,notificationId:pe.id}).catch(()=>{})},[q,De,e]),Ie=o.useRef(null),Oe=o.useRef(null),Ue=o.useRef(null),J=o.useRef(null),Me=o.useRef(null),{containerRef:Ve,normalizedGroupAssignments:Fe,numGroups:D,isSplitMode:ee,groupedConvs:ce,moveTabToGroup:Ke,closeGroup:Le,handleResizeStart:Ee,splitTabRelative:Xe}=oh({groupAssignments:k,setGroupAssignments:v,setFocusedGroup:$,setGroupActiveTabIds:M,setGroupTabOrders:W,groupSizes:H,setGroupSizes:N,isMobile:P,visibleConversations:qe,visibleTabKeys:At}),je=o.useMemo(()=>{var pe,ge;if(!P){if(T){const fe=Be.find(Je=>Je.tabKey===T);if(fe)return fe}return qe[0]}const ne=L[y];if(ne){const fe=Be.find(Je=>Je.tabKey===ne);if(fe)return fe}return((pe=ce[y])==null?void 0:pe[0])||((ge=ce[0])==null?void 0:ge[0])},[T,P,L,y,Be,ce,qe]);o.useEffect(()=>{const ne=()=>{Ue.current&&(clearTimeout(Ue.current),Ue.current=null),J.current&&(clearTimeout(J.current),J.current=null),Me.current&&(document.removeEventListener("visibilitychange",Me.current),Me.current=null),Oe.current=null};if(P){ne(),Ie.current=null;return}if(!(je!=null&&je.sessionId)){ne(),Ie.current=null;return}const pe=dn(je,Z),ge=Wx({tabKey:je.tabKey,historySessionId:kr(je)||"",lastMessageHash:je.lastMessageHash||"",lastMessageAt:Number(je.lastMessageAt||0),timestamp:ps(je),liveState:pe}),fe=ge.autoReadKey,Je=Ox({autoReadKey:fe,shouldMarkSeen:ge.shouldMarkSeen,completedKey:Ie.current,pendingKey:Oe.current});if(!ge.shouldMarkSeen){Je.shouldCancelPending&&ne(),Ie.current=fe;return}if(!Je.shouldSchedule)return;Je.shouldCancelPending&&ne();const xt=cc(je),Et=()=>{if(document.visibilityState!=="visible"||Ie.current===fe)return;Ie.current=fe,Oe.current=null,Ue.current=null,J.current=null,Me.current&&(document.removeEventListener("visibilitychange",Me.current),Me.current=null);const yt=ge.readAt;z({...xt},yt),e(je.daemonId||je.routeId,"mark_session_seen",{sessionId:je.sessionId,seenAt:yt}).catch(()=>{})};if(Oe.current=Je.nextPendingKey,document.visibilityState==="visible"){Ue.current=setTimeout(Et,1500);const yt=()=>{document.visibilityState!=="visible"&&Ue.current&&(clearTimeout(Ue.current),Ue.current=null)};Me.current=yt,document.addEventListener("visibilitychange",yt);return}const Yt=()=>{document.visibilityState==="visible"&&(J.current&&clearTimeout(J.current),J.current=setTimeout(Et,800),Me.current&&(document.removeEventListener("visibilitychange",Me.current),Me.current=null))};Me.current=Yt,document.addEventListener("visibilitychange",Yt)},[je,P,Z,z,e]),o.useEffect(()=>()=>{Ue.current&&clearTimeout(Ue.current),J.current&&clearTimeout(J.current),Me.current&&document.removeEventListener("visibilitychange",Me.current)},[]);const{requestedDesktopTabKey:ut,requestedMobileTabKey:ts,consumeRequestedActiveTab:Ys}=Op({isMobile:P,urlActiveTab:l,resolveConversationBySessionId:bt,setSearchParams:c}),{remoteDialogConv:Xs,remoteDialogIdeEntry:Ar,remoteDialogActiveConv:zl,setRemoteDialogActiveConv:Rn,openRemoteDialog:Vl,closeRemoteDialog:Gl}=th({isMobile:P,location:n,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:ut,conversations:Be,ides:g,resolveConversationByTarget:jt}),ht=zl||Xs||je,Ut=!!ht&&nt(ht)&&!Ze(ht),Mr=o.useMemo(()=>{if(!ht||!Ut)return null;const ne=ht.daemonId||ht.routeId||"",pe=Wt(ht);return`${ne}:${pe}`},[ht,Ut]),ql=o.useMemo(()=>qe,[qe]),Tr=P&&le==="chat",Yl=o.useMemo(()=>Be.filter(ne=>co(Ct,ne)),[Be,Ct]),Lr=o.useCallback(ne=>{const pe=new URLSearchParams(i);pe.set("activeTab",ne),c(pe,{replace:!0})},[i,c]),Xl=o.useCallback(async(ne,pe)=>In(e,ne,pe),[e]),Jl=o.useCallback(async(ne,pe)=>{if(!pe.trim())return{ok:!1,error:"Choose a workspace path first."};try{const ge=await e(ne,"workspace_add",{path:pe.trim()});return ge!=null&&ge.success?{ok:!0}:{ok:!1,error:(ge==null?void 0:ge.error)||"Could not save workspace"}}catch(ge){return{ok:!1,error:ge instanceof Error?ge.message:"Could not save workspace"}}},[e]),Ql=o.useCallback(async(ne,pe,ge)=>{var fe;try{const Je={ideType:pe,enableCdp:!0};(fe=ge==null?void 0:ge.workspacePath)!=null&&fe.trim()&&(Je.workspace=ge.workspacePath.trim());const xt=await e(ne,"launch_ide",Je);return!(xt!=null&&xt.success)&&(xt==null?void 0:xt.success)!==void 0?{ok:!1,error:(xt==null?void 0:xt.error)||"Could not launch IDE"}:(_e({machineId:ne,kind:"ide",providerType:pe,workspacePath:(ge==null?void 0:ge.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(Je){return{ok:!1,error:Je instanceof Error?Je.message:"Could not launch IDE"}}},[e]),Zl=o.useCallback(async(ne,pe,ge,fe)=>{var xt,Et,Yt;const Je=Date.now();try{const yt={cliType:ge};(xt=fe==null?void 0:fe.workspacePath)!=null&&xt.trim()?yt.dir=fe.workspacePath.trim():fe!=null&&fe.workspaceId&&(yt.workspaceId=fe.workspaceId),(Et=fe==null?void 0:fe.resumeSessionId)!=null&&Et.trim()&&(yt.resumeSessionId=fe.resumeSessionId.trim()),Array.isArray(fe==null?void 0:fe.cliArgs)&&fe.cliArgs.length>0&&(yt.cliArgs=fe.cliArgs),(Yt=fe==null?void 0:fe.initialModel)!=null&&Yt.trim()&&(yt.initialModel=fe.initialModel.trim());const vt=await e(ne,"launch_cli",yt),$t=(vt==null?void 0:vt.result)||vt,Js=($t==null?void 0:$t.sessionId)||($t==null?void 0:$t.id);return vt!=null&&vt.success&&Js?(Lr(Js),{ok:!0}):vt!=null&&vt.success?(_e({machineId:ne,kind:pe,providerType:ge,workspacePath:(fe==null?void 0:fe.workspacePath)||null,resumeSessionId:(fe==null?void 0:fe.resumeSessionId)||null,startedAt:Je}),{ok:!0}):{ok:!1,error:(vt==null?void 0:vt.error)||($t==null?void 0:$t.error)||`Could not launch ${pe.toUpperCase()} session`}}catch(yt){return Fx(yt)?(_e({machineId:ne,kind:pe,providerType:ge,workspacePath:(fe==null?void 0:fe.workspacePath)||null,resumeSessionId:(fe==null?void 0:fe.resumeSessionId)||null,startedAt:Je}),{ok:!0}):{ok:!1,error:yt instanceof Error?yt.message:`Could not launch ${pe.toUpperCase()} session`}}},[Lr,e]),ed=o.useCallback(async(ne,pe)=>{if(!ne||!pe)return[];try{const ge=await e(ne,"list_saved_sessions",{providerType:pe,kind:"cli",limit:30}),fe=(ge==null?void 0:ge.result)??ge;return Array.isArray(fe==null?void 0:fe.sessions)?fe.sessions:[]}catch(ge){return console.error("List saved sessions failed",ge),[]}},[e]);o.useEffect(()=>{if(!ye)return;const ne=_i(ye.workspacePath),pe=g.find(fe=>{var yt,vt,$t,Js;if(!fe||fe.type==="adhdev-daemon"||Hx(fe.daemonId||fe.id)!==ye.machineId||(br(fe)?"cli":Ds(fe)?"acp":"ide")!==ye.kind||String(fe.agentType||fe.type||"")!==ye.providerType)return!1;if(ye.resumeSessionId)return String(fe.providerSessionId||"")===ye.resumeSessionId;if(ne){const Pn=_i(fe.workspace||fe.runtimeWorkspaceLabel);return Pn?Pn===ne:!1}return Number(fe.lastUpdated||fe._lastUpdate||fe.timestamp||((Js=($t=(vt=(yt=fe.activeChat)==null?void 0:yt.messages)==null?void 0:vt.at)==null?void 0:$t.call(vt,-1))==null?void 0:Js.timestamp)||0)>=ye.startedAt-5e3});if(!pe)return;const ge=Ic({entrySessionId:pe.sessionId,entryInstanceId:pe.instanceId,entryRouteId:pe.id,conversations:Be});ge&&(_e(null),Lr(ge))},[Be,Lr,g,ye]),o.useEffect(()=>{if(!ye)return;const ne=window.setTimeout(()=>{_e(pe=>!pe||pe.startedAt!==ye.startedAt?pe:null)},45e3);return()=>window.clearTimeout(ne)},[ye]),Mp({visibleConversations:qe,clearedTabs:Se,setClearedTabs:Ae,setActionLogs:oe}),Wp({ides:g,sendDaemonCommand:e,setToasts:m,setLocalUserMessages:ue,resolveConversationByTarget:jt});const{isRefreshingHistory:td,handleRefreshHistory:sd}=fi({sendDaemonCommand:e,activeConv:je,chats:(Mo=g.find(ne=>ne.id===(je==null?void 0:je.routeId)))==null?void 0:Mo.chats,updateRouteChats:A,setToasts:m,setLocalUserMessages:ue,setClearedTabs:Ae}),{isCreatingChat:rd,isRefreshingHistory:nd,handleSwitchSession:ad,handleNewChat:od,handleRefreshHistory:id}=fi({sendDaemonCommand:e,activeConv:ht,chats:(To=g.find(ne=>ne.id===(ht==null?void 0:ht.routeId)))==null?void 0:To.chats,updateRouteChats:A,setToasts:m,setLocalUserMessages:ue,setClearedTabs:Ae}),_n=o.useCallback(async()=>{if(!(!ht||!Ut||he)){O(!0);try{const ne=ht.daemonId||ht.routeId,pe=Wt(ht),ge=await e(ne,"list_saved_sessions",{agentType:pe,providerType:pe,kind:"cli",limit:50}),fe=(ge==null?void 0:ge.result)??ge;Y(Array.isArray(fe==null?void 0:fe.sessions)?fe.sessions:[])}catch(ne){console.error("Refresh saved sessions failed",ne),Y([])}finally{O(!1)}}},[ht,he,Ut,e]);o.useEffect(()=>{if(!E){We.current=null;return}if(!Ut){We.current=null,Y([]),O(!1);return}!Mr||he||We.current!==Mr&&(We.current=Mr,_n())},[_n,E,he,Ut,Mr]);const cd=o.useCallback(async ne=>{if(!ht||!Ut||!ne.providerSessionId||!ne.workspace)return;const pe=ht.daemonId||ht.routeId,ge=Wt(ht);try{ie(ne.providerSessionId);const fe=await e(pe,"launch_cli",{cliType:ge,dir:ne.workspace,resumeSessionId:ne.providerSessionId,initialModel:hc(ne.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Je=(fe==null?void 0:fe.result)??fe,xt=typeof(Je==null?void 0:Je.sessionId)=="string"?Je.sessionId:typeof(Je==null?void 0:Je.id)=="string"?Je.id:"";xt&&c(Et=>{const Yt=new URLSearchParams(Et);return Yt.set("activeTab",xt),Yt},{replace:!0}),B(!1)}catch(fe){console.error("Resume saved session failed",fe)}finally{ie(null)}},[ht,Ut,e,c]);eh({urlActiveTab:P&&!Tr?l:null,conversations:Be,resolveConversationBySessionId:bt,normalizedGroupAssignments:Fe,hasHydratedStoredLayout:P&&!Tr?G:!0,hydrateStoredLayout:P&&!Tr?I:()=>{},setGroupActiveTabIds:M,setFocusedGroup:$,setSearchParams:c,historyModalOpen:E,activeConv:je,isRefreshingHistory:td,ides:g,handleRefreshHistory:sd});const wo=o.useCallback(async(ne,pe)=>{const ge=pe||ae||je;if(!ge||!nt(ge)&&!Ze(ge))return;const fe=Wt(ge),Je=ge.routeId||ge.daemonId||"";try{await e(Je,"stop_cli",{cliType:fe,targetSessionId:ge.sessionId,mode:ne})}catch(xt){console.error("Stop CLI failed:",xt)}},[je,ae,e]),ld=o.useCallback(async ne=>{const pe=ne||je;!pe||!nt(pe)&&!Ze(pe)||(we(pe),V(!0))},[je]),dd=o.useMemo(()=>!je||!nt(je)||Ze(je)?null:Hs(je),[je]),ud=o.useCallback(async ne=>{if(!je||!nt(je)||Ze(je))return;const pe=Hs(je);if(pe===ne)return;const ge=je.sessionId;ge&&Ne(fe=>({...fe,[ge]:ne}));try{await e(cs(je)||je.routeId,"set_cli_view_mode",{targetSessionId:je.sessionId,cliType:Wt(je),mode:ne})}catch(fe){const Je=uo(fe);ge&&!Je&&Ne(xt=>{const Et={...xt};return pe===dl(g,ge)?delete Et[ge]:Et[ge]=pe,Et}),lo(fe)?console.warn(Je?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",fe instanceof Error?fe.message:String(fe)):console.error("Failed to switch CLI view mode:",fe)}},[je,g,e]),{versionMismatchDaemons:md,hasRequiredVersionDaemons:jo,appVersion:fd,versionBannerDismissed:pd,setVersionBannerDismissed:hd,upgradingDaemons:xd,handleBannerUpgrade:bd}=ih({ides:g,sendDaemonCommand:e}),ko=o.useCallback(ne=>{xe(ne.tabKey),c(pe=>{const ge=new URLSearchParams(pe),fe=Sm(ne);return fe?ge.set("activeTab",fe):ge.delete("activeTab"),ge},{replace:!0})},[c]),So=o.useCallback(ne=>{Dt(ne.tabKey),ko(ne)},[ko,Dt]),gd=o.useCallback(ne=>{Mt(ne.tabKey)},[Mt]),No=o.useCallback((ne,pe)=>{const ge=Bx(ne,pe);ge&&Q(ge)},[]);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(wf,{wsStatus:S,showReconnected:C}),t.jsx(jf,{terminalBackend:it,isStandalone:Qe,machineLabel:et,machineKey:ft}),(!pd||jo)&&t.jsx(Ex,{daemons:md,targetVersion:fd,required:jo,upgradingDaemons:xd,onUpgrade:bd,onDismiss:()=>hd(!0)}),t.jsx(Mx,{showMobileChatMode:Tr,isMobile:P,activeConv:je,wsStatus:S,isConnected:R,onOpenHistory:ne=>{ne&&Rn(ne),B(!0)},onOpenRemote:Vl,onStopCli:ld,activeCliViewMode:dd,onSetActiveCliViewMode:ud,mobileChatConversations:ql,ides:g,actionLogs:de,sendDaemonCommand:e,setLocalUserMessages:ue,setActionLogs:oe,isStandalone:Qe,initialDataLoaded:w,userName:x.userName,requestedMobileTabKey:ts,onRequestedMobileTabConsumed:Ys,requestedMachineId:p,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:d,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:Ve,isSplitMode:ee,numGroups:D,groupSizes:H,groupedConvs:ce,clearedTabs:Se,focusedGroup:y,setFocusedGroup:$,moveTabToGroup:Ke,splitTabRelative:Xe,closeGroup:Le,handleResizeStart:Ee,groupActiveTabIds:L,setGroupActiveTabIds:M,groupTabOrders:_,setGroupTabOrders:W,toggleHiddenTab:Tt,visibleConversations:qe,hiddenConversations:Yl,requestedDesktopTabKey:ut,onRequestedDesktopTabConsumed:Ys,onDesktopActiveTabChange:xe,onRequestScrollToBottom:No,onHideConversation:gd,onShowHiddenConversation:So,onShowAllHiddenConversations:Ge,scrollToBottomRequest:ve,machineEntries:Pe,onBrowseMachineDirectory:Xl,onSaveMachineWorkspace:Jl,onLaunchMachineIde:Ql,onLaunchMachineProvider:Zl,onListMachineSavedSessions:ed,notifications:De,notificationUnreadCount:$e,notificationStateBySessionId:ot,liveSessionInboxState:Z,onMarkNotificationRead:re,onMarkNotificationUnread:Ce,onDeleteNotification:Te,onMarkNotificationTargetRead:z}),t.jsx("style",{children:`
60
- body { overflow: hidden; overscroll-behavior: none; }
61
- `}),t.jsx(Dx,{historyModalOpen:E,historyTargetConv:ht,ides:g,isHistoryCreatingChat:rd,isHistoryRefreshingHistory:Ut?!1:nd,savedHistorySessions:be,isSavedHistoryLoading:he,isResumingSavedHistorySessionId:X,onCloseHistory:()=>B(!1),onNewHistoryChat:od,onSwitchHistorySession:ad,onRefreshHistory:Ut?_n:id,onResumeSavedHistorySession:cd,remoteDialogConv:Xs,remoteDialogIdeEntry:Ar,connectionStates:j,actionLogs:de,localUserMessages:se,sendDaemonCommand:e,setLocalUserMessages:ue,setActionLogs:oe,isStandalone:Qe,userName:x.userName,onOpenRemoteHistory:ne=>{ne&&Rn(ne),B(!0)},onRemoteConversationChange:Rn,onCloseRemoteDialog:Gl,cliStopDialogOpen:U,cliStopTargetConv:ae,onCancelCliStop:()=>{V(!1),we(null)},onStopCliNow:async()=>{V(!1),await wo("hard",ae),we(null)},onSaveCliAndStop:async()=>{V(!1),await wo("save",ae),we(null)},toasts:h,onDismissToast:ne=>m(pe=>pe.filter(ge=>ge.id!==ne)),onClickToast:ne=>{if(ne.targetKey){const pe=jt(ne.targetKey);pe&&($(Fe.get(pe.tabKey)??0),So(pe),No(pe.tabKey,"toast-open"))}},showOnboarding:f,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}b(!1)}})]})}function zx({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,u]=o.useState(null),[p,d]=o.useState(null),[x,g]=o.useState(!1),[w,A]=o.useState(null),[m,f]=o.useState(!1),[b,h]=o.useState(""),S=o.useRef(null),R=o.useCallback(I=>{S.current=I},[]),j=o.useCallback((I,E,B=!1)=>{c(U=>[...U.slice(-100),{timestamp:Date.now(),level:I,message:E}]),setTimeout(()=>{var U;return(U=a.current)==null?void 0:U.scrollIntoView({behavior:"smooth"})},100),B&&at.showToast(E,I==="error"||I==="warn"?"warning":"success")},[a]),C=o.useCallback(I=>{const E=I instanceof Error?I.message:String(I||"");return E.includes("P2P command timeout")||E.includes("P2P not connected")||E.includes("P2P not available")},[]),k=o.useCallback(async(I,E)=>{var B;if(!e||l)return!1;u(I),j("info",`Launching ${dt(I)}${E!=null&&E.workspace?` in ${E.workspace}`:""}...`);try{const U={ideType:I,enableCdp:!0};(B=E==null?void 0:E.workspace)!=null&&B.trim()?U.workspace=E.workspace.trim():E!=null&&E.useDefaultWorkspace&&(U.useDefaultWorkspace=!0);const V=await r(e,"launch_ide",U);return j(V!=null&&V.success?"info":"error",V!=null&&V.success?`${dt(I)} launched`:`Failed: ${V==null?void 0:V.error}`,!0),!!(V!=null&&V.success)}catch(U){return j("error",`Launch error: ${U.message}`,!0),!1}finally{u(null)}},[e,l,j,r]),v=o.useCallback(async I=>{if(!e)return{success:!1};const{cliType:E,dir:B,workspaceId:U,useDefaultWorkspace:V,useHome:ae,argsStr:we,model:be,resumeSessionId:Y}=I;if(!E)return j("warn","Select a CLI or ACP provider first",!0),{success:!1};const he=we?we.split(/\s+/).filter(Boolean):void 0,O=(B==null?void 0:B.trim())||(U?"(saved id)":V?"(default workspace)":ae?"(home)":"");j("info",`Launching ${E}${O?` in ${O}`:""}${be?` (model: ${be})`:""}...`),d(E);try{const X={cliType:E,cliArgs:he,initialModel:be||void 0};B!=null&&B.trim()?X.dir=B.trim():U?X.workspaceId=U:V?X.useDefaultWorkspace=!0:ae&&(X.useHome=!0),Y&&(X.resumeSessionId=Y);const ie=await r(e,"launch_cli",X),le=(ie==null?void 0:ie.result)||ie;return ie!=null&&ie.success?(j("info",`${E} launched`,!0),(le==null?void 0:le.launchSource)==="home"?j("info","📂 Running in home directory (explicit choice)"):(le==null?void 0:le.launchSource)==="defaultWorkspace"&&j("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:le==null?void 0:le.sessionId}):(j("error",`Failed: ${(ie==null?void 0:ie.error)||(le==null?void 0:le.error)}`,!0),(ie==null?void 0:ie.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&A({cliType:E,argsStr:we,model:be}),{success:!1,sessionId:le==null?void 0:le.sessionId})}catch(X){return C(X)?(j("warn",`${E} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(j("error",`Launch error: ${X.message}`,!0),{success:!1})}finally{d(null)}},[e,j,C,r]),y=o.useCallback(async(I,E,B,U)=>e?I?E.trim()?v({cliType:I,dir:E,argsStr:B,model:U}):(A({cliType:I,argsStr:B,model:U}),{success:!1}):(j("warn","Select a provider",!0),{success:!1}):{success:!1},[e,j,v]),$=o.useCallback(async(I,E,B)=>{if(e&&window.confirm(`Stop ${I}?
62
- This will terminate the process.`))try{const U=await r(e,"stop_cli",{cliType:I,dir:E,targetSessionId:B});U!=null&&U.success?j("info",`${I} stopped`,!0):j("error",`Stop failed: ${(U==null?void 0:U.error)||"Unknown error"}`,!0)}catch(U){j("error",`Stop failed: ${U.message}`,!0)}},[e,j,r]),L=o.useCallback(async I=>{try{await r(I.daemonId,"restart_ide",{ideType:I.type}),j("info",`${dt(I.type)} restart initiated`,!0)}catch(E){j("error",`Restart failed: ${E.message}`,!0)}},[j,r]),M=o.useCallback(async I=>{if(window.confirm(`Stop ${dt(I.type)}?
63
- This will disconnect CDP and optionally kill the process.`))try{const E=await r(I.daemonId,"stop_ide",{ideType:I.type,killProcess:!0});E!=null&&E.success?j("info",`${dt(I.type)} stopped`,!0):j("error",`Stop failed: ${(E==null?void 0:E.error)||"Unknown error"}`,!0)}catch(E){j("error",`Stop failed: ${E.message}`,!0)}},[j,r]),_=o.useCallback(async()=>{if(e)try{const I=await r(e,"detect_ides",{});j("info",`Found ${((I==null?void 0:I.result)||[]).length} IDE(s)`,!0)}catch(I){j("error",`Detection failed: ${I.message}`,!0)}},[e,j,r]),W=o.useCallback(async I=>{if(!e||!I.trim())return!1;g(!0);try{const E=await r(e,"workspace_add",{path:I.trim()});return E!=null&&E.success?(j("info",`Workspace added: ${I.trim()}`),!0):(j("error",(E==null?void 0:E.error)||"workspace_add failed"),!1)}catch(E){return j("error",E.message),!1}finally{g(!1)}},[e,j,r]),H=o.useCallback(async I=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){g(!0);try{const E=await r(e,"workspace_remove",{id:I});E!=null&&E.success?j("info","Workspace removed",!0):j("error",(E==null?void 0:E.error)||"workspace_remove failed",!0)}catch(E){j("error",E.message,!0)}finally{g(!1)}}},[e,j,r]),N=o.useCallback(async I=>{var E;if(e){g(!0);try{const B=await r(e,"workspace_set_default",I===null?{clear:!0}:{id:I});if(B!=null&&B.success){j("info",I?"Default workspace updated":"Default workspace cleared",!0);const U=typeof B.defaultWorkspacePath=="string"?B.defaultWorkspacePath:"";U&&((E=S.current)==null||E.call(S,U))}else j("error",(B==null?void 0:B.error)||"workspace_set_default failed",!0)}catch(B){j("error",B.message,!0)}finally{g(!1)}}},[e,j,r]),P=o.useCallback(async I=>{var B;if(!e||!I.trim())return;const E=I.trim();g(!0);try{const U=await r(e,"workspace_set_default",{path:E});U!=null&&U.success?(j("info","Default workspace set from history"),(B=S.current)==null||B.call(S,E)):j("error",(U==null?void 0:U.error)||"Could not set default (path missing on disk?)")}catch(U){j("error",U.message)}finally{g(!1)}},[e,j,r]),G=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:b}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:b})}catch(I){j("warn",`Live nickname updated, but account sync failed: ${I.message}`)}j("info",`Nickname set to "${b||"(cleared)"}"`),f(!1)}catch(I){j("error",`Failed: ${I.message}`)}},[e,b,s,j,n,r]);return{logs:i,launchingIde:l,launchingAgentType:p,workspaceBusy:x,launchPick:w,setLaunchPick:A,editingNickname:m,setEditingNickname:f,nicknameInput:b,setNicknameInput:h,addLog:j,handleLaunchIde:k,runLaunchCliCore:v,handleLaunchCli:y,handleStopCli:$,handleRestartIde:L,handleStopIde:M,handleDetectIdes:_,handleWorkspaceAdd:W,handleWorkspaceRemove:H,handleWorkspaceSetDefault:N,handleWorkspaceResumePath:P,handleSaveNickname:G,setOnDefaultWorkspaceChanged:R}}function Vx({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var L;const{workspaceBusy:l,handleWorkspaceAdd:u,handleWorkspaceRemove:p,handleWorkspaceSetDefault:d}=i,[x,g]=o.useState(!1),[w,A]=o.useState(""),[m,f]=o.useState([]),[b,h]=o.useState(!1),[S,R]=o.useState(""),j=o.useCallback(async M=>{h(!0),R("");try{const _=await In(c,e,M);A(_.path),f(_.directories)}catch(_){R(_ instanceof Error?_.message:"Could not load folder")}finally{h(!1)}},[e,c]),C=o.useCallback(()=>{g(!0);const M=[...r.map(W=>W.workspace),...n.map(W=>W.workspace),...a.map(W=>W.workspace)],_=Cn(s.platform,Nn(M,s.defaultWorkspacePath,(s.workspaces||[]).map(W=>W.path)));j(_)},[a,n,r,j,s.defaultWorkspacePath,s.platform,s.workspaces]),k=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,v=s.availableMem??s.freeMem??s.totalMem,y=k&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-v)/s.totalMem*100))):0,$=((L=s.loadavg)==null?void 0:L[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(Dr,{icon:t.jsx(sc,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?Pu(s.uptime):"Waiting…"}),t.jsx(Dr,{icon:t.jsx(Pt,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(Dr,{icon:t.jsx(yn,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(Dr,{icon:t.jsx(Qd,{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(Wo,{value:k?Math.min(Math.round($/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:k?`${$.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(Wo,{value:y,max:100,label:"Memory",color:"#3b82f6",detail:k?`${Bn(s.totalMem-v)} / ${Bn(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Bn(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(Os,{size:14})," Workspaces"]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[t.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),t.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:l,value:s.defaultWorkspaceId||"",onChange:M=>void d(M.target.value===""?null:M.target.value),children:[t.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(M=>t.jsx("option",{value:M.id,children:M.label||M.path},M.id))]}),s.defaultWorkspacePath&&t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:s.defaultWorkspacePath,children:s.defaultWorkspacePath})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded transition-colors text-xs",disabled:l,onClick:C,children:"Select workspace…"}),t.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(s.workspaces||[]).length>0&&t.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(s.workspaces||[]).map(M=>t.jsxs("li",{className:"flex items-start gap-2 text-[11px] text-text-muted rounded-lg border border-border-subtle bg-bg-primary px-2.5 py-2",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[M.id===s.defaultWorkspaceId&&t.jsx("span",{className:"text-[10px]",children:"⭐"}),t.jsx("span",{className:"font-medium text-text-primary truncate",children:kn(M.path,M.label)})]}),t.jsx("div",{className:"font-mono truncate text-[10px]",title:M.path,children:M.path})]}),t.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void p(M.id),children:"Remove"})]},M.id))})]}),x&&t.jsx(An,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:w,directories:m,busy:b,error:S,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:M=>{j(M)},onConfirm:M=>{(async()=>{if(!M)return;await u(M)&&g(!1)})()}})]})}function Gx(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 qx(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 ra(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 Pi(e){if(!e||typeof e!="object")return null;if(ra(e))return e;const s=e,r=s.result;return ra(r)?r:ra(s.sourceConfig)?s.sourceConfig:null}function Yx(e){const s=e.trim();return s||null}const Di=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Xx=[{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 Jx({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[u,p]=o.useState([]),[d,x]=o.useState(""),[g,w]=o.useState([]),[A,m]=o.useState(""),f=o.useRef(null),b=o.useRef(null),h=v=>{p(y=>y.includes(v)?y.filter($=>$!==v):[...y,v])},S=()=>p([...Di]),R=()=>p([]);o.useEffect(()=>{var v;(v=f.current)==null||v.scrollIntoView({behavior:"smooth"})},[g]),o.useEffect(()=>()=>{b.current&&clearInterval(b.current)},[]);const j=o.useCallback(()=>{b.current&&clearInterval(b.current),b.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"),w(y=>[...y,`
64
- ✅ Auto-fix completed!`]),b.current&&clearInterval(b.current))}catch{}},3e3)},[e,s.type,r,a]),C=async()=>{if(u.length!==0){i("running"),w(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,d?`💬 Comment: ${d}`:"",""]),m("");try{const v=await r(e,"provider_auto_fix",{providerType:s.type,functions:u,agent:c,...d?{comment:d}:{}});v!=null&&v.success&&(v!=null&&v.started||v!=null&&v.running)?(w(y=>[...y,"✅ Agent started. Monitoring progress..."]),j()):(i("error"),m((v==null?void 0:v.error)||"Failed to start auto-fix"))}catch(v){i("error"),m((v==null?void 0:v.message)||"Connection failed")}}},k=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),w(v=>[...v,`
65
- ⚠️ Auto-fix cancelled.`]),i("done"),b.current&&clearInterval(b.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:Xx.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:S,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:R,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Di.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:d,onChange:v=>x(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:[g.map((v,y)=>t.jsx("div",{className:v.startsWith("✅")?"text-green-400":"",style:v.startsWith("❌")||v.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:v},y)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:f})]}),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:C,disabled:u.length===0,className:"machine-btn",style:{background:u.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:u.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:u.length>0?"#a78bfa":void 0,opacity:u.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&t.jsx("button",{onClick:k,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{i("config"),w([]),m("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Qx({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var j;const i=s.filter(C=>C.category==="ide"),[c,l]=o.useState(((j=i[0])==null?void 0:j.type)||""),[u,p]=o.useState(""),[d,x]=o.useState(""),[g,w]=o.useState(!1),[A,m]=o.useState(""),[f,b]=o.useState(!1),h=C=>{const k=C.toLowerCase().replace(/[^a-z0-9-]/g,"");p(k),(!d||d===S(u))&&x(S(k))},S=C=>C.split("-").map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join(" "),R=async()=>{if(!(!u||!d||!c)){w(!0),m("");try{const C=await r(e,"provider_clone",{type:u,name:d,category:"ide",location:"user",cloneFrom:c});C!=null&&C.success||C!=null&&C.created?(b(!0),a==null||a(u)):m((C==null?void 0:C.error)||"Failed to create provider")}catch(C){m((C==null?void 0:C.message)||"Connection failed")}w(!1)}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:C=>C.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[t.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:f?t.jsxs("div",{className:"text-center py-6",children:[t.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),t.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[t.jsx("code",{className:"text-violet-400",children:u})," has been created at ",t.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",u,"/"]})]}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",t.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",u]})," or use Auto-Fix to implement scripts."]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(C=>t.jsxs("button",{onClick:()=>l(C.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===C.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===C.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:C.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===C.type?"#a78bfa":"var(--text-secondary)"},children:C.displayName})]},C.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:C=>h(C.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),t.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",t.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",u||"...","/"]})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),t.jsx("input",{value:d,onChange:C=>x(C.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:f?t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:R,disabled:!u||!d||g,className:"machine-btn",style:{background:u&&d?"rgba(34,197,94,0.12)":void 0,borderColor:u&&d?"rgba(34,197,94,0.3)":void 0,color:u&&d?"#86efac":void 0,opacity:!u||!d||g?.4:1},children:g?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Zx({machineId:e,providers:s,sendDaemonCommand:r}){var L;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[p,d]=o.useState("all"),[x,g]=o.useState(null),[w,A]=o.useState(!1),[m,f]=o.useState(null),[b,h]=o.useState("normal"),[S,R]=o.useState(""),[j,C]=o.useState(!1),k=o.useCallback(async()=>{if(e)try{const M=await r(e,"get_provider_source_config",{}),_=Pi(M);_&&(f(_),h(_.sourceMode),R(_.explicitProviderDir||""))}catch{}},[e,r]),v=o.useCallback(async()=>{if(e){c(!0);try{const M=await r(e,"get_provider_settings",{}),_=Gx(M);if(_){const W=qx(_,s);W.sort((H,N)=>H.category.localeCompare(N.category)||H.displayName.localeCompare(N.displayName)),a(W)}}catch{}c(!1)}},[e,s,r]);o.useEffect(()=>{n.length===0&&v(),m||k()},[]);const y=async(M,_,W)=>{u(`${M}.${_}`),a(H=>H.map(N=>N.type===M?{...N,values:{...N.values,[_]:W}}:N));try{const H=await r(e,"set_provider_setting",{providerType:M,key:_,value:W});H!=null&&H.success||v()}catch{v()}u(null)},$=async()=>{C(!0);try{const M=await r(e,"set_provider_source_config",{providerSourceMode:b,providerDir:Yx(S)}),_=Pi(M);_?(f(_),h(_.sourceMode),R(_.explicitProviderDir||"")):await k(),await v()}catch{await k()}C(!1)};return t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-4",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(M=>t.jsx("button",{onClick:()=>d(M),className:`machine-btn text-[10px] px-2 py-0.5 ${p===M?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:M.toUpperCase()},M))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>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:k,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),t.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),t.jsxs("select",{value:b,onChange:M=>h(M.target.value),className:"machine-input text-[11px]",children:[t.jsx("option",{value:"normal",children:"normal"}),t.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),t.jsx("input",{type:"text",value:S,onChange:M=>R(M.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void $(),disabled:j,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:j?"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:"})," ",(m==null?void 0:m.userDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(m==null?void 0:m.upstreamDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((L=m==null?void 0:m.providerRoots)==null?void 0:L.join(" → "))||"loading…"]})]})]}),p!=="all"&&n.filter(M=>M.category===p).length>1&&(()=>{const M=n.filter(N=>N.category===p),_=new Map;for(const N of M)for(const P of N.schema){if(P.type!=="boolean")continue;const G=_.get(P.key),I=!!(N.values[P.key]??P.default);G?(G.onCount+=I?1:0,G.total+=1):_.set(P.key,{label:P.label||P.key,onCount:I?1:0,total:1})}const W=[..._.entries()].filter(([,N])=>N.total===M.length);if(W.length===0)return null;const H=async(N,P)=>{for(const G of M)await y(G.type,N,P)};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 (",M.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:W.map(([N,P])=>{const G=P.onCount===P.total,I=P.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:P.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",P.onCount,"/",P.total,")"]}),t.jsx("button",{onClick:()=>void H(N,!0),disabled:G,className:`machine-btn text-[9px] px-1.5 py-px ${G?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void H(N,!1),disabled:I,className:`machine-btn text-[9px] px-1.5 py-px ${I?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},N)})})]})})(),i&&n.length===0?t.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):t.jsx("div",{className:"flex flex-col gap-2",children:n.filter(M=>p==="all"||M.category===p).map(M=>t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[t.jsx("span",{className:"text-lg",children:M.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:M.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:M.category==="acp"?"rgba(139,92,246,0.08)":M.category==="cli"?"rgba(59,130,246,0.08)":M.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:M.category==="acp"?"#a78bfa":M.category==="cli"?"#60a5fa":M.category==="ide"?"#86efac":"var(--status-warning)"},children:M.category}),M.category==="ide"&&t.jsx("button",{onClick:()=>g(s.find(_=>_.type===M.type)||{type:M.type,name:M.displayName,displayName:M.displayName,icon:M.icon,category:M.category}),className:"ml-auto machine-btn text-[9px] px-2 py-0.5 bg-violet-500/[0.06] border-violet-500/20 text-violet-400 hover:bg-violet-500/[0.12]",children:"🔧 Auto-Fix"})]}),t.jsx("div",{className:"flex flex-col gap-2",children:M.schema.map(_=>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:[_.label||_.key,l===`${M.type}.${_.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),_.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:_.description})]}),t.jsx("div",{className:"shrink-0",children:_.type==="boolean"?t.jsx("button",{onClick:()=>y(M.type,_.key,!(M.values[_.key]??_.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:M.values[_.key]??_.default?"#8b5cf6":"var(--border-subtle)"},children:t.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:M.values[_.key]??_.default?21:3}})}):_.type==="number"?t.jsx("input",{type:"number",value:Number(M.values[_.key]??_.default??0)||0,min:_.min,max:_.max,onChange:W=>{const H=parseInt(W.target.value)||0;_.min!==void 0&&H<_.min||_.max!==void 0&&H>_.max||y(M.type,_.key,H)},className:"machine-input w-20 text-center text-[11px]"}):_.type==="select"&&_.options?t.jsx("select",{value:String(M.values[_.key]??_.default??""),onChange:W=>y(M.type,_.key,W.target.value),className:"machine-input text-[11px]",children:_.options.map(W=>t.jsx("option",{value:W,children:W},W))}):t.jsx("input",{type:"text",value:String(M.values[_.key]??_.default??""),onBlur:W=>y(M.type,_.key,W.target.value),className:"machine-input w-[120px] text-[11px]"})})]},_.key))})]},M.type))}),x&&t.jsx(Jx,{machineId:e,provider:x,sendDaemonCommand:r,onClose:()=>g(null)}),w&&t.jsx(Qx,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>A(!1),onCreated:()=>{A(!1),v()}})]})}const eb=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function tb({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function sb(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function rb(e){return e.trim().toLowerCase()}function Tn(e,s){const r=rb(s);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function yo(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function vr(e,s=220){const r=yo(e);return r?r.length>s?`${r.slice(0,s)}…`:r:""}function nb(e){const s=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(s))return{kind:s.length>0?"structured":"empty",entries:s.map(r=>{const n=r;return{timestamp:Number(n.ts)||0,level:n.level||"info",message:`[${String(n.category||"daemon")}] ${String(n.message||"")}`.trim()}}),rawText:""};if(typeof s=="string"){const r=s.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function Ol(e,s){return e.filter(r=>Tn([r.level,r.message],s))}function ab(e,s){return e.split(`
66
- `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>Tn([r],s))}function Wl(e,s){return e.filter(r=>Tn([r.level,r.category,r.stage,r.interactionId,yo(r.payload)],s))}function Hl(e,s){return e.filter(r=>Tn([r.kind,r.topic,r.interactionId,yo(r.payload)],s))}function Ei(e){return e==="warn"||e==="error"}function ob({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){return{all:e.length+s.length+r.length+n.length,info:e.filter(a=>a.level!=="debug").length+r.filter(a=>a.level!=="debug").length+n.length,issues:e.filter(a=>Ei(a.level)).length+r.filter(a=>Ei(a.level)).length}}function ib({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(i=>`${new Date(i.timestamp).toISOString()} ${i.level.toUpperCase()} ${i.message}`)].join(`
67
- `)):s.length>0&&a.push(["[daemon logs]",...s].join(`
68
- `)),r.length>0&&a.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${vr(i.payload,500)}`.trim())].join(`
69
- `)),n.length>0&&a.push(["[browser events]",...n.map(i=>`${new Date(i.ts).toISOString()} ${i.kind}${i.topic?` topic=${i.topic}`:""} ${vr(i.payload,500)}`.trim())].join(`
70
- `)),a.join(`
71
-
72
- `)}function cb({daemonLogs:e,trace:s,webEvents:r,daemonLogKind:n,daemonFetchError:a,traceFetchError:i,searchQuery:c}){const l=Ol(e,c),u=Wl(s,c),p=Hl(r,c),d=l.filter(w=>w.level==="warn"||w.level==="error").map(w=>({source:"daemon",level:w.level,timestamp:w.timestamp,label:"daemon",detail:w.message})),x=u.filter(w=>w.level==="warn"||w.level==="error").map(w=>({source:"trace",level:w.level,timestamp:w.ts,label:`${w.category}.${w.stage}`,detail:vr(w.payload,320)||`${w.category}.${w.stage}`})),g=[...d,...x].sort((w,A)=>A.timestamp-w.timestamp);return{daemonCount:l.length,traceCount:u.length,webCount:p.length,issueCount:g.length,latestIssue:g[0]||null,hasAnyData:n==="text"||l.length>0||u.length>0||p.length>0,hasBlockingError:!!(a||i)}}function $i(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Ki(e){return e==="error"?"text-red-300 border-red-500/25 bg-red-500/[0.05]":e==="warn"?"text-amber-200 border-amber-500/25 bg-amber-500/[0.05]":e==="debug"?"text-slate-300 border-slate-500/25 bg-slate-500/[0.05]":"text-text-secondary border-border-subtle bg-bg-primary"}function na(e){return e==="good"?"border-emerald-500/20 bg-emerald-500/[0.05]":e==="warning"?"border-amber-500/20 bg-amber-500/[0.05]":e==="danger"?"border-red-500/20 bg-red-500/[0.05]":"border-border-subtle bg-bg-secondary"}function lb({machineId:e,sendDaemonCommand:s}){var Se,Ae;const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[u,p]=o.useState([]),[d,x]=o.useState([]),[g,w]=o.useState(0),[A,m]=o.useState(0),[f,b]=o.useState(null),[h,S]=o.useState(!0),[R,j]=o.useState("info"),[C,k]=o.useState("info"),[v,y]=o.useState("all"),[$,L]=o.useState(""),[M,_]=o.useState(!0),[W,H]=o.useState(!0),[N,P]=o.useState(""),[G,I]=o.useState(""),[E,B]=o.useState(0),[U,V]=o.useState({daemon:!0,trace:!1,web:!1}),ae=o.useRef(null),we=o.useRef(!1),be=o.useMemo(()=>sb(u,v),[u,v]),Y=o.useMemo(()=>Ol(r,$),[r,$]),he=o.useMemo(()=>ab(c,$),[c,$]),O=o.useMemo(()=>Wl(be,$),[be,$]),X=o.useMemo(()=>Hl(d,$),[d,$]),ie=o.useMemo(()=>C==="issues"?Y.filter(T=>T.level==="warn"||T.level==="error"):C==="info"?Y.filter(T=>T.level!=="debug"):Y,[Y,C]),le=o.useMemo(()=>C==="all"?he:[],[he,C]),me=o.useMemo(()=>C==="issues"?O.filter(T=>T.level==="warn"||T.level==="error"):C==="info"?O.filter(T=>T.level!=="debug"):O,[O,C]),ke=o.useMemo(()=>C==="issues"?[]:X,[X,C]),de=o.useMemo(()=>ob({daemonLogs:Y,daemonRawLines:he,trace:O,webEvents:X}),[Y,he,O,X]),oe=o.useMemo(()=>cb({daemonLogs:r,trace:be,webEvents:d,daemonLogKind:a,daemonFetchError:N,traceFetchError:G,searchQuery:$}),[N,a,r,be,$,G,d]),se=o.useCallback(async()=>{if(!e)return;const[T,xe]=await Promise.allSettled([s(e,"get_logs",{count:200,minLevel:R,since:g}),s(e,"get_debug_trace",tb({count:120,since:A,category:v}))]);if(T.status==="fulfilled"){const ve=T.value,Q=(ve==null?void 0:ve.result)||ve,ye=nb(Q);if(_(!1),P((ve==null?void 0:ve.success)===!1?String((ve==null?void 0:ve.error)||"Could not load daemon logs"):""),i(ye.kind),l(ye.rawText),ye.entries.length>0){n(We=>(g>0?[...We,...ye.entries]:ye.entries).slice(-300));const _e=ye.entries.reduce((We,Pe)=>Math.max(We,Number(Pe.timestamp||0)),g);_e>g&&w(_e)}else ye.kind!=="structured"&&g===0&&n([])}else _(!1),P(T.reason instanceof Error?T.reason.message:"Could not load daemon logs");if(xe.status==="fulfilled"){const ve=xe.value,Q=(ve==null?void 0:ve.result)||ve;if((ve==null?void 0:ve.success)===!1)I(String((ve==null?void 0:ve.error)||"Could not load daemon trace"));else if(Array.isArray(Q==null?void 0:Q.trace)){I(""),p(Q.trace.slice(-120));const ye=Q.trace.reduce((_e,We)=>Math.max(_e,Number(We.ts||0)),A);ye>A&&m(ye)}else I(""),p([]);H(!1)}else H(!1),I(xe.reason instanceof Error?xe.reason.message:"Could not load daemon trace");x(Bs.list({limit:120})),b(Date.now())},[g,A,R,e,s,v]);o.useEffect(()=>{if(!e||(se(),!h))return;const T=setInterval(()=>{se()},3e3);return()=>clearInterval(T)},[h,se,e,E]),o.useEffect(()=>{if(h&&(ie.length>0||le.length>0||me.length>0||ke.length>0)){const T=we.current?"smooth":"instant";setTimeout(()=>{var xe;(xe=ae.current)==null||xe.scrollIntoView({behavior:T}),we.current=!0},50)}},[ie.length,le.length,me.length,ke.length,h]),o.useEffect(()=>{p([]),m(0),H(!0)},[v]);const ue=((Se=oe.latestIssue)==null?void 0:Se.level)==="error"?"danger":((Ae=oe.latestIssue)==null?void 0:Ae.level)==="warn"?"warning":"good",te=N||G?"danger":h?"good":"neutral",Ne=o.useCallback(async()=>{var xe;const T=ib({daemonLogs:ie,daemonRawLines:le,trace:me,webEvents:ke});if(!T.trim()){at.showToast("복사할 visible logs가 없습니다.","info");return}try{await((xe=navigator.clipboard)==null?void 0:xe.writeText(T)),at.showToast("Visible logs를 클립보드에 복사했습니다.","success")}catch(ve){at.showToast(ve instanceof Error?ve.message:"Could not copy visible logs","warning")}},[ie,le,me,ke]);return t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"Level"}),["debug","info","warn","error"].map(T=>t.jsx("button",{onClick:()=>{j(T),n([]),l(""),i("empty"),w(0),_(!0)},className:`machine-btn text-[10px] px-2 py-0.5 ${R===T?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:T.toUpperCase()},T)),t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider ml-3 mr-1",children:"Trace"}),eb.map(T=>t.jsx("button",{onClick:()=>y(T.value),className:`machine-btn text-[10px] px-2 py-0.5 ${v===T.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:T.label},T.value))]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${de.info})`},{id:"issues",label:`Issues (${de.issues})`},{id:"all",label:`All (${de.all})`}].map(T=>t.jsx("button",{type:"button",onClick:()=>k(T.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${C===T.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:T.label},T.id))}),t.jsx("input",{value:$,onChange:T=>L(T.target.value),placeholder:"Search visible logs, trace, events…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"}),t.jsx("button",{onClick:()=>{Ne()},className:"machine-btn",children:"Copy visible"}),t.jsx("button",{onClick:()=>S(T=>!T),className:`machine-btn ${h?"text-green-500 border-green-500/30":""}`,children:h?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>B(T=>T+1),className:"machine-btn",children:"↻ Refresh"}),t.jsx("button",{onClick:()=>{n([]),l(""),i("empty"),p([]),x([]),w(0),m(0),b(null),P(""),I(""),_(!0),H(!0),Bs.clear()},className:"machine-btn",children:"Clear"})]})]}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[t.jsxs("div",{className:`rounded-xl border p-3 ${na(oe.issueCount>0?"warning":"good")}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Visible signals"}),t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:["daemon ",ie.length+le.length," · trace ",me.length," · web ",ke.length]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:$.trim()?`Filtered by “${$.trim()}”`:"Showing the latest buffered entries"})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${na(ue)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Attention needed"}),oe.latestIssue?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[oe.latestIssue.source," · ",oe.latestIssue.label]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:oe.latestIssue.detail}),t.jsxs("div",{className:"text-[10px] text-text-muted mt-2",children:[oe.issueCount," warn/error signal(s) · ",$i(oe.latestIssue.timestamp)]})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No recent warn/error signal"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use search or lower the log level if you need more context."})]})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${na(te)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Fetch status"}),t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:N||G?"Needs attention":h?"Live polling every 3s":"Paused"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",$i(f)]}),(N||G)&&t.jsxs("div",{className:"text-[11px] text-red-300 mt-2 space-y-1",children:[N&&t.jsxs("div",{children:["Daemon logs: ",N]}),G&&t.jsxs("div",{children:["Daemon trace: ",G]})]})]})]}),t.jsxs("div",{className:"grid gap-3",children:[t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>V(T=>({...T,daemon:!T.daemon})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:a==="text"?`${le.length} visible raw line(s) from file fallback`:`${ie.length} visible structured line(s)`})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:U.daemon?"Hide":"Show"})]}),U.daemon&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[M&&!oe.hasAnyData&&!N&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!M&&N&&a==="empty"&&t.jsx("div",{className:"p-6 text-center text-red-300",children:N}),!M&&a==="empty"&&!N&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),a==="text"&&le.length===0&&c&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:C==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),a==="structured"&&ie.length===0&&r.length>0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),a==="text"&&le.map((T,xe)=>t.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:T},`raw-${xe}`)),a!=="text"&&ie.map((T,xe)=>t.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Ki(T.level)}`,children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(T.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:T.level==="error"?"ERR":T.level==="warn"?"WRN":T.level==="debug"?"DBG":"INF"}),t.jsx("span",{className:"break-words",children:T.message})]},`log-${xe}`))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>V(T=>({...T,trace:!T.trace})),children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",v==="session_host"?" · session_host only":""]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[me.length," visible trace event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:U.trace?"Hide":"Show"})]}),U.trace&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[W&&me.length===0&&!G&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!W&&G&&me.length===0&&t.jsx("div",{className:"p-6 text-center text-red-300",children:G}),!W&&me.length===0&&!G&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:$.trim()?"No trace entries match the current search.":v==="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."}),me.map(T=>t.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ki(T.level)}`,children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(T.ts).toLocaleTimeString()}),t.jsx("span",{children:T.level.toUpperCase()}),t.jsxs("span",{children:[T.category,".",T.stage]}),T.interactionId&&t.jsxs("span",{children:["ix=",T.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:vr(T.payload,360)||"No payload"})]},T.id))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>V(T=>({...T,web:!T.web})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[ke.length," visible browser event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:U.web?"Hide":"Show"})]}),U.web&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[ke.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:$.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),ke.map(T=>t.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(T.ts).toLocaleTimeString()}),t.jsx("span",{children:T.kind}),T.topic&&t.jsxs("span",{children:["topic=",T.topic]}),T.interactionId&&t.jsxs("span",{children:["ix=",T.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:vr(T.payload,360)||"No payload"})]},T.id))]})]})]}),t.jsx("div",{ref:ae})]})}function aa(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function oa(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Bi(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 db(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function ub(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 mb(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 fb({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),p=ol(e,{enabled:!!e,includeSessions:!0,limit:Yo,intervalMs:Km}),d=p.diagnostics,x=p.loading,g=p.applyDiagnostics,w=o.useMemo(()=>yx({diagnostics:d,loading:x,refreshing:l,error:n}),[d,x,l,n]),A=o.useMemo(()=>new Map(s.map(L=>[L.sessionId||L.id,L])),[s]),m=o.useCallback(async()=>{if(e){u(!0);try{const L=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Yo}),M=aa(L);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Could not load hosted runtime diagnostics");g(M.diagnostics||M.result||null),a("")}catch(L){const M=L instanceof Error?L.message:"Could not load hosted runtime diagnostics";a(M)}finally{u(!1)}}},[g,e,r]);o.useEffect(()=>{!e||d||x||l||m()},[d,x,e,m,l]);const f=o.useCallback(async(L,M)=>{const _=`${L}:${M.sessionId}`;if(!(L==="session_host_stop_session"&&!window.confirm(`Stop ${M.displayName}?
73
- This will terminate the hosted runtime.`))){c(_);try{const W=await r(e,L,{sessionId:M.sessionId}),H=aa(W);if(!(H!=null&&H.success))throw new Error((H==null?void 0:H.error)||"Session host action failed");const N=L==="session_host_resume_session"?"resumed":L==="session_host_restart_session"?"restarted":"stopped";at.showToast(`Session host ${N}: ${M.displayName}`,"success"),await m()}catch(W){const H=W instanceof Error?W.message:"Session host action failed";at.showToast(H,"warning"),a(H)}finally{c(W=>W===_?null:W)}}},[e,m,r]),b=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
74
- The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const M=await r(e,"session_host_prune_duplicate_sessions",{}),_=aa(M);if(!(_!=null&&_.success))throw new Error((_==null?void 0:_.error)||"Duplicate prune failed");const W=_.result||{},H=Array.isArray(W.prunedSessionIds)?W.prunedSessionIds.length:0,N=typeof W.duplicateGroupCount=="number"?W.duplicateGroupCount:0;at.showToast(`Pruned ${H} duplicate runtime(s) across ${N} group(s)`,"success"),await m()}catch(M){const _=M instanceof Error?M.message:"Duplicate prune failed";at.showToast(_,"warning"),a(_)}finally{c(M=>M==="session_host_prune_duplicate_sessions"?null:M)}}},[e,m,r]),h=o.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((L,M)=>(M.lastActivityAt||0)-(L.lastActivityAt||0)),[d==null?void 0:d.sessions]),S=o.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:El(h),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,h]),R=S.liveRuntimes,j=S.recoverySnapshots,C=S.inactiveRecords,k=o.useMemo(()=>mb(R),[R]),v=o.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),y=o.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(L=>L.level==="warn"||L.level==="error")||null,[d==null?void 0:d.recentLogs]),$=(L,M)=>{var B;const _=i===`session_host_resume_session:${L.sessionId}`,W=i===`session_host_restart_session:${L.sessionId}`,H=i===`session_host_stop_session:${L.sessionId}`,N=go(L.meta),P=A.get(L.sessionId),G=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,I=M==="recovery"?"Recover":"Resume",E=$l(M);return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:L.displayName||(P==null?void 0:P.cliName)||L.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${ub(L.lifecycle)}`,children:L.lifecycle}),N&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:N})]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:"text-text-primary/90",children:L.workspaceLabel||(P==null?void 0:P.runtimeWorkspaceLabel)||L.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:L.runtimeKey}),L.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",L.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((B=L.writeOwner)==null?void 0:B.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:db(L.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($a,{size:11})," ",G]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",Bi(L.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",E]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[M==="recovery"&&(L.lifecycle==="interrupted"||L.lifecycle==="failed"||L.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{f("session_host_resume_session",L)},children:_?`${I}ing…`:I}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{f("session_host_restart_session",L)},children:W?"Restarting…":"Restart"}),M==="live"&&(L.lifecycle==="running"||L.lifecycle==="starting"||L.lifecycle==="interrupted")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{f("session_host_stop_session",L)},children:H?"Stopping…":"Stop"})]})]})},L.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(Zt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Tf()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[k>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{b()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${k})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${w.toneClass}`,children:w.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{m()},disabled:x||l,children:[t.jsx(Gs,{size:13}),x||l?"Refreshing…":"Refresh"]})]})]}),n&&!d&&t.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(Ss,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),d&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.runtimeCount})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:j.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.recentRequests.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),t.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Bi(d.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:oa(d.hostStartedAt)})]})]}),y&&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(Ss,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:y.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[oa(y.timestamp),y.sessionId?` · ${y.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(yn,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ks("live")}),R.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:R.map(L=>$(L,"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(Zt,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ks("recovery")}),j.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:j.map(L=>$(L,"recovery"))})]}),C.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:Ks("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:C.map(L=>$(L,"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(L=>{var _;const M=h.find(W=>W.sessionId===L.sessionId);return t.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary font-medium",children:(M==null?void 0:M.displayName)||((_=A.get(L.sessionId))==null?void 0:_.cliName)||L.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[L.action,L.lifecycle?` · ${L.lifecycle}`:"",L.detail?` · ${L.detail}`:"",L.error?` · ${L.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${L.success===!1?"text-red-300":"text-text-secondary"}`,children:oa(L.timestamp)})]},`${L.sessionId}:${L.timestamp}:${L.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function pb({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 ia({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 ca({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 hb({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),d=dr(e,"0.8.96");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(ia,{icon:t.jsx(es,{size:13}),children:"Current Chats"}),t.jsx(ca,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(x=>{const g=ya(x);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(x),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:mt(x)}),g>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:wn(g)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Is(x)})]},x.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ia,{icon:t.jsx(sc,{size:13}),children:"Recent Launches"}),t.jsx(ca,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(x=>{const{metaText:g,updatedLabel:w}=vl(x);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(x),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:x.label}),w&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:w})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:g})]},x.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ia,{icon:t.jsx(Ss,{size:13}),children:"Daemon Update"}),t.jsx(ca,{className:"border-amber-500/20 bg-amber-500/5",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:d?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:d?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),t.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[t.jsx(Gs,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function xb(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const bb={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 Jr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function la({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:p}){const d=Vs(),{handleLaunchIde:x,handleStopCli:g,handleRestartIde:w,handleStopIde:A,handleDetectIdes:m,launchingIde:f,launchingAgentType:b,addLog:h}=c,[S,R]=o.useState(null),j=o.useCallback(D=>{D&&d(as(D))},[d]),C=bb[e],k=e==="ide",v=e==="acp",y=o.useMemo(()=>n.filter(D=>D.category===e&&(e==="ide"||D.installed!==!1)),[e,n]),$=o.useMemo(()=>new Map(y.map(D=>[D.type,D.displayName||D.type])),[y]),[L,M]=o.useState(""),[_,W]=o.useState(""),[H,N]=o.useState([]),[P,G]=o.useState(""),[I,E]=o.useState(""),[B,U]=o.useState([]),[V,ae]=o.useState(!1),[we,be]=o.useState(!1),[Y,he]=o.useState(""),[O,X]=o.useState(!1),[ie,le]=o.useState(()=>wt()),[me,ke]=o.useState(null),[de,oe]=o.useState(p?"__custom__":u||s.defaultWorkspaceId||""),[se,ue]=o.useState(p||""),[te,Ne]=o.useState([]),[Se,Ae]=o.useState(!1),[T,xe]=o.useState(""),[ve,Q]=o.useState([]),[ye,_e]=o.useState(!1),[We,Pe]=o.useState(""),ze=o.useRef(null),[Qe,it]=o.useState(null),et=o.useRef("__home__"),[ft,tt]=o.useState("__home__"),[Ct,pt]=o.useState(!1),st=o.useRef(0),Re=te.filter(D=>!a.some(ee=>ee.type===D&&St(ee.status)!=="stopped")),Ge=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!de&&oe(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(p){oe("__custom__"),ue(p);return}u&&(oe(u),ue(""))},[u,p]),o.useEffect(()=>{k||L&&(y.some(D=>D.type===L)||(M(""),E("")))},[y,k,L]);const Be=(()=>{if(de==="__custom__")return se.trim();if(!de)return"";const D=(s.workspaces||[]).find(ee=>ee.id===de);return(D==null?void 0:D.path)||""})(),qe=o.useCallback(D=>{const ee=Ge.current[D];ee&&(clearTimeout(ee),delete Ge.current[D]),Ne(ce=>ce.includes(D)?ce.filter(Ke=>Ke!==D):ce)},[]),At=o.useRef(new Set),bt=o.useCallback(async D=>{if(l){_e(!0),Pe("");try{const ee=await In(l,r,D);xe(ee.path),ue(ee.path),Q(ee.directories)}catch(ee){Pe(ee instanceof Error?ee.message:"Could not load folder")}finally{_e(!1)}}},[r,l]),jt=o.useCallback(()=>{if(!l)return;oe("__custom__"),Ae(!0);const D=a.map(ce=>ce.workspace),ee=Cn(s.platform,Nn(se.trim(),Be,p,D,s.defaultWorkspacePath,(s.workspaces||[]).map(ce=>ce.path)));bt(ee)},[se,p,bt,s.defaultWorkspacePath,s.platform,s.workspaces,a,Be,l]),gt=o.useCallback(D=>{const ee=String(D.workspace||"").trim();if(!ee)return;const ce=(s.workspaces||[]).find(Ke=>Jr(Ke.path)===Jr(ee));if(ce){oe(ce.id),ue("");return}oe("__custom__"),ue(ee)},[s.workspaces]),Mt=o.useCallback(D=>{const ee=String(D.workspace||"").trim();if(!ee)return{workspaceId:null,workspacePath:"",useHome:!0};const ce=(s.workspaces||[]).find(Ke=>Jr(Ke.path)===Jr(ee));return ce?{workspaceId:ce.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ee,useHome:!1}},[s.workspaces]),Tt=o.useCallback(async D=>{if(!l||!D||e!=="cli"){U([]),ae(!1),be(!1),he("");return}const ee=st.current+1;st.current=ee,ae(!0),he("");try{const ce=await l(r,"list_saved_sessions",{providerType:D,kind:"cli",limit:30});if(st.current!==ee)return;const Ke=(ce==null?void 0:ce.result)??ce;U(Array.isArray(Ke==null?void 0:Ke.sessions)?Ke.sessions:[])}catch(ce){if(st.current!==ee)return;U([]),he(ce instanceof Error?ce.message:"Could not load saved sessions")}finally{st.current===ee&&(ae(!1),be(!0))}},[e,r,l]),Dt=o.useMemo(()=>{if(e!=="cli"||!L)return null;const D=$.get(L)||L;return{routeId:r,daemonId:r,providerSessionId:I||void 0,transport:"pty",mode:"chat",agentName:D,agentType:L,status:"idle",title:D,messages:[],ideType:L,workspaceName:Be,displayPrimary:D,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${L}`}},[e,r,$,Be,I,L]),Z=o.useCallback(D=>{if(e==="ide"||!D){N([]);return}N(Pl(r,D))},[e,r]);o.useEffect(()=>{st.current+=1,E(""),Z(L),be(!1),U([]),he(""),ae(!1)},[e,Z,Tt,L]);const De=o.useMemo(()=>B.find(D=>D.providerSessionId===I)||null,[B,I]);o.useEffect(()=>{if(!I)return;const D=B.find(ee=>ee.providerSessionId===I);D!=null&&D.canResume||E("")},[B,I]);const $e=o.useCallback((D,ee)=>{ze.current=ee,et.current=D.selectedWorkspaceKey||"__home__",tt(D.selectedWorkspaceKey||"__home__"),it(D)},[]),ot=o.useCallback(()=>{ze.current&&(pt(!0),ze.current().finally(()=>{ze.current=null,pt(!1),it(null)}))},[]),K=o.useCallback(D=>{if(!D)return;Ne(ce=>ce.includes(D)?ce:[...ce,D]);const ee=Ge.current[D];ee&&clearTimeout(ee),Ge.current[D]=setTimeout(()=>{Ne(ce=>ce.includes(D)?ce.filter(Ke=>Ke!==D):ce),delete Ge.current[D]},2e4)},[]);o.useEffect(()=>{for(const ee of a)St(ee.status)!=="stopped"&&(te.includes(ee.type)&&!At.current.has(ee.type)&&(At.current.add(ee.type),h("info",`${$.get(ee.type)||ee.type} launched`,!0)),qe(ee.type));const D=new Set(a.filter(ee=>St(ee.status)!=="stopped").map(ee=>ee.type));At.current.forEach(ee=>{!te.includes(ee)&&!D.has(ee)&&At.current.delete(ee)})},[h,qe,a,te,$]),o.useEffect(()=>()=>{Object.values(Ge.current).forEach(clearTimeout),Ge.current={}},[]);const[F,z]=o.useState({}),[q,re]=o.useState(null);o.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const ee=await l(r,"get_ide_extensions",{}),ce=(ee==null?void 0:ee.result)||ee;ce!=null&&ce.success&&(ce!=null&&ce.ideExtensions)&&z(ce.ideExtensions)}catch{}})()},[k,r,l]);const Ce=D=>k?dt(D.type):e==="cli"?D.cliName:D.acpName,Te=k?s.detectedIdes||[]:[],Ie=o.useCallback(async D=>{const ee=(D==null?void 0:D.type)||L,ce=(D==null?void 0:D.workspacePath)??Be;if(k){await x(ee,ce?{workspace:ce}:void 0)&&K(ee);return}const Ke=await c.runLaunchCliCore({cliType:ee,dir:D!=null&&D.workspaceId?void 0:ce||void 0,workspaceId:(D==null?void 0:D.workspaceId)||void 0,useHome:(D==null?void 0:D.useHome)||!(D!=null&&D.workspaceId)&&!ce,argsStr:(D==null?void 0:D.argsStr)??(_||void 0),model:(D==null?void 0:D.model)??(v&&P||void 0),resumeSessionId:(D==null?void 0:D.resumeSessionId)||!v&&e==="cli"&&ee===L&&I||void 0});if(Ke.success||Ke.pending){const Le=(D==null?void 0:D.argsStr)??_;!k&&(Le!=null&&Le.trim())&&(Dl(r,ee,Le),Z(ee)),K(ee),Ke.success&&Ke.sessionId&&j(Ke.sessionId)}},[c,x,v,k,_,P,Z,K,r,j,Be,I,L]),Oe=Uc(k?"ide":v?"acp":"cli",!k&&!v&&!!I),Ue=zc(k?"ide":v?"acp":"cli",!k&&!v&&!!I),J=()=>{var Le;const D=k?dt(L):$.get(L)||L,ee=!k&&!v&&!!I,{options:ce,selectedKey:Ke}=ws({machine:s,currentWorkspaceId:de&&de!=="__custom__"?de:null,currentWorkspacePath:Be});$e({title:ee?eo(D):bs("start-fresh",D),description:ee?to():gs("start-fresh"),confirmLabel:Oe,busyLabel:Ue,workspaceOptions:ce,selectedWorkspaceKey:Ke,details:[{label:"Mode",value:C.label},{label:"Provider",value:D},...!k&&e==="cli"&&I?[{label:"Resume",value:((Le=B.find(Ee=>Ee.providerSessionId===I))==null?void 0:Le.title)||I}]:[],...!k&&_.trim()?[{label:"Arguments",value:_.trim()}]:[],...v&&P.trim()?[{label:"Model",value:P.trim()}]:[]]},async()=>{const Ee=ce.find(Xe=>Xe.key===et.current);Ee!=null&&Ee.workspaceId?(oe(Ee.workspaceId),ue("")):Ee!=null&&Ee.workspacePath?(oe("__custom__"),ue(Ee.workspacePath)):(oe(""),ue("")),await Ie({workspaceId:(Ee==null?void 0:Ee.workspaceId)??null,workspacePath:(Ee==null?void 0:Ee.workspacePath)??"",useHome:!(Ee!=null&&Ee.workspaceId)&&!(Ee!=null&&Ee.workspacePath)})})},Me=D=>{k?A(D):g(D.type,D.workspace,D.id)},Ve=o.useCallback(async(D,ee,ce=!1)=>{if(D.mode===ee){ce&&D.sessionId&&j(D.sessionId);return}if(!l||!D.sessionId){ce&&D.sessionId&&j(D.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:D.sessionId,cliType:D.type,mode:ee}),ce&&j(D.sessionId)}catch(Ke){const Le=uo(Ke);lo(Ke)?console.warn(Le?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Ke instanceof Error?Ke.message:String(Ke)):console.error("Failed to switch CLI view mode:",Ke)}},[r,j,l]),Fe=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:de,onChange:D=>{const ee=D.target.value;if(oe(ee),ee==="__custom__"&&l){jt();return}ee!=="__custom__"&&ue("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(s.workspaces||[]).length>0?t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map(D=>t.jsxs("option",{value:D.id,children:[D.id===s.defaultWorkspaceId?"⭐ ":"",kn(D.path,D.label)]},D.id)),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]}):t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]})}),de==="__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:jt,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:se,onChange:D=>ue(D.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),t.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:de==="__custom__"?Be?t.jsx("span",{className:"font-mono truncate block",title:Be,children:Be}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Be?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:de===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:Be,children:Be})]}):"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 ${C.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 ",C.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?Te.length>0?Te.map(D=>{const ee=a.find(Xe=>(Xe.type||"").toLowerCase()===(D.type||"").toLowerCase()&&St(Xe.status)!=="stopped"),ce=D.running||!!ee,Ke=!!ee&&ee.cdpConnected,Le=te.includes(D.type||D.id||""),Ee=L===(D.type||"");return t.jsxs("button",{onClick:()=>{if(Ke&&ee){const Xe=ee.sessionId;Xe?d(as(Xe),{state:{openRemoteForTabKey:Xe}}):d("/dashboard",{state:{openRemoteForTabKey:ee.id}});return}Le||M(Xe=>Xe===(D.type||"")?"":D.type||"")},disabled:!!f||Le,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Ke?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ee?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:f&&f!==D.type?.4:1},children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(D.type)}),ce&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Ke?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:D.name||dt(D.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Ke?"text-green-400":Le?"text-orange-400":Ee?"text-accent-primary":"text-text-muted"}`,children:Ke?"Open Session":Le?"Starting...":Ee?"Configure":"Select"})]})]},D.type)}):t.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",t.jsxs("button",{onClick:m,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(Gd,{size:14})," Scan System"]})]}):y.length>0?y.map(D=>{const ee=L===D.type,ce=te.includes(D.type),Le=!!a.find(Ee=>Ee.type===D.type&&St(Ee.status)!=="stopped");return t.jsxs("button",{onClick:()=>M(Ee=>Ee===D.type?"":D.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ee?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:D.icon}),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:D.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ce?"text-orange-400":ee?"text-accent-primary":"text-text-muted"}`,children:ce?"Starting...":ee?"Configure":"Select"})]})]},D.type)}):t.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",t.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),L&&(k?Te.find(D=>D.type===L):y.find(D=>D.type===L))&&t.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:k?dt(L):$.get(L)||L})]}),Fe,!k&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&e==="cli"&&t.jsx(Bl,{busy:!!b||!!f||te.includes(L),savedSessionsLoading:V,savedSessionsError:Y,selectedSession:De,onRefresh:()=>void Tt(L),onOpenHistory:()=>{L&&(X(!0),Kl({hasLoadedInitialResults:we,isLoading:V})&&Tt(L))},onClearSelection:()=>E("")}),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:P,onChange:D=>G(D.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),t.jsx("input",{type:"text",placeholder:"Optional flags...",value:_,onChange:D=>W(D.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),H.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:H.map(D=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>W(D),title:D,children:D},D))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:J,disabled:!!b||!!f||te.includes(L),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:b===L||f===L?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+te.filter(D=>!a.some(ee=>ee.type===D&&St(ee.status)!=="stopped")).length,")"]}),a.length===0&&Re.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 ",C.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Re.map(D=>t.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i(D)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?dt(D):$.get(D)||D}),t.jsx("div",{className:"text-[11px] text-text-muted",children:b===D?"Launching process...":"Waiting for process and session to register..."})]})]}),t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${D}`)),a.map(D=>{const ee=k?D:null,ce=!k&&!v?D:null,Ke=St(D.status);return t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center mb-2",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i(D.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ce(D),(ee==null?void 0:ee.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",ee.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:D.workspace||"—"}),(ce==null?void 0:ce.mode)&&t.jsx("span",{className:ce.mode==="chat"?"text-violet-400":"text-text-secondary",children:ce.mode==="chat"?"Chat view":"Terminal view"})]}),ce&&(ce.runtimeKey||ce.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ce.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 ",ce.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 ${ce.runtimeKey}`),R(ce.runtimeKey||null),window.setTimeout(()=>{R(Ee=>Ee===ce.runtimeKey?null:Ee)},1200)},children:S===ce.runtimeKey?"Copied":"Copy"})]}),ce.runtimeWriteOwner&&t.jsx("span",{style:{color:ce.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ce.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:xb(ce.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 ${Ke==="stopped"?"bg-red-500/[0.08] text-red-500":Ke==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Ke}),k&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Le=D.sessionId;if(Le){d(as(Le),{state:{openRemoteForTabKey:Le}});return}d("/dashboard",{state:{openRemoteForTabKey:D.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:t.jsx(Pt,{size:13})}),t.jsx("button",{onClick:()=>{const Le=D.workspace||"",{options:Ee,selectedKey:Xe}=ws({machine:s,currentWorkspacePath:Le});$e({title:bs("restart-ide",dt(D.type)),description:gs("restart-ide"),confirmLabel:Us("restart-ide"),busyLabel:zs("restart-ide"),workspaceOptions:Ee,selectedWorkspaceKey:Xe,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:dt(D.type)}]},async()=>{const je=Ee.find(ts=>ts.key===et.current),ut=(je==null?void 0:je.workspacePath)??"";if(ut&&ut!==Le){await Ie({type:D.type,workspacePath:ut});return}await w(D)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:t.jsx(Gs,{size:14})})]}),v&&t.jsx("button",{onClick:()=>{const Le=D.sessionId;Le&&j(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:!D.sessionId,children:t.jsx(es,{size:14})}),ce&&Ke!=="stopped"&&t.jsxs(t.Fragment,{children:[ce.mode&&t.jsx(Ja,{mode:ce.mode,onChange:Le=>void Ve(ce,Le,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Le=D.sessionId;Le&&j(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:!D.sessionId,children:ce.mode==="chat"?t.jsx(es,{size:14}):t.jsx(Pt,{size:13})})]}),Ke==="stopped"?t.jsx("button",{onClick:()=>{const Le=D.workspace||"",Ee=k?dt(D.type):Ce(D),{options:Xe,selectedKey:je}=ws({machine:s,currentWorkspacePath:Le});$e({title:bs("restart-stopped",Ee),description:gs("restart-stopped"),confirmLabel:Us("restart-stopped"),busyLabel:zs("restart-stopped"),workspaceOptions:Xe,selectedWorkspaceKey:je,details:[{label:"Mode",value:C.label},{label:"Provider",value:Ee}]},async()=>{const ut=Xe.find(ts=>ts.key===et.current);await Ie({type:D.type,workspaceId:(ut==null?void 0:ut.workspaceId)??null,workspacePath:(ut==null?void 0:ut.workspacePath)??"",useHome:!(ut!=null&&ut.workspaceId)&&!(ut!=null&&ut.workspacePath)})})},disabled:te.includes(D.type),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-green-500/20 text-green-400 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",title:"Restart",children:te.includes(D.type)?"⏳":t.jsx(Ba,{size:14})}):t.jsx("button",{onClick:()=>Me(D),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:t.jsx(It,{size:14})})]})]}),ee&&ee.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ee.aiAgents.map(Le=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${mc(Le.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Le.name," · ",St(Le.status)]},Le.id))}),ee&&(F[ee.type]||[]).length>0&&l&&t.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[t.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:(F[ee.type]||[]).map(Le=>t.jsxs("button",{disabled:q===`${ee.type}.${Le.type}`,onClick:async()=>{const Ee=`${ee.type}.${Le.type}`;re(Ee);try{await l(r,"set_ide_extension",{ideType:ee.type,extensionType:Le.type,enabled:!Le.enabled}),z(Xe=>({...Xe,[ee.type]:(Xe[ee.type]||[]).map(je=>je.type===Le.type?{...je,enabled:!je.enabled}:je)}))}catch(Xe){console.error("Extension toggle failed:",Xe)}finally{re(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))})]})]},D.id)})]}),Se&&l&&t.jsx(An,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:T,directories:ve,busy:ye,error:We,confirmLabel:"Use this folder",onClose:()=>Ae(!1),onNavigate:D=>{bt(D)},onConfirm:D=>{ue(D),oe("__custom__"),Ae(!1)}}),Qe&&t.jsx(xo,{title:Qe.title,description:Qe.description,details:Qe.details,workspaceOptions:Qe.workspaceOptions,selectedWorkspaceKey:ft,onWorkspaceChange:D=>{et.current=D,tt(D)},confirmLabel:Qe.confirmLabel,busyLabel:Qe.busyLabel,busy:Ct,onConfirm:ot,onCancel:()=>{ze.current=null,it(null)}}),O&&Dt&&t.jsx(so,{activeConv:Dt,ides:[],isCreatingChat:!1,isRefreshingHistory:V,savedSessions:B,isSavedSessionsLoading:V,isResumingSavedSessionId:me,savedHistoryFilters:ie,onSavedHistoryFiltersChange:le,onClose:()=>X(!1),onNewChat:()=>{E(""),X(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Tt(L)},onResumeSavedSession:D=>{if(!D.canResume||me)return;const ee=Mt(D);E(D.providerSessionId),gt(D),ke(D.providerSessionId),X(!1),Ie({type:D.providerType,workspaceId:ee.workspaceId,workspacePath:ee.workspacePath,useHome:ee.useHome,resumeSessionId:D.providerSessionId}).finally(()=>{ke(ce=>ce===D.providerSessionId?null:ce)})}})]})}const Oi=[{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 gb({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:p,initialWorkspacePath:d,sendDaemonCommand:x}){var m;const[g,w]=o.useState(u);o.useEffect(()=>{w(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:Oi.map(f=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${g===f.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>w(f.id),children:[t.jsx("span",{children:f.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${g===f.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:A[f.id]})]},f.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(m=Oi.find(f=>f.id===g))==null?void 0:m.helper})]}),g==="ide"&&t.jsx(la,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:p,initialWorkspacePath:d}),g==="cli"&&t.jsx(la,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:p,initialWorkspacePath:d}),g==="acp"&&t.jsx(la,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:p,initialWorkspacePath:d})]})}function yb({onNicknameSynced:e}={}){var ke,de,oe,se,ue,te,Ne,Se,Ae;const{id:s}=Nd(),r=Vs(),n=Pa(),{sendCommand:a}=Lt(),i=Nr(),c=al(),l=Dc(),u=l.ides||[],p=l.initialLoaded??!0,d=u.find(T=>T.id===s&&T.type==="adhdev-daemon"),x=u.some(T=>T.type==="adhdev-daemon"),[g,w]=o.useState("workspace"),[A,m]=o.useState("ide"),f=o.useRef(null),[b,h]=o.useState(null),S=o.useRef("__home__"),[R,j]=o.useState("__home__"),[C,k]=o.useState(!1),v=o.useRef(null);o.useEffect(()=>{!s||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,d,s]),o.useEffect(()=>{if(!s||!d||g!=="overview")return;const T=d.machine;(typeof(T==null?void 0:T.cpus)!="number"||typeof(T==null?void 0:T.totalMem)!="number"||typeof(T==null?void 0:T.arch)!="string"||typeof(T==null?void 0:T.release)!="string")&&c(s,{minFreshMs:3e4}).catch(()=>{})},[g,c,d,s]),kp(s&&g==="overview"?[s]:[],{enabled:g==="overview",intervalMs:Pm});const y=()=>{if(x){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},$=zx({machineId:s,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:v});o.useEffect(()=>at.onToast(xe=>{l.setToasts(Q=>{if(Q.some(We=>We.message===xe.message&&xe.timestamp-We.timestamp<3e3))return Q;const _e={id:xe.id,message:xe.message,type:xe.type,timestamp:xe.timestamp,targetKey:xe.targetKey,actions:xe.actions};return[...Q.slice(-4),_e]});const ve=xe.duration||5e3;setTimeout(()=>l.setToasts(Q=>Q.filter(ye=>ye.id!==xe.id)),ve)}),[l]);const L=(d==null?void 0:d.availableProviders)||[],M={};for(const T of L)M[T.type]=T.icon;const _=T=>M[T]||"",W=d?{id:d.id,hostname:fc(d,{fallbackId:d.id}),platform:((ke=d.machine)==null?void 0:ke.platform)||"unknown",arch:((de=d.machine)==null?void 0:de.arch)||"",cpus:((oe=d.machine)==null?void 0:oe.cpus)||0,totalMem:((se=d.machine)==null?void 0:se.totalMem)||0,freeMem:(ue=d.machine)==null?void 0:ue.freeMem,availableMem:(te=d.machine)==null?void 0:te.availableMem,loadavg:(Ne=d.machine)==null?void 0:Ne.loadavg,uptime:(Se=d.machine)==null?void 0:Se.uptime,release:((Ae=d.machine)==null?void 0:Ae.release)||"",cdpConnected:!!d.cdpConnected,machineNickname:d.machineNickname||null,p2p:d.p2p?{screenshotActive:!1,...d.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:d.detectedIdes||[],workspaces:d.workspaces||[],defaultWorkspaceId:d.defaultWorkspaceId??d.activeWorkspaceId??null,defaultWorkspacePath:d.defaultWorkspacePath??d.activeWorkspacePath??null}:null,H=u.filter(T=>T.daemonId===s&&T.type!=="adhdev-daemon").filter(T=>!br(T)&&!Ds(T)).map(T=>({id:T.id,sessionId:T.sessionId,type:T.type,version:T.version||"",instanceId:T.instanceId||"",status:T.status,workspace:T.workspace||null,terminals:T.terminals||0,aiAgents:Wu(T.aiAgents||(T.agents||[]).map(xe=>({id:xe.name,name:xe.name,status:xe.status,version:xe.version}))),activeChat:T.activeChat||null,chats:T.chats||[],childSessions:T.childSessions||[],cdpConnected:T.cdpConnected||!1,daemonId:s})),N=u.filter(T=>T.daemonId===s&&br(T)).map(T=>({id:T.id,sessionId:T.sessionId,type:T.type,cliName:T.cliName||T.type,status:T.status,workspace:T.workspace||"",activeChat:T.activeChat||null,providerSessionId:T.providerSessionId,mode:T.mode,runtimeKey:T.runtimeKey,runtimeDisplayName:T.runtimeDisplayName,runtimeWorkspaceLabel:T.runtimeWorkspaceLabel,runtimeWriteOwner:T.runtimeWriteOwner||null,runtimeAttachedClients:T.runtimeAttachedClients||[],daemonId:s})),P=u.filter(T=>T.daemonId===s&&Ds(T)).map(T=>({id:T.id,sessionId:T.sessionId,type:T.type,acpName:T.cliName||T.type,status:T.status,workspace:T.workspace||"",activeChat:T.activeChat||null,providerSessionId:T.providerSessionId,daemonId:s})),G=d?_t(d,{fallbackId:s}):"",I="workspace",E=n.state,B=E==null?void 0:E.initialMachineTab,U=E==null?void 0:E.initialWorkspaceCategory,V=E==null?void 0:E.initialWorkspaceId,ae=E==null?void 0:E.initialWorkspacePath,we=B==="ides"||B==="clis"||B==="acps"?"workspace":B||I,be=B==="ides"?"ide":B==="clis"?"cli":B==="acps"?"acp":U,Y=[...H.map(T=>{var xe,ve,Q,ye,_e;return{id:`ide:${T.type}:${T.workspace||""}`,label:((xe=T.activeChat)==null?void 0:xe.title)||T.type,kind:"ide",providerType:T.type,subtitle:T.workspace||void 0,workspace:T.workspace||void 0,lastLaunchedAt:((_e=(ye=(Q=(ve=T.activeChat)==null?void 0:ve.messages)==null?void 0:Q.at)==null?void 0:ye.call(Q,-1))==null?void 0:_e.timestamp)||0}}),...N.map(T=>{var xe,ve,Q,ye,_e;return{id:`cli:${T.type}:${T.workspace||""}`,label:((xe=T.activeChat)==null?void 0:xe.title)||T.cliName,kind:"cli",providerType:T.type,providerSessionId:T.providerSessionId,subtitle:T.workspace||void 0,workspace:T.workspace||void 0,lastLaunchedAt:((_e=(ye=(Q=(ve=T.activeChat)==null?void 0:ve.messages)==null?void 0:Q.at)==null?void 0:ye.call(Q,-1))==null?void 0:_e.timestamp)||0}}),...P.map(T=>{var xe,ve,Q,ye,_e;return{id:`acp:${T.type}:${T.workspace||""}`,label:((xe=T.activeChat)==null?void 0:xe.title)||T.acpName,kind:"acp",providerType:T.type,providerSessionId:T.providerSessionId,subtitle:Ns(T.summaryMetadata)||T.workspace||void 0,workspace:T.workspace||void 0,lastLaunchedAt:((_e=(ye=(Q=(ve=T.activeChat)==null?void 0:ve.messages)==null?void 0:Q.at)==null?void 0:ye.call(Q,-1))==null?void 0:_e.timestamp)||0}})].sort((T,xe)=>(xe.lastLaunchedAt||0)-(T.lastLaunchedAt||0)),he=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(T=>({id:T.id,label:T.title||T.providerName||T.providerType,kind:T.kind,providerType:T.providerType,providerSessionId:T.providerSessionId,subtitle:Ns(T.summaryMetadata)||T.workspace||void 0,workspace:T.workspace,summaryMetadata:T.summaryMetadata,lastLaunchedAt:T.lastLaunchedAt})):Y,O=o.useMemo(()=>{var xe;const T=((xe=l.connectionStates)==null?void 0:xe[s||""])||void 0;return u.filter(ve=>ve.daemonId===s&&ve.type!=="adhdev-daemon").flatMap(ve=>ro(ve,{},{connectionStates:s&&T?{[s]:T}:void 0,defaultConnectionState:T})).filter(ve=>!(ve.transport==="pty"&&ve.mode==="terminal")).sort((ve,Q)=>ya(Q)-ya(ve))},[u,l.connectionStates,s]),X=o.useCallback(T=>{const xe=Ga(T);xe&&r(as(xe))},[r]),ie=o.useCallback(()=>{f.current&&(k(!0),f.current().finally(()=>{f.current=null,k(!1),h(null)}))},[]),le=o.useCallback(T=>{if(!W)return;const{options:xe,selectedKey:ve}=ws({machine:W,currentWorkspacePath:T.workspace}),Q=async()=>{m(T.kind),w("workspace")};f.current=async()=>{const ye=xe.find(Pe=>Pe.key===S.current),_e=(ye==null?void 0:ye.workspacePath)??null,We=(ye==null?void 0:ye.workspaceId)??null;if(T.kind==="ide"&&T.providerType){await $.handleLaunchIde(T.providerType,_e?{workspace:_e}:void 0);return}if((T.kind==="cli"||T.kind==="acp")&&T.providerType){await $.runLaunchCliCore({cliType:T.providerType,dir:We?void 0:_e||"",workspaceId:We||void 0,model:T.kind==="acp"&&hc(T.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:T.providerSessionId});return}await Q()},S.current=ve,j(ve),h({title:T.kind==="ide"?bs("restart-ide",T.label):T.providerSessionId?eo(T.label):bs("start-fresh",T.label),description:T.kind==="ide"?gs("restart-ide"):T.providerSessionId?to():gs("start-fresh"),confirmLabel:T.kind==="ide"?Us("restart-ide"):T.providerSessionId?fn(!0):Us("start-fresh"),busyLabel:T.kind==="ide"?zs("restart-ide"):T.providerSessionId?Qa(!0):zs("start-fresh"),workspaceOptions:xe,details:[{label:"Mode",value:T.kind.toUpperCase()},...T.providerType?[{label:"Provider",value:T.providerType}]:[]]})},[$,W]);if(o.useEffect(()=>{w(we)},[I,we,s]),o.useEffect(()=>{be&&m(be)},[be,s]),!W)return p?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:y,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 me=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Pt,{size:14})," Workspace"]}),count:H.length+N.length+P.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Zt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(gn,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(qd,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(zd,{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:y,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:[$.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:$.nicknameInput,onChange:T=>$.setNicknameInput(T.target.value),onKeyDown:T=>{T.key==="Enter"&&$.handleSaveNickname(),T.key==="Escape"&&$.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:$.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:()=>$.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:()=>{$.setEditingNickname(!0),$.setNicknameInput(W.machineNickname||"")},title:"Click to set nickname",children:G}),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:[W.platform," · ",W.arch]}),t.jsxs("span",{children:[W.cpus," cores"]}),(d==null?void 0:d.version)&&t.jsxs("span",{children:["v",d.version]}),W.p2p.available&&t.jsxs("span",{children:["P2P ",W.p2p.state==="connected"?"connected":W.p2p.state]}),W.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:W.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:me.map(T=>t.jsxs("button",{onClick:()=>w(T.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${g===T.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[T.label,T.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${g===T.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:T.count})]},T.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:[g==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(hb,{machineEntry:d,providers:L,recentLaunches:he,currentConversations:O,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:le,onOpenConversation:X}),t.jsx(gb,{machine:W,machineId:s,providers:L,ideSessions:H,cliSessions:N,acpSessions:P,actions:$,getIcon:_,initialCategory:A,initialWorkspaceId:V,initialWorkspacePath:ae,sendDaemonCommand:a})]}),g==="providers"&&t.jsx(Zx,{machineId:s,providers:L,sendDaemonCommand:a}),g==="overview"&&t.jsx(Vx,{machineId:s,machine:W,ideSessions:H,cliSessions:N,acpSessions:P,actions:$,sendDaemonCommand:a}),g==="session-host"&&t.jsx(fb,{machineId:s,cliSessions:N,sendDaemonCommand:a}),g==="logs"&&t.jsx(lb,{machineId:s,sendDaemonCommand:a})]})})}),$.launchPick&&W&&t.jsx(pb,{machine:W,launchPick:$.launchPick,actions:$}),b&&t.jsx(xo,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:R,onWorkspaceChange:T=>{S.current=T,j(T)},confirmLabel:b.confirmLabel,busyLabel:b.busyLabel,busy:C,onConfirm:ie,onCancel:()=>{f.current=null,h(null)}}),t.jsx(Vc,{toasts:l.toasts||[],onDismiss:T=>l.setToasts(xe=>xe.filter(ve=>ve.id!==T)),onClickToast:T=>{T.targetKey&&r(as(T.targetKey))}}),t.jsx("style",{children:`
75
- @keyframes toast-in {
76
- from { opacity: 0; transform: translateX(40px); }
77
- to { opacity: 1; transform: translateX(0); }
78
- }
79
- `})]})}function vo(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function vb(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=vo();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(vb(e),{credentials:"same-origin",...s})}function Fl(){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 wb{constructor(){Ye(this,"adapters",new Map);Ye(this,"states",new Map);Ye(this,"runtimeListeners",new Map);Ye(this,"screenshotCallbacks",new Map);Ye(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}onScreenshot(s,r){return this.screenshotCallbacks.set(s,r),()=>{this.screenshotCallbacks.delete(s)}}emitScreenshot(s,r){this.screenshotCallbacks.forEach(n=>n(s,r))}onStatus(s){return this.statusCallbacks.add(s),()=>{this.statusCallbacks.delete(s)}}emitStatus(s,r){this.statusCallbacks.forEach(n=>n(s,r))}emitRuntimeSnapshot(s,r,n=0,a=!1,i,c){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:a,cols:i,rows:c})}emitSessionOutput(s,r,n){!s||typeof r!="string"||!r||this.emitRuntimeEvent(s,{type:"session_output",sessionId:s,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(s,r){const n=this.runtimeListeners.get(s)||new Set;return n.add(r),this.runtimeListeners.set(s,n),()=>{const a=this.runtimeListeners.get(s);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(s))}}async requestRuntimeSnapshot(s,r){if(!r)return;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 Xt=new wb;function jb(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=vo();return r?`${s}?token=${encodeURIComponent(r)}`:s}const Qr=jb(),Wi=3e3,kb=3e4;let Vt=null,Sb=0;const bn=new Map;let us=null,mr=null;function Hi(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function rr(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function Nb(e){return e==="connected"?"connected":e}async function an(e,s,r){const n=Hf(e,r||{}),a=Vt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++Sb}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{bn.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);bn.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 Ta(e,s){const r=Vt;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 Cb{constructor(s){Ye(this,"daemonId");Ye(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Vt==null?void 0:Vt.readyState)===WebSocket.OPEN}get connectionState(){return(Vt==null?void 0:Vt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return an(this.daemonId,s,r)}async sendInput(s,r){return an(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,us&&(clearInterval(us),us=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await an(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());Xt.emitScreenshot(this.daemonId,a)}}catch{}};r(),us=setInterval(r,2e3)}stopScreenshots(s){us&&(clearInterval(us),us=null)}}let Bt=null;function Ib(e){return(!Bt||Bt.daemonId!==e)&&(Bt=new Cb(e)),Bt}function Ab({children:e}){const s=o.useRef(pr()),r=pr();s.current=r;const{setUserName:n}=ks(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((m,f)=>{l(m),mr==null||mr(m,f)},[]),p=o.useRef(null),d=o.useRef(),x=o.useRef(Wi),g=o.useRef(!0),w=o.useRef(!1),A=o.useRef("initial_connect");return o.useEffect(()=>{g.current=!0,w.current=!1;function m(){var h,S;if(!g.current||((h=p.current)==null?void 0:h.readyState)===WebSocket.OPEN||((S=p.current)==null?void 0:S.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Qr}...`),rr("connect_attempt",{url:Qr,reason:A.current,delayMs:x.current});let b;try{b=new WebSocket(Qr)}catch(R){console.error("[Standalone WS] Failed to create WebSocket:",R),f();return}p.current=b,b.onopen=()=>{if(!g.current){b.close();return}u("connected"),x.current=Wi,rr("open",{url:Qr,reason:A.current}),os.resubscribeAll({sendData:Ta}),console.log("[Standalone WS] Connected")},Vt=b,b.onmessage=R=>{var j,C;try{const k=JSON.parse(R.data);if((k.type==="command_result"||k.type==="error")&&k.requestId){const v=bn.get(k.requestId);v&&(bn.delete(k.requestId),k.type==="error"?v.reject(new Error(((j=k.data)==null?void 0:j.message)||"Command failed")):v.resolve(k.data));return}if(k.type==="session_output"){const v=k.sessionId||k.cliId||k.cliType;v&&Xt.emitSessionOutput(v,typeof k.data=="string"?k.data:"",typeof k.seq=="number"?k.seq:void 0);return}if(k.type==="runtime_snapshot"){Xt.emitRuntimeSnapshot(k.sessionId,typeof k.text=="string"?k.text:"",typeof k.seq=="number"?k.seq:0,!!k.truncated,typeof k.cols=="number"?k.cols:void 0,typeof k.rows=="number"?k.rows:void 0);return}if(k.type==="topic_update"){const v=k.update;v&&os.publish(v);return}if(k.type==="status"||k.type==="initial_state"){const v=k.data;if(!v)return;const{injectEntries:y,markLoaded:$,getIdes:L}=s.current,M=v.instanceId||"standalone",_=L().find(N=>N.id===M),W=Ib(M);Xt.register(M,W),Xt.setState(M,"connected"),u("connected",M),Xt.emitStatus(M,v);const H=mn(v,{daemonId:M,existingDaemon:_,existingEntries:L()});Hi("ws_status",{type:k.type,daemonId:M,sessions:(v.sessions||[]).map(N=>({id:N.id,parentId:N.parentId,providerType:N.providerType,kind:N.kind,transport:N.transport,unread:N.unread,inboxBucket:N.inboxBucket,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,title:N.title})),recentLaunches:(v.recentLaunches||[]).map(N=>({id:N.id,providerType:N.providerType,kind:N.kind,workspace:N.workspace,lastLaunchedAt:N.lastLaunchedAt}))}),Hi("entries",{daemonId:M,entries:H.filter(N=>N.type!=="adhdev-daemon").map(N=>({id:N.id,type:N.type,unread:N.unread,inboxBucket:N.inboxBucket,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,sessionId:N.sessionId}))}),H.length>0&&y(H,{authoritativeDaemonIds:[M]}),$(),c.current!==M&&((C=i.current)==null||C.call(i),c.current=M,i.current=os.subscribe({sendData:Ta},M,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${M}`,params:{includeSessions:!0}},N=>{if(N.topic!=="daemon.metadata")return;const P=s.current.getIdes(),G=P.find(E=>E.id===M),I=mn(N.status,{daemonId:M,existingDaemon:G,existingEntries:P,timestamp:N.timestamp});I.length>0&&s.current.injectEntries(I),N.userName&&a.current&&a.current(N.userName)}))}}catch(k){console.error("[Standalone WS] Parse error:",k)}},b.onclose=R=>{g.current&&(Bt==null||Bt.stopScreenshots(),Bt&&Xt.setState(Bt.daemonId,"disconnected"),u("disconnected"),p.current=null,A.current=`close:${R.code}${R.wasClean?":clean":":unclean"}`,rr("close",{code:R.code,reason:R.reason||"",wasClean:R.wasClean}),f())},b.onerror=R=>{w.current||!g.current||(A.current="error",rr("error",{message:R instanceof Event?"event":String(R),readyState:b.readyState}),console.warn("[Standalone WS] Error, will reconnect:",R))}}function f(){if(!g.current)return;clearTimeout(d.current);const b=x.current;console.log(`[Standalone WS] Reconnecting in ${b}ms...`),rr("schedule_reconnect",{reason:A.current,delayMs:b}),d.current=setTimeout(()=>{x.current=Math.min(x.current*1.5,kb),m()},b)}return m(),()=>{var b;g.current=!1,w.current=!0,(b=i.current)==null||b.call(i),i.current=null,c.current=null,clearTimeout(d.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,Vt=null),Bt&&(Bt.stopScreenshots(),Xt.unregister(Bt.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function Mb({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(mr=(c,l)=>{r(c),l&&a(l)},()=>{mr=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=Nb(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(Dd,{connectionOverrides:i,children:t.jsx(Ab,{children:e})})}const Ul="adhdev_standalone_font_preferences",js={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Ln=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],wr=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],Tb=new Set(Ln.map(e=>e.id)),Lb=new Set(wr.map(e=>e.id));function Gt(e){const s=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:on("chat",s.chat),code:on("code",s.code),terminal:on("terminal",s.terminal)}}function on(e,s){const r=js[e],n=s&&typeof s=="object"&&!Array.isArray(s)?s:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?Tb:Lb).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function cn(e,s){var a;const r=on(e,s);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?Ln:wr;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function Rb(e){const s=Gt(e),r=cn("chat",s.chat),n=cn("code",s.code),a=cn("terminal",s.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function fs(e,s=document.documentElement){const r=Gt(e),n=Rb(r);s.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))s.style.setProperty(a,i);return r}function La(e){const s=Gt(e);try{localStorage.setItem(Ul,JSON.stringify(s))}catch{}return s}function _b(){try{const e=localStorage.getItem(Ul);if(e)return Gt(JSON.parse(e))}catch{}return js}function Pb(){return fs(_b())}function nr(e,s){var n;const r=e==="chat"?Ln:wr;return((n=r.find(a=>a.id===s))==null?void 0:n.label)||r[0].label}const Db=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Ji,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(Zt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(gn,{}),label:"Settings"}];function Eb({children:e}){const s=Vs(),r=Pa(),[n,a]=o.useState(!1),[i,c]=o.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),l=d=>{s(d),a(!1)},u=()=>{c(d=>{const x=!d;try{localStorage.setItem("sidebar-collapsed",x?"1":"0")}catch{}return x})},p=d=>`nav-item${r.pathname.startsWith(d)?" active":""} cursor-pointer ${i?"justify-center py-2.5 px-0":""}`;return t.jsxs("div",{className:`app-layout${n?" mobile-menu-open":""}${i?" sidebar-collapsed":""}`,children:[t.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:()=>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:d=>d.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:Db.map(d=>t.jsxs("div",{className:p(d.path),id:`nav-${d.id}`,onClick:()=>l(d.path),title:i?d.label:void 0,children:[t.jsx("span",{className:"nav-icon",children:d.icon}),!i&&d.label]},d.id))}),t.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":""}`,id:"nav-docs",onClick:()=>window.open("https://docs.adhf.dev","_blank"),title:i?"Docs":void 0,children:[t.jsx("span",{className:"nav-icon",children:t.jsx(Qi,{})}),!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(Zi,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.96"]}),t.jsx(ep,{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 $b=[{icon:t.jsx(Zt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(es,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(ec,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Pt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(hr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(Qi,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Kb=[{icon:t.jsx(Jd,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Ji,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(vn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(Ud,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx($a,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(Vd,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Bb=[{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 Ob(){return t.jsxs(Qc,{icon:t.jsx(Zi,{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.96"]}),children:[t.jsx(Rt,{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(Rt,{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:$b.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(Rt,{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:Yc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Jc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Xc.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(Rt,{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:Kb.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(Rt,{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:Bb.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(Zc,{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(iu,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function da(e,s,r){return{...e,[s]:r}}function ua({surface:e,title:s,description:r,value:n,options:a,onChange:i}){return t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-text-primary",children:s}),t.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:c=>{const l=c.target.value;i(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>t.jsx("option",{value:c.id,children:c.label},c.id))}),n.preset==="custom"&&t.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:c=>i({preset:"custom",customFamily:c.target.value})}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:[t.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",t.jsx("span",{className:"font-mono break-all",children:cn(e,n)})]})]})]})}function Wb({value:e,savedValue:s,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:u}){const p=JSON.stringify(e)!==JSON.stringify(s);return t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&t.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&t.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),t.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[t.jsx(ua,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Ln,onChange:d=>i(da(e,"chat",d))}),t.jsx(ua,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:wr,onChange:d=>i(da(e,"code",d))}),t.jsx(ua,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:wr,onChange:d=>i(da(e,"terminal",d))})]}),t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),t.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",nr("chat",e.chat.preset)," · Code: ",nr("code",e.code.preset)," · Terminal: ",nr("terminal",e.terminal.preset)]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",nr("chat",js.chat.preset)," / ",nr("code",js.code.preset)]})]}),t.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:t.jsxs("div",{className:"chat-container-content",children:[t.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:t.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[t.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[t.jsx("span",{className:"chat-sender",children:"Hermes"}),t.jsx("span",{className:"chat-time",children:"now"})]}),t.jsxs("div",{className:"chat-markdown",children:[t.jsxs("p",{children:["Readable prose, ",t.jsx("strong",{children:"bold text"}),", and ",t.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),t.jsx("pre",{children:t.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),t.jsxs("div",{className:"chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"▸"}),t.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),t.jsxs("div",{className:"chat-msg-terminal",children:[t.jsx("div",{className:"chat-msg-header",children:"Terminal"}),t.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:c,disabled:r||!p,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),t.jsx("button",{type:"button",onClick:l,disabled:r||!p,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),t.jsx("button",{type:"button",onClick:u,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function Hb(){const{ides:e}=ks(),s=e.find(O=>O.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Lt(),{userName:a}=ks(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[p,d]=o.useState(null),[x,g]=o.useState(js),[w,A]=o.useState(!1),[m,f]=o.useState(""),[b,h]=o.useState(""),[S,R]=o.useState("127.0.0.1"),[j,C]=o.useState(""),[k,v]=o.useState(""),[y,$]=o.useState(""),[L,M]=o.useState(""),[_,W]=o.useState(""),[H,N]=o.useState(!1),P=async()=>{const X=await(await zt("/auth/session")).json();u(X)},G=async()=>{const X=await(await zt("/api/v1/standalone/preferences")).json();d(X),R(X.standaloneBindHost);const ie=Gt(X.standaloneFontPreferences);g(ie),fs(ie),La(ie)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([P(),G()]).catch(O=>{M(O instanceof Error?O.message:String(O))})},[]),o.useEffect(()=>{fs(x)},[x]);const I=O=>{const X=O.target.value.trim();s!=null&&s.id&&X!==a&&n(s.id,"set_user_name",{userName:X}).catch(console.error)},[E,B]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),U=O=>{B(O);try{localStorage.setItem("adhdev_sound",O?"1":"0")}catch{}},V=async()=>{f(""),h(""),A(!0);try{const O=Gt(x),X=await zt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:O})}),ie=await X.json();if(!X.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to save standalone font preferences");const le=Gt(ie.standaloneFontPreferences);d(ie),g(le),fs(le),La(le),h("Standalone chat fonts saved for this self-hosted dashboard.")}catch(O){f(O instanceof Error?O.message:String(O))}finally{A(!1)}},ae=()=>{const O=Gt(p==null?void 0:p.standaloneFontPreferences);f(""),h(""),g(O),fs(O)},we=()=>{f(""),h(""),g(js),fs(js)},be=async()=>{M(""),W(""),N(!0);try{const O=await zt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:S})}),X=await O.json();if(!O.ok)throw new Error((X==null?void 0:X.error)||"Failed to save standalone network preference");d(X),R(X.standaloneBindHost),W(X.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){M(O instanceof Error?O.message:String(O))}finally{N(!1)}},Y=async()=>{if(M(""),W(""),k.trim().length<4){M("Password must be at least 4 characters.");return}if(k!==y){M("New password and confirmation do not match.");return}N(!0);try{const O=await zt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:j,newPassword:k})}),X=await O.json();if(!O.ok)throw new Error((X==null?void 0:X.error)||"Failed to save password");u(X),await G(),C(""),v(""),$(""),W(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Fl()}catch(O){M(O instanceof Error?O.message:String(O))}finally{N(!1)}},he=async()=>{M(""),W(""),N(!0);try{const O=await zt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:j,clear:!0})}),X=await O.json();if(!O.ok)throw new Error((X==null?void 0:X.error)||"Failed to clear password");u(X),await G(),C(""),v(""),$(""),W("Standalone password disabled.")}catch(O){M(O instanceof Error?O.message:String(O))}finally{N(!1)}};return t.jsxs(Qc,{icon:t.jsx(gn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(Wr,{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(Wr,{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(Rt,{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.96"]}),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(Rt,{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:S==="127.0.0.1",onChange:()=>R("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:S==="0.0.0.0",onChange:()=>R("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:()=>{be()},disabled:H,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:H?"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(Rt,{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."}),L&&t.jsx(Wr,{variant:"error",children:L}),_&&t.jsx(Wr,{variant:"success",children:_}),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:j,onChange:O=>C(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:k,onChange:O=>v(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=>$(O.target.value)})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{Y()},disabled:H,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:H?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&t.jsx("button",{type:"button",onClick:()=>{he()},disabled:H,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(Rt,{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(Rt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(np,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Rt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),t.jsx(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:"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(xp,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),t.jsx(Wb,{value:x,savedValue:Gt(p==null?void 0:p.standaloneFontPreferences),saving:w,error:m,notice:b,onChange:g,onSave:()=>{V()},onResetToSaved:ae,onResetToDefaults:we})]}),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(yp,{})]})]})}),t.jsx(Rt,{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(tp,{}),t.jsx(ms,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(ou,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:U})]})}),t.jsx(Rt,{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(Fd,{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:I,onKeyDown:O=>{O.key==="Enter"&&O.currentTarget.blur()}})]})})})]})}Zf();pp();Pb();const Fb=qi({baseUrl:"",getToken:vo});function Ub({children:e}){const[s,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[p,d]=o.useState(!1),x=async()=>{a(!0),u("");try{const A=await(await zt("/auth/session")).json();r(A)}catch(w){u(w instanceof Error?w.message:String(w))}finally{a(!1)}};o.useEffect(()=>{x()},[]),o.useEffect(()=>{if(!s||s.required&&!s.authenticated)return;let w=!1;return(async()=>{try{const A=await zt("/api/v1/standalone/preferences");if(!A.ok)return;const m=await A.json();if(w)return;const f=Gt(m.standaloneFontPreferences);fs(f),La(f)}catch{}})(),()=>{w=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const g=async w=>{w.preventDefault(),d(!0),u("");try{const A=await zt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),m=await A.json();if(!A.ok)throw new Error((m==null?void 0:m.error)||"Login failed");r(m),c(""),Fl()}catch(A){u(A instanceof Error?A.message:String(A))}finally{d(!1)}};return n?t.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):s?!s.required||s.authenticated?t.jsx(t.Fragment,{children:e}):t.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:t.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),t.jsx("p",{className:"text-sm text-text-muted mt-1",children:s.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),s.hasPasswordAuth?t.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[t.jsx("input",{type:"password",value:i,onChange:w=>c(w.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),t.jsx("button",{type:"submit",disabled: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 Fi(){const{ides:e,initialLoaded:s}=ks();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(pa,{to:`/machines/${r.id}`,replace:!0}):t.jsx(pa,{to:"/dashboard",replace:!0})}function zb(){const e=o.useMemo(()=>({sendCommand:an,sendData:Ta}),[]);return t.jsx(Cd,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(Kd,{client:Fb,children:t.jsx(Ub,{children:t.jsx(Mb,{children:t.jsx(Od,{value:e,children:t.jsx(Eb,{children:t.jsxs(Id,{children:[t.jsx(ls,{path:"/dashboard",element:t.jsx(Ux,{})}),t.jsx(ls,{path:"/machine",element:t.jsx(Fi,{})}),t.jsx(ls,{path:"/machines/:id",element:t.jsx(yb,{})}),t.jsx(ls,{path:"/machines",element:t.jsx(Fi,{})}),t.jsx(ls,{path:"/about",element:t.jsx(Ob,{})}),t.jsx(ls,{path:"/settings",element:t.jsx(Hb,{})}),t.jsx(ls,{path:"*",element:t.jsx(pa,{to:"/dashboard",replace:!0})})]})})})})})})})}pf({connectionManager:Xt});Ad(document.getElementById("root")).render(t.jsx(zb,{}));